]> oss.titaniummirror.com Git - tinyos-2.x.git/commitdiff
Merge TinyOS 2.1.1 into master.
authorR. Steve McKown <rsmckown@gmail.com>
Fri, 7 May 2010 20:42:29 +0000 (14:42 -0600)
committerR. Steve McKown <rsmckown@gmail.com>
Fri, 7 May 2010 20:42:29 +0000 (14:42 -0600)
How this merge was done:
* Rebase patchset/2.1.0-4.2 onto tinyos/2.1.1 as topic/patchup211
* cp topic/patchup211 tree to tmp dir
* Checkout master, rm all files, cp in from tmp dir, git add .

Future work on TinyOS 2.1.0 w/TMI enhancements via release/2.1.0.

1789 files changed:
apps/6lowpancli/CliAppC.nc [deleted file]
apps/6lowpancli/CliC.nc [deleted file]
apps/6lowpancli/Makefile [deleted file]
apps/6lowpancli/README [deleted file]
apps/AntiTheft/Nodes/AntiTheftC.nc
apps/AntiTheft/Nodes/Makefile
apps/AntiTheft/Root/AntiTheftRootC.nc
apps/AntiTheft/Root/Makefile
apps/BaseStation/BaseStationC.nc
apps/BaseStation/Makefile
apps/BaseStation/README.txt
apps/Blink/BlinkAppC.nc
apps/IPBaseStation/BaseStationC.nc [new file with mode: 0644]
apps/IPBaseStation/BaseStationP.nc [new file with mode: 0644]
apps/IPBaseStation/Makefile [new file with mode: 0644]
apps/IPBaseStation/README [new file with mode: 0644]
apps/IPBaseStation/Reset.h [new file with mode: 0644]
apps/IPBaseStation/Reset.nc [new file with mode: 0644]
apps/IPBaseStation/ResetC.nc [new file with mode: 0644]
apps/MViz/MVizC.nc
apps/MultihopOscilloscope/MultihopOscilloscopeC.nc
apps/MultihopOscilloscope/oscilloscope.py [new file with mode: 0644]
apps/Null/NullC.nc
apps/Oscilloscope/OscilloscopeC.nc
apps/Oscilloscope/java/Window.java
apps/Oscilloscope/oscilloscope.py [new file with mode: 0644]
apps/Powerup/PowerupC.nc
apps/RadioCountToLeds/Makefile
apps/RadioSenseToLeds/RadioSenseToLedsC.nc
apps/TCPEcho/HttpdP.nc [new file with mode: 0644]
apps/TCPEcho/Makefile [new file with mode: 0644]
apps/TCPEcho/README [new file with mode: 0644]
apps/TCPEcho/TCPEchoC.nc [new file with mode: 0644]
apps/TCPEcho/TCPEchoP.nc [new file with mode: 0644]
apps/TCPEcho/UDPReport.h [new file with mode: 0644]
apps/UDPEcho/Makefile [new file with mode: 0644]
apps/UDPEcho/Makefile.local [new file with mode: 0644]
apps/UDPEcho/NodeConnectivity/NodeConnectivity.nc [new file with mode: 0644]
apps/UDPEcho/NodeConnectivity/TestbedConnectivityM.nc [new file with mode: 0644]
apps/UDPEcho/NodeConnectivity/createNodeConnectivityM.pl [new file with mode: 0644]
apps/UDPEcho/NodeConnectivity/exampleMap.txt [new file with mode: 0644]
apps/UDPEcho/NodeConnectivity/testBed.nss [new file with mode: 0644]
apps/UDPEcho/NodeConnectivity/testBedMap.txt [new file with mode: 0644]
apps/UDPEcho/README [new file with mode: 0644]
apps/UDPEcho/UDPEchoC.nc [new file with mode: 0644]
apps/UDPEcho/UDPEchoP.nc [new file with mode: 0644]
apps/UDPEcho/UDPReport.h [new file with mode: 0644]
apps/UDPEcho/tests/echotest.pl [new file with mode: 0644]
apps/UDPEcho/tests/seqtest.pl [new file with mode: 0755]
apps/UDPEcho/util/Listener.py [new file with mode: 0644]
apps/UDPEcho/util/MySQLListener.py [new file with mode: 0644]
apps/UDPEcho/util/UdpReport.py [new file with mode: 0644]
apps/UDPEcho/volumes-at45db.xml [new file with mode: 0644]
apps/UDPEcho/volumes-stm25p.xml [new file with mode: 0644]
apps/tests/NxFloat/.cvsignore [new file with mode: 0644]
apps/tests/NxFloat/Makefile [new file with mode: 0644]
apps/tests/NxFloat/README.txt [new file with mode: 0644]
apps/tests/NxFloat/TestSerial.h [new file with mode: 0644]
apps/tests/NxFloat/TestSerial.java [new file with mode: 0644]
apps/tests/NxFloat/TestSerialAppC.nc [new file with mode: 0644]
apps/tests/NxFloat/TestSerialC.nc [new file with mode: 0644]
apps/tests/TestDhv/DhvInject.java [new file with mode: 0644]
apps/tests/TestDhv/Makefile [new file with mode: 0644]
apps/tests/TestDhv/README [new file with mode: 0644]
apps/tests/TestDhv/TestDhv.h [new file with mode: 0644]
apps/tests/TestDhv/TestDhvC-Master.nc [new file with mode: 0644]
apps/tests/TestDhv/TestDhvC.nc [new file with mode: 0644]
apps/tests/TestDhv/TestDhvP-Master.nc [new file with mode: 0644]
apps/tests/TestDhv/TestDhvP.nc [new file with mode: 0644]
apps/tests/TestDhv/TestDipP.nc [new file with mode: 0644]
apps/tests/TestDhv/gentest.py [new file with mode: 0644]
apps/tests/TestDip/Makefile
apps/tests/TestDip/README
apps/tests/TestDip/TestDipC-Master.nc
apps/tests/TestDip/TestDipP-Master.nc
apps/tests/TestDissemination/Makefile
apps/tests/TestEui/Makefile [new file with mode: 0644]
apps/tests/TestEui/README.txt [new file with mode: 0644]
apps/tests/TestEui/TestEuiAppC.nc [new file with mode: 0644]
apps/tests/TestEui/TestEuiC.nc [new file with mode: 0644]
apps/tests/TestFtsp/Ftsp/FtspDataAnalyzer.m [new file with mode: 0755]
apps/tests/TestFtsp/Ftsp/FtspDataLogger.java [new file with mode: 0755]
apps/tests/TestFtsp/Ftsp/FtspDataLogger.py [new file with mode: 0755]
apps/tests/TestFtsp/Ftsp/Makefile [new file with mode: 0755]
apps/tests/TestFtsp/Ftsp/README.MATLAB.txt [new file with mode: 0755]
apps/tests/TestFtsp/Ftsp/README.txt [new file with mode: 0755]
apps/tests/TestFtsp/Ftsp/TestFtsp.h [new file with mode: 0755]
apps/tests/TestFtsp/Ftsp/TestFtspAppC.nc [new file with mode: 0755]
apps/tests/TestFtsp/Ftsp/TestFtspC.nc [new file with mode: 0755]
apps/tests/TestFtsp/FtspDataAnalyzer.m [deleted file]
apps/tests/TestFtsp/FtspDataLogger.java [deleted file]
apps/tests/TestFtsp/FtspLpl/FtspDataLogger.py [new file with mode: 0755]
apps/tests/TestFtsp/FtspLpl/Makefile [new file with mode: 0755]
apps/tests/TestFtsp/FtspLpl/README [new file with mode: 0755]
apps/tests/TestFtsp/FtspLpl/TestFtsp.h [new file with mode: 0755]
apps/tests/TestFtsp/FtspLpl/TestFtspAppC.nc [new file with mode: 0755]
apps/tests/TestFtsp/FtspLpl/TestFtspC.nc [new file with mode: 0755]
apps/tests/TestFtsp/FtspLpl/TestFtspMsg.py [new file with mode: 0755]
apps/tests/TestFtsp/FtspLplBeaconer/Makefile [new file with mode: 0755]
apps/tests/TestFtsp/FtspLplBeaconer/RadioCountToLeds.h [new file with mode: 0755]
apps/tests/TestFtsp/FtspLplBeaconer/RadioCountToLedsAppC.nc [new file with mode: 0755]
apps/tests/TestFtsp/FtspLplBeaconer/RadioCountToLedsC.nc [new file with mode: 0755]
apps/tests/TestFtsp/Makefile [deleted file]
apps/tests/TestFtsp/README.txt [deleted file]
apps/tests/TestFtsp/TestFtsp.h [deleted file]
apps/tests/TestFtsp/TestFtspAppC.nc [deleted file]
apps/tests/TestFtsp/TestFtspC.nc [deleted file]
apps/tests/TestLocalTime/README.txt
apps/tests/TestLocalTime/dump.py [new file with mode: 0644]
apps/tests/TestLpl/README.txt
apps/tests/TestLpl/TestLplAppC.nc
apps/tests/TestLpl/TestLplC.nc
apps/tests/TestNetwork/README.txt
apps/tests/TestNetwork/TestNetworkAppC.nc
apps/tests/TestNetwork/TestNetworkC.nc
apps/tests/TestNetworkLpl/Makefile [new file with mode: 0644]
apps/tests/TestNetworkLpl/README.txt [new file with mode: 0644]
apps/tests/TestNetworkLpl/TestNetworkLplAppC.nc [new file with mode: 0644]
apps/tests/TestNetworkLpl/TestNetworkLplC.nc [new file with mode: 0644]
apps/tests/TestNetworkLpl/ctp-dump.py [new file with mode: 0644]
apps/tests/TestSerial/README.txt
apps/tests/TestSerialBandwidth/Makefile
apps/tests/TestSerialBandwidth/TestSerialMsg.java [deleted file]
apps/tests/TestSimComm/README
apps/tests/TestSimComm/run
apps/tests/TestSimComm/test-asym.py
apps/tests/TestSimComm/test-equal.py
apps/tests/TestSimComm/test-unequal.py
apps/tests/TestSimTimers/README
apps/tests/TestTrickleTimer/TestTrickleTimerAppC.nc
apps/tests/TestTrickleTimer/TestTrickleTimerAppP.nc
apps/tests/TestTrickleTimer/test.py
apps/tests/arbiters/TestFcfsArbiter/README.txt
apps/tests/arbiters/TestFcfsArbiter/TestFcfsArbiterAppC.nc
apps/tests/arbiters/TestFcfsArbiter/TestFcfsArbiterC.nc
apps/tests/arbiters/TestRoundRobinArbiter/README.txt
apps/tests/arbiters/TestRoundRobinArbiter/TestRoundRobinArbiterAppC.nc
apps/tests/arbiters/TestRoundRobinArbiter/TestRoundRobinArbiterC.nc
apps/tests/cc2420/LplBroadcastCountToLeds/Makefile
apps/tests/cc2420/LplBroadcastCountToLeds/RadioCountMsg.java [deleted file]
apps/tests/cc2420/LplBroadcastCountToLeds/RadioCountToLedsAppC.nc
apps/tests/cc2420/LplBroadcastCountToLeds/RadioCountToLedsC.nc
apps/tests/cc2420/LplBroadcastPeriodicDelivery/README.txt
apps/tests/cc2420/LplBroadcastPeriodicDelivery/TestPeriodicAppC.nc
apps/tests/cc2420/LplBroadcastPeriodicDelivery/TestPeriodicC.nc
apps/tests/cc2420/LplUnicastPeriodicDelivery/TestPeriodicAppC.nc
apps/tests/cc2420/LplUnicastPeriodicDelivery/TestPeriodicC.nc
apps/tests/cc2420/RssiToSerial/Makefile
apps/tests/cc2420/TestPacketLink/Makefile
apps/tests/cc2420/TestPacketLink/README.txt
apps/tests/cc2420/TestSecurity/BaseStation/BaseStationC.nc [new file with mode: 0644]
apps/tests/cc2420/TestSecurity/BaseStation/BaseStationP.nc [new file with mode: 0644]
apps/tests/cc2420/TestSecurity/BaseStation/Makefile [new file with mode: 0644]
apps/tests/cc2420/TestSecurity/README.txt [new file with mode: 0644]
apps/tests/cc2420/TestSecurity/RadioCountToLeds1/Makefile [new file with mode: 0644]
apps/tests/cc2420/TestSecurity/RadioCountToLeds1/RadioCountToLeds.h [new file with mode: 0644]
apps/tests/cc2420/TestSecurity/RadioCountToLeds1/RadioCountToLedsAppC.nc [new file with mode: 0644]
apps/tests/cc2420/TestSecurity/RadioCountToLeds1/RadioCountToLedsC.nc [new file with mode: 0644]
apps/tests/cc2420/TxThroughput/Makefile
apps/tests/deluge/Basestation/BasestationAppC.nc [new file with mode: 0644]
apps/tests/deluge/Basestation/Makefile [new file with mode: 0644]
apps/tests/deluge/Basestation/README.txt [new file with mode: 0644]
apps/tests/deluge/Basestation/volumes-at45db.xml [new file with mode: 0644]
apps/tests/deluge/Basestation/volumes-stm25p.xml [new file with mode: 0644]
apps/tests/deluge/Blink/BlinkAppC.nc
apps/tests/deluge/Blink/burn
apps/tests/deluge/Blink/burn-net
apps/tests/deluge/GoldenImage/GoldenImageAppC.nc
apps/tests/deluge/GoldenImage/Makefile
apps/tests/deluge/GoldenImage/README.txt
apps/tests/eyesIFX/RadioCountToFlash/Makefile
apps/tests/msp430/Adc12/TestAdcAppC.nc
apps/tests/msp430/Adc12/TestAdcMultiC.nc
apps/tests/msp430/Adc12/TestAdcSingleC.nc
apps/tests/rf230/Ieee154CountToLeds/Makefile [new file with mode: 0644]
apps/tests/rf230/Ieee154CountToLeds/RadioCountToLeds.h [new file with mode: 0644]
apps/tests/rf230/Ieee154CountToLeds/RadioCountToLedsAppC.nc [new file with mode: 0644]
apps/tests/rf230/Ieee154CountToLeds/RadioCountToLedsC.nc [new file with mode: 0644]
apps/tests/rf230/RF230Sniffer/Makefile
apps/tests/rf230/RF230Sniffer/RF230SnifferC.nc
apps/tests/rf230/RF230Sniffer/RF230SnifferP.nc
apps/tests/rf230/RF230Test/RF230TestC.nc
apps/tests/rf230/RadioCountToDiag/RadioCountToDiagC.nc
apps/tests/rf230/RadioCountToDiag/RadioCountToDiagP.nc
apps/tests/storage/Config/volumes-at45db.xml
apps/tests/storage/Log/RandRWC.nc
apps/tests/tkn154/Makefile.include
apps/tests/tkn154/README.txt
apps/tests/tkn154/TestAssociate/README.txt [deleted file]
apps/tests/tkn154/TestAssociate/app_profile.h [deleted file]
apps/tests/tkn154/TestAssociate/coordinator/Makefile [deleted file]
apps/tests/tkn154/TestAssociate/coordinator/TestAssociateAppC.nc [deleted file]
apps/tests/tkn154/TestAssociate/coordinator/TestCoordC.nc [deleted file]
apps/tests/tkn154/TestAssociate/device/Makefile [deleted file]
apps/tests/tkn154/TestAssociate/device/TestAssociateAppC.nc [deleted file]
apps/tests/tkn154/TestAssociate/device/TestDeviceC.nc [deleted file]
apps/tests/tkn154/TestData/README.txt [deleted file]
apps/tests/tkn154/TestData/app_profile.h [deleted file]
apps/tests/tkn154/TestData/coordinator/Makefile [deleted file]
apps/tests/tkn154/TestData/coordinator/TestCoordReceiverC.nc [deleted file]
apps/tests/tkn154/TestData/coordinator/TestDataAppC.nc [deleted file]
apps/tests/tkn154/TestData/device/Makefile [deleted file]
apps/tests/tkn154/TestData/device/TestDataAppC.nc [deleted file]
apps/tests/tkn154/TestData/device/TestDeviceSenderC.nc [deleted file]
apps/tests/tkn154/TestIndirect/README.txt [deleted file]
apps/tests/tkn154/TestIndirect/app_profile.h [deleted file]
apps/tests/tkn154/TestIndirect/coordinator/Makefile [deleted file]
apps/tests/tkn154/TestIndirect/coordinator/TestCoordSenderC.nc [deleted file]
apps/tests/tkn154/TestIndirect/coordinator/TestIndirectAppC.nc [deleted file]
apps/tests/tkn154/TestIndirect/device/Makefile [deleted file]
apps/tests/tkn154/TestIndirect/device/TestDeviceReceiverC.nc [deleted file]
apps/tests/tkn154/TestIndirect/device/TestIndirectAppC.nc [deleted file]
apps/tests/tkn154/TestPromiscuous/Makefile [deleted file]
apps/tests/tkn154/TestPromiscuous/README.txt [deleted file]
apps/tests/tkn154/TestPromiscuous/TestPromiscuousAppC.nc [deleted file]
apps/tests/tkn154/TestPromiscuous/TestPromiscuousC.nc [deleted file]
apps/tests/tkn154/TestStartSync/README.txt [deleted file]
apps/tests/tkn154/TestStartSync/app_profile.h [deleted file]
apps/tests/tkn154/TestStartSync/coordinator/Makefile [deleted file]
apps/tests/tkn154/TestStartSync/coordinator/TestCoordC.nc [deleted file]
apps/tests/tkn154/TestStartSync/coordinator/TestStartSyncAppC.nc [deleted file]
apps/tests/tkn154/TestStartSync/device/Makefile [deleted file]
apps/tests/tkn154/TestStartSync/device/TestDeviceC.nc [deleted file]
apps/tests/tkn154/TestStartSync/device/TestStartSyncAppC.nc [deleted file]
apps/tests/tkn154/beacon-enabled/TestAssociate/README.txt [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestAssociate/app_profile.h [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestAssociate/coordinator/Makefile [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestAssociate/coordinator/TestAssociateAppC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestAssociate/coordinator/TestCoordC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestAssociate/device/Makefile [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestAssociate/device/TestAssociateAppC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestAssociate/device/TestDeviceC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestData/README.txt [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestData/app_profile.h [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestData/coordinator/Makefile [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestData/coordinator/TestCoordReceiverC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestData/coordinator/TestDataAppC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestData/device/Makefile [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestData/device/TestDataAppC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestData/device/TestDeviceSenderC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestIndirect/README.txt [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestIndirect/app_profile.h [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestIndirect/coordinator/Makefile [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestIndirect/coordinator/TestCoordSenderC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestIndirect/coordinator/TestIndirectAppC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestIndirect/device/Makefile [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestIndirect/device/TestDeviceReceiverC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestIndirect/device/TestIndirectAppC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestStartSync/README.txt [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestStartSync/app_profile.h [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestStartSync/coordinator/Makefile [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestStartSync/coordinator/TestCoordC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestStartSync/coordinator/TestStartSyncAppC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestStartSync/device/Makefile [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestStartSync/device/TestDeviceC.nc [new file with mode: 0644]
apps/tests/tkn154/beacon-enabled/TestStartSync/device/TestStartSyncAppC.nc [new file with mode: 0644]
apps/tests/tkn154/makeall.sh [new file with mode: 0755]
apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/README.txt [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/app_profile.h [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/coordinator/Makefile [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/coordinator/TestActiveScanCoordAppC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/coordinator/TestActiveScanCoordC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/device/Makefile [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/device/TestActiveScanDeviceAppC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/device/TestActiveScanDeviceC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestAssociate/README.txt [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestAssociate/app_profile.h [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestAssociate/coordinator/Makefile [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestAssociate/coordinator/TestAssociateAppC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestAssociate/coordinator/TestCoordC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestAssociate/device/Makefile [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestAssociate/device/TestAssociateAppC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestAssociate/device/TestDeviceC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/README.txt [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/app_profile.h [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/coordinator/Makefile [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/coordinator/TestIndirectDataCoordAppC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/coordinator/TestIndirectDataCoordC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/device/Makefile [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/device/TestIndirectDataDeviceAppC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/device/TestIndirectDataDeviceC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/Makefile [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/README.txt [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/TestPromiscuousAppC.nc [new file with mode: 0644]
apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/TestPromiscuousC.nc [new file with mode: 0644]
apps/tosthreads/apps/BaseStation/BaseSendReceiveP.nc
apps/tosthreads/apps/BaseStation/BaseStationAppC.nc
apps/tosthreads/apps/BaseStation/BaseStationC.nc
apps/tosthreads/apps/BaseStation/README
apps/tosthreads/apps/Blink/BlinkAppC.nc
apps/tosthreads/apps/Blink/BlinkC.nc
apps/tosthreads/apps/Blink/README
apps/tosthreads/apps/Blink_DynamicThreads/BlinkAppC.nc [new file with mode: 0644]
apps/tosthreads/apps/Blink_DynamicThreads/BlinkC.nc [new file with mode: 0644]
apps/tosthreads/apps/Blink_DynamicThreads/Makefile [new file with mode: 0644]
apps/tosthreads/apps/Blink_DynamicThreads/README [new file with mode: 0644]
apps/tosthreads/apps/Bounce/README
apps/tosthreads/apps/RadioStress/README
apps/tosthreads/apps/TestBasicsbSensors/Makefile
apps/tosthreads/apps/TestBasicsbSensors/TestBasicsbSensorsAppC.nc
apps/tosthreads/apps/TestBasicsbSensors/TestBasicsbSensorsC.nc
apps/tosthreads/apps/TestBlockStorage/TestBlockStorageAppC.nc
apps/tosthreads/apps/TestBlockStorage/TestBlockStorageP.nc
apps/tosthreads/apps/TestCollection/README
apps/tosthreads/apps/TestCollection/TestCollectionAppC.nc
apps/tosthreads/apps/TestCollection/TestCollectionC.nc
apps/tosthreads/apps/TestJoin/Makefile [new file with mode: 0644]
apps/tosthreads/apps/TestJoin/README [new file with mode: 0644]
apps/tosthreads/apps/TestJoin/TestJoinAppC.nc [new file with mode: 0644]
apps/tosthreads/apps/TestJoin/TestJoinC.nc [new file with mode: 0644]
apps/tosthreads/apps/TestPrintf/README
apps/tosthreads/apps/TestPrintf/TestPrintfAppC.nc
apps/tosthreads/apps/TestPrintf/TestPrintfC.nc
apps/tosthreads/apps/TestSineSensor/README
apps/tosthreads/apps/TestSineSensor/TestSineSensorAppC.nc
apps/tosthreads/apps/TestSineSensor/TestSineSensorC.nc
apps/tosthreads/capps/BaseStation/BaseStation.c
apps/tosthreads/capps/BaseStation/README
apps/tosthreads/capps/Blink/Blink.c
apps/tosthreads/capps/Blink/README
apps/tosthreads/capps/Bounce/Bounce.c
apps/tosthreads/capps/Bounce/README
apps/tosthreads/capps/Null/Null.c
apps/tosthreads/capps/Null/README
apps/tosthreads/capps/RadioStress/README
apps/tosthreads/capps/SenseAndSend/Makefile
apps/tosthreads/capps/SenseAndSend/SenseAndSend.c
apps/tosthreads/capps/SenseStoreAndForward/SenseStoreAndForward.c
apps/tosthreads/capps/TestCollection/Makefile
apps/tosthreads/capps/TestCollection/README
apps/tosthreads/capps/TestCollection/TestCollection.c
apps/tosthreads/capps/TestJoin/Makefile [new file with mode: 0644]
apps/tosthreads/capps/TestJoin/README [new file with mode: 0644]
apps/tosthreads/capps/TestJoin/TestJoin.c [new file with mode: 0644]
apps/tosthreads/capps/TestJoin/stack.h [new file with mode: 0644]
apps/tosthreads/capps/TestLogStorage/Makefile
apps/tosthreads/capps/TestLogStorage/README
apps/tosthreads/capps/TestLogStorage/TestLogStorage.c
apps/tosthreads/capps/TestPrintf/README
apps/tosthreads/capps/TestPrintf/TestPrintf.c
apps/tosthreads/capps/TestSineSensor/README
apps/tosthreads/capps/TestSineSensor/TestSineSensor.c
apps/tosthreads/capps/ThreadStress/README
apps/tosthreads/capps/ThreadStress/ThreadStress.c
apps/tosthreads/tinyld/LoadFromRAM/LoadFromRAMAppC.nc [new file with mode: 0644]
apps/tosthreads/tinyld/LoadFromRAM/LoadFromRAMP.nc [new file with mode: 0644]
apps/tosthreads/tinyld/LoadFromRAM/Makefile [new file with mode: 0644]
apps/tosthreads/tinyld/LoadFromRAM/README [new file with mode: 0644]
apps/tosthreads/tinyld/LoadFromRAM/volumes-at45db.xml [new file with mode: 0644]
apps/tosthreads/tinyld/LoadFromRAM/volumes-stm25p.xml [new file with mode: 0755]
apps/tosthreads/tinyld/Makefile [new file with mode: 0644]
apps/tosthreads/tinyld/SerialLoader/Makefile [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoader/README [new file with mode: 0644]
apps/tosthreads/tinyld/SerialLoader/SerialLoader.h [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoader/SerialLoaderAppC.nc [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoader/SerialLoaderP.nc [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoader/serialloader.py [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoader/tinyos.py [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoaderFlash/FlashVolumeManager.h [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoaderFlash/FlashVolumeManagerC.nc [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoaderFlash/FlashVolumeManagerP.nc [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoaderFlash/Makefile [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoaderFlash/README [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoaderFlash/SerialLoaderFlashAppC.nc [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoaderFlash/serialloader.py [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoaderFlash/tinyos.py [new file with mode: 0755]
apps/tosthreads/tinyld/SerialLoaderFlash/volumes-at45db.xml [new file with mode: 0644]
apps/tosthreads/tinyld/SerialLoaderFlash/volumes-stm25p.xml [new file with mode: 0755]
apps/tutorials/LowPowerSensing/Base/LowPowerSensingBaseAppC.nc
apps/tutorials/LowPowerSensing/Base/LowPowerSensingBaseC.nc
apps/tutorials/LowPowerSensing/Sampler/LowPowerSensingPeriodicSamplerAppC.nc
apps/tutorials/LowPowerSensing/Sampler/LowPowerSensingPeriodicSamplerC.nc
apps/tutorials/RssiDemo/RssiBase/RssiBaseAppC.nc
doc/html/deluge-t2-manual.html [deleted file]
doc/html/tep102.html
doc/html/tep109.html
doc/html/tep112.html
doc/html/tep115.html
doc/html/tep116.html
doc/html/tep118.html
doc/html/tep119.html
doc/html/tep121.html
doc/html/tep123.html
doc/html/tep124.html
doc/html/tep125.html
doc/html/tep131.html
doc/html/tep132.html
doc/html/tep133.html
doc/html/tep134.html
doc/html/tep135.html
doc/html/tep136.html [new file with mode: 0644]
doc/html/tep137.html [new file with mode: 0644]
doc/html/tep2.html
doc/html/tep4.html
doc/pdf/deluge-t2-manual.pdf [deleted file]
doc/stylesheets/deluge-t2-manual.css [deleted file]
doc/txt/tep109.txt
doc/txt/tep112.txt
doc/txt/tep119.txt
doc/txt/tep123.txt
doc/txt/tep124.txt
doc/txt/tep135.txt
doc/txt/tep136.txt [new file with mode: 0644]
doc/txt/tep137.txt [new file with mode: 0644]
doc/txt/tep3.txt
doc/txt/tep4.txt
licenses/INTEL-LICENSE.txt [new file with mode: 0644]
overall-todo.txt [deleted file]
release-notes.txt
support/make/Makerules
support/make/avr/avr-studio-debug.extra [new file with mode: 0644]
support/make/avr/avr.rules
support/make/avr/avrisp.extra
support/make/avr/avrispmkii.extra [new file with mode: 0644]
support/make/avr/mib510.extra
support/make/avr/xnp.extra [deleted file]
support/make/blip.extra [new file with mode: 0644]
support/make/clean.target
support/make/cthreads.extra
support/make/dynthreads.extra
support/make/epic.target [new file with mode: 0644]
support/make/epic/digi.extra [new file with mode: 0644]
support/make/epic/epic.rules [new file with mode: 0644]
support/make/epic/miniprog.extra [new file with mode: 0644]
support/make/iris.target
support/make/m16c62p/crt.S [new file with mode: 0755]
support/make/m16c62p/debug.extra [new file with mode: 0755]
support/make/m16c62p/debugopt.extra [new file with mode: 0755]
support/make/m16c62p/install.extra [new file with mode: 0755]
support/make/m16c62p/m16c.x [new file with mode: 0755]
support/make/m16c62p/m16c62p.rules [new file with mode: 0755]
support/make/m16c62p/reinstall.extra [new file with mode: 0644]
support/make/m16c62p/sm16cf.extra [new file with mode: 0755]
support/make/msp/msp.rules
support/make/mulle.target [new file with mode: 0755]
support/make/null/null.rules
support/make/safe.extra
support/make/shimmer.target
support/make/shimmer2.target [new file with mode: 0644]
support/make/sim.extra
support/make/stack-check.extra [new file with mode: 0644]
support/make/threads.extra
support/make/tosboot.extra
support/sdk/c/blip/Makefile.am [new file with mode: 0644]
support/sdk/c/blip/bootstrap.sh [new file with mode: 0755]
support/sdk/c/blip/configure.ac [new file with mode: 0644]
support/sdk/c/blip/driver/Makefile.am [new file with mode: 0644]
support/sdk/c/blip/driver/config.c [new file with mode: 0644]
support/sdk/c/blip/driver/config.h [new file with mode: 0644]
support/sdk/c/blip/driver/hashtable.c [new file with mode: 0644]
support/sdk/c/blip/driver/hashtable.h [new file with mode: 0644]
support/sdk/c/blip/driver/hashtable_private.h [new file with mode: 0644]
support/sdk/c/blip/driver/logging.c [new file with mode: 0644]
support/sdk/c/blip/driver/logging.h [new file with mode: 0644]
support/sdk/c/blip/driver/mcast.c [new file with mode: 0644]
support/sdk/c/blip/driver/mcast.h [new file with mode: 0644]
support/sdk/c/blip/driver/netlink.c [new file with mode: 0644]
support/sdk/c/blip/driver/netlink.h [new file with mode: 0644]
support/sdk/c/blip/driver/nwstate.c [new file with mode: 0644]
support/sdk/c/blip/driver/nwstate.h [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/CHANGES [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/COPYRIGHT [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/INTRO.html [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/Makefile.am [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/README [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/TODO [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/VERSION [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/config.guess [new file with mode: 0755]
support/sdk/c/blip/driver/radvd-1.0/config.h.in [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/config.sub [new file with mode: 0755]
support/sdk/c/blip/driver/radvd-1.0/configure.in [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/copyright.blurb [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/defaults.h [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/depcomp [new file with mode: 0755]
support/sdk/c/blip/driver/radvd-1.0/device-bsd44.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/device-common.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/device-linux.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/gram.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/gram.h [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/gram.y [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/includes.h [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/install-sh [new file with mode: 0755]
support/sdk/c/blip/driver/radvd-1.0/interface.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/log.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/missing [new file with mode: 0755]
support/sdk/c/blip/driver/radvd-1.0/mkinstalldirs [new file with mode: 0755]
support/sdk/c/blip/driver/radvd-1.0/pathnames.h [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/process.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/radvd.8.man [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/radvd.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/radvd.conf.5.man [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/radvd.conf.example [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/radvd.h [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/radvdump.8.man [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/radvdump.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/recv.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/scanner.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/scanner.l [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/send.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/socket.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/stamp-h [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/stamp-h.in [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/timer.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-1.0/util.c [new file with mode: 0644]
support/sdk/c/blip/driver/radvd-wrapper.c [new file with mode: 0644]
support/sdk/c/blip/driver/routing.c [new file with mode: 0644]
support/sdk/c/blip/driver/routing.h [new file with mode: 0644]
support/sdk/c/blip/driver/serial_tun.c [new file with mode: 0644]
support/sdk/c/blip/driver/tun_dev.c [new file with mode: 0644]
support/sdk/c/blip/driver/tun_dev.h [new file with mode: 0644]
support/sdk/c/blip/driver/tunnel.c [new file with mode: 0644]
support/sdk/c/blip/driver/vty/Makefile [new file with mode: 0644]
support/sdk/c/blip/driver/vty/test_srv.c [new file with mode: 0644]
support/sdk/c/blip/driver/vty/vty-util.c [new file with mode: 0644]
support/sdk/c/blip/driver/vty/vty.c [new file with mode: 0644]
support/sdk/c/blip/driver/vty/vty.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/6lowpan.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/IEEE154Packet.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/Makefile.am [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/TrackFlows.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/blip-platform.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/devconf.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/in_cksum.c [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/in_cksum.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/ip.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/ip_malloc.c [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/ip_malloc.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/lib6lowpan.c [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/lib6lowpan.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/lib6lowpanFrag.c [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/lib6lowpanIP.c [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/nwbyte.h [new file with mode: 0644]
support/sdk/c/blip/lib6lowpan/printpacket.c [new file with mode: 0644]
support/sdk/c/blip/libtcp/Makefile [new file with mode: 0644]
support/sdk/c/blip/libtcp/circ.c [new file with mode: 0644]
support/sdk/c/blip/libtcp/circ.h [new file with mode: 0644]
support/sdk/c/blip/libtcp/tcplib.c [new file with mode: 0644]
support/sdk/c/blip/libtcp/tcplib.h [new file with mode: 0644]
support/sdk/c/blip/libtcp/test_circ.c [new file with mode: 0644]
support/sdk/c/blip/libtcp/test_server.c [new file with mode: 0644]
support/sdk/c/blip/serial_tun.conf [new file with mode: 0644]
support/sdk/c/sf/Makefile.am
support/sdk/c/sf/message.c
support/sdk/c/sf/message.h
support/sdk/c/sf/serialsource.c
support/sdk/c/sf/serialsource.h
support/sdk/c/sf/sf.c
support/sdk/c/sf/sfsource.c
support/sdk/cpp/sf/serialcomm.cpp
support/sdk/cpp/sf/serialcomm.h
support/sdk/cpp/sf/sfcontrol.cpp
support/sdk/cpp/sf/sfpacket.cpp
support/sdk/cpp/sf/tcpcomm.cpp
support/sdk/java/net/tinyos/tools/.cvsignore [new file with mode: 0644]
support/sdk/python/tos.py
tinyos.sh
tools/configure.ac
tools/platforms/msp430/cppbsl/Makefile.in
tools/platforms/msp430/cppbsl/aclocal.m4
tools/platforms/msp430/cppbsl/config.h.in
tools/platforms/msp430/cppbsl/config/Makefile.in
tools/platforms/msp430/cppbsl/configure
tools/platforms/msp430/cppbsl/configure.in
tools/platforms/msp430/cppbsl/src/Makefile.in
tools/platforms/msp430/cppbsl/src/Serial.cc
tools/platforms/msp430/pybsl/serial/__init__.py
tools/platforms/msp430/pybsl/serial/serialjava.py
tools/platforms/msp430/pybsl/serial/serialposix.py
tools/platforms/msp430/pybsl/serial/serialwin32.py
tools/release/build-rpms
tools/release/deputy.files [new file with mode: 0755]
tools/release/deputy.spec [new file with mode: 0644]
tools/release/external-tools/avarice.spec [new file with mode: 0755]
tools/release/external-tools/avr-gcc.spec [new file with mode: 0755]
tools/release/external-tools/avr-insight.spec [new file with mode: 0755]
tools/release/external-tools/avr-libc.spec [new file with mode: 0644]
tools/release/external-tools/binutils.spec [new file with mode: 0755]
tools/release/external-tools/msp430-libc.spec [new file with mode: 0755]
tools/release/external-tools/xscale-elf.gcc.spec [new file with mode: 0755]
tools/release/extractor
tools/release/nesc.spec [new file with mode: 0644]
tools/release/tinyos-tools.files
tools/release/tinyos-tools.spec
tools/release/tinyos.files
tools/release/tinyos.filter [deleted file]
tools/release/tinyos.spec
tools/tinyos/java/env/Makefile.am
tools/tinyos/java/serial/Makefile.am
tools/tinyos/misc/Makefile.am
tools/tinyos/misc/tos-build-deluge-image
tools/tinyos/misc/tos-deluge
tools/tinyos/misc/tos-dump.py [new file with mode: 0644]
tools/tinyos/misc/tos-nwprog [new file with mode: 0755]
tools/tinyos/misc/tos-storage-at45db.1
tools/tinyos/misc/tos-storage-at45db.in
tools/tinyos/misc/tos-storage-pxa27xp30.in
tools/tinyos/misc/tos-storage-stm25p.in
tools/tinyos/ncc/nesdoc-py/archive.py
tools/tinyos/ncc/nesdoc.1
tools/tinyos/ncc/nesdoc.in
tools/tinyos/safe/.cvsignore [new file with mode: 0644]
tools/tinyos/safe/Makefile.am
tools/tinyos/safe/tos-ramsize [new file with mode: 0755]
tools/tinyos/safe/tos-ramsize.1 [new file with mode: 0755]
tools/tinyos/tosthreads/Makefile.am
tools/tinyos/tosthreads/tosthreads-gen-dynamic-app [new file with mode: 0755]
tools/tinyos/tosthreads/tosthreads-gen-dynamic-app.1 [new file with mode: 0755]
tools/tinyos/tosthreads/tosthreads_standard_api.py
tools/tinyos/tosthreads/tosthreads_tenet_api.py [deleted file]
tos.mk
tos/chips/atm128/Atm128Uart.h
tos/chips/atm128/atm128hardware.h
tos/chips/atm128/i2c/Atm128I2C.h
tos/chips/atm128/i2c/Atm128I2CMasterPacketP.nc
tos/chips/atm128/spi/Atm128SpiC.nc
tos/chips/atm128/spi/Atm128SpiP.nc
tos/chips/atm1281/McuSleepC.nc
tos/chips/atm1281/atm128hardware.h
tos/chips/bq2403x/BQ2403X.h
tos/chips/bq2403x/BQ2403X.nc
tos/chips/bq2403x/BQ2403XC.nc
tos/chips/bq2403x/BQ2403XP.nc
tos/chips/cc1000/CC1000ActiveMessageC.nc
tos/chips/cc1000/CC1000CsmaP.nc
tos/chips/cc1000/CC1000CsmaRadioC.nc
tos/chips/cc1000/CC1000Msg.h
tos/chips/cc1000/CC1000SendReceiveP.nc
tos/chips/cc1000/CC1000TimeSyncMessage.h [new file with mode: 0644]
tos/chips/cc1000/CC1000TimeSyncMessageC.nc [new file with mode: 0644]
tos/chips/cc1000/CC1000TimeSyncMessageP.nc [new file with mode: 0644]
tos/chips/cc1000/LowPowerListening.nc [deleted file]
tos/chips/cc1000/PacketTimeSyncOffset.nc [new file with mode: 0644]
tos/chips/cc2420/CC2420.h
tos/chips/cc2420/CC2420ActiveMessageC.nc
tos/chips/cc2420/CC2420ActiveMessageP.nc
tos/chips/cc2420/CC2420Ieee154MessageC.nc [new file with mode: 0644]
tos/chips/cc2420/CC2420Ieee154MessageP.nc [new file with mode: 0644]
tos/chips/cc2420/CC2420RadioC.nc [new file with mode: 0644]
tos/chips/cc2420/CC2420TimeSyncMessage.h
tos/chips/cc2420/CC2420TimeSyncMessageC.nc
tos/chips/cc2420/CC2420TimeSyncMessageP.nc
tos/chips/cc2420/control/CC2420ControlP.nc
tos/chips/cc2420/csma/CC2420CsmaP.nc
tos/chips/cc2420/interfaces/CC2420Keys.nc [new file with mode: 0644]
tos/chips/cc2420/interfaces/CC2420Packet.nc
tos/chips/cc2420/interfaces/CC2420SecurityMode.nc [new file with mode: 0644]
tos/chips/cc2420/link/PacketLinkC.nc
tos/chips/cc2420/link/PacketLinkDummyC.nc
tos/chips/cc2420/link/PacketLinkP.nc
tos/chips/cc2420/lowpan/CC2420TinyosNetworkC.nc
tos/chips/cc2420/lowpan/CC2420TinyosNetworkP.nc
tos/chips/cc2420/lpl/DefaultLpl.h
tos/chips/cc2420/lpl/DefaultLplC.nc
tos/chips/cc2420/lpl/DefaultLplP.nc
tos/chips/cc2420/lpl/DummyLplP.nc
tos/chips/cc2420/lpl/PowerCycleC.nc
tos/chips/cc2420/lpl/PowerCycleP.nc
tos/chips/cc2420/packet/CC2420PacketC.nc
tos/chips/cc2420/packet/CC2420PacketP.nc
tos/chips/cc2420/receive/CC2420ReceiveC.nc
tos/chips/cc2420/receive/CC2420ReceiveP.nc
tos/chips/cc2420/security/CC2420KeysC.nc [new file with mode: 0644]
tos/chips/cc2420/security/CC2420KeysP.nc [new file with mode: 0644]
tos/chips/cc2420/security/SecAMSenderC.nc [new file with mode: 0644]
tos/chips/cc2420/security/SecAMSenderP.nc [new file with mode: 0644]
tos/chips/cc2420/spi/CC2420SpiC.nc
tos/chips/cc2420/transmit/CC2420TransmitC.nc
tos/chips/cc2420/transmit/CC2420TransmitP.nc
tos/chips/cc2420_tkn154/CC2420AsyncSplitControl.nc
tos/chips/cc2420_tkn154/CC2420ControlP.nc
tos/chips/cc2420_tkn154/CC2420ControlTransmitC.nc
tos/chips/cc2420_tkn154/CC2420Power.nc
tos/chips/cc2420_tkn154/CC2420Receive.nc
tos/chips/cc2420_tkn154/CC2420ReceiveC.nc
tos/chips/cc2420_tkn154/CC2420ReceiveP.nc
tos/chips/cc2420_tkn154/CC2420Rx.nc
tos/chips/cc2420_tkn154/CC2420TKN154C.nc
tos/chips/cc2420_tkn154/CC2420TKN154P.nc
tos/chips/cc2420_tkn154/CC2420TransmitP.nc
tos/chips/cc2420_tkn154/CC2420Tx.nc
tos/chips/cc2420_tkn154/CaptureTime.nc
tos/chips/cc2420_tkn154/ReferenceTime.nc
tos/chips/cc2420_tkn154/ReliableWait.nc
tos/chips/cc2420_tkn154/TKN154_PHY.h
tos/chips/cc2420_tkn154/Timestamp.nc
tos/chips/cp210x/CP210X.nc
tos/chips/cp210x/CP210XC.nc
tos/chips/cp210x/CP210XP.nc
tos/chips/ds2401/CachedIeeeEui64P.nc [new file with mode: 0644]
tos/chips/ds2401/Ds2401.h [new file with mode: 0644]
tos/chips/ds2401/Ds2401ToIeeeEui64C.nc [new file with mode: 0644]
tos/chips/ds2401/HplDs2401.nc [new file with mode: 0644]
tos/chips/ds2401/HplDs2401C.nc [new file with mode: 0644]
tos/chips/ds2401/OneWireMaster.nc [new file with mode: 0644]
tos/chips/ds2401/OneWireMasterC.nc [new file with mode: 0644]
tos/chips/ds2782/DS2782.h [new file with mode: 0644]
tos/chips/ds2782/HplDS2782.nc [new file with mode: 0644]
tos/chips/ds2782/HplDS2782LogicP.nc [new file with mode: 0644]
tos/chips/m16c62p/McuSleepC.nc [new file with mode: 0755]
tos/chips/m16c62p/McuSleepP.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/Adc.h [new file with mode: 0755]
tos/chips/m16c62p/adc/AdcP.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/AdcReadClientC.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/AdcReadNowClientC.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/AdcReadStreamClientC.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/AdcStreamP.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/HplM16c62pAdc.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/HplM16c62pAdcC.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/HplM16c62pAdcP.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/M16c62pAdc.h [new file with mode: 0755]
tos/chips/m16c62p/adc/M16c62pAdcC.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/M16c62pAdcConfig.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/M16c62pAdcMultiple.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/M16c62pAdcP.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/M16c62pAdcPlatform.nc [new file with mode: 0644]
tos/chips/m16c62p/adc/M16c62pAdcSingle.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/WireAdcP.nc [new file with mode: 0755]
tos/chips/m16c62p/adc/WireAdcStreamP.nc [new file with mode: 0755]
tos/chips/m16c62p/bits.h [new file with mode: 0755]
tos/chips/m16c62p/control/M16c62pControl.h [new file with mode: 0644]
tos/chips/m16c62p/control/M16c62pControl.nc [new file with mode: 0755]
tos/chips/m16c62p/control/M16c62pControlC.nc [new file with mode: 0755]
tos/chips/m16c62p/control/M16c62pControlP.nc [new file with mode: 0755]
tos/chips/m16c62p/control/M16c62pControlPlatform.nc [new file with mode: 0644]
tos/chips/m16c62p/control/StopModeControl.nc [new file with mode: 0644]
tos/chips/m16c62p/control/StopModeControlC.nc [new file with mode: 0644]
tos/chips/m16c62p/control/SystemClockControl.nc [new file with mode: 0644]
tos/chips/m16c62p/control/SystemClockControlC.nc [new file with mode: 0644]
tos/chips/m16c62p/dac/HplM16c62pDac.nc [new file with mode: 0755]
tos/chips/m16c62p/dac/HplM16c62pDacC.nc [new file with mode: 0755]
tos/chips/m16c62p/dac/HplM16c62pDacP.nc [new file with mode: 0755]
tos/chips/m16c62p/interrupts.h [new file with mode: 0755]
tos/chips/m16c62p/iom16c62p.h [new file with mode: 0755]
tos/chips/m16c62p/m16c62phardware.h [new file with mode: 0755]
tos/chips/m16c62p/pins/HplM16c62pGeneralIOC.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/HplM16c62pGeneralIOPinP.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/HplM16c62pGeneralIOPinPRC2P.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/HplM16c62pGeneralIOPortP.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/HplM16c62pInterrupt.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/HplM16c62pInterruptC.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/HplM16c62pInterruptPinP.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/HplM16c62pInterruptSig.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/HplM16c62pInterruptSigP.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/M16c62pInterruptC.nc [new file with mode: 0755]
tos/chips/m16c62p/pins/M16c62pPin.h [new file with mode: 0644]
tos/chips/m16c62p/printf/elib.c [new file with mode: 0644]
tos/chips/m16c62p/printf/m16c62p_printf.h [new file with mode: 0644]
tos/chips/m16c62p/timer/HplM16c62pTimer.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/HplM16c62pTimerACtrl.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/HplM16c62pTimerACtrlP.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/HplM16c62pTimerBCtrl.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/HplM16c62pTimerBCtrlP.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/HplM16c62pTimerC.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/HplM16c62pTimerInterrupt.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/HplM16c62pTimerInterruptP.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/HplM16c62pTimerP.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/M16c62pAlarm16C.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/M16c62pAlarm32C.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/M16c62pCounter16C.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/M16c62pCounter32C.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/M16c62pTimer.h [new file with mode: 0755]
tos/chips/m16c62p/timer/M16c62pTimerAInitC.nc [new file with mode: 0755]
tos/chips/m16c62p/timer/M16c62pTimerBInitC.nc [new file with mode: 0755]
tos/chips/m16c62p/uart/HplM16c62pUart.nc [new file with mode: 0755]
tos/chips/m16c62p/uart/HplM16c62pUartC.nc [new file with mode: 0755]
tos/chips/m16c62p/uart/HplM16c62pUartInterrupt.nc [new file with mode: 0755]
tos/chips/m16c62p/uart/HplM16c62pUartInterruptP.nc [new file with mode: 0755]
tos/chips/m16c62p/uart/HplM16c62pUartP.nc [new file with mode: 0755]
tos/chips/m16c62p/uart/M16c62pUart.h [new file with mode: 0644]
tos/chips/m16c62p/uart/M16c62pUartC.nc [new file with mode: 0755]
tos/chips/m16c62p/uart/M16c62pUartP.nc [new file with mode: 0755]
tos/chips/mma7261qt/HplMMA7261QT.h [new file with mode: 0644]
tos/chips/mma7261qt/HplMMA7261QTControl.nc [new file with mode: 0644]
tos/chips/mma7261qt/HplMMA7261QTControlC.nc [new file with mode: 0644]
tos/chips/mma7261qt/HplMMA7261QTControlP.nc [new file with mode: 0644]
tos/chips/mma7261qt/HplMMA7261QTReaderC.nc [new file with mode: 0644]
tos/chips/msp430/McuSleepC.nc
tos/chips/msp430/adc12/AdcStreamP.nc
tos/chips/msp430/adc12/HplAdc12P.nc
tos/chips/msp430/adc12/Msp430Adc12ImplP.nc
tos/chips/msp430/adc12/Msp430Adc12MultiChannel.nc
tos/chips/msp430/adc12/Msp430RefVoltGeneratorP.nc
tos/chips/msp430/clock2/Msp430ClockP.nc
tos/chips/msp430/msp430hardware.h
tos/chips/msp430/pins/HplMsp430GeneralIORenP.nc
tos/chips/msp430/timer/Msp430ClockC.nc
tos/chips/msp430/timer/Msp430ClockP.nc
tos/chips/msp430/timer/Msp430TimerCapComP.nc
tos/chips/msp430/usart/msp430usart.h
tos/chips/msp430/usci/AsyncConfigure.nc
tos/chips/msp430/usci/HplMsp430UsciC.nc
tos/chips/msp430/usci/HplMsp430UsciInt.nc
tos/chips/msp430/usci/HplMsp430UsciInt0P.nc
tos/chips/msp430/usci/HplMsp430UsciInt1P.nc
tos/chips/msp430/usci/HplMsp430UsciReg.nc
tos/chips/msp430/usci/HplMsp430UsciRegP.nc
tos/chips/msp430/usci/Msp430SpiA0C.nc
tos/chips/msp430/usci/Msp430SpiB0C.nc
tos/chips/msp430/usci/Msp430SpiB1C.nc
tos/chips/msp430/usci/Msp430SpiP.nc
tos/chips/msp430/usci/Msp430UartA0C.nc
tos/chips/msp430/usci/Msp430UartA1C.nc
tos/chips/msp430/usci/Msp430UartP.nc
tos/chips/msp430/usci/Msp430Usci.h
tos/chips/msp430/usci/Msp430UsciA0C.nc
tos/chips/msp430/usci/Msp430UsciA1C.nc
tos/chips/msp430/usci/Msp430UsciB0C.nc
tos/chips/msp430/usci/Msp430UsciB1C.nc
tos/chips/msp430/usci/Msp430UsciIntDispatchP.nc
tos/chips/pxa27x/cif/HplPXA27XQuickCaptIntM.nc
tos/chips/pxa27x/cif/dmaArray.h
tos/chips/pxa27x/i2c/HplPXA27xI2CP.nc
tos/chips/pxa27x/ssp/HplPXA27xSSP2C.nc
tos/chips/rf230/ActiveMessageConfig.nc [deleted file]
tos/chips/rf230/ActiveMessageLayerC.nc [deleted file]
tos/chips/rf230/CsmaConfig.nc [deleted file]
tos/chips/rf230/CsmaLayerC.nc [deleted file]
tos/chips/rf230/CsmaLayerP.nc [deleted file]
tos/chips/rf230/DummyConfig.nc [deleted file]
tos/chips/rf230/DummyLayerC.nc [deleted file]
tos/chips/rf230/DummyLayerP.nc [deleted file]
tos/chips/rf230/IEEE154NetworkLayerC.nc [deleted file]
tos/chips/rf230/IEEE154NetworkLayerP.nc [deleted file]
tos/chips/rf230/IEEE154Packet.h [deleted file]
tos/chips/rf230/IEEE154Packet.nc [deleted file]
tos/chips/rf230/IEEE154PacketC.nc [deleted file]
tos/chips/rf230/IEEE154PacketP.nc [deleted file]
tos/chips/rf230/LowPowerListeningLayerC.nc [deleted file]
tos/chips/rf230/LowPowerListeningLayerP.nc [deleted file]
tos/chips/rf230/MessageBufferLayerC.nc [deleted file]
tos/chips/rf230/MessageBufferLayerP.nc [deleted file]
tos/chips/rf230/Neighborhood.h [deleted file]
tos/chips/rf230/Neighborhood.nc [deleted file]
tos/chips/rf230/NeighborhoodC.nc [deleted file]
tos/chips/rf230/NeighborhoodFlag.nc [deleted file]
tos/chips/rf230/NeighborhoodFlagC.nc [deleted file]
tos/chips/rf230/NeighborhoodP.nc [deleted file]
tos/chips/rf230/PacketField.nc [deleted file]
tos/chips/rf230/RF230.h [deleted file]
tos/chips/rf230/RF230ActiveMessageC.nc [deleted file]
tos/chips/rf230/RF230ActiveMessageP.nc [deleted file]
tos/chips/rf230/RF230Config.nc [deleted file]
tos/chips/rf230/RF230LayerC.nc [deleted file]
tos/chips/rf230/RF230LayerP.nc [deleted file]
tos/chips/rf230/RF230Packet.h [deleted file]
tos/chips/rf230/RF230PacketC.nc [deleted file]
tos/chips/rf230/RF230PacketP.nc [deleted file]
tos/chips/rf230/RF230TimeSyncMessageC.nc [deleted file]
tos/chips/rf230/RF230TimeSyncMessageP.nc [deleted file]
tos/chips/rf230/RadioAlarm.nc [deleted file]
tos/chips/rf230/RadioAlarmC.nc [deleted file]
tos/chips/rf230/RadioAlarmP.nc [deleted file]
tos/chips/rf230/RadioAssert.h [deleted file]
tos/chips/rf230/RadioCCA.nc [deleted file]
tos/chips/rf230/RadioReceive.nc [deleted file]
tos/chips/rf230/RadioSend.nc [deleted file]
tos/chips/rf230/RadioState.nc [deleted file]
tos/chips/rf230/RandomCollisionConfig.nc [deleted file]
tos/chips/rf230/RandomCollisionLayerC.nc [deleted file]
tos/chips/rf230/RandomCollisionLayerP.nc [deleted file]
tos/chips/rf230/SlottedCollisionConfig.nc [deleted file]
tos/chips/rf230/SlottedCollisionLayerC.nc [deleted file]
tos/chips/rf230/SlottedCollisionLayerP.nc [deleted file]
tos/chips/rf230/SoftwareAckConfig.nc [deleted file]
tos/chips/rf230/SoftwareAckLayerC.nc [deleted file]
tos/chips/rf230/SoftwareAckLayerP.nc [deleted file]
tos/chips/rf230/Tasklet.h [deleted file]
tos/chips/rf230/Tasklet.nc [deleted file]
tos/chips/rf230/TaskletC.nc [deleted file]
tos/chips/rf230/TimeSyncMessage.h [deleted file]
tos/chips/rf230/TrafficMonitorConfig.nc [deleted file]
tos/chips/rf230/TrafficMonitorLayerC.nc [deleted file]
tos/chips/rf230/TrafficMonitorLayerP.nc [deleted file]
tos/chips/rf230/UniqueConfig.nc [deleted file]
tos/chips/rf230/UniqueLayerC.nc [deleted file]
tos/chips/rf230/UniqueLayerP.nc [deleted file]
tos/chips/rf2xx/README [new file with mode: 0644]
tos/chips/rf2xx/layers/ActiveMessageConfig.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/ActiveMessageLayer.h [new file with mode: 0644]
tos/chips/rf2xx/layers/ActiveMessageLayerC.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/ActiveMessageLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/AutoResourceAcquireLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/CsmaConfig.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/CsmaLayerC.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/CsmaLayerP.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/DummyConfig.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/DummyLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/Ieee154MessageLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/Ieee154PacketLayer.h [new file with mode: 0644]
tos/chips/rf2xx/layers/Ieee154PacketLayer.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/Ieee154PacketLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/Ieee154PacketLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/LowPowerListeningConfig.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/LowPowerListeningDummyC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/LowPowerListeningDummyP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/LowPowerListeningLayer.h [new file with mode: 0644]
tos/chips/rf2xx/layers/LowPowerListeningLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/LowPowerListeningLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/MessageBufferLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/MessageBufferLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/MetadataFlagsLayer.h [new file with mode: 0644]
tos/chips/rf2xx/layers/MetadataFlagsLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/PacketLinkLayer.h [new file with mode: 0644]
tos/chips/rf2xx/layers/PacketLinkLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/PacketLinkLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/RandomCollisionConfig.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/RandomCollisionLayerC.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/RandomCollisionLayerP.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/SlottedCollisionConfig.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/SlottedCollisionLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/SlottedCollisionLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/SoftwareAckConfig.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/SoftwareAckLayerC.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/SoftwareAckLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/TimeStampingLayer.h [new file with mode: 0644]
tos/chips/rf2xx/layers/TimeStampingLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/TimeStampingLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/TimeSyncMessageLayer.h [new file with mode: 0644]
tos/chips/rf2xx/layers/TimeSyncMessageLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/TimeSyncMessageLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/TinyosNetworkLayer.h [new file with mode: 0644]
tos/chips/rf2xx/layers/TinyosNetworkLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/TrafficMonitorConfig.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/TrafficMonitorLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/TrafficMonitorLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/layers/UniqueConfig.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/UniqueLayerC.nc [new file with mode: 0755]
tos/chips/rf2xx/layers/UniqueLayerP.nc [new file with mode: 0755]
tos/chips/rf2xx/rf212/README [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212ActiveMessageC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212DriverConfig.nc [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212DriverLayer.h [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212DriverLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212DriverLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212Ieee154MessageC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212Radio.h [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212RadioC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212RadioP.nc [new file with mode: 0644]
tos/chips/rf2xx/rf212/RF212TimeSyncMessageC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/README [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230ActiveMessageC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230DriverConfig.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230DriverHwAckC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230DriverHwAckP.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230DriverLayer.h [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230DriverLayerC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230DriverLayerP.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230Ieee154MessageC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230Radio.h [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230RadioC.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230RadioP.nc [new file with mode: 0644]
tos/chips/rf2xx/rf230/RF230TimeSyncMessageC.nc [new file with mode: 0644]
tos/chips/rf2xx/util/BareReceive.nc [new file with mode: 0644]
tos/chips/rf2xx/util/BareSend.nc [new file with mode: 0644]
tos/chips/rf2xx/util/MetadataFlagC.nc [new file with mode: 0644]
tos/chips/rf2xx/util/Neighborhood.h [new file with mode: 0755]
tos/chips/rf2xx/util/Neighborhood.nc [new file with mode: 0644]
tos/chips/rf2xx/util/NeighborhoodC.nc [new file with mode: 0755]
tos/chips/rf2xx/util/NeighborhoodFlag.nc [new file with mode: 0755]
tos/chips/rf2xx/util/NeighborhoodFlagC.nc [new file with mode: 0755]
tos/chips/rf2xx/util/NeighborhoodP.nc [new file with mode: 0755]
tos/chips/rf2xx/util/PacketField.nc [new file with mode: 0644]
tos/chips/rf2xx/util/PacketFlag.nc [new file with mode: 0644]
tos/chips/rf2xx/util/RadioAlarm.nc [new file with mode: 0755]
tos/chips/rf2xx/util/RadioAlarmC.nc [new file with mode: 0644]
tos/chips/rf2xx/util/RadioAlarmP.nc [new file with mode: 0644]
tos/chips/rf2xx/util/RadioAssert.h [new file with mode: 0644]
tos/chips/rf2xx/util/RadioCCA.nc [new file with mode: 0755]
tos/chips/rf2xx/util/RadioChannel.nc [new file with mode: 0644]
tos/chips/rf2xx/util/RadioPacket.nc [new file with mode: 0644]
tos/chips/rf2xx/util/RadioReceive.nc [new file with mode: 0755]
tos/chips/rf2xx/util/RadioSend.nc [new file with mode: 0755]
tos/chips/rf2xx/util/RadioState.nc [new file with mode: 0644]
tos/chips/rf2xx/util/Tasklet.h [new file with mode: 0644]
tos/chips/rf2xx/util/Tasklet.nc [new file with mode: 0755]
tos/chips/rf2xx/util/TaskletC.nc [new file with mode: 0755]
tos/chips/scp1000/Scp1000.h
tos/chips/scp1000/Scp1000C.nc
tos/chips/scp1000/Scp1000P.nc
tos/chips/sht11/SensirionBusyWaitC.nc
tos/chips/stm25p/Stm25pLogP.nc
tos/chips/tda5250/mac/CsmaMacC.nc
tos/chips/tda5250/mac/CsmaMacP.nc
tos/chips/tda5250/mac/RedMacP.nc
tos/chips/tda5250/mac/SpeckMacDP.nc
tos/chips/xe1205/XE1205SendReceiveP.nc
tos/chips/xe1205/phy/XE1205PhyP.nc
tos/interfaces/FastSpiByte.nc [new file with mode: 0644]
tos/interfaces/Ieee154Packet.nc [new file with mode: 0644]
tos/interfaces/Ieee154Send.nc [new file with mode: 0644]
tos/interfaces/LocalIeeeEui64.nc [new file with mode: 0644]
tos/interfaces/LowPowerListening.nc
tos/interfaces/ResourceQueue.nc
tos/interfaces/SystemLowPowerListening.nc [new file with mode: 0644]
tos/interfaces/UartControl.nc [new file with mode: 0644]
tos/lib/byte_radio/PacketSerializerP.nc
tos/lib/diagmsg/DiagMsgC.nc
tos/lib/diagmsg/DiagMsgM.nc [deleted file]
tos/lib/diagmsg/DiagMsgP.nc [new file with mode: 0644]
tos/lib/ftsp/TimeSync32kC.nc [changed mode: 0644->0755]
tos/lib/ftsp/TimeSyncC.nc
tos/lib/ftsp/TimeSyncMsg.h
tos/lib/ftsp/TimeSyncP.nc
tos/lib/mac/tkn154/AssociateP.nc
tos/lib/mac/tkn154/BeaconRequestRxP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/BeaconSynchronizeP.nc
tos/lib/mac/tkn154/BeaconTransmitP.nc
tos/lib/mac/tkn154/CapP.nc [deleted file]
tos/lib/mac/tkn154/CapQueueP.nc [deleted file]
tos/lib/mac/tkn154/CoordBroadcastP.nc
tos/lib/mac/tkn154/CoordRealignmentP.nc
tos/lib/mac/tkn154/DataP.nc
tos/lib/mac/tkn154/DebugC.nc [new file with mode: 0644]
tos/lib/mac/tkn154/DebugP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/DisassociateP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/DispatchQueueP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/DispatchSlottedCsmaP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/DispatchUnslottedCsmaP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/FrameDispatchImplP.nc [deleted file]
tos/lib/mac/tkn154/FrameDispatchP.nc [deleted file]
tos/lib/mac/tkn154/IndirectTxP.nc
tos/lib/mac/tkn154/PibP.nc
tos/lib/mac/tkn154/PollP.nc
tos/lib/mac/tkn154/PromiscuousModeP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/README.txt
tos/lib/mac/tkn154/RadioClientC.nc
tos/lib/mac/tkn154/RadioControlImplP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/RadioControlP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/RxEnableP.nc
tos/lib/mac/tkn154/ScanP.nc
tos/lib/mac/tkn154/SimpleRoundRobinTransferArbiterC.nc [deleted file]
tos/lib/mac/tkn154/SimpleTransferArbiterP.nc
tos/lib/mac/tkn154/TKN154.h
tos/lib/mac/tkn154/TKN154BeaconEnabledP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/TKN154NonBeaconEnabledP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/TKN154P.nc [deleted file]
tos/lib/mac/tkn154/TKN154_DEBUG.h [deleted file]
tos/lib/mac/tkn154/TKN154_MAC.h
tos/lib/mac/tkn154/TKN154_PIB.h
tos/lib/mac/tkn154/TransferClientP.nc [deleted file]
tos/lib/mac/tkn154/dummies/NoAssociateP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/dummies/NoBeaconSynchronizeP.nc
tos/lib/mac/tkn154/dummies/NoBeaconTransmitP.nc
tos/lib/mac/tkn154/dummies/NoCapP.nc [deleted file]
tos/lib/mac/tkn154/dummies/NoCapQueueP.nc [deleted file]
tos/lib/mac/tkn154/dummies/NoCoordBroadcastP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/dummies/NoCoordCfpP.nc
tos/lib/mac/tkn154/dummies/NoCoordRealignmentP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/dummies/NoDebugP.nc [deleted file]
tos/lib/mac/tkn154/dummies/NoDeviceCapQueueP.nc [deleted file]
tos/lib/mac/tkn154/dummies/NoDeviceCfpP.nc
tos/lib/mac/tkn154/dummies/NoDisassociateP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/dummies/NoDispatchQueueP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/dummies/NoDispatchSlottedCsmaP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/dummies/NoPromiscuousModeP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/dummies/NoRxEnableP.nc [new file with mode: 0644]
tos/lib/mac/tkn154/dummies/NoScanP.nc
tos/lib/mac/tkn154/interfaces/MCPS/MCPS_DATA.nc
tos/lib/mac/tkn154/interfaces/MCPS/MCPS_PURGE.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_ASSOCIATE.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_BEACON_NOTIFY.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_COMM_STATUS.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_DISASSOCIATE.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_GET.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_GTS.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_ORPHAN.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_POLL.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_RESET.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_RX_ENABLE.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_SCAN.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_SET.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_START.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_SYNC.nc
tos/lib/mac/tkn154/interfaces/MLME/MLME_SYNC_LOSS.nc
tos/lib/mac/tkn154/interfaces/private/EnergyDetection.nc
tos/lib/mac/tkn154/interfaces/private/FrameRx.nc
tos/lib/mac/tkn154/interfaces/private/FrameTx.nc
tos/lib/mac/tkn154/interfaces/private/FrameTxNow.nc
tos/lib/mac/tkn154/interfaces/private/Ieee802154Debug.nc [deleted file]
tos/lib/mac/tkn154/interfaces/private/RadioOff.nc
tos/lib/mac/tkn154/interfaces/private/RadioRx.nc
tos/lib/mac/tkn154/interfaces/private/RadioTx.nc
tos/lib/mac/tkn154/interfaces/private/ResourceTransfer.nc [deleted file]
tos/lib/mac/tkn154/interfaces/private/ResourceTransferConnector.nc [deleted file]
tos/lib/mac/tkn154/interfaces/private/ResourceTransferControl.nc [deleted file]
tos/lib/mac/tkn154/interfaces/private/ResourceTransferred.nc [deleted file]
tos/lib/mac/tkn154/interfaces/private/SlottedCsmaCa.nc [new file with mode: 0644]
tos/lib/mac/tkn154/interfaces/private/SuperframeStructure.nc [new file with mode: 0644]
tos/lib/mac/tkn154/interfaces/private/TransferableResource.nc [new file with mode: 0644]
tos/lib/mac/tkn154/interfaces/private/UnslottedCsmaCa.nc [new file with mode: 0644]
tos/lib/mac/tkn154/interfaces/public/IEEE154BeaconFrame.nc
tos/lib/mac/tkn154/interfaces/public/IEEE154Frame.nc
tos/lib/mac/tkn154/interfaces/public/IEEE154TxBeaconPayload.nc
tos/lib/net/4bitle/LinkEstimator.h
tos/lib/net/4bitle/LinkEstimatorP.nc
tos/lib/net/Deluge/BlockStorageManager/BlockStorageManagerC.nc
tos/lib/net/Deluge/BlockStorageManager/BlockStorageManagerP.nc
tos/lib/net/Deluge/Crc.nc [deleted file]
tos/lib/net/Deluge/CrcP.nc [deleted file]
tos/lib/net/Deluge/Deluge.h
tos/lib/net/Deluge/DelugeMetadataP.nc
tos/lib/net/Deluge/DelugeP.nc
tos/lib/net/Deluge/DelugePageTransfer.h
tos/lib/net/Deluge/FlashVolumeManager/FlashVolumeManagerP.nc
tos/lib/net/Deluge/ObjectTransferC.nc
tos/lib/net/Deluge/extra/NetProgC.nc
tos/lib/net/Deluge/extra/NetProgM.nc
tos/lib/net/Deluge/extra/epic/TOSBoot_platform.h [new file with mode: 0644]
tos/lib/net/Deluge/extra/iris/NetProgC.nc
tos/lib/net/Deluge/extra/m16c62p/HplM16c62pFlash.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/m16c62p/HplM16c62pFlashC.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/m16c62p/InternalFlashC.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/m16c62p/InternalFlashP.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/m16c62p/M16c62pFlash.h [new file with mode: 0644]
tos/lib/net/Deluge/extra/msp430/InternalFlashC.nc
tos/lib/net/Deluge/extra/mulle/NetProg_platform.h [new file with mode: 0644]
tos/lib/net/Deluge/extra/mulle/ReprogramGuardC.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/mulle/ReprogramGuardP.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/mulle/TOSBoot_platform.h [new file with mode: 0644]
tos/lib/net/Deluge/extra/telos/ReprogramGuardC.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/telos/ReprogramGuardP.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/telosb/InternalFlash.h [deleted file]
tos/lib/net/Deluge/extra/telosb/InternalFlash.nc [deleted file]
tos/lib/net/Deluge/extra/tinynode/NetProg_platform.h [new file with mode: 0644]
tos/lib/net/Deluge/extra/tinynode/README [new file with mode: 0644]
tos/lib/net/Deluge/extra/tinynode/ReprogramGuardC.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/tinynode/ReprogramGuardP.nc [new file with mode: 0644]
tos/lib/net/Deluge/extra/tinynode/TOSBoot_platform.h [new file with mode: 0644]
tos/lib/net/TrickleTimerImplP.nc
tos/lib/net/blip/ICMP.h [new file with mode: 0644]
tos/lib/net/blip/ICMPResponderC.nc [new file with mode: 0644]
tos/lib/net/blip/ICMPResponderP.nc [new file with mode: 0644]
tos/lib/net/blip/IPAddressC.nc [new file with mode: 0644]
tos/lib/net/blip/IPAddressP.nc [new file with mode: 0644]
tos/lib/net/blip/IPDispatch.h [new file with mode: 0644]
tos/lib/net/blip/IPDispatchC.nc [new file with mode: 0644]
tos/lib/net/blip/IPDispatchP.nc [new file with mode: 0644]
tos/lib/net/blip/IPExtensionP.nc [new file with mode: 0644]
tos/lib/net/blip/IPExtensionsP.nc [new file with mode: 0644]
tos/lib/net/blip/IPRoutingP.nc [new file with mode: 0644]
tos/lib/net/blip/PrintfUART.h [new file with mode: 0644]
tos/lib/net/blip/ReadLqiC.nc [new file with mode: 0644]
tos/lib/net/blip/ResourceSendP.nc [new file with mode: 0644]
tos/lib/net/blip/Statistics.h [new file with mode: 0644]
tos/lib/net/blip/TcpC.nc [new file with mode: 0644]
tos/lib/net/blip/TcpP.nc [new file with mode: 0644]
tos/lib/net/blip/TcpSocketC.nc [new file with mode: 0644]
tos/lib/net/blip/TrackFlowsC.nc [new file with mode: 0644]
tos/lib/net/blip/TrackFlowsP.nc [new file with mode: 0644]
tos/lib/net/blip/UdpC.nc [new file with mode: 0644]
tos/lib/net/blip/UdpP.nc [new file with mode: 0644]
tos/lib/net/blip/UdpSocketC.nc [new file with mode: 0644]
tos/lib/net/blip/doc/README [new file with mode: 0644]
tos/lib/net/blip/doc/README-IP [new file with mode: 0644]
tos/lib/net/blip/doc/README-MERAKI [new file with mode: 0644]
tos/lib/net/blip/doc/README-NWPROG [new file with mode: 0644]
tos/lib/net/blip/doc/README-SHELL [new file with mode: 0644]
tos/lib/net/blip/doc/README-SIM [new file with mode: 0644]
tos/lib/net/blip/doc/README-TCP [new file with mode: 0644]
tos/lib/net/blip/doc/README-UDP [new file with mode: 0644]
tos/lib/net/blip/interfaces/ICMP.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/ICMPPing.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/IP.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/IPAddress.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/IPExtensions.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/IPRouting.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/InternalIPExtension.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/ReadLqi.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/Statistics.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/TLVHeader.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/Tcp.nc [new file with mode: 0644]
tos/lib/net/blip/interfaces/UDP.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/BootImage.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/Deluge.h [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugePatch.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugePatchC.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugePatchClientC.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugePatchP.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugeReadIdent.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugeReadIdentC.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugeReadIdentClientC.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugeReadIdentP.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugeVerify.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugeVerifyC.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugeVerifyClientC.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/DelugeVerifyP.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/NWProgC.nc [new file with mode: 0644]
tos/lib/net/blip/nwprog/NWProgP.nc [new file with mode: 0644]
tos/lib/net/blip/platform/CC2420ReadLqiC.nc [new file with mode: 0644]
tos/lib/net/blip/platform/RF230ReadLqiC.nc [new file with mode: 0644]
tos/lib/net/blip/serial/SerialDevConf.h [new file with mode: 0644]
tos/lib/net/blip/serial/SerialDevConfC.nc [new file with mode: 0644]
tos/lib/net/blip/serial/SerialPacketInfoDevConfP.nc [new file with mode: 0644]
tos/lib/net/blip/shell/FlashShellC.nc [new file with mode: 0644]
tos/lib/net/blip/shell/FlashShellP.nc [new file with mode: 0644]
tos/lib/net/blip/shell/RegisterShellCommand.nc [new file with mode: 0644]
tos/lib/net/blip/shell/Shell.h [new file with mode: 0644]
tos/lib/net/blip/shell/ShellCommand.nc [new file with mode: 0644]
tos/lib/net/blip/shell/ShellCommandC.nc [new file with mode: 0644]
tos/lib/net/blip/shell/ShellCommandP.nc [new file with mode: 0644]
tos/lib/net/blip/shell/UDPShellC.nc [new file with mode: 0644]
tos/lib/net/blip/shell/UDPShellP.nc [new file with mode: 0644]
tos/lib/net/blip/table.c [new file with mode: 0644]
tos/lib/net/blip/table.h [new file with mode: 0644]
tos/lib/net/ctp/CompareBit.nc
tos/lib/net/ctp/Ctp.h
tos/lib/net/ctp/CtpForwardingEngine.h
tos/lib/net/ctp/CtpForwardingEngineP.nc
tos/lib/net/ctp/CtpInfo.nc
tos/lib/net/ctp/CtpP.nc
tos/lib/net/ctp/CtpRoutingEngineP.nc
tos/lib/net/ctp/CtpRoutingPacket.nc
tos/lib/net/dhv/AMDhvC.nc [new file with mode: 0755]
tos/lib/net/dhv/AMDhvP.nc [new file with mode: 0755]
tos/lib/net/dhv/Dhv.h [new file with mode: 0755]
tos/lib/net/dhv/DhvDataC.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvDataP.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvHSumC.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvHSumP.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvLogicC.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvLogicP.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvSummaryC.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvSummaryP.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvTrickleMilliC.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvTrickleMilliP.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvVBitC.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvVBitP.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvVectorC.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvVectorP.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvVersionC.nc [new file with mode: 0755]
tos/lib/net/dhv/DhvVersionP.nc [new file with mode: 0755]
tos/lib/net/dhv/DisseminationC.nc [new file with mode: 0755]
tos/lib/net/dhv/DisseminatorC.nc [new file with mode: 0755]
tos/lib/net/dhv/DisseminatorP.nc [new file with mode: 0755]
tos/lib/net/dhv/README [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvCache.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvDecision.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvEstimates.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvHelp.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvLogic.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvNeighbour.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvReceive.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvSend.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvStateLogic.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvTrickleTimer.nc [new file with mode: 0755]
tos/lib/net/dhv/interfaces/DhvVersion.nc [new file with mode: 0755]
tos/lib/net/dip/AMDipC.nc
tos/lib/net/dip/AMDipP.nc
tos/lib/net/dip/Dip.h
tos/lib/net/dip/DipLogicP.nc
tos/lib/net/dip/DipSummaryP.nc
tos/lib/net/dip/DipVersionP.nc
tos/lib/net/dip/README
tos/lib/net/le/LinkEstimatorP.nc
tos/lib/net/tymo/ForwardingEngineM.nc
tos/lib/net/tymo/LinkMonitor.nc
tos/lib/net/tymo/dymo/DymoTableM.nc
tos/lib/net/tymo/mh/MHPacketM.nc
tos/lib/net/zigbee/apps/AssociationExample/AssociationExample.nc [deleted file]
tos/lib/net/zigbee/apps/AssociationExample/AssociationExampleC.nc [new file with mode: 0644]
tos/lib/net/zigbee/apps/AssociationExample/AssociationExampleM.nc [deleted file]
tos/lib/net/zigbee/apps/AssociationExample/AssociationExampleP.nc [new file with mode: 0644]
tos/lib/net/zigbee/apps/AssociationExample/Makefile
tos/lib/net/zigbee/apps/DataSendExample/DataSendExample.nc [deleted file]
tos/lib/net/zigbee/apps/DataSendExample/DataSendExampleC.nc [new file with mode: 0644]
tos/lib/net/zigbee/apps/DataSendExample/DataSendExampleM.nc [deleted file]
tos/lib/net/zigbee/apps/DataSendExample/DataSendExampleP.nc [new file with mode: 0644]
tos/lib/net/zigbee/apps/DataSendExample/Makefile
tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExample.nc [deleted file]
tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExampleC.nc [new file with mode: 0644]
tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExampleM.nc [deleted file]
tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExampleP.nc [new file with mode: 0644]
tos/lib/net/zigbee/apps/GTSManagementExample/Makefile
tos/lib/net/zigbee/apps/SimpleRoutingExample/Makefile
tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExample.nc [deleted file]
tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExampleC.nc [new file with mode: 0644]
tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExampleM.nc [deleted file]
tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExampleP.nc [new file with mode: 0644]
tos/lib/net/zigbee/apps/Test_APL/Makefile
tos/lib/net/zigbee/apps/Test_APL/Test_APL.nc [deleted file]
tos/lib/net/zigbee/apps/Test_APL/Test_APLC.nc [new file with mode: 0644]
tos/lib/net/zigbee/apps/Test_APL/Test_APLM.nc [deleted file]
tos/lib/net/zigbee/apps/Test_APL/Test_APLP.nc [new file with mode: 0644]
tos/lib/net/zigbee/cc2420/CC2420Config.nc [new file with mode: 0644]
tos/lib/net/zigbee/cc2420/CC2420ReceiveP.nc
tos/lib/net/zigbee/ieee802154/includes/PrintfUART.h [deleted file]
tos/lib/net/zigbee/ieee802154/includes/printfUART.h [new file with mode: 0644]
tos/lib/net/zigbee/ieee802154/mac/Mac.nc [deleted file]
tos/lib/net/zigbee/ieee802154/mac/MacC.nc [new file with mode: 0644]
tos/lib/net/zigbee/ieee802154/mac/MacM.nc [deleted file]
tos/lib/net/zigbee/ieee802154/mac/MacP.nc [new file with mode: 0644]
tos/lib/net/zigbee/ieee802154/macTDBS/Mac.nc [deleted file]
tos/lib/net/zigbee/ieee802154/macTDBS/MacC.nc [new file with mode: 0644]
tos/lib/net/zigbee/ieee802154/macTDBS/MacM.nc [deleted file]
tos/lib/net/zigbee/ieee802154/macTDBS/MacP.nc [new file with mode: 0644]
tos/lib/net/zigbee/ieee802154/macTDBS/mac_enumerations.h
tos/lib/net/zigbee/ieee802154/nwk/Makefile
tos/lib/net/zigbee/ieee802154/nwk/NWK.nc [deleted file]
tos/lib/net/zigbee/ieee802154/nwk/NWKC.nc [new file with mode: 0644]
tos/lib/net/zigbee/ieee802154/nwk/NWKM.nc [deleted file]
tos/lib/net/zigbee/ieee802154/nwk/NWKP.nc [new file with mode: 0644]
tos/lib/net/zigbee/ieee802154/nwk/nwk_const.h
tos/lib/net/zigbee/ieee802154/phy/Phy.nc [deleted file]
tos/lib/net/zigbee/ieee802154/phy/PhyC.nc [new file with mode: 0644]
tos/lib/net/zigbee/ieee802154/phy/PhyM.nc [deleted file]
tos/lib/net/zigbee/ieee802154/phy/PhyP.nc [new file with mode: 0644]
tos/lib/net/zigbee/readme.txt
tos/lib/net/zigbee/wrapper/WrapperC.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/WrapperP.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/includes/frame_format.h [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/includes/mac_const.h [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/includes/mac_enumerations.h [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/includes/mac_func.h [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/includes/nwk_func.h [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/includes/phy_const.h [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/includes/phy_enumerations.h [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/includes/printfUART.h [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MCPS_DATA.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MCPS_PURGE.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_ASSOCIATE.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_BEACON_NOTIFY.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_DISASSOCIATE.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_GET.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_GTS.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_ORPHAN.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_POLL.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_RESET.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_RX_ENABLE.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SCAN.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SET.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_START.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SYNC.nc [new file with mode: 0644]
tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SYNC_LOSS.nc [new file with mode: 0644]
tos/lib/power/DeferredPowerManagerP.nc
tos/lib/printf/PrintfP.nc
tos/lib/printf/generic_printf.h [new file with mode: 0644]
tos/lib/printf/printf.h
tos/lib/safe/SafeFailureHandlerC.nc [new file with mode: 0644]
tos/lib/safe/SafeFailureHandlerP.nc [new file with mode: 0644]
tos/lib/safe/avr/fail.c [deleted file]
tos/lib/safe/include/deputy/checks.h
tos/lib/safe/msp430/fail.c [deleted file]
tos/lib/serial/SerialActiveMessageP.nc
tos/lib/serial/SerialDispatcherP.nc
tos/lib/timer/VirtualizeAlarmC.nc
tos/lib/tosboot/Makefile
tos/lib/tosboot/TOSBoot.h [deleted file]
tos/lib/tosboot/TOSBoot.nc [deleted file]
tos/lib/tosboot/TOSBootM.nc [deleted file]
tos/lib/tosboot/TosBoot.h [new file with mode: 0644]
tos/lib/tosboot/TosBootC.nc [new file with mode: 0644]
tos/lib/tosboot/TosBootP.nc [new file with mode: 0644]
tos/lib/tosboot/at45db/ExtFlashC.nc
tos/lib/tosboot/avr/InternalFlashC.nc
tos/lib/tosboot/avr/ProgFlashC.nc [new file with mode: 0644]
tos/lib/tosboot/avr/ProgFlashM.nc [deleted file]
tos/lib/tosboot/epic/ExtFlashC.nc [new file with mode: 0644]
tos/lib/tosboot/epic/ExtFlashP.nc [new file with mode: 0644]
tos/lib/tosboot/epic/hardware.h [new file with mode: 0644]
tos/lib/tosboot/iris/ProgFlashC.nc [new file with mode: 0644]
tos/lib/tosboot/iris/ProgFlashM.nc [deleted file]
tos/lib/tosboot/m16c62p/HardwareC.nc [new file with mode: 0644]
tos/lib/tosboot/m16c62p/ProgFlashC.nc [new file with mode: 0644]
tos/lib/tosboot/m16c62p/ProgFlashP.nc [new file with mode: 0644]
tos/lib/tosboot/micaz/TOSBoot_platform.h
tos/lib/tosboot/micaz/hardware.h
tos/lib/tosboot/msp430/HPLUSART0M.nc [deleted file]
tos/lib/tosboot/msp430/HPLUSARTControl.nc [deleted file]
tos/lib/tosboot/msp430/HplUsart0C.nc [new file with mode: 0644]
tos/lib/tosboot/msp430/HplUsartControl.nc [new file with mode: 0644]
tos/lib/tosboot/msp430/InternalFlashC.nc
tos/lib/tosboot/msp430/ProgFlashC.nc [new file with mode: 0644]
tos/lib/tosboot/msp430/ProgFlashM.nc [deleted file]
tos/lib/tosboot/msp430f1611/PluginC.nc [new file with mode: 0644]
tos/lib/tosboot/msp430f1611/PowerOffC.nc [new file with mode: 0644]
tos/lib/tosboot/msp430f1611/TOSBoot_platform.h [new file with mode: 0644]
tos/lib/tosboot/mulle/ExecC.nc [new file with mode: 0644]
tos/lib/tosboot/mulle/PluginC.nc [new file with mode: 0644]
tos/lib/tosboot/mulle/VoltageC.nc [new file with mode: 0644]
tos/lib/tosboot/mulle/hardware.h [new file with mode: 0644]
tos/lib/tosboot/mulle/m16chardware.h [new file with mode: 0644]
tos/lib/tosboot/stm25p/ExtFlashC.nc
tos/lib/tosboot/stm25p/ExtFlashM.nc [deleted file]
tos/lib/tosboot/stm25p/ExtFlashP.nc [new file with mode: 0644]
tos/lib/tosboot/telosb/InternalFlash.h [deleted file]
tos/lib/tosboot/telosb/InternalFlash.nc [deleted file]
tos/lib/tosboot/telosb/PluginC.nc [deleted file]
tos/lib/tosboot/telosb/PowerOffM.nc [deleted file]
tos/lib/tosboot/telosb/TOSBoot_platform.h [deleted file]
tos/lib/tosboot/tinynode/ExecC.nc [new file with mode: 0644]
tos/lib/tosboot/tinynode/ExtFlashC.nc [new file with mode: 0644]
tos/lib/tosboot/tinynode/PowerOffC.nc [new file with mode: 0644]
tos/lib/tosboot/tinynode/README [new file with mode: 0644]
tos/lib/tosboot/tinynode/TOSBoot_platform.h [new file with mode: 0644]
tos/lib/tosboot/tinynode/VoltageC.nc [new file with mode: 0644]
tos/lib/tosboot/tinynode/hardware.h [new file with mode: 0644]
tos/lib/tossim/CpmModelC.nc
tos/lib/tossim/GainRadioModel.nc
tos/lib/tossim/HilTimerMilliC.nc [deleted file]
tos/lib/tossim/TOSSIM.py
tos/lib/tossim/TossimPacketModelC.nc
tos/lib/tossim/tossim.c
tos/lib/tossim/tossim.i
tos/lib/tossim/tossim_wrap.cxx
tos/lib/tosthreads/chips/cc2420/CC2420ActiveMessageC.nc
tos/lib/tosthreads/chips/cc2420/CC2420ActiveMessageP.nc
tos/lib/tosthreads/chips/msp430/sensors/BlockingMsp430InternalTemperatureC.nc [new file with mode: 0644]
tos/lib/tosthreads/chips/msp430/sensors/BlockingMsp430InternalVoltageC.nc [new file with mode: 0644]
tos/lib/tosthreads/chips/rf230/ActiveMessageLayerC.nc
tos/lib/tosthreads/chips/rf230/ActiveMessageLayerP.nc [new file with mode: 0644]
tos/lib/tosthreads/chips/rf230/RF230ActiveMessageC.nc
tos/lib/tosthreads/chips/rf230/RF230RadioC.nc [new file with mode: 0644]
tos/lib/tosthreads/csystem/CAMRadioC.nc
tos/lib/tosthreads/csystem/CAMRadioP.nc
tos/lib/tosthreads/csystem/CAMSerialC.nc
tos/lib/tosthreads/csystem/CAMSerialP.nc
tos/lib/tosthreads/csystem/CBlockStorageP.nc
tos/lib/tosthreads/csystem/CConfigStorageC.nc [new file with mode: 0644]
tos/lib/tosthreads/csystem/CConfigStorageP.nc [new file with mode: 0644]
tos/lib/tosthreads/csystem/CLedsP.nc
tos/lib/tosthreads/csystem/CLinkedListP.nc
tos/lib/tosthreads/csystem/CLogStorageP.nc
tos/lib/tosthreads/csystem/CQueueC.nc
tos/lib/tosthreads/csystem/CRandomC.nc [new file with mode: 0644]
tos/lib/tosthreads/csystem/CRandomP.nc [new file with mode: 0644]
tos/lib/tosthreads/csystem/CThreadP.nc
tos/lib/tosthreads/csystem/CThreadSynchronizationP.nc
tos/lib/tosthreads/csystem/TosThreadApiC.nc
tos/lib/tosthreads/csystem/VolumeMapC.nc
tos/lib/tosthreads/csystem/VolumeMapP.nc
tos/lib/tosthreads/csystem/tosthread.h
tos/lib/tosthreads/csystem/tosthread_configstorage.h [new file with mode: 0644]
tos/lib/tosthreads/csystem/tosthread_random.h [new file with mode: 0644]
tos/lib/tosthreads/csystem/tosthread_tenet.h [deleted file]
tos/lib/tosthreads/interfaces/BlockingBlockWrite.nc [deleted file]
tos/lib/tosthreads/interfaces/BlockingConfig.nc [new file with mode: 0644]
tos/lib/tosthreads/interfaces/BlockingMount.nc [new file with mode: 0644]
tos/lib/tosthreads/interfaces/DynamicThread.nc
tos/lib/tosthreads/interfaces/Thread.nc
tos/lib/tosthreads/interfaces/ThreadInfo.nc
tos/lib/tosthreads/interfaces/ThreadScheduler.nc
tos/lib/tosthreads/lib/net/BlockingCollectionControlC.nc
tos/lib/tosthreads/lib/net/BlockingCollectionControlP.nc
tos/lib/tosthreads/lib/net/BlockingCollectionSenderImplP.nc [deleted file]
tos/lib/tosthreads/lib/net/BlockingCollectionSenderP.nc [deleted file]
tos/lib/tosthreads/lib/net/CCollectionId.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/net/CCollectionP.nc [deleted file]
tos/lib/tosthreads/lib/net/ctp/BlockingCollectionSenderImplP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/net/ctp/BlockingCollectionSenderP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/net/ctp/CCollectionC.nc
tos/lib/tosthreads/lib/net/ctp/CCollectionIdP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/net/ctp/CCollectionP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/net/ctp/ccollection.h [new file with mode: 0644]
tos/lib/tosthreads/lib/net/lqi/BlockingCollectionSenderC.nc
tos/lib/tosthreads/lib/net/lqi/BlockingCollectionSenderImplP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/net/lqi/BlockingCollectionSenderP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/net/lqi/CCollectionC.nc
tos/lib/tosthreads/lib/net/lqi/CCollectionIdP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/net/lqi/CCollectionP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/net/lqi/ccollection.h [new file with mode: 0644]
tos/lib/tosthreads/lib/net/tosthread_collection.h
tos/lib/tosthreads/lib/serial/SerialActiveMessageC.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/serial/SerialActiveMessageP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/tinyld/BigCrc.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/tinyld/BigCrcC.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/tinyld/BigCrcP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/tinyld/DynamicLoader.h [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/DynamicLoader.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/DynamicLoaderC.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/DynamicLoaderP.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/LoadSourceMapC.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/LoadSourceMapP.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/MemoryStorageC.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/MemoryStorageP.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/NullVolumeMapC.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/PMManager.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/tinyld/PMManagerC.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/tinyld/PMManagerP.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/tinyld/TosThreadApiC.nc [new file with mode: 0644]
tos/lib/tosthreads/lib/tinyld/UserButton.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/UserButtonC.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/UserButtonP.nc [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/slcs_types.h [new file with mode: 0755]
tos/lib/tosthreads/lib/tinyld/tosthread_slcs_types.h [new file with mode: 0755]
tos/lib/tosthreads/platforms/epic/ActiveMessageC.nc [new file with mode: 0644]
tos/lib/tosthreads/platforms/epic/TelosSerialP.nc [new file with mode: 0644]
tos/lib/tosthreads/platforms/iris/ActiveMessageC.nc
tos/lib/tosthreads/sensorboards/basicsb/CPhotoP.nc
tos/lib/tosthreads/sensorboards/basicsb/CTempP.nc
tos/lib/tosthreads/sensorboards/tmote_onboard/CHamamatsuS10871TsrC.nc
tos/lib/tosthreads/sensorboards/tmote_onboard/CHamamatsuS10871TsrP.nc
tos/lib/tosthreads/sensorboards/tmote_onboard/CHamamatsuS1087ParC.nc
tos/lib/tosthreads/sensorboards/tmote_onboard/CHamamatsuS1087ParP.nc
tos/lib/tosthreads/sensorboards/tmote_onboard/CSensirionSht11C.nc
tos/lib/tosthreads/sensorboards/tmote_onboard/CSensirionSht11P.nc
tos/lib/tosthreads/sensorboards/universal/CSineSensorP.nc
tos/lib/tosthreads/system/BlockingAMReceiverC.nc
tos/lib/tosthreads/system/BlockingAMReceiverImplP.nc
tos/lib/tosthreads/system/BlockingAMSenderC.nc
tos/lib/tosthreads/system/BlockingAMSenderImplP.nc
tos/lib/tosthreads/system/BlockingAMSnooperC.nc
tos/lib/tosthreads/system/BlockingActiveMessageC.nc
tos/lib/tosthreads/system/BlockingConfigStorageC.nc [new file with mode: 0644]
tos/lib/tosthreads/system/BlockingConfigStorageImplP.nc [new file with mode: 0644]
tos/lib/tosthreads/system/BlockingConfigStorageP.nc [new file with mode: 0644]
tos/lib/tosthreads/system/BlockingLogStorageImplP.nc
tos/lib/tosthreads/system/BlockingResourceC.nc
tos/lib/tosthreads/system/BlockingResourceP.nc
tos/lib/tosthreads/system/BlockingSendC.nc [new file with mode: 0644]
tos/lib/tosthreads/system/BlockingSendImplP.nc [new file with mode: 0644]
tos/lib/tosthreads/system/BlockingSendP.nc [new file with mode: 0644]
tos/lib/tosthreads/system/BlockingSerialAMReceiverC.nc
tos/lib/tosthreads/system/BlockingSerialAMSenderC.nc
tos/lib/tosthreads/system/BlockingSerialActiveMessageC.nc
tos/lib/tosthreads/system/BlockingStdControlImplP.nc
tos/lib/tosthreads/system/DynamicThreadP.nc
tos/lib/tosthreads/system/MainC.nc
tos/lib/tosthreads/system/StaticThreadP.nc
tos/lib/tosthreads/system/ThreadInfoP.nc
tos/lib/tosthreads/system/ThreadMapP.nc
tos/lib/tosthreads/system/ThreadSleepP.nc
tos/lib/tosthreads/system/TinyOSMainP.nc
tos/lib/tosthreads/system/TinyThreadSchedulerC.nc
tos/lib/tosthreads/system/TinyThreadSchedulerP.nc
tos/lib/tosthreads/system/TosMallocC.nc
tos/lib/tosthreads/types/thread.h
tos/platforms/btnode3/hardware.h
tos/platforms/epic/.platform [new file with mode: 0644]
tos/platforms/epic/DemoSensorC.nc [new file with mode: 0644]
tos/platforms/epic/DemoSensorNowC.nc [new file with mode: 0644]
tos/platforms/epic/DemoSensorStreamC.nc [new file with mode: 0644]
tos/platforms/epic/HplUserButtonC.nc [new file with mode: 0644]
tos/platforms/epic/Ieee154MessageC.nc [new file with mode: 0644]
tos/platforms/epic/MoteClockC.nc [new file with mode: 0644]
tos/platforms/epic/MoteClockP.nc [new file with mode: 0644]
tos/platforms/epic/MotePlatformC.nc [new file with mode: 0644]
tos/platforms/epic/PlatformC.nc [new file with mode: 0644]
tos/platforms/epic/PlatformLedsC.nc [new file with mode: 0644]
tos/platforms/epic/PlatformP.nc [new file with mode: 0644]
tos/platforms/epic/UserButton.h [new file with mode: 0644]
tos/platforms/epic/UserButtonC.nc [new file with mode: 0644]
tos/platforms/epic/UserButtonP.nc [new file with mode: 0644]
tos/platforms/epic/VoltageC.nc [new file with mode: 0644]
tos/platforms/epic/VoltageStreamC.nc [new file with mode: 0644]
tos/platforms/epic/chips/at45db/HplAt45dbC.nc [new file with mode: 0644]
tos/platforms/epic/chips/at45db/HplAt45dbP.nc [new file with mode: 0644]
tos/platforms/epic/chips/at45db/HplAt45db_chip.h [new file with mode: 0644]
tos/platforms/epic/chips/ds2411/CachedIeeeEui64C.nc [new file with mode: 0644]
tos/platforms/epic/chips/ds2411/LocalIeeeEui64C.nc [new file with mode: 0644]
tos/platforms/epic/chips/ds2411/PlatformIeeeEui64.h [new file with mode: 0644]
tos/platforms/epic/hardware.h [new file with mode: 0644]
tos/platforms/epic/platform.h [new file with mode: 0644]
tos/platforms/epic/platform_message.h [new file with mode: 0644]
tos/platforms/eyesIFX/RadioDataLinkC.nc
tos/platforms/eyesIFX/WhiteBitAccessorC.nc [new file with mode: 0644]
tos/platforms/eyesIFX/byte_radio/RssiFixedThresholdCMP.nc
tos/platforms/eyesIFX/eyesIFXv1/hardware.h
tos/platforms/eyesIFX/eyesIFXv2/hardware.h
tos/platforms/eyesIFX/net/lqi/CC2420ActiveMessageC.nc [new file with mode: 0644]
tos/platforms/eyesIFX/net/lqi/CC2420Packet.nc [new file with mode: 0644]
tos/platforms/intelmote2/.platform
tos/platforms/intelmote2/hardware.h
tos/platforms/iris/.platform
tos/platforms/iris/ActiveMessageC.nc
tos/platforms/iris/Ieee154MessageC.nc [new file with mode: 0644]
tos/platforms/iris/TimeSyncMessageC.nc
tos/platforms/iris/chips/ds2401/PlatformIeeeEui64.h [new file with mode: 0644]
tos/platforms/iris/chips/rf230/HplRF230.h [deleted file]
tos/platforms/iris/chips/rf230/HplRF230.nc [deleted file]
tos/platforms/iris/chips/rf230/HplRF230C.nc
tos/platforms/iris/chips/rf230/HplRF230P.nc
tos/platforms/iris/chips/rf230/RadioConfig.h [new file with mode: 0644]
tos/platforms/iris/platform_message.h
tos/platforms/mica/Counter32khz32C.nc
tos/platforms/mica2/ActiveMessageC.nc
tos/platforms/mica2/TimeSyncMessageC.nc [new file with mode: 0644]
tos/platforms/mica2/chips/ds2401/CachedIeeeEui64C.nc [new file with mode: 0644]
tos/platforms/mica2/chips/ds2401/LocalIeeeEui64C.nc [new file with mode: 0644]
tos/platforms/mica2/hardware.h
tos/platforms/mica2dot/hardware.h
tos/platforms/micaz/.platform
tos/platforms/micaz/ActiveMessageC.nc
tos/platforms/micaz/Ieee154MessageC.nc [new file with mode: 0644]
tos/platforms/micaz/TimeSyncMessageC.nc
tos/platforms/micaz/hardware.h
tos/platforms/micaz/mac/tkn154/Makefile.include [new file with mode: 0644]
tos/platforms/micaz/mac/tkn154/README.txt [new file with mode: 0644]
tos/platforms/micaz/mac/tkn154/TKN154TimingP.nc [new file with mode: 0644]
tos/platforms/micaz/mac/tkn154/TKN154_platform.h [new file with mode: 0644]
tos/platforms/micaz/mac/tkn154/platform_message.h [new file with mode: 0644]
tos/platforms/micaz/sim/.platform
tos/platforms/mulle/.platform [new file with mode: 0755]
tos/platforms/mulle/ActiveMessageC.nc [new file with mode: 0755]
tos/platforms/mulle/DemoSensorC.nc [new file with mode: 0755]
tos/platforms/mulle/DemoSensorNowC.nc [new file with mode: 0644]
tos/platforms/mulle/DemoSensorP.nc [new file with mode: 0644]
tos/platforms/mulle/DemoSensorStreamC.nc [new file with mode: 0644]
tos/platforms/mulle/Ieee154MessageC.nc [new file with mode: 0644]
tos/platforms/mulle/PlatformC.nc [new file with mode: 0755]
tos/platforms/mulle/PlatformLedsC.nc [new file with mode: 0755]
tos/platforms/mulle/PlatformP.nc [new file with mode: 0755]
tos/platforms/mulle/PlatformSerialC.nc [new file with mode: 0755]
tos/platforms/mulle/PlatformSerialP.nc [new file with mode: 0644]
tos/platforms/mulle/TimeSyncMessageC.nc [new file with mode: 0755]
tos/platforms/mulle/button/HplUserButtonC.nc [new file with mode: 0644]
tos/platforms/mulle/button/UserButton.h [new file with mode: 0644]
tos/platforms/mulle/button/UserButtonC.nc [new file with mode: 0644]
tos/platforms/mulle/button/UserButtonP.nc [new file with mode: 0644]
tos/platforms/mulle/chips/at45db/At45dbSpi.h [new file with mode: 0644]
tos/platforms/mulle/chips/at45db/HplAt45dbC.nc [new file with mode: 0644]
tos/platforms/mulle/chips/at45db/HplAt45dbP.nc [new file with mode: 0644]
tos/platforms/mulle/chips/at45db/HplAt45db_chip.h [new file with mode: 0644]
tos/platforms/mulle/chips/at45db/SoftSpiAt45dbC.nc [new file with mode: 0755]
tos/platforms/mulle/chips/at45db/SoftSpiAt45dbP.nc [new file with mode: 0755]
tos/platforms/mulle/chips/ds2782/DS2782InternalC.nc [new file with mode: 0644]
tos/platforms/mulle/chips/m16c62p/M16c62pAdcPlatformC.nc [new file with mode: 0644]
tos/platforms/mulle/chips/m16c62p/M16c62pAdcPlatformP.nc [new file with mode: 0644]
tos/platforms/mulle/chips/m16c62p/M16c62pControlPlatformC.nc [new file with mode: 0644]
tos/platforms/mulle/chips/mma7261qt/HplMMA7261QTC.nc [new file with mode: 0644]
tos/platforms/mulle/chips/mma7261qt/HplMMA7261QTP.nc [new file with mode: 0644]
tos/platforms/mulle/chips/rf230/HplRF230C.nc [new file with mode: 0755]
tos/platforms/mulle/chips/rf230/HplRF230P.nc [new file with mode: 0755]
tos/platforms/mulle/chips/rf230/Mulle_RF230Spi.h [new file with mode: 0755]
tos/platforms/mulle/chips/rf230/RF230SplitControlP.nc [new file with mode: 0644]
tos/platforms/mulle/chips/rf230/RadioConfig.h [new file with mode: 0644]
tos/platforms/mulle/chips/rf230/SoftSpiRF230C.nc [new file with mode: 0755]
tos/platforms/mulle/chips/rf230/SoftSpiRF230P.nc [new file with mode: 0755]
tos/platforms/mulle/chips/rv8564/RV8564.nc [new file with mode: 0755]
tos/platforms/mulle/chips/rv8564/RV8564C.nc [new file with mode: 0755]
tos/platforms/mulle/chips/rv8564/RV8564P.nc [new file with mode: 0755]
tos/platforms/mulle/chips/rv8564/rv8564.h [new file with mode: 0755]
tos/platforms/mulle/debug/m_printf.h [new file with mode: 0644]
tos/platforms/mulle/hardware.h [new file with mode: 0755]
tos/platforms/mulle/platform.h [new file with mode: 0755]
tos/platforms/mulle/platform_message.h [new file with mode: 0755]
tos/platforms/mulle/softwarei2c/MulleI2C.h [new file with mode: 0755]
tos/platforms/mulle/softwarei2c/SoftI2CBatteryMonitorRTCC.nc [new file with mode: 0755]
tos/platforms/mulle/softwarei2c/SoftI2CBatteryMonitorRTCP.nc [new file with mode: 0644]
tos/platforms/mulle/softwarei2c/SoftI2CBus.nc [new file with mode: 0755]
tos/platforms/mulle/softwarei2c/SoftI2CBusP.nc [new file with mode: 0755]
tos/platforms/mulle/softwarei2c/SoftI2CMasterImplP.nc [new file with mode: 0755]
tos/platforms/mulle/softwarei2c/SoftI2CMasterP.nc [new file with mode: 0755]
tos/platforms/mulle/softwarei2c/SoftI2CMasterPacketP.nc [new file with mode: 0755]
tos/platforms/mulle/softwarespi/SoftSpiBus.nc [new file with mode: 0755]
tos/platforms/mulle/softwarespi/SoftSpiBusP.nc [new file with mode: 0755]
tos/platforms/mulle/softwarespi/SoftSpiMasterImplP.nc [new file with mode: 0755]
tos/platforms/mulle/softwarespi/SoftSpiMasterP.nc [new file with mode: 0755]
tos/platforms/mulle/softwarespi/SoftSpiMasterPacketP.nc [new file with mode: 0755]
tos/platforms/mulle/system/LedsP.nc [new file with mode: 0755]
tos/platforms/mulle/timers/AlarmMicro16C.nc [new file with mode: 0755]
tos/platforms/mulle/timers/AlarmMicro32C.nc [new file with mode: 0755]
tos/platforms/mulle/timers/BusyWaitMicroC.nc [new file with mode: 0755]
tos/platforms/mulle/timers/CounterMicro16C.nc [new file with mode: 0755]
tos/platforms/mulle/timers/CounterMicro32C.nc [new file with mode: 0755]
tos/platforms/mulle/timers/HilTimerMilliC.nc [new file with mode: 0755]
tos/platforms/mulle/timers/LocalTimeMicroC.nc [new file with mode: 0755]
tos/platforms/mulle/timers/TimerConfig.h [new file with mode: 0755]
tos/platforms/mulle/timers/rf230/AlarmRF23016C.nc [new file with mode: 0644]
tos/platforms/mulle/timers/rf230/CounterRF23016C.nc [new file with mode: 0644]
tos/platforms/mulle/timers/stop/RV8564AlarmCounterMilli32C.nc [new file with mode: 0755]
tos/platforms/mulle/timers/stop/RV8564AlarmCounterMilli32P.nc [new file with mode: 0755]
tos/platforms/mulle/timers/wait/AlarmCounterMilli32C.nc [new file with mode: 0755]
tos/platforms/null/.platform
tos/platforms/null/hardware.h
tos/platforms/olimexp169/DemoSensorC.nc
tos/platforms/olimexp169/DemoSensorNowC.nc
tos/platforms/olimexp169/DemoSensorStreamC.nc
tos/platforms/olimexp169/HplUserButtonC.nc
tos/platforms/olimexp169/MotePlatformC.nc
tos/platforms/olimexp169/PlatformLedsC.nc
tos/platforms/olimexp169/PlatformSerialP.nc
tos/platforms/olimexp169/SwitchToggleC.nc
tos/platforms/olimexp169/UserButton.h
tos/platforms/olimexp169/UserButtonC.nc
tos/platforms/olimexp169/UserButtonP.nc
tos/platforms/shimmer/.platform
tos/platforms/shimmer/ActiveMessageC.nc
tos/platforms/shimmer/HplUserButtonC.nc [new file with mode: 0644]
tos/platforms/shimmer/Ieee154MessageC.nc [new file with mode: 0644]
tos/platforms/shimmer/MotePlatformC.nc
tos/platforms/shimmer/Msp430Timer32khzMapC.nc
tos/platforms/shimmer/PlatformLedsC.nc
tos/platforms/shimmer/SwitchToggleC.nc [new file with mode: 0644]
tos/platforms/shimmer/TimeSyncMessageC.nc
tos/platforms/shimmer/UserButton.h [new file with mode: 0644]
tos/platforms/shimmer/UserButtonC.nc [new file with mode: 0644]
tos/platforms/shimmer/UserButtonP.nc [new file with mode: 0644]
tos/platforms/shimmer/chips/bluetooth/Bluetooth.nc [new file with mode: 0644]
tos/platforms/shimmer/chips/bluetooth/RovingNetworks.h [new file with mode: 0644]
tos/platforms/shimmer/chips/bluetooth/RovingNetworksC.nc [new file with mode: 0644]
tos/platforms/shimmer/chips/bluetooth/RovingNetworksP.nc [new file with mode: 0644]
tos/platforms/shimmer/chips/bluetooth/bluetoothBaudrateConversion.pdf [new file with mode: 0644]
tos/platforms/shimmer/chips/msp430/msp430hardware.h [new file with mode: 0644]
tos/platforms/shimmer/chips/sd/SD.nc
tos/platforms/shimmer/chips/sd/SDC.nc
tos/platforms/shimmer/chips/sd/SDP.nc
tos/platforms/shimmer/hardware.h
tos/platforms/shimmer/shimmerMessage.h [new file with mode: 0644]
tos/platforms/shimmer2/.platform [new file with mode: 0644]
tos/platforms/shimmer2/ActiveMessageC.nc [new file with mode: 0644]
tos/platforms/shimmer2/HplUserButtonC.nc [new file with mode: 0644]
tos/platforms/shimmer2/Leds.nc [new file with mode: 0644]
tos/platforms/shimmer2/LedsC.nc [new file with mode: 0644]
tos/platforms/shimmer2/LedsP.nc [new file with mode: 0644]
tos/platforms/shimmer2/MoteClockC.nc [new file with mode: 0644]
tos/platforms/shimmer2/MotePlatformC.nc [new file with mode: 0644]
tos/platforms/shimmer2/Msp430Timer32khzMapC.nc [new file with mode: 0644]
tos/platforms/shimmer2/NoLedsC.nc [new file with mode: 0644]
tos/platforms/shimmer2/PlatformC.nc [new file with mode: 0644]
tos/platforms/shimmer2/PlatformLedsC.nc [new file with mode: 0644]
tos/platforms/shimmer2/PlatformP.nc [new file with mode: 0644]
tos/platforms/shimmer2/PlatformSerialC.nc [new file with mode: 0644]
tos/platforms/shimmer2/ShimmerSerialP.nc [new file with mode: 0644]
tos/platforms/shimmer2/chips/cc2420/HplCC2420AlarmC.nc [new file with mode: 0644]
tos/platforms/shimmer2/chips/cc2420/HplCC2420InterruptsC.nc [new file with mode: 0644]
tos/platforms/shimmer2/chips/cc2420/HplCC2420InterruptsP.nc [new file with mode: 0644]
tos/platforms/shimmer2/chips/cc2420/HplCC2420PinsC.nc [new file with mode: 0644]
tos/platforms/shimmer2/chips/cc2420/HplCC2420SpiC.nc [new file with mode: 0644]
tos/platforms/shimmer2/chips/tilt/HplTiltDetectorC.nc [new file with mode: 0644]
tos/platforms/shimmer2/chips/tilt/TiltDetectorC.nc [new file with mode: 0644]
tos/platforms/shimmer2/hardware.h [new file with mode: 0644]
tos/platforms/shimmer2/platform.h [new file with mode: 0644]
tos/platforms/shimmer2/platform_message.h [new file with mode: 0644]
tos/platforms/telosa/ActiveMessageC.nc
tos/platforms/telosa/Ieee154MessageC.nc [new file with mode: 0644]
tos/platforms/telosa/TimeSyncMessageC.nc
tos/platforms/telosa/chips/at45db/HplAt45dbC.nc
tos/platforms/telosa/chips/at45db/HplAt45dbP.nc
tos/platforms/telosa/hardware.h
tos/platforms/telosb/.platform
tos/platforms/telosb/hardware.h
tos/platforms/telosb/mac/tkn154/Ieee802154BeaconEnabledC.nc [new file with mode: 0644]
tos/platforms/telosb/mac/tkn154/Ieee802154MacC.nc [deleted file]
tos/platforms/telosb/mac/tkn154/Ieee802154NonBeaconEnabledC.nc [new file with mode: 0644]
tos/platforms/telosb/mac/tkn154/Makefile.include
tos/platforms/telosb/mac/tkn154/TKN154TimingP.nc
tos/platforms/telosb/mac/tkn154/TKN154_platform.h
tos/platforms/telosb/mac/tkn154/platform_message.h
tos/platforms/telosb/mac/tkn154/timer/Alarm32khz32VirtualizedP.nc
tos/platforms/telosb/mac/tkn154/timer/Alarm32khzTo62500hzTransformC.nc
tos/platforms/telosb/mac/tkn154/timer/Alarm62500hz32C.nc [new file with mode: 0644]
tos/platforms/telosb/mac/tkn154/timer/Alarm62500hz32P.nc [new file with mode: 0644]
tos/platforms/tinynode/hardware.h
tos/platforms/tmicore/DemoSensorC.nc
tos/platforms/tmicore/DemoSensorNowC.nc
tos/platforms/tmicore/DemoSensorStreamC.nc
tos/platforms/tmicore/HplUserButtonC.nc
tos/platforms/tmicore/MoteClockC.nc
tos/platforms/tmicore/MoteClockP.nc
tos/platforms/tmicore/MotePlatformC.nc
tos/platforms/tmicore/PlatformLedsC.nc
tos/platforms/tmicore/PlatformSerialC.nc
tos/platforms/tmicore/SwitchToggleC.nc
tos/platforms/tmicore/UserButton.h
tos/platforms/tmicore/UserButtonC.nc
tos/platforms/tmicore/UserButtonP.nc
tos/platforms/tmicore/chips/at25df/At25dfSpiConfigP.nc
tos/platforms/tmicore/chips/at25df/NoMsp430GpioC.nc
tos/platforms/tmicore/chips/bq2403x/BQ2403XPinsC.nc
tos/platforms/tmicore/chips/cp210x/CP210XPinsC.nc
tos/platforms/tmirws/MotePlatformC.nc
tos/platforms/tmirws/chips/scp1000/Scp1000PinsC.nc
tos/platforms/tmirws/chips/scp1000/Scp1000PinsP.nc
tos/platforms/tmirws/chips/scp1000/Scp1000SpiC.nc
tos/platforms/tmirws/chips/scp1000/Scp1000SpiConfigC.nc
tos/platforms/tmirws/chips/sht11/HalSensirionSht11C.nc
tos/platforms/tmirws/chips/sht11/HplSensirionSht11C.nc
tos/platforms/tmirws/chips/sht11/HplSensirionSht11P.nc
tos/platforms/tmirws/chips/sht11/Msp430OpenDrainC.nc
tos/platforms/tmirws/chips/sht11/Msp430OpenDrainP.nc
tos/platforms/tmirws/chips/sht11/OpenDrainC.nc
tos/platforms/tmirws/chips/sht11/OpenDrainP.nc
tos/system/AMSenderC.nc
tos/system/ArbiterP.nc
tos/system/BitVectorC.nc
tos/system/DirectAMSenderC.nc [new file with mode: 0644]
tos/system/FcfsResourceQueueC.nc
tos/system/LplAMSenderC.nc [new file with mode: 0644]
tos/system/LplAMSenderP.nc [new file with mode: 0644]
tos/system/MainC.nc
tos/system/PoolP.nc
tos/system/QueueC.nc
tos/system/SimpleArbiterP.nc
tos/system/SystemLowPowerListeningC.nc [new file with mode: 0644]
tos/system/SystemLowPowerListeningP.nc [new file with mode: 0644]
tos/types/Ieee154.h [new file with mode: 0644]
tos/types/IeeeEui64.h [new file with mode: 0644]
tos/types/Lpl.h [new file with mode: 0644]
tos/types/message.h

diff --git a/apps/6lowpancli/CliAppC.nc b/apps/6lowpancli/CliAppC.nc
deleted file mode 100644 (file)
index 5c6fd64..0000000
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (c) 2007 Matus Harvan
- * All rights reserved
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- *       copyright notice, this list of conditions and the following
- *       disclaimer in the documentation and/or other materials provided
- *       with the distribution.
- *     * The name of the author may not be used to endorse or promote
- *       products derived from this software without specific prior
- *       written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "printf.h"
-
-#if defined(ENABLE_MICAZ_TEMP_SENSOR) || defined(ENABLE_TELOSB_TEMP_SENSOR)
-#define ENABLE_TEMP_SENSOR
-#endif /* ENABLE_MICAZ_TEMP_SENSOR || ENABLE_TELOSB_TEMP_SENSOR */
-
-#if defined(ENABLE_MICAZ_LIGHT_SENSOR) || defined(ENABLE_TELOSB_LIGHT_SENSOR)
-#define ENABLE_LIGHT_SENSOR
-#endif /* ENABLE_MICAZ_LIGHT_SENSOR || ENABLE_TELOSB_LIGHT_SENSOR */
-
-enum {
-    AM_IP_MSG = 0x41,
-};
-
-configuration CliAppC {}
-implementation {
-    components CliC as App, LedsC, MainC;
-    components IPC;
-    
-    App.Boot -> MainC.Boot;
-    App.Leds -> LedsC;
-    App.IPControl -> IPC.IPControl;
-    App.IP -> IPC.IP;
-    App.UDPClient -> IPC.UDPClient[unique("UDPClient")];
-
-#ifdef ENABLE_SOUNDER
-    components SounderC;
-    App.Sounder -> SounderC;
-#endif /* ENABLE_SOUNDER */
-
-#ifdef ENABLE_MICAZ_TEMP_SENSOR
-    components new TempC(); // telosb temp/humidity sensor
-    App.TempSensorC -> TempC;
-#endif /* ENABLE_MICAZ_TEMP_SENSOR */
-
-#ifdef ENABLE_TELOSB_TEMP_SENSOR
-    components new SensirionSht11C(); // telosb temp/humidity sensor
-    App.TempSensorC -> SensirionSht11C.Temperature;
-#endif /* ENABLE_TELOSB_TEMP_SENSOR */
-
-#ifdef ENABLE_MICAZ_LIGHT_SENSOR
-    components new PhotoC();// telosb visible light sensor
-    App.LightSensorC -> PhotoC;
-#endif /* ENABLE_MICAZ_TEMP_SENSOR */
-
-#ifdef ENABLE_TELOSB_LIGHT_SENSOR
-    // total solar radiation sensor
-    //new HamamatsuS10871TsrC() as Sensor, // telosb (IR) light sensor
-    // photosynthetically-active radiation sensor
-    components new HamamatsuS1087ParC();// telosb visible light sensor
-    App.LightSensorC -> HamamatsuS1087ParC;
-#endif /* ENABLE_TELOSB_TEMP_SENSOR */
-}
-
-
-
diff --git a/apps/6lowpancli/CliC.nc b/apps/6lowpancli/CliC.nc
deleted file mode 100644 (file)
index 89225cd..0000000
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (c) 2007 Matus Harvan
- * All rights reserved
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- *       copyright notice, this list of conditions and the following
- *       disclaimer in the documentation and/or other materials provided
- *       with the distribution.
- *     * The name of the author may not be used to endorse or promote
- *       products derived from this software without specific prior
- *       written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "Timer.h"
-
-#define min(a,b) ( (a>b) ? b : a )
-#define max(a,b) ( (a>b) ? a : b )
-
-module CliC {
-  uses {
-    interface Leds;
-    interface Boot;
-    interface IP;
-    interface UDPClient;
-    interface SplitControl as IPControl;
-#ifdef ENABLE_SOUNDER
-    interface Mts300Sounder as Sounder;
-#endif /* ENABLE_SOUNDER */
-#ifdef ENABLE_TEMP_SENSOR
-    interface Read<uint16_t> as TempSensorC;
-#endif /* ENABLE_TEMP_SENSOR */
-#ifdef ENABLE_LIGHT_SENSOR
-    interface Read<uint16_t> as LightSensorC;
-#endif /* ENABLE_LIGHT_SENSOR */
-  }
-}
-implementation {
-#ifndef MINIMIZE_MEMORY
-    char *help_buf = "6lowpan cli supported commands:\n"
-                     "\tset led {0,1,2} {on,off} -- toggle leds\n"
-#ifdef ENABLE_SOUNDER
-                     "\tsounder time_in_ms\n"
-#endif /* ENABLE_SOUNDER */
-#ifdef ENABLE_TEMP_SENSOR
-                     "\tget temp\n"
-#endif /* ENABLE_TEMP_SENSOR */
-#ifdef ENABLE_LIGHT_SENSOR
-                     "\tget light\n"
-#endif /* ENABLE_LIGHT_SENSOR */
-                     "\tsend small udp\n"
-                     "\tsend large udp\n"
-                     "\thelp\n";
-    char *small_udp_buf = "\n";
-    char *large_udp_buf = "\n";
-    /*
-    char *small_udp_buf = "----- SMALL UDP DATA BUFFER -----\n";
-    char *large_udp_buf =
-           "This is a large testing string. It should undergo " \
-           "6lowpan fragmentation\n" \
-            "0............................................................\n" \
-            "1............................................................\n" \
-            "2............................................................\n" \
-            "3............................................................\n" \
-            "4............................................................\n" \
-            "5............................................................\n" \
-            "6............................................................\n" \
-            "7............................................................\n" \
-            "8............................................................\n" \
-            "9............................................................\n" \
-            "A............................................................\n" \
-            "B............................................................\n" \
-            "C............................................................\n" \
-            "D............................................................\n" \
-            "E............................................................\n" \
-            "10...........................................................\n" \
-            "11...........................................................\n" \
-            "12...........................................................\n" \
-            "13(shorter)\n" \
-           "---- END OF THE LARGE UDP DATA ----\n";
-    */
-#if defined(ENABLE_TEMP_SENSOR) || defined(ENABLE_LIGHT_SENSOR)
-    char sensor_buf[15];
-    bool sensor_buf_busy = FALSE;
-    ip6_addr_t sensor_addr;
-    uint16_t sensor_port;
-#endif /* ENABLE_TEMP_SENSOR | ENABLE_LIGHT_SENSOR */
-#endif /* MINIMIZE_MEMORY */
-
-    event void Boot.booted() {
-      /* set an IP address */
-      ip6_addr_t addr = {{0x20, 0x01,
-                        0x06, 0x38,
-                        0x07, 0x09,
-                        0x12, 0x34,
-                        0x00, 0x00,
-                        0x00, 0x00,
-                        0x00, 0x00,
-                        0x00, 0x00
-      }};
-      //call IP.setAddress(&addr);
-        call IP.setAddressAutoconf(&addr);
-
-       call IPControl.start();
-    }
-    
-    event void IPControl.startDone(error_t err) {
-
-       call UDPClient.listen(1234);
-    }
-    event void IPControl.stopDone(error_t err) {}
-
-    event void UDPClient.receive(const ip6_addr_t *addr, const uint16_t port,
-                                uint8_t *buf, uint16_t len )
-    {
-#ifndef MINIMIZE_MEMORY
-       if ( strncmp(buf, "set ", min(len, 4)) == 0 && len>0) {
-           buf += 4;
-           len -= 4;
-           if ( strncmp(buf, "led ", min(len, 4)) == 0 && len>0) {
-               buf += 4;
-               len -= 4;
-
-               if ( strncmp(buf, "0 ", min(len, 2)) == 0 && len>0) {
-                   buf += 2;
-                   len -= 2;
-                   if ( strncmp(buf, "on", min(len, 2)) == 0 && len>0) {
-                       call Leds.led0On();
-                   } else if (strncmp(buf, "off", min(len, 3)) == 0 && len>0){
-                       call Leds.led0Off();
-                   }
-               } else if ( strncmp(buf, "1 ", min(len, 2)) == 0 && len>0) {
-                   buf += 2;
-                   len -= 2;
-                   if ( strncmp(buf, "on", min(len, 2)) == 0 && len>0) {
-                       call Leds.led1On();
-                   } else if (strncmp(buf, "off", min(len, 3)) == 0 && len>0){
-                       call Leds.led1Off();
-                   }
-               } else if ( strncmp(buf, "2 ", min(len, 2)) == 0 && len>0) {
-                   buf += 2;
-                   len -= 2;
-                   if ( strncmp(buf, "on", min(len, 2)) == 0 && len>0) {
-                       call Leds.led2On();
-                   } else if (strncmp(buf, "off", min(len, 3)) == 0 && len>0){
-                       call Leds.led2Off();
-                   }
-               } 
-           }
-#ifdef ENABLE_SOUNDER
-       } else if ( strncmp(buf, "sounder ", min(len, 8)) == 0
-                   && len>0) {
-           buf += 8;
-           len -= 8;
-           call Sounder.beep(atoi(buf));
-#endif /* ENABLE_SOUNDER */
-
-#ifdef ENABLE_TEMP_SENSOR
-       } else if ( strncmp(buf, "get temp", min(len, 8)) == 0
-                   && len>0) {
-           memcpy(&sensor_addr, addr, sizeof(*addr));
-           sensor_port = port;
-           //call UDPClient.sendTo(addr, port, "reading temp...\n", 16);
-           call TempSensorC.read();
-#endif /* ENABLE_TEMP_SENSOR */
-
-#ifdef ENABLE_LIGHT_SENSOR
-       } else if ( strncmp(buf, "get light", min(len, 8)) == 0
-                   && len>0) {
-           memcpy(&sensor_addr, addr, sizeof(*addr));
-           sensor_port = port;
-           //call UDPClient.sendTo(addr, port, "reading light...\n", 17);
-           call LightSensorC.read();
-#endif /* ENABLE_LIGHT_SENSOR */
-
-       } else if (strncmp(buf, "send large udp", min(len, 14)) == 0
-                  && len>0) {
-           call UDPClient.sendTo(addr, port,
-                                 large_udp_buf, strlen(large_udp_buf));
-       } else if (strncmp(buf, "send small udp", min(len, 14)) == 0
-                  && len>0) {
-           call UDPClient.sendTo(addr, port,
-                                 small_udp_buf, strlen(small_udp_buf));
-       } else if (strncmp(buf, "help", min(len, 14)) == 0
-                  && len>0) {
-           call UDPClient.sendTo(addr, port,
-                                 help_buf, strlen(help_buf));
-       } else {
-           call UDPClient.sendTo(addr, port,
-                                 help_buf, strlen(help_buf));
-       }
-#endif /* MINIMIZE_MEMORY */
-    }
-    
-    event void UDPClient.sendDone(error_t result, void* buf)
-    {
-#if defined(ENABLE_TEMP_SENSOR) || defined(ENABLE_LIGHT_SENSOR)
-       if (buf == sensor_buf) {
-           sensor_buf_busy = FALSE;
-       }
-#endif /* ENABLE_TEMP_SENSOR | ENABLE_LIGHT_SENSOR */
-    }
-
-#ifdef ENABLE_TEMP_SENSOR
-  event void TempSensorC.readDone(error_t result, uint16_t data) {
-      if (sensor_buf_busy == FALSE) {
-         sensor_buf_busy = TRUE;
-         if (result == SUCCESS) {
-             snprintf(sensor_buf, sizeof(sensor_buf), "temp: %d\n", data);
-         } else {
-             snprintf(sensor_buf, sizeof(sensor_buf), "temp: -\n");
-         }
-         call UDPClient.sendTo(&sensor_addr, sensor_port,
-                               sensor_buf, strlen(sensor_buf));
-      } else {
-         call UDPClient.sendTo(&sensor_addr, sensor_port,
-                               "busy\n", 5);
-      }
-  }
-#endif /* ENABLE_TEMP_SENSOR */
-
-#ifdef ENABLE_LIGHT_SENSOR
-  event void LightSensorC.readDone(error_t result, uint16_t data) {
-      if (sensor_buf_busy == FALSE) {
-         sensor_buf_busy = TRUE;
-         if (result == SUCCESS) {
-             snprintf(sensor_buf, sizeof(sensor_buf), "light: %d\n", data);
-         } else {
-             snprintf(sensor_buf, sizeof(sensor_buf), "light: -\n");
-         }
-         call UDPClient.sendTo(&sensor_addr, sensor_port,
-                               sensor_buf, strlen(sensor_buf));
-      } else {
-         call UDPClient.sendTo(&sensor_addr, sensor_port,
-                               "busy\n", 5);
-      }
-  }
-#endif /* ENABLE_LIGHT_SENSOR */
-}
diff --git a/apps/6lowpancli/Makefile b/apps/6lowpancli/Makefile
deleted file mode 100644 (file)
index a4c380e..0000000
+++ /dev/null
@@ -1,12 +0,0 @@
-COMPONENT=CliAppC
-
-CFLAGS += -I$(TOSDIR)/lib/printf -I$(TOSDIR)/lib/net/6lowpan -D'TOSH_DATA_LENGTH=102'
-
-# TelosB
-# CFLAGS + = "-D'ENABLE_TELOSB_LIGHT_SENSOR=1' -D'ENABLE_TELOSB_TEMP_SENSOR=1'"
-
-# MicaZ with the mts300 sensorboard
-# CFLAGS += "-D'ENABLE_MICAZ_LIGHT_SENSOR=1' -D'ENABLE_MICAZ_TEMP_SENSOR=1' -D'ENABLE_SOUNDER=1'"
-
-
-include $(MAKERULES)
diff --git a/apps/6lowpancli/README b/apps/6lowpancli/README
deleted file mode 100644 (file)
index 0ccacf1..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-6lowpan cli is a sample application using the 6lowpan stack. It
-implements a cli listening on UDP port 1234 for commands and replying
-with answers.
-
-Besides that, the mote answers to pings.
-
-The IPv6 addresses
- * a global address with prefix 2001:0638:0709:1234::/64
- * a link-local address
-are assigned using an interface identifier computed from the Active
-Message address of the mote. This is almost like the stateless
-autoconfiguration, but Duplicate Address Detection or Router
-Solicitations are not implemented.
-
-
-Note that you also need a BaseStation application and the serial_tun
-daemon running. See tos/lib/net/6lowpan/REAME for more details.
-
-                              BUILDING
-Debugging output with printf over USB can be enabled with
-       CFLAGS="-D'ENABLE_PRINTF_DEBUG=1'
-
-To minimize memory usage, i.e. disable everything (at the moment only
-the UDP cli) to determine minimum RAM/ROM requirements, use
-       CFLAGS="-D'MINIMIZE_MEMORY=1'
-
-
-                              TESTING
-Assuming active message address (mote id) 20 (0x14):
-
-Small unfragmented ping
-       sudo ping6 -s 50 2001:638:709:1234::fffe:14
-
-Large fragmented ping
-       sudo ping6 -s 1230 -i 3 2001:638:709:1234::fffe:14
-
-Link-local all-nodes ping
-       sudo ping6 -s 20 ff02::01
-
-UDP cli
-       nc6 -u  2001:638:709:1234::fffe:14 1234 
-
index 1e42baa3e7c2a0a99f18d8b5a5799ab936a6602e..3d502a929713062d388d1dd524f5501483391feb 100644 (file)
@@ -138,13 +138,13 @@ implementation
   }
 
   /* Radio started. Now start the collection protocol and set the
-     radio to a 2% low-power-listening duty cycle */
+     wakeup interval for low-power-listening wakeup to half a second. */
   event void RadioControl.startDone(error_t ok) {
     if (ok == SUCCESS)
       {
        call DisseminationControl.start();
        call CollectionControl.start();
-       call LowPowerListening.setLocalDutyCycle(200);
+       call LowPowerListening.setLocalWakeupInterval(512);
       }
     else
       errorLed();
index 6d49bff887097efc0c1cff5b6e00e6fd7e3308c5..f05ae3bea8d614e12e772466d7a5a4ad74816c52 100644 (file)
@@ -1,5 +1,11 @@
 SENSORBOARD=mts300
 PFLAGS += -I%T/lib/net/ctp -I%T/lib/net -I%T/lib/net/4bitle -I%T/lib/net/drip
 COMPONENT=AntiTheftAppC
+
+#CFLAGS += -DLOW_POWER_LISTENING
+#CFLAGS += -DLPL_DEF_LOCAL_WAKEUP=512
+#CFLAGS += -DLPL_DEF_REMOTE_WAKEUP=512
+#CFLAGS += -DDELAY_AFTER_RECEIVE=20
+
 include $(MAKERULES)
 
index 896bc812a89d332afbeda66a391cc993f026316a..ada387b5ec1a9ba6750b5d8bf5b3b3c0c67996de 100644 (file)
@@ -55,7 +55,7 @@ implementation
        tree */
     if (error == SUCCESS)
       {
-       call LowPowerListening.setLocalDutyCycle(200);
+       call LowPowerListening.setLocalWakeupInterval(512);
        call DisseminationControl.start();
        call CollectionControl.start();
        call RootControl.setRoot();
index 247c8a0d64d4306bc32aa78c030233dfae22ea75..4719dcfc59b970365356b971619d13a1e5da5487 100644 (file)
@@ -1,4 +1,10 @@
 PFLAGS += -I%T/lib/net/ctp -I%T/lib/net -I%T/lib/net/4bitle -I%T/lib/net/drip
 COMPONENT=AntiTheftRootAppC
+
+#CFLAGS += -DLOW_POWER_LISTENING
+#CFLAGS += -DLPL_DEF_LOCAL_WAKEUP=512
+#CFLAGS += -DLPL_DEF_REMOTE_WAKEUP=512
+#CFLAGS += -DDELAY_AFTER_RECEIVE=20
+
 include $(MAKERULES)
 
index e0727e8f7b3993cbd078bbf36ac19c269c301a95..1a08fc768b00c37f65ad6d8bf8a295464d9188db 100644 (file)
@@ -76,7 +76,7 @@ implementation {
   BaseStationP.SerialControl -> Serial;
   
   BaseStationP.UartSend -> Serial;
-  BaseStationP.UartReceive -> Serial;
+  BaseStationP.UartReceive -> Serial.Receive;
   BaseStationP.UartPacket -> Serial;
   BaseStationP.UartAMPacket -> Serial;
   
index 3c052e790cdf2f3a46e52aeaf9f2e7275ce4b264..98109ed5ba4f99181777e1cc9d19ec41ef72ae2a 100644 (file)
@@ -1,6 +1,7 @@
 COMPONENT=BaseStationC
 CFLAGS += -DCC2420_NO_ACKNOWLEDGEMENTS
 CFLAGS += -DCC2420_NO_ADDRESS_RECOGNITION
+CFLAGS += -DTASKLET_IS_TASK
 
 include $(MAKERULES)
 
index dedd144f51a7d7f31049776ee8fc50b667855aca..110eb04dda88770000e9e65c7a29ccf48ad0764b 100644 (file)
@@ -48,7 +48,7 @@ Other combinations can be defined to meet your application's needs:
 
 Tools:
 
-tools/java/net/tinyos/sf/SerialForwarder.  
+support/sdk/java/net/tinyos/sf/SerialForwarder  
 
 See the TinyOS Tutorial on Mote-PC serial communication and
 SerialForwarder on docs.tinyos.net for more details.
index 4f8286940a0068f3cd0966ca2dedf4b3ea757e97..e5a672c1ccee3bb4b346dc5afae713a2e0e3cf79 100644 (file)
@@ -30,7 +30,7 @@
  */
 
 /**
- * Blink is a basic application that toggles the a mote LED periodically.
+ * Blink is a basic application that toggles a mote's LED periodically.
  * It does so by starting a Timer that fires every second. It uses the
  * OSKI TimerMilli service to achieve this goal.
  *
diff --git a/apps/IPBaseStation/BaseStationC.nc b/apps/IPBaseStation/BaseStationC.nc
new file mode 100644 (file)
index 0000000..8c53be0
--- /dev/null
@@ -0,0 +1,138 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+z * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ * The TinyOS 2.x base station that forwards packets between the UART
+ * and radio.It replaces the GenericBase of TinyOS 1.0 and the
+ * TOSBase of TinyOS 1.1.
+ *
+ * <p>On the serial link, BaseStation sends and receives simple active
+ * messages (not particular radio packets): on the radio link, it
+ * sends radio active messages, whose format depends on the network
+ * stack being used. BaseStation will copy its compiled-in group ID to
+ * messages moving from the serial link to the radio, and will filter
+ * out incoming radio messages that do not contain that group ID.</p>
+ *
+ * <p>BaseStation includes queues in both directions, with a guarantee
+ * that once a message enters a queue, it will eventually leave on the
+ * other interface. The queues allow the BaseStation to handle load
+ * spikes.</p>
+ *
+ * <p>BaseStation acknowledges a message arriving over the serial link
+ * only if that message was successfully enqueued for delivery to the
+ * radio link.</p>
+ *
+ * <p>The LEDS are programmed to toggle as follows:</p>
+ * <ul>
+ * <li><b>RED Toggle:</b>: Message bridged from serial to radio</li>
+ * <li><b>GREEN Toggle:</b> Message bridged from radio to serial</li>
+ * <li><b>YELLOW/BLUE Toggle:</b> Dropped message due to queue overflow in either direction</li>
+ * </ul>
+ *
+ * @author Phil Buonadonna
+ * @author Gilman Tolle
+ * @author David Gay
+ * @author Philip Levis
+ * @date August 10 2005
+ */
+#include <Ieee154.h>
+
+configuration BaseStationC {
+}
+implementation {
+
+  enum {
+    // becasue we're the only one's using the radio, we're lazy and
+    // don't acquire the resource.  For some reason, it seems to crash
+    // occasionally if we don't do this.
+    RESOURCE_IDX = unique(IEEE154_SEND_CLIENT),
+  };
+
+  components MainC, BaseStationP, LedsC;
+  components Ieee154MessageC as Radio;
+  components SerialDispatcherC as SerialControl, Serial802_15_4C as Serial;
+  
+  MainC.Boot <- BaseStationP;
+
+  BaseStationP.RadioControl -> Radio;
+  BaseStationP.SerialControl -> SerialControl;
+  BaseStationP.UartSend -> Serial.Send;
+  BaseStationP.UartReceive -> Serial.Receive;
+  
+
+  BaseStationP.RadioSend -> Radio;
+  BaseStationP.RadioReceive -> Radio.Ieee154Receive;
+
+  BaseStationP.RadioPacket -> Radio.Packet;
+  BaseStationP.RadioIeeePacket -> Radio;
+  
+  BaseStationP.Leds -> LedsC;
+
+  BaseStationP.PacketLink -> Radio;
+  BaseStationP.LowPowerListening -> Radio;
+
+  components ResetC;
+  BaseStationP.Reset -> ResetC;
+
+  components SerialDevConfC as Configure;
+  BaseStationP.ConfigureSend -> Configure;
+  BaseStationP.ConfigureReceive -> Configure;
+
+  components new TimerMilliC();
+  BaseStationP.ConfigureTimer -> TimerMilliC;
+
+  components IPAddressC;
+  BaseStationP.IPAddress -> IPAddressC;
+
+  components CC2420ControlC;
+  BaseStationP.CC2420Config -> CC2420ControlC;
+}
diff --git a/apps/IPBaseStation/BaseStationP.nc b/apps/IPBaseStation/BaseStationP.nc
new file mode 100644 (file)
index 0000000..71645ca
--- /dev/null
@@ -0,0 +1,448 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/*
+ * @author Phil Buonadonna
+ * @author Gilman Tolle
+ * @author David Gay
+ * Revision:   $Id$
+ */
+  
+/* 
+ * BaseStationP bridges packets between a serial channel and the radio.
+ * Messages moving from serial to radio will be tagged with the group
+ * ID compiled into the TOSBase, and messages moving from radio to
+ * serial will be filtered by that same group id.
+ */
+
+#ifndef SIM
+#include "CC2420.h"
+#endif
+#include "AM.h"
+#include "Serial.h"
+#include "devconf.h"
+#include "lib6lowpan.h"
+
+module BaseStationP {
+  uses {
+    interface Boot;
+    interface SplitControl as SerialControl;
+    interface SplitControl as RadioControl;
+
+    interface Send as UartSend;
+    interface Ieee154Send as RadioSend;
+
+    interface Receive as UartReceive;
+    interface Receive as RadioReceive;
+    interface Packet as RadioPacket;
+
+    interface Send as ConfigureSend;
+    interface Receive as ConfigureReceive;
+    interface Timer<TMilli> as ConfigureTimer;
+    interface IPAddress;
+
+
+    interface Ieee154Packet as RadioIeeePacket;
+
+    interface PacketLink;
+    interface LowPowerListening;
+    interface CC2420Config;
+
+    interface Leds;
+
+    interface Reset;
+  }
+}
+
+implementation
+{
+  enum {
+    UART_QUEUE_LEN = 10,
+    RADIO_QUEUE_LEN = 10,
+  };
+
+  uint16_t radioRetries = BLIP_L2_RETRIES;
+  uint16_t radioDelay   = BLIP_L2_DELAY;
+
+  uint16_t serial_read;
+  uint16_t radio_read;
+  uint16_t serial_fail;
+  uint16_t radio_fail;
+
+  bool echo_busy;
+  message_t echo_buf;
+  config_reply_t *reply;
+
+  message_t  uartQueueBufs[UART_QUEUE_LEN];
+  message_t  *uartQueue[UART_QUEUE_LEN];
+  uint8_t    uartIn, uartOut;
+  bool       uartBusy, uartFull;
+
+  message_t  radioQueueBufs[RADIO_QUEUE_LEN];
+  message_t  *radioQueue[RADIO_QUEUE_LEN];
+  uint8_t    radioIn, radioOut;
+  bool       radioBusy, radioFull;
+
+  task void uartSendTask();
+  task void radioSendTask();
+
+  void dropBlink() {
+    call Leds.led2Toggle();
+  }
+
+  void failBlink() {
+    call Leds.led2Toggle();
+  }
+
+#ifndef SIM
+#define CHECK_NODE_ID if (0) return
+#else
+#define CHECK_NODE_ID if (TOS_NODE_ID != BASESTATION_ID) return
+#endif
+  task void configureReply() {
+    if (echo_busy) return;
+
+    reply->addr = call IPAddress.getShortAddr();
+    reply->serial_read = serial_read;
+    reply->radio_read = radio_read;
+    reply->serial_fail = serial_fail;
+    reply->radio_fail = radio_fail;
+
+    echo_busy = TRUE;
+    // delay sending the reply for a bit
+    // the pc seems to usually drop the packet if we don't do this; 
+    call ConfigureTimer.startOneShot(100);
+  }
+
+  event void Boot.booted() {
+    uint8_t i;
+
+    CHECK_NODE_ID;
+
+    for (i = 0; i < UART_QUEUE_LEN; i++)
+      uartQueue[i] = &uartQueueBufs[i];
+    uartIn = uartOut = 0;
+    uartBusy = FALSE;
+    uartFull = TRUE;
+
+    for (i = 0; i < RADIO_QUEUE_LEN; i++)
+      radioQueue[i] = &radioQueueBufs[i];
+    radioIn = radioOut = 0;
+    radioBusy = FALSE;
+    radioFull = TRUE;
+
+    echo_busy = FALSE;
+    serial_read = 0;
+    radio_read = 0;
+    serial_fail = 0;
+    radio_fail = 0;
+
+    call RadioControl.start();
+    call SerialControl.start();
+
+    reply = (config_reply_t *)(&(echo_buf.data));
+  }
+
+  event void RadioControl.startDone(error_t error) {
+    CHECK_NODE_ID;
+    if (error == SUCCESS) {
+      radioFull = FALSE;
+#ifdef LPL_SLEEP_INTERVAL
+      // SDH : can actually leave the base on full time in most cases.
+      // call LowPowerListening.setLocalSleepInterval(LPL_SLEEP_INTERVAL);
+#endif
+    }
+  }
+
+  event void SerialControl.startDone(error_t error) {
+    CHECK_NODE_ID;
+    if (error == SUCCESS) {
+      uartFull = FALSE;
+    }
+    reply->error = CONFIG_ERROR_BOOTED;
+    post configureReply();
+  }
+
+  event void SerialControl.stopDone(error_t error) {}
+  event void RadioControl.stopDone(error_t error) {}
+
+  uint8_t count = 0;
+
+  message_t* receive(message_t* msg, void* payload, uint8_t len);
+  
+  event message_t *RadioReceive.receive(message_t *msg,
+                                           void *payload,
+                                           uint8_t len) {
+    CHECK_NODE_ID NULL;
+    dbg("base", "radio message received (%i)\n", len);
+    return receive(msg, payload, len);
+  }
+
+  message_t* receive(message_t *msg, void *payload, uint8_t len) {
+    message_t *ret = msg;
+    CHECK_NODE_ID NULL;
+
+    atomic {
+      if (!uartFull)
+       {
+         ret = uartQueue[uartIn];
+         uartQueue[uartIn] = msg;
+
+         uartIn = (uartIn + 1) % UART_QUEUE_LEN;
+       
+         if (uartIn == uartOut)
+           uartFull = TRUE;
+
+         if (!uartBusy)
+           {
+             post uartSendTask();
+             uartBusy = TRUE;
+           }
+       }
+      else
+       dropBlink();
+    }
+    
+    return ret;
+  }
+
+  task void uartSendTask() {
+    uint8_t len;
+    message_t* msg;
+    atomic
+      if (uartIn == uartOut && !uartFull)
+       {
+         uartBusy = FALSE;
+         return;
+       }
+
+    msg = uartQueue[uartOut];
+
+    // Since we're forwarding fully formed radio packets, we can use
+    // these headers.
+    len = call RadioPacket.payloadLength(msg);
+
+    if (call UartSend.send(uartQueue[uartOut], len) == SUCCESS) {
+      call Leds.led1Toggle();
+    }    else
+      {
+       failBlink();
+       post uartSendTask();
+      }
+  }
+
+  event void UartSend.sendDone(message_t* msg, error_t error) {
+    if (error != SUCCESS)
+      failBlink();
+    else
+      atomic
+       if (msg == uartQueue[uartOut])
+         {
+           if (++uartOut >= UART_QUEUE_LEN)
+             uartOut = 0;
+           if (uartFull)
+             uartFull = FALSE;
+         }
+    post uartSendTask();
+
+  }
+
+  event message_t *UartReceive.receive(message_t *msg,
+                                       void *payload,
+                                       uint8_t len) {
+    message_t *ret = msg;
+    bool reflectToken = FALSE;
+    CHECK_NODE_ID msg;
+    dbg("base", "uartreceive len %i of 0x%x\n", len, call SerialAMPacket.destination(msg));
+#if defined(BLIP_WATCHDOG) && (defined(PLATFORM_TELOS) || defined(PLATFORM_TELOSB) || defined(PLATFORM_EPIC))
+    WDTCTL = WDT_ARST_1000;
+#endif
+    atomic
+      if (!radioFull)
+       {
+         reflectToken = TRUE;
+         ret = radioQueue[radioIn];
+         radioQueue[radioIn] = msg;
+         if (++radioIn >= RADIO_QUEUE_LEN)
+           radioIn = 0;
+         if (radioIn == radioOut)
+           radioFull = TRUE;
+
+         if (!radioBusy)
+           {
+             post radioSendTask();
+             radioBusy = TRUE;
+           }
+       }
+      else
+        dbg("base", "no enqueue\n");
+//     dropBlink();
+
+    if (reflectToken) {
+      //call UartTokenReceive.ReflectToken(Token);
+    }
+    
+    return ret;
+  }
+
+  task void radioSendTask() {
+    uint8_t len;
+    ieee154_saddr_t addr;
+    message_t* msg;
+    
+    dbg ("base", "radioSendTask()\n");
+    atomic
+      if (radioIn == radioOut && !radioFull)
+       {
+         radioBusy = FALSE;
+         return;
+       }
+
+    msg = radioQueue[radioOut];
+    len = call RadioPacket.payloadLength(msg);
+    addr = call RadioIeeePacket.destination(msg);
+
+    if (addr != 0xFFFF) {
+      call PacketLink.setRetries(msg, radioRetries);
+      call PacketLink.setRetryDelay(msg, radioDelay);
+    } else {
+      call PacketLink.setRetries(msg, 0);
+    }
+#ifdef LPL_SLEEP_INTERVAL
+    call LowPowerListening.setRemoteWakeupInterval(msg, LPL_SLEEP_INTERVAL);
+#endif
+    dbg("base", "radio send to: 0x%x len: %i\n", addr, len);
+    if (call RadioSend.send(addr, msg, len) == SUCCESS)
+      call Leds.led0Toggle();
+    else
+      {
+       failBlink();
+       post radioSendTask();
+      }
+  }
+
+  event void RadioSend.sendDone(message_t* msg, error_t error) {
+    CHECK_NODE_ID;
+    dbg("base", "sendDone()\n");
+    
+    //if (!call PacketLink.wasDelivered(msg))
+    // failBlink();
+    if (error != SUCCESS)
+      failBlink();
+    else
+      atomic
+       if (msg == radioQueue[radioOut])
+         {
+           if (++radioOut >= RADIO_QUEUE_LEN)
+             radioOut = 0;
+           if (radioFull)
+             radioFull = FALSE;
+         }
+    
+    post radioSendTask();
+  }
+
+#ifndef SIM
+  event message_t *ConfigureReceive.receive(message_t *msg,
+                                            void *payload,
+                                            uint8_t len) {
+    config_cmd_t *cmd;
+    uint8_t error = CONFIG_ERROR_OK;
+#if defined(BLIP_WATCHDOG) && (defined(PLATFORM_TELOS) || defined(PLATFORM_TELOSB) || defined(PLATFORM_EPIC))
+    WDTCTL = WDT_ARST_1000;
+#endif
+
+    if (len != sizeof(config_cmd_t) || msg == NULL) return msg;
+    // don't parse the message if we can't reply
+
+    cmd = (config_cmd_t *)&msg->data;
+
+    switch (cmd->cmd) {
+    case CONFIG_ECHO:
+      break;
+    case CONFIG_SET_PARM:
+      call CC2420Config.setChannel(cmd->rf.channel);
+      // IPAddress calls sync() for you, I think, so we'll put it second 
+      call IPAddress.setShortAddr(cmd->rf.addr);
+      call CC2420Config.sync();
+      radioRetries = cmd->retx.retries;
+      radioDelay   = cmd->retx.delay;
+      break;
+    case CONFIG_REBOOT:
+      call Reset.reset();
+      break;
+    case CONFIG_KEEPALIVE:
+      return msg;
+    }
+    if (!echo_busy) {
+      reply->error = error;
+      post configureReply();
+    }
+    return msg;
+  }
+
+
+  event void CC2420Config.syncDone(error_t error) {
+
+  }
+
+  event void ConfigureSend.sendDone(message_t *msg, error_t error) {
+    echo_busy = FALSE;
+  }
+
+  event void ConfigureTimer.fired() {
+    call Leds.led2Toggle();
+    if (call ConfigureSend.send(&echo_buf, sizeof(config_reply_t)) != SUCCESS)
+      echo_busy = FALSE;
+  }
+#endif
+}  
diff --git a/apps/IPBaseStation/Makefile b/apps/IPBaseStation/Makefile
new file mode 100644 (file)
index 0000000..49fd6ee
--- /dev/null
@@ -0,0 +1,39 @@
+COMPONENT=BaseStationC
+
+# radio options.  channel settings will be overridden by the driver
+# CFLAGS += -DCC2420_DEF_RFPOWER=4
+
+# this is necessary, otherwise we will allocate a heap by including
+# the lowpan target
+CFLAGS += -DNO_IP_MALLOC 
+
+# this aligns the 802.15.4 payload on the data field of a message_t.
+# very convenient for forwarding, and means we don't have to do a
+# memmove.  This doesn't mean that motes running blip also need this--
+# they can use IFRAMES or IEEE154FRAMES
+CFLAGS += -DIEEE154FRAMES_ENABLED
+
+# if you're worried about your interface mote crashing, enable this to
+# turn on a hardware watchdog that will reset it if it does.  CFLAGS
+# += -DBLIP_WATCHDOG
+#
+# debugging
+#
+
+# filter packets based on a specified topology
+# PFLAGS += -I../UDPEcho/NodeConnectivity -DSW_TOPOLOGY
+
+# part of the test harness
+# CFLAGS += -DDBG_TRACK_FLOWS
+
+# for simulation
+# CFLAGS += -DBASESTATION_ID=100
+
+# defs for snooping-- handy for debugging LPL, etc.
+# CFLAGS += -DCC2420_NO_UNIQUE
+# CFLAGS += -DCC2420_DEF_CHANNEL=15
+# CFLAGS += -DCC2420_NO_ACKNOWLEDGEMENTS
+# CFLAGS += -DCC2420_NO_ADDRESS_RECOGNITION
+
+include $(MAKERULES)
+
diff --git a/apps/IPBaseStation/README b/apps/IPBaseStation/README
new file mode 100644 (file)
index 0000000..ca1412a
--- /dev/null
@@ -0,0 +1,74 @@
+README for BaseStation
+Author/Contact: tinyos-help@millennium.berkeley.edu
+
+IPBaseStation is a modification of the generic BaseStation which ships
+with tinyOS-2.x.  It alters the serial protocol to pass 802.15.4
+frames instead of Serial.h packets.  It also adds an out-of-band
+configuration protocol which allows a driver running over the serial
+port to reboot the mote, and to set the device address, channel, and
+retransmission parameters.  These changes are useful when one wishes
+to use a mote attached to a computer as an 802.15.4 interface rather
+then an actual mote.  The actual queuing logic for copying packets is
+mostly unchanged, and it continues to make use of serial ACKs.
+
+To build, add the 'blip' make extra.  IE,
+
+$ make <platform> blip ...
+
+For more information on setting up an IPv6 network, please see the tutorial:
+http://docs.tinyos.net/index.php/BLIP_Tutorial
+
+Description of BaseStation:
+
+BaseStation is an application that acts as a simple Active Message
+bridge between the serial and radio links. It replaces the GenericBase
+of TinyOS 1.0 and the TOSBase of TinyOS 1.1.
+
+On the serial link, BaseStation sends and receives simple active
+messages (not particular radio packets): on the radio link, it sends
+radio active messages, whose format depends on the network stack being
+used. BaseStation will copy its compiled-in group ID to messages
+moving from the serial link to the radio, and will filter out incoming
+radio messages that do not contain that group ID.
+
+BaseStation includes queues in both directions, with a guarantee that
+once a message enters a queue, it will eventually leave on the other
+interface. The queues allow the BaseStation to handle load spikes more
+gracefully.
+
+BaseStation acknowledges a message arriving over the serial link only if
+that message was successfully enqueued for delivery to the radio link.
+
+The LEDS are programmed to toggle as follows:
+
+RED Toggle         - Message bridged from serial to radio
+GREEN Toggle       - Message bridged from radio to serial
+YELLOW/BLUE Toggle - Dropped message due to queue overflow 
+                     in either direction
+
+When using a CC2420 radio, several default preprocessor configurations
+are defined in the Makefile:
+  * CC2420_NO_ACKNOWLEDGEMENTS
+    - Prevents the base station from falsly acknowledging packets
+  * CC2420_NO_ADDRESS_RECOGNITION
+    - Allows the base station to sniff packets from any transmitter
+
+Other combinations can be defined to meet your application's needs:
+  * CC2420_NO_ADDRESS_RECOGNITION only
+    - Sniff all packets, but acknowledge packets only if they
+      are sent to the base station's address
+
+  * Removing all preprocessor definitions in the Makefile
+    - Only accept packets destined for the base station's address,
+      and acknowledge those packets
+
+
+Tools:
+
+tools/java/net/tinyos/sf/SerialForwarder.  
+
+See doc/serialcomm/index.html for more information using these tools.
+
+Known bugs/limitations:
+
+
diff --git a/apps/IPBaseStation/Reset.h b/apps/IPBaseStation/Reset.h
new file mode 100644 (file)
index 0000000..59951ef
--- /dev/null
@@ -0,0 +1,59 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/* 
+ * Authors:  Wei Hong
+ *           Intel Research Berkeley Lab
+ * Date:     7/15/2002
+ *
+ */
+
+/**
+ * @author Wei Hong
+ * @author Intel Research Berkeley Lab
+ */
+
+
+void resetMote()
+{
+#if defined(PLATFORM_MICA) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT) || defined(PLATFORM_MICAZ)
+       cli(); 
+       wdt_enable(0); 
+       while (1) { 
+               __asm__ __volatile__("nop" "\n\t" ::);
+       }
+#elif defined(PLATFORM_TELOS) || defined(PLATFORM_TELOSB) || defined(PLATFORM_EPIC)
+        WDTCTL = 0;
+#else
+#error "Reset.h not defined/supported for your platform, aborting..."
+#endif
+}
+
diff --git a/apps/IPBaseStation/Reset.nc b/apps/IPBaseStation/Reset.nc
new file mode 100644 (file)
index 0000000..a503b99
--- /dev/null
@@ -0,0 +1,47 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/* 
+ * Authors:  Wei Hong
+ *           Intel Research Berkeley Lab
+ * Date:     7/15/2002
+ *
+ */
+
+/**
+ * @author Wei Hong
+ * @author Intel Research Berkeley Lab
+ */
+
+
+interface Reset {
+  command void reset();
+}
diff --git a/apps/IPBaseStation/ResetC.nc b/apps/IPBaseStation/ResetC.nc
new file mode 100644 (file)
index 0000000..3684166
--- /dev/null
@@ -0,0 +1,56 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/* 
+ * Authors:  Wei Hong
+ *           Intel Research Berkeley Lab
+ * Date:     7/15/2002
+ *
+ */
+
+/**
+ * @author Wei Hong
+ * @author Intel Research Berkeley Lab
+ */
+
+includes Reset;
+
+module ResetC
+{
+       provides interface Reset;
+}
+implementation
+{
+       command void Reset.reset()
+       {
+               resetMote();
+       }
+}
index 82f39986de91ab96cbc999904790bb7f1bf99a75..f62a26cbf66e2aa29ba398294b09fe2f4cd27703 100644 (file)
@@ -19,7 +19,7 @@
 
 #include "MViz.h"
 
-module MVizC {
+module MVizC @safe(){
   uses {
     // Interfaces for initialization:
     interface Boot;
@@ -218,7 +218,7 @@ implementation {
     }
     local.reading = data;
     call CtpInfo.getEtx(&val);
-    local.link_route_value = val;
+    local.etx = val;
     call CtpInfo.getParent(&val);
     local.link_route_addr = val;
     local.link_route_value = call LinkEstimator.getLinkQuality(local.link_route_addr);
index fab099031e6077b7c5f6c489762187276c11c7cf..5179b3500d46aa8a37c9c3ba2a40a0e1a22d8687 100644 (file)
@@ -19,7 +19,7 @@
 #include "Timer.h"
 #include "MultihopOscilloscope.h"
 
-module MultihopOscilloscopeC {
+module MultihopOscilloscopeC @safe(){
   uses {
     // Interfaces for initialization:
     interface Boot;
diff --git a/apps/MultihopOscilloscope/oscilloscope.py b/apps/MultihopOscilloscope/oscilloscope.py
new file mode 100644 (file)
index 0000000..de29c89
--- /dev/null
@@ -0,0 +1,30 @@
+#!/usr/bin/env python
+
+import sys
+import tos
+
+AM_OSCILLOSCOPE = 0x93
+
+class OscilloscopeMsg(tos.Packet):
+    def __init__(self, packet = None):
+        tos.Packet.__init__(self,
+                            [('version',  'int', 2),
+                             ('interval', 'int', 2),
+                             ('id',       'int', 2),
+                             ('count',    'int', 2),
+                             ('readings', 'blob', None)],
+                            packet)
+
+if '-h' in sys.argv:
+    print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:57600"
+    sys.exit()
+
+am = tos.AM()
+
+while True:
+    p = am.read()
+    if p and p.type == AM_OSCILLOSCOPE:
+        msg = OscilloscopeMsg(p.data)
+        print msg.id, msg.count, [i<<8 | j for (i,j) in zip(msg.readings[::2], msg.readings[1::2])]
+        #print msg
+
index 6320e88ec4ffeb52db4d53a03139d694d60b98ae..a25e0c082e6357ad12576342d1733bd14d65b2f4 100644 (file)
@@ -38,7 +38,7 @@
  * @author Cory Sharp <cssharp@eecs.berkeley.edu>
  * @date February 4, 2006
  */
-module NullC
+module NullC @safe()
 {
   uses interface Boot;
 }
index a73dd60be019be29c7b718fefded35a4f22a9c0e..c4e0a1c0dc90ab0949860478dc91095e0f93189b 100644 (file)
@@ -16,7 +16,7 @@
 #include "Timer.h"
 #include "Oscilloscope.h"
 
-module OscilloscopeC
+module OscilloscopeC @safe()
 {
   uses {
     interface Boot;
index 61859994a4df71d2a2910d5e606b0f129933fea6..df26ebaf912b059737da3aeb6dad4185bf65bec0 100644 (file)
@@ -19,7 +19,7 @@ import java.util.*;
 class Window {
     Oscilloscope parent;
     Graph graph;
-
+    
     Font smallFont = new Font("Dialog", Font.PLAIN, 8);
     Font boldFont = new Font("Dialog", Font.BOLD, 12);
     Font normalFont = new Font("Dialog", Font.PLAIN, 12);
@@ -29,279 +29,285 @@ class Window {
     JFrame frame;
 
     Window(Oscilloscope parent) {
-    this.parent = parent;
+       this.parent = parent;
     }
 
     /* A model for the mote table, and general utility operations on the mote
        list */
     class MoteTableModel extends AbstractTableModel {
-    private ArrayList motes = new ArrayList();
-    private ArrayList colors = new ArrayList();
-
-    /* Initial mote colors cycle through this list. Add more colors if
-       you want. */
-    private Color[] cycle = {
-        Color.RED, Color.WHITE, Color.GREEN, Color.MAGENTA,
-        Color.YELLOW, Color.GRAY, Color.YELLOW
-    };
-    int cycleIndex;
+       private ArrayList<Integer> motes = new ArrayList<Integer>();
+       private ArrayList<Color> colors = new ArrayList<Color>();
+
+       /* Initial mote colors cycle through this list. Add more colors if
+          you want. */
+       private Color[] cycle = {
+           Color.RED, Color.WHITE, Color.GREEN, Color.MAGENTA,
+           Color.YELLOW, Color.GRAY, Color.YELLOW
+       };
+       int cycleIndex;
+       
+       /* TableModel methods for achieving our table appearance */
+       public String getColumnName(int col) {
+           if (col == 0) {
+               return "Mote";
+           } else {
+               return "Color";
+           }
+       }
+
+       public int getColumnCount() { return 2; }
+
+       public synchronized int getRowCount() { return motes.size(); }
+       
+       public synchronized Object getValueAt(int row, int col) {
+           if (col == 0) {
+               return motes.get(row);
+           } else {
+               return colors.get(row);
+           }
+       }
 
-    /* TableModel methods for achieving our table appearance */
-    public String getColumnName(int col) {
-        if (col == 0) {
-            return "Mote";
-        } else {
-            return "Color";
-        }
-    }
-    public int getColumnCount() { return 2; }
-    public synchronized int getRowCount() { return motes.size(); }
-    public synchronized Object getValueAt(int row, int col) {
-        if (col == 0) {
-            return motes.get(row);
-        } else {
-            return colors.get(row);
-        }
-    }
         public Class getColumnClass(int col) {
             return getValueAt(0, col).getClass();
         }
-    public boolean isCellEditable(int row, 
-            int col) { return col == 1; }
-        public synchronized void setValueAt(Object value, 
-                  int row, int col) {
-        colors.set(row, value);
-            fireTableCellUpdated(row, col);
-        graph.repaint();
-        }
-
-    /* Return mote id of i'th mote */
-    int get(int i) { return ((Integer)motes.get(i)).intValue(); }
-    
-    /* Return color of i'th mote */
-    Color getColor(int i)  { return (Color)colors.get(i); }
 
-    /* Return number of motes */
-    int size() { return motes.size(); }
+       public boolean isCellEditable(int row, int col) {
+           return col == 1;
+       }
 
-    /* Add a new mote */
-    synchronized void newNode(int nodeId) {
-        /* Shock, horror. No binary search. */
-        int i, len = motes.size();
-
-        for (i = 0; ; i++) {
-            if (i == len || nodeId < get(i)) {
-                motes.add(i, new Integer(nodeId));
-                // Cycle through a set of initial colors
-                colors.add(i, cycle[cycleIndex++ % cycle.length]);
-                break;
-            }
+       public synchronized void setValueAt(Object value, int row, int col) {
+           colors.set(row, (Color)value);
+            fireTableCellUpdated(row, col);
+           graph.repaint();
         }
-        fireTableRowsInserted(i, i);
-    }
 
-    /* Remove all motes */
-    void clear() {
-        motes = new ArrayList();
-        colors = new ArrayList();
-        fireTableDataChanged();
-    }
-    }
+       /* Return mote id of i'th mote */
+       int get(int i) { return (motes.get(i)).intValue(); }
+       
+       /* Return color of i'th mote */
+       Color getColor(int i)  { return colors.get(i); }
+       
+       /* Return number of motes */
+       int size() { return motes.size(); }
+       
+       /* Add a new mote */
+       synchronized void newNode(int nodeId) {
+           /* Shock, horror. No binary search. */
+           int i, len = motes.size();
+           
+           for (i = 0; ; i++) {
+               if (i == len || nodeId < get(i)) {
+                   motes.add(i, new Integer(nodeId));
+                   // Cycle through a set of initial colors
+                   colors.add(i, cycle[cycleIndex++ % cycle.length]);
+                   break;
+               }
+           }
+           fireTableRowsInserted(i, i);
+       }
+       
+       /* Remove all motes */
+       void clear() {
+           motes = new ArrayList<Integer>();
+           colors = new ArrayList<Color>();
+           fireTableDataChanged();
+       }
+    } /* End of MoteTableModel */
 
     /* A simple full-color cell */
     static class MoteColor extends JLabel implements TableCellRenderer {
-    public MoteColor() { setOpaque(true); }
-    public Component getTableCellRendererComponent
-        (JTable table, Object color,
-         boolean isSelected, boolean hasFocus, 
-         int row, int column) {
-        setBackground((Color)color);
-        return this;
-    }
+       public MoteColor() { setOpaque(true); }
+       public Component getTableCellRendererComponent
+           (JTable table, Object color,
+            boolean isSelected, boolean hasFocus, 
+            int row, int column) {
+           setBackground((Color)color);
+           return this;
+       }
     }
 
     /* Convenience methods for making buttons, labels and textfields.
        Simplifies code and ensures a consistent style. */
 
     JButton makeButton(String label, ActionListener action) {
-    JButton button = new JButton();
+       JButton button = new JButton();
         button.setText(label);
         button.setFont(boldFont);
-    button.addActionListener(action);
-    return button;
+       button.addActionListener(action);
+       return button;
     }
 
     JLabel makeLabel(String txt, int alignment) {
-    JLabel label = new JLabel(txt, alignment);
-    label.setFont(boldFont);
-    return label;
+       JLabel label = new JLabel(txt, alignment);
+       label.setFont(boldFont);
+       return label;
     }
-
+    
     JLabel makeSmallLabel(String txt, int alignment) {
-    JLabel label = new JLabel(txt, alignment);
-    label.setFont(smallFont);
-    return label;
+       JLabel label = new JLabel(txt, alignment);
+       label.setFont(smallFont);
+       return label;
     }
-
+    
     JTextField makeTextField(int columns, ActionListener action) {
-    JTextField tf = new JTextField(columns);
-    tf.setFont(normalFont);
-    tf.setMaximumSize(tf.getPreferredSize());
-    tf.addActionListener(action);
-    return tf;
+       JTextField tf = new JTextField(columns);
+       tf.setFont(normalFont);
+       tf.setMaximumSize(tf.getPreferredSize());
+       tf.addActionListener(action);
+       return tf;
     }
 
     /* Build the GUI */
     void setup() {
-    JPanel main = new JPanel(new BorderLayout());
-
-    main.setMinimumSize(new Dimension(500, 250));
-    main.setPreferredSize(new Dimension(800, 400));
-
-    // Three panels: mote list, graph, controls
-    moteListModel = new  MoteTableModel();
-    JTable moteList = new JTable(moteListModel);
-    moteList.setDefaultRenderer(Color.class, new MoteColor());
-    moteList.setDefaultEditor(Color.class, 
-              new ColorCellEditor("Pick Mote Color"));
-    moteList.setPreferredScrollableViewportSize(new Dimension(100, 400));
-    JScrollPane motePanel = new JScrollPane();
-    motePanel.getViewport().add(moteList, null);
-    main.add(motePanel, BorderLayout.WEST);
-
-    graph = new Graph(this);
-    main.add(graph, BorderLayout.CENTER);
-
-    // Controls. Organised using box layouts.
-
-    // Sample period.
-    JLabel sampleLabel = makeLabel("Sample period (ms):", JLabel.RIGHT);
-    sampleText = makeTextField(6, new ActionListener() {
-        public void actionPerformed(ActionEvent e) { setSamplePeriod(); }
-        } );
-    updateSamplePeriod();
-
-    // Clear data.
-    JButton clearButton = makeButton("Clear data", new ActionListener() {
-        public void actionPerformed(ActionEvent e) { clearData(); }
-        } );
-
-    // Adjust X-axis zoom.
-    Box xControl = new Box(BoxLayout.Y_AXIS);
-    xLabel = makeLabel("", JLabel.CENTER);
-    final JSlider xSlider = new JSlider(JSlider.HORIZONTAL, 0, 8, graph.scale);
-    Hashtable xTable = new Hashtable();
-    for (int i = 0; i <= 8; i += 2) {
-        xTable.put(new Integer(i),
-               makeSmallLabel("" + (Graph.MIN_WIDTH << i),
-                      JLabel.CENTER));
-    }
-    xSlider.setLabelTable(xTable);
-    xSlider.setPaintLabels(true);
-    graph.updateXLabel();
-    graph.setScale(graph.scale);
-    xSlider.addChangeListener(new ChangeListener() {
-        public void stateChanged(ChangeEvent e) {
-            //if (!xSlider.getValueIsAdjusting())
-            graph.setScale((int)xSlider.getValue());
-        }
-        });
-    xControl.add(xLabel);
-    xControl.add(xSlider);
-
-    // Adjust Y-axis range.
-    JLabel yLabel = makeLabel("Y:", JLabel.RIGHT);
-    yText = makeTextField(12, new ActionListener() {
-        public void actionPerformed(ActionEvent e) { setYAxis(); }
-        } );
-    yText.setText(graph.gy0 + " - " + graph.gy1);
-
-    Box controls = new Box(BoxLayout.X_AXIS);
-    controls.add(clearButton);
-    controls.add(Box.createHorizontalGlue());
-    controls.add(Box.createRigidArea(new Dimension(20, 0)));
-    controls.add(sampleLabel);
-    controls.add(sampleText);
-    controls.add(Box.createHorizontalGlue());
-    controls.add(Box.createRigidArea(new Dimension(20, 0)));
-    controls.add(xControl);
-    controls.add(yLabel);
-    controls.add(yText);
-    main.add(controls, BorderLayout.SOUTH);
-
-    // The frame part
-    frame = new JFrame("Oscilloscope");
-    frame.setSize(main.getPreferredSize());
-    frame.getContentPane().add(main);
-    frame.setVisible(true);
-    frame.addWindowListener(new WindowAdapter() {
-        public void windowClosing(WindowEvent e) { System.exit(0); }
-        });
+       JPanel main = new JPanel(new BorderLayout());
+
+       main.setMinimumSize(new Dimension(500, 250));
+       main.setPreferredSize(new Dimension(800, 400));
+       
+       // Three panels: mote list, graph, controls
+       moteListModel = new  MoteTableModel();
+       JTable moteList = new JTable(moteListModel);
+       moteList.setDefaultRenderer(Color.class, new MoteColor());
+       moteList.setDefaultEditor(Color.class, 
+                                 new ColorCellEditor("Pick Mote Color"));
+       moteList.setPreferredScrollableViewportSize(new Dimension(100, 400));
+       JScrollPane motePanel = new JScrollPane();
+       motePanel.getViewport().add(moteList, null);
+       main.add(motePanel, BorderLayout.WEST);
+       
+       graph = new Graph(this);
+       main.add(graph, BorderLayout.CENTER);
+       
+       // Controls. Organised using box layouts.
+       
+       // Sample period.
+       JLabel sampleLabel = makeLabel("Sample period (ms):", JLabel.RIGHT);
+       sampleText = makeTextField(6, new ActionListener() {
+               public void actionPerformed(ActionEvent e) { setSamplePeriod(); }
+           } );
+       updateSamplePeriod();
+       
+       // Clear data.
+       JButton clearButton = makeButton("Clear data", new ActionListener() {
+               public void actionPerformed(ActionEvent e) { clearData(); }
+           } );
+       
+       // Adjust X-axis zoom.
+       Box xControl = new Box(BoxLayout.Y_AXIS);
+       xLabel = makeLabel("", JLabel.CENTER);
+       final JSlider xSlider = new JSlider(JSlider.HORIZONTAL, 0, 8, graph.scale);
+       Hashtable<Integer, JLabel> xTable = new Hashtable<Integer, JLabel>();
+       for (int i = 0; i <= 8; i += 2) {
+           xTable.put(new Integer(i),
+                      makeSmallLabel("" + (Graph.MIN_WIDTH << i),
+                                     JLabel.CENTER));
+       }
+       xSlider.setLabelTable(xTable);
+       xSlider.setPaintLabels(true);
+       graph.updateXLabel();
+       graph.setScale(graph.scale);
+       xSlider.addChangeListener(new ChangeListener() {
+               public void stateChanged(ChangeEvent e) {
+                   //if (!xSlider.getValueIsAdjusting())
+                   graph.setScale((int)xSlider.getValue());
+               }
+           });
+       xControl.add(xLabel);
+       xControl.add(xSlider);
+       
+       // Adjust Y-axis range.
+       JLabel yLabel = makeLabel("Y:", JLabel.RIGHT);
+       yText = makeTextField(12, new ActionListener() {
+               public void actionPerformed(ActionEvent e) { setYAxis(); }
+           } );
+       yText.setText(graph.gy0 + " - " + graph.gy1);
+       
+       Box controls = new Box(BoxLayout.X_AXIS);
+       controls.add(clearButton);
+       controls.add(Box.createHorizontalGlue());
+       controls.add(Box.createRigidArea(new Dimension(20, 0)));
+       controls.add(sampleLabel);
+       controls.add(sampleText);
+       controls.add(Box.createHorizontalGlue());
+       controls.add(Box.createRigidArea(new Dimension(20, 0)));
+       controls.add(xControl);
+       controls.add(yLabel);
+       controls.add(yText);
+       main.add(controls, BorderLayout.SOUTH);
+
+       // The frame part
+       frame = new JFrame("Oscilloscope");
+       frame.setSize(main.getPreferredSize());
+       frame.getContentPane().add(main);
+       frame.setVisible(true);
+       frame.addWindowListener(new WindowAdapter() {
+               public void windowClosing(WindowEvent e) { System.exit(0); }
+           });
     }
 
     /* User operation: clear data */
     void clearData() {
-    synchronized (parent) {
-        moteListModel.clear();
-        parent.clear();
-        graph.newData();
-    }
+       synchronized (parent) {
+           moteListModel.clear();
+           parent.clear();
+           graph.newData();
+       }
     }
 
     /* User operation: set Y-axis range. */
     void setYAxis() {
-    String val = yText.getText();
-
-    try {
-        int dash = val.indexOf('-');
-        if (dash >= 0) {
-        String min = val.substring(0, dash).trim();
-        String max = val.substring(dash + 1).trim();
-
-        if (!graph.setYAxis(Integer.parseInt(min), Integer.parseInt(max))) {
-            error("Invalid range " 
-                      + min 
-                      + " - " 
-                      + max 
-                      + " (expected values between 0 and 65535)");
-        }
-        return;
-        }
-    }
-    catch (NumberFormatException e) { }
-    error("Invalid range " + val + " (expected NN-MM)");
+       String val = yText.getText();
+
+       try {
+           int dash = val.indexOf('-');
+           if (dash >= 0) {
+               String min = val.substring(0, dash).trim();
+               String max = val.substring(dash + 1).trim();
+
+               if (!graph.setYAxis(Integer.parseInt(min), Integer.parseInt(max))) {
+                   error("Invalid range " 
+                         + min 
+                         + " - " 
+                         + max 
+                         + " (expected values between 0 and 65535)");
+               }
+               return;
+           }
+       }
+       catch (NumberFormatException e) { }
+       error("Invalid range " + val + " (expected NN-MM)");
     }
 
     /* User operation: set sample period. */
     void setSamplePeriod() {
-    String periodS = sampleText.getText().trim();
-    try {
-        int newPeriod = Integer.parseInt(periodS);
-        if (parent.setInterval(newPeriod)) {
-            return;
-        }
-    }
-    catch (NumberFormatException e) { }
-    error("Invalid sample period " + periodS);
+       String periodS = sampleText.getText().trim();
+       try {
+           int newPeriod = Integer.parseInt(periodS);
+           if (parent.setInterval(newPeriod)) {
+               return;
+           }
+       }
+       catch (NumberFormatException e) { }
+       error("Invalid sample period " + periodS);
     }
 
     /* Notification: sample period changed. */
     void updateSamplePeriod() {
-    sampleText.setText("" + parent.interval);
+       sampleText.setText("" + parent.interval);
     }
 
     /* Notification: new node. */
     void newNode(int nodeId) {
-    moteListModel.newNode(nodeId);
+       moteListModel.newNode(nodeId);
     }
 
     /* Notification: new data. */
     void newData() {
-    graph.newData();
+       graph.newData();
     }
 
     void error(String msg) {
-    JOptionPane.showMessageDialog(frame, msg, "Error",
-                      JOptionPane.ERROR_MESSAGE);
+       JOptionPane.showMessageDialog(frame, msg, "Error",
+                                     JOptionPane.ERROR_MESSAGE);
     }
 }
diff --git a/apps/Oscilloscope/oscilloscope.py b/apps/Oscilloscope/oscilloscope.py
new file mode 100644 (file)
index 0000000..3b881ad
--- /dev/null
@@ -0,0 +1,29 @@
+#!/usr/bin/env python
+
+import sys
+import tos
+
+AM_OSCILLOSCOPE = 0x93
+
+class OscilloscopeMsg(tos.Packet):
+    def __init__(self, packet = None):
+        tos.Packet.__init__(self,
+                            [('version',  'int', 2),
+                             ('interval', 'int', 2),
+                             ('id',       'int', 2),
+                             ('count',    'int', 2),
+                             ('readings', 'blob', None)],
+                            packet)
+if '-h' in sys.argv:
+    print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:57600"
+    sys.exit()
+
+am = tos.AM()
+
+while True:
+    p = am.read()
+    if p and p.type == AM_OSCILLOSCOPE:
+        msg = OscilloscopeMsg(p.data)
+        print msg.id, msg.count, [i<<8 | j for (i,j) in zip(msg.readings[::2], msg.readings[1::2])]
+        #print msg
+
index 3a2c898a588659393b54550158ed6b47b7786841..175d2a1ad34807f22aedcc8a1b8a2baec6e9f427 100644 (file)
@@ -34,7 +34,7 @@
   *
   * @author Cory Sharp <cssharp@eecs.berkeley.edu>
   */
-module PowerupC
+module PowerupC @safe()
 {
   uses interface Boot;
   uses interface Leds;
index 0a8e2eb9d7aba8fdebeb7bdd8cf56a2f1be36a4b..5cab01d6fcbbf92f2a0428ac822b562ef8da3420 100644 (file)
@@ -1,5 +1,6 @@
 COMPONENT=RadioCountToLedsAppC
 BUILD_EXTRA_DEPS = RadioCountMsg.py RadioCountMsg.class
+CLEAN_EXTRA = RadioCountMsg.py RadioCountMsg.class RadioCountMsg.java
 
 RadioCountMsg.py: RadioCountToLeds.h
        mig python -target=$(PLATFORM) $(CFLAGS) -python-classname=RadioCountMsg RadioCountToLeds.h radio_count_msg -o $@
index 2762d59da96f001707dec14efdd11ff18d77c63e..dd8710b2dde67fd34de3d4e526cff89f2fcb7da6 100644 (file)
@@ -43,7 +43,7 @@
  * @date   June 6 2005
  */
 
-module RadioSenseToLedsC {
+module RadioSenseToLedsC @safe(){
   uses {
     interface Leds;
     interface Boot;
diff --git a/apps/TCPEcho/HttpdP.nc b/apps/TCPEcho/HttpdP.nc
new file mode 100644 (file)
index 0000000..26b1046
--- /dev/null
@@ -0,0 +1,152 @@
+
+module HttpdP {
+  uses {
+    interface Leds;
+    interface Boot;
+    interface Tcp;
+  }
+} implementation {
+
+  static char *http_okay = "HTTP/1.0 200 OK\r\n\r\n";
+  static int http_okay_len = 19;
+
+  enum {
+    S_IDLE,
+    S_CONNECTED,
+    S_REQUEST_PRE,
+    S_REQUEST,
+    S_HEADER,
+    S_BODY,
+  };
+
+  enum {
+    HTTP_GET,
+    HTTP_POST,
+  };
+
+  void process_request(int verb, char *request, int len) {
+    char reply[24];
+    memcpy(reply, "led0: 0 led1: 0 led2: 0\n", 24);
+
+    printfUART("request: '%s'\n", request);
+
+    if (len >= 10 &&
+        request[0] == '/' &&
+        request[1] == 'r' &&
+        request[2] == 'e' &&
+        request[3] == 'a' &&
+        request[4] == 'd' &&
+        request[5] == '/') {
+      if (request[6] == 'l' &&
+          request[7] == 'e' &&
+          request[8] == 'd' &&
+          request[9] == 's') {
+        uint8_t bitmap = call Leds.get();
+        call Tcp.send(http_okay, http_okay_len);
+        if (bitmap & 1) reply[6] = '1';
+        if (bitmap & 2) reply[14] = '1';
+        if (bitmap & 4) reply[22] = '1';
+        call Tcp.send(reply, 24);
+      }
+    }
+    call Tcp.close();
+  }
+
+  int http_state;
+  int req_verb;
+  char request_buf[150], *request;
+  char tcp_buf[100];
+
+  event void Boot.booted() {
+    http_state = S_IDLE;
+    call Tcp.bind(80);
+  }
+
+  event bool Tcp.accept(struct sockaddr_in6 *from, 
+                            void **tx_buf, int *tx_buf_len) {
+    if (http_state == S_IDLE) {
+      http_state = S_CONNECTED;
+      *tx_buf = tcp_buf;
+      *tx_buf_len = 100;
+      return TRUE;
+    }
+    printfUART("rejecting connection\n");
+    return FALSE;
+  }
+  event void Tcp.connectDone(error_t e) {
+    
+  }
+  event void Tcp.recv(void *payload, uint16_t len) {
+    static int crlf_pos;
+    char *msg = payload;
+    switch (http_state) {
+    case S_CONNECTED:
+      crlf_pos = 0;
+      request = request_buf;
+      if (len < 3) {
+        call Tcp.close();
+        return;
+      }
+      if (msg[0] == 'G') {
+        req_verb = HTTP_GET;
+        msg += 3;
+        len -= 3;
+      }
+      http_state = S_REQUEST_PRE;
+    case S_REQUEST_PRE:
+      while (len > 0 && *msg == ' ') {
+        len--; msg++;
+      }
+      if (len == 0) break;
+      http_state = S_REQUEST;
+    case S_REQUEST:
+      while (len > 0 && *msg != ' ') {
+        *request++ = *msg++;
+        len--;
+      }
+      if (len == 0) break;
+      *request++ = '\0';
+      http_state = S_HEADER;
+    case S_HEADER:
+      while (len > 0) {
+        switch (crlf_pos) {
+        case 0:
+        case 2:
+          if (*msg == '\r') crlf_pos ++;
+          else if (*msg == '\n') crlf_pos += 2;
+          else crlf_pos = 0;
+          break;
+        case 1:
+        case 3:
+          if (*msg == '\n') crlf_pos ++;
+          else crlf_pos = 0;
+          break;
+        }
+        len--; msg++;
+        // if crlf == 2, we just finished a header line.  you know.  fyi.
+        if (crlf_pos == 4) {
+          http_state = S_BODY;
+          process_request(req_verb, request_buf, request - request_buf - 1);
+          break;
+        } 
+      }
+    if (crlf_pos < 4) break;
+
+    case S_BODY:
+      // len might be zero here... just a note.
+    default:
+      call Tcp.close();
+    }
+  }
+
+  event void Tcp.closed(error_t e) {
+    call Leds.led2Toggle();
+
+    call Tcp.bind(80);
+    http_state = S_IDLE;
+  }
+
+  event void Tcp.acked() {
+
+  }
+}
diff --git a/apps/TCPEcho/Makefile b/apps/TCPEcho/Makefile
new file mode 100644 (file)
index 0000000..a8a9101
--- /dev/null
@@ -0,0 +1,26 @@
+COMPONENT=TCPEchoC
+
+# uncomment this for network programming support
+# BOOTLOADER=tosboot
+
+# radio opts
+CFLAGS += -DCC2420_DEF_CHANNEL=15
+# CFLAGS += -DCC2420_DEF_RFPOWER=4
+
+
+# CFLAGS += -DNO_LIB6LOWPAN_ASCII
+
+# if this is set, motes will send debugging information to the address
+# listed.
+# CFLAGS += -DREPORT_DEST=\"2001:470:1f04:56d::64\"
+
+# sim/test harness
+# CFLAGS += -I../IPBaseStation
+# CFLAGS += -DDBG_TRACK_FLOWS -DDBG_FLOWS_REPORT
+
+# printf debugs.  works only on telosb/tmote sky
+# CFLAGS += -DPRINTFUART_ENABLED
+
+
+include $(MAKERULES)
+
diff --git a/apps/TCPEcho/README b/apps/TCPEcho/README
new file mode 100644 (file)
index 0000000..4d6e1d6
--- /dev/null
@@ -0,0 +1,15 @@
+
+A simple application which verifies the 6loWPAN stack is functioning
+correctly.  A mote running this will respond to ICMP Echo requests
+(0x80), and provide a UDP echo service on port 7 (a la rfc862).
+
+It also provides a TCP echo service on port 7, and a simple HTTP
+server on port 80.  The only resource supported is '/read/leds'.  This
+functionality can be used to verify that the TCP stack is functional.
+
+To build, use the 'blip' make target extra.  IE, 
+
+$ make <platform> blip ...
+
+For more information on setting up an IPv6 network, please see the tutorial:
+http://docs.tinyos.net/index.php/BLIP_Tutorial
diff --git a/apps/TCPEcho/TCPEchoC.nc b/apps/TCPEcho/TCPEchoC.nc
new file mode 100644 (file)
index 0000000..7f9e28f
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <6lowpan.h>
+
+configuration TCPEchoC {
+
+} implementation {
+  components MainC, LedsC;
+  components TCPEchoP;
+
+  TCPEchoP.Boot -> MainC;
+  TCPEchoP.Leds -> LedsC;
+
+  components new TimerMilliC();
+  components IPDispatchC;
+
+  TCPEchoP.RadioControl -> IPDispatchC;
+  components new UdpSocketC() as Echo,
+    new UdpSocketC() as Status;
+  TCPEchoP.Echo -> Echo;
+
+  components new TcpSocketC() as TcpEcho;
+  TCPEchoP.TcpEcho -> TcpEcho;
+
+  components new TcpSocketC() as TcpWeb, HttpdP;
+  HttpdP.Boot -> MainC;
+  HttpdP.Leds -> LedsC;
+  HttpdP.Tcp -> TcpWeb;
+
+  TCPEchoP.Status -> Status;
+
+  TCPEchoP.StatusTimer -> TimerMilliC;
+
+  components UdpC;
+
+  TCPEchoP.IPStats -> IPDispatchC.IPStats;
+  TCPEchoP.RouteStats -> IPDispatchC.RouteStats;
+  TCPEchoP.ICMPStats -> IPDispatchC.ICMPStats;
+  TCPEchoP.UDPStats -> UdpC;
+
+  components RandomC;
+  TCPEchoP.Random -> RandomC;
+
+  components UDPShellC;
+}
diff --git a/apps/TCPEcho/TCPEchoP.nc b/apps/TCPEcho/TCPEchoP.nc
new file mode 100644 (file)
index 0000000..4386089
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <IPDispatch.h>
+#include <lib6lowpan.h>
+#include <ip.h>
+#include <lib6lowpan.h>
+#include <ip.h>
+
+#include "UDPReport.h"
+#include "PrintfUART.h"
+
+#define REPORT_PERIOD 75L
+
+module TCPEchoP {
+  uses {
+    interface Boot;
+    interface SplitControl as RadioControl;
+
+    interface UDP as Echo;
+    interface UDP as Status;
+    interface Tcp as TcpEcho;
+
+    interface Leds;
+    
+    interface Timer<TMilli> as StatusTimer;
+   
+    interface Statistics<ip_statistics_t> as IPStats;
+    interface Statistics<route_statistics_t> as RouteStats;
+    interface Statistics<icmp_statistics_t> as ICMPStats;
+    interface Statistics<udp_statistics_t> as UDPStats;
+
+    interface Random;
+
+  }
+
+} implementation {
+
+  bool timerStarted;
+  nx_struct udp_report stats;
+  struct sockaddr_in6 route_dest;
+
+#ifndef SIM
+#define CHECK_NODE_ID
+#else
+#define CHECK_NODE_ID if (TOS_NODE_ID == BASESTATION_ID) return
+#endif
+
+  event void Boot.booted() {
+    CHECK_NODE_ID;
+    call RadioControl.start();
+    timerStarted = FALSE;
+
+    call IPStats.clear();
+    call RouteStats.clear();
+    call ICMPStats.clear();
+    printfUART_init();
+
+
+#ifdef REPORT_DEST
+    route_dest.sin6_port = hton16(7000);
+    inet_pton6(REPORT_DEST, &route_dest.sin6_addr);
+    call StatusTimer.startOneShot(call Random.rand16() % (1024 * REPORT_PERIOD));
+#endif
+
+    dbg("Boot", "booted: %i\n", TOS_NODE_ID);
+    call Echo.bind(7);
+    call TcpEcho.bind(7);
+    call Status.bind(7001);
+  }
+
+  event void RadioControl.startDone(error_t e) {
+
+  }
+
+  event void RadioControl.stopDone(error_t e) {
+
+  }
+
+  event void Status.recvfrom(struct sockaddr_in6 *from, void *data, 
+                             uint16_t len, struct ip_metadata *meta) {
+
+  }
+
+  event void Echo.recvfrom(struct sockaddr_in6 *from, void *data, 
+                           uint16_t len, struct ip_metadata *meta) {
+    CHECK_NODE_ID;
+    call Echo.sendto(from, data, len);
+  }
+
+  enum {
+    STATUS_SIZE = sizeof(ip_statistics_t) + 
+    sizeof(route_statistics_t) +
+    sizeof(icmp_statistics_t) + sizeof(udp_statistics_t),
+  };
+
+
+  event void StatusTimer.fired() {
+
+    if (!timerStarted) {
+      call StatusTimer.startPeriodic(1024 * REPORT_PERIOD);
+      timerStarted = TRUE;
+    }
+
+    stats.seqno++;
+    stats.sender = TOS_NODE_ID;
+
+    call IPStats.get(&stats.ip);
+    call RouteStats.get(&stats.route);
+    call ICMPStats.get(&stats.icmp);
+    call UDPStats.get(&stats.udp);
+
+    call Status.sendto(&route_dest, &stats, sizeof(stats));
+  }
+
+  /* 
+   * Example code for setting up a TCP echo socket.
+   */
+
+  bool sock_connected = FALSE;
+  char tcp_buf[150];
+
+  event bool TcpEcho.accept(struct sockaddr_in6 *from,
+                            void **tx_buf, int *tx_buf_len) {
+    *tx_buf = tcp_buf;
+    *tx_buf_len = 150;
+    return TRUE;
+  }
+  event void TcpEcho.connectDone(error_t e) {
+    
+  }
+  event void TcpEcho.recv(void *payload, uint16_t len) {
+    if (call TcpEcho.send(payload,len) != SUCCESS)
+      call Leds.led2Toggle();
+  }
+  event void TcpEcho.closed(error_t e) {
+    call Leds.led0Toggle();
+    call TcpEcho.bind(7);
+  }
+  event void TcpEcho.acked() {}
+
+}
diff --git a/apps/TCPEcho/UDPReport.h b/apps/TCPEcho/UDPReport.h
new file mode 100644 (file)
index 0000000..2efaaa0
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _UDPREPORT_H
+#define _UDPREPORT_H
+
+#include <Statistics.h>
+
+nx_struct udp_report {
+  nx_uint16_t seqno;
+  nx_uint16_t sender;
+  ip_statistics_t    ip;
+  udp_statistics_t   udp;
+  icmp_statistics_t  icmp;
+  route_statistics_t route;
+} ;
+
+#endif
diff --git a/apps/UDPEcho/Makefile b/apps/UDPEcho/Makefile
new file mode 100644 (file)
index 0000000..5db98c8
--- /dev/null
@@ -0,0 +1,30 @@
+COMPONENT=UDPEchoC
+
+# uncomment this for network programming support
+# BOOTLOADER=tosboot
+
+CFLAGS += -DCC2420_DEF_CHANNEL=15
+CFLAGS += -DRF230_DEF_CHANNEL=15
+# CFLAGS += -DCC2420_DEF_RFPOWER=4
+
+# disables support for the AM stack, which somewhat reduces code size
+# and compresses packet formats.  If you want to use other tinyos
+# protocols which are AM-based, you should not include this.
+CFLAGS += -DIEEE154FRAMES_ENABLED
+
+
+# lib6lowpan contains inet_ntop6 and inet_pton6 to process ascii
+# representations of IPv6 addresses.  You can remove them to save some
+# code if you don't use them
+# CFLAGS += -DNO_LIB6LOWPAN_ASCII
+
+# if this is set, motes will send debugging information to the address
+# listed.
+# CFLAGS += -DREPORT_DEST=\"2001:470:1f04:56d::64\"
+
+# printf debugs.  works only on telosb/tmote sky
+# CFLAGS += -DPRINTFUART_ENABLED
+
+
+include $(MAKERULES)
+
diff --git a/apps/UDPEcho/Makefile.local b/apps/UDPEcho/Makefile.local
new file mode 100644 (file)
index 0000000..a911f10
--- /dev/null
@@ -0,0 +1,32 @@
+# -*- makefile -*-
+
+SOURCES=$(LOWPAN_ROOT)/support/sdk/c/lib6lowpan/lib6lowpan.c  \
+       $(LOWPAN_ROOT)/support/sdk/c/lib6lowpan/lib6lowpanIP.c \
+       $(LOWPAN_ROOT)/support/sdk/c/lib6lowpan/lib6lowpanFrag.c \
+       $(LOWPAN_ROOT)/support/sdk/c/lib6lowpan/in_cksum.c \
+       $(LOWPAN_ROOT)/support/sdk/c/lib6lowpan/ip_malloc.c \
+       $(LOWPAN_ROOT)/tos/lib/net/b6lowpan/table.c
+OBJS=$(SOURCES:%.c=%.o)
+
+remake: $(OBJS)
+       make micaz sim-sf lowpan
+       g++ -shared -fPIC  simbuild/micaz/pytossim.o simbuild/micaz/sim.o simbuild/micaz/tossim.o simbuild/micaz/c-support.o simbuild/micaz/c-sf.o simbuild/micaz/sf.o simbuild/micaz/throttle.o $(OBJS) -lstdc++  -lm -o _TOSSIMmodule.so
+       make -f Makefile.local cppdriver
+
+cppdriver:
+       g++ -g -c -o sim/Driver.o sim/Driver.c -I$(TOSROOT)/tos/lib/tossim/
+       g++ -o sim/Driver sim/Driver.o simbuild/micaz/tossim.o simbuild/micaz/sim.o simbuild/micaz/c-support.o simbuild/micaz/c-sf.o simbuild/micaz/sf.o simbuild/micaz/throttle.o $(OBJS)
+# simbuild/micaz/c-sf.o       simbuild/micaz/pytossim.o  simbuild/micaz/sim.o       simbuild/micaz/tossim.o
+# simbuild/micaz/c-support.o  simbuild/micaz/sf.o        simbuild/micaz/throttle.o
+
+
+
+clean:
+       rm $(OBJS)
+
+%.o: %.c
+       $(CC) -c -fPIC -o $@ $<
+
+msg:   
+       mig -DMIG -I$(LOWPAN_ROOT)/tos/lib/net/blip -I$(TOSROOT)/tos/chips/cc2420 -I$(LOWPAN_ROOT)/support/sdk/c/blip/include  python -python-classname=UdpReport UDPReport.h udp_report -o util/UdpReport.py
+       mig -DMIG -I$(LOWPAN_ROOT)/tos/lib/net/blip -I$(TOSROOT)/tos/chips/cc2420 -I$(LOWPAN_ROOT)/support/sdk/c/blip/include  python -python-classname=TestDriverMsg TestDriver.h testdriver_msg -o util/TestDriverMsg.py
diff --git a/apps/UDPEcho/NodeConnectivity/NodeConnectivity.nc b/apps/UDPEcho/NodeConnectivity/NodeConnectivity.nc
new file mode 100644 (file)
index 0000000..c106615
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+// For conversion of topology from .nss to motelab
+// See NodeConnectivityM.nc 
+
+interface NodeConnectivity {
+  command int8_t mapping(uint16_t moteid);
+  command bool connected(uint16_t srcnode, uint16_t dstnode);
+}
diff --git a/apps/UDPEcho/NodeConnectivity/TestbedConnectivityM.nc b/apps/UDPEcho/NodeConnectivity/TestbedConnectivityM.nc
new file mode 100644 (file)
index 0000000..643bf2e
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+// Filename: NodeConnectivityM.nc
+// Generated on Wed Jun 11 19:54:54 UTC 2008
+
+// Created by createMotelabTopology.pl
+
+module TestbedConnectivityM {
+  provides {
+    interface NodeConnectivity;
+  }
+} implementation {
+  uint8_t connectivity[8][8] =
+  {
+    { 1, 1, 0, 0, 0, 0, 0, 0 },
+    { 1, 1, 1, 0, 0, 0, 0, 0 },
+    { 0, 1, 1, 1, 0, 0, 0, 0 },
+    { 0, 0, 1, 1, 1, 0, 0, 0 },
+    { 0, 0, 0, 1, 1, 1, 0, 0 },
+    { 0, 0, 0, 0, 1, 1, 1, 0 },
+    { 0, 0, 0, 0, 0, 1, 1, 1 },
+    { 0, 0, 0, 0, 0, 0, 1, 1 }
+  };
+  uint16_t mapping[8] = { 100, 101, 102, 37, 35, 33, 32, 106 };
+  
+  command int8_t NodeConnectivity.mapping(uint16_t moteid) {
+    uint8_t i;
+    for (i = 0; i < 8; i++) {
+      if (mapping[i] == moteid) {
+        return i;
+      }
+    }
+    return -1;
+  }
+
+  command bool NodeConnectivity.connected(uint16_t srcnode, uint16_t dstnode) {
+    int8_t src = call NodeConnectivity.mapping(srcnode);
+    int8_t dst = call NodeConnectivity.mapping(dstnode);
+
+    if ((src == -1) ||
+        (dst == -1)) {
+      return FALSE;
+    }
+
+    if (connectivity[src][dst] == 1) {
+      return TRUE;
+    } else {
+      return FALSE;
+    }
+  }
+}
diff --git a/apps/UDPEcho/NodeConnectivity/createNodeConnectivityM.pl b/apps/UDPEcho/NodeConnectivity/createNodeConnectivityM.pl
new file mode 100644 (file)
index 0000000..fdf9e16
--- /dev/null
@@ -0,0 +1,167 @@
+#!/usr/bin/perl
+
+# FileName:    createMotelabTopology.pl 
+# Date:        December 31, 2004
+#
+# Description: Converts a TOSSIM .nss (topology) file into Motelab format
+# Usage:  ./createMotelabTopology.pl  .nssfile     
+
+# Input:  A TOSSIM .nss topology file
+# Output: A nesc file containing a 2D array that represents 
+#         the latency for each node and a func that returns true or false
+#         as to whether that node can communicate with other nodes
+
+
+use strict;
+
+######################
+#                    #
+#  Parse Parameters  #
+#                    #
+######################
+
+if ( 2 > @ARGV ) {
+    die "Usage: ./createMotelabTopology <mapfile(see exampleMap.txt as a sample)>  <.nss file> ";
+}
+
+#######################
+#                     #
+#  Open file handles  #
+#                     #
+#######################
+
+open(INPUT_MAP,  "$ARGV[0]")
+    or die "Unable to open input file $ARGV[0] ($!)";
+
+open(INPUT_NSS,  "$ARGV[1]")
+    or die "Unable to open input file $ARGV[1] ($!)";
+
+#########################
+#                       #
+#  Parse and store file #
+#  outputs              #
+#                       #
+#########################
+
+my @mappingArray;
+while (my @input = split(/\s+/, <INPUT_MAP>)) {
+  $mappingArray[$input[0]] = $input[1];
+}
+
+my %probHash;
+my $maxI = 0;
+my $maxJ = 0;
+
+while (my @input = split(/:/, <INPUT_NSS>)) {
+
+  # 09 Jan 2005 : GWA : Yikes, not sure about ordering here.  Also what the
+  #               .nss file includes is the bit error probability,
+  #               essentially the inverse of what we want.
+
+  $probHash{"$input[0]x$input[1]"} = (1 - $input[2]);
+  
+  if ($input[0] > $maxI) {
+    $maxI = $input[0];
+  }
+  if ($input[1] > $maxJ) {
+    $maxJ = $input[1];
+  }
+}
+
+#############################
+#                           #
+#  Write out the nesC code  #
+#                           #
+#############################
+
+my $dateString = `date`;
+print <<TOP;
+// Filename: NodeConnectivityM.nc
+// Generated on $dateString
+// Created by createMotelabTopology.pl
+
+module NodeConnectivityM {
+  provides {
+    interface NodeConnectivity;
+  }
+} implementation {
+TOP
+
+my $arrayWidth = $maxI + 1;
+my $arrayHeight = $maxJ + 1;
+my $connectivityString = <<START;
+  uint8_t connectivity[$arrayWidth][$arrayHeight] =
+  {
+START
+$connectivityString .= "    ";
+for (my $i = 0; $i <= $maxI; $i++) {
+  $connectivityString .= "{ ";
+  for (my $j = 0; $j <= $maxJ; $j++) {
+    if ($i == $j) {
+      $connectivityString .= "1";
+    } elsif (!defined($probHash{"$i" . "x" . "$j"})) {
+      $connectivityString .= "0";
+    } else {
+      $connectivityString .= $probHash{"$i" . "x" . "$j"};
+    }
+    if ($j != $maxJ) {
+      $connectivityString .= ", ";
+    }
+  }
+  $connectivityString .= " }";
+  if ($i != $maxI) {
+    $connectivityString .= ",";
+  }
+  $connectivityString .= "\n";
+  if ($i != $maxI) {
+    $connectivityString .= "    ";
+  }
+}
+$connectivityString .= <<END;
+  };
+END
+print "$connectivityString";
+
+my $mappingString = "{ ";
+my $mappingSize = @mappingArray;
+for (my $i = 0; $i < @mappingArray; $i++) {
+  $mappingString .= $mappingArray[$i];
+  if ($i != (@mappingArray - 1)) {
+    $mappingString .= ", ";
+  }
+}
+$mappingString .= " };";
+
+print <<MAPPING;
+  uint16_t mapping[$mappingSize] = $mappingString
+MAPPING
+
+print <<REALEND;
+  
+  command int8_t NodeConnectivity.mapping(uint16_t moteid) {
+    uint8_t i;
+    for (i = 0; i < $mappingSize; i++) {
+      if (mapping[i] == moteid) {
+        return i;
+      }
+    }
+    return -1;
+  }
+
+  command bool NodeConnectivity.connected(uint16_t srcnode, uint16_t dstnode) {
+    int8_t src = call NodeConnectivity.mapping(srcnode);
+    int8_t dst = call NodeConnectivity.mapping(dstnode);
+
+    if ((src == -1) ||
+        (dst == -1)) {
+      return FALSE;
+    }
+
+    if (connectivity[src][dst] == 1) {
+      return TRUE;
+    } else {
+      return FALSE;
+    }
+  }
+}
+REALEND
diff --git a/apps/UDPEcho/NodeConnectivity/exampleMap.txt b/apps/UDPEcho/NodeConnectivity/exampleMap.txt
new file mode 100644 (file)
index 0000000..ba16bfd
--- /dev/null
@@ -0,0 +1,16 @@
+0 12
+1 30
+2 24
+3 7
+4 18
+5 4
+6 28
+7 2
+8 16
+9 1
+10 22
+11 13
+12 23
+13 25
+14 26
+15 5
diff --git a/apps/UDPEcho/NodeConnectivity/testBed.nss b/apps/UDPEcho/NodeConnectivity/testBed.nss
new file mode 100644 (file)
index 0000000..b304f8b
--- /dev/null
@@ -0,0 +1,63 @@
+0:1:0.0
+0:2:1.0
+0:3:1.0
+0:4:1.0
+0:5:1.0
+0:6:1.0
+0:7:1.0
+
+1:0:0.0
+1:2:0.0
+1:3:1.0
+1:4:1.0
+1:5:1.0
+1:6:1.0
+1:7:1.0
+
+2:0:1.0
+2:1:0.0
+2:3:0.0
+2:4:1.0
+2:5:1.0
+2:6:1.0
+2:7:1.0
+
+3:0:1.0
+3:1:1.0
+3:2:0.0
+3:4:0.0
+3:5:1.0
+3:6:1.0
+3:7:1.0
+
+4:0:1.0
+4:1:1.0
+4:2:1.0
+4:3:0.0
+4:5:0.0
+4:6:1.0
+4:7:1.0
+
+5:0:1.0
+5:1:1.0
+5:2:1.0
+5:3:1.0
+5:4:0.0
+5:6:0.0
+5:7:1.0
+
+6:0:1.0
+6:1:1.0
+6:2:1.0
+6:3:1.0
+6:4:1.0
+6:5:0.0
+6:7:0.0
+
+7:0:1.0
+7:1:1.0
+7:2:1.0
+7:3:1.0
+7:4:1.0
+7:6:0.0
+
diff --git a/apps/UDPEcho/NodeConnectivity/testBedMap.txt b/apps/UDPEcho/NodeConnectivity/testBedMap.txt
new file mode 100644 (file)
index 0000000..66d6cdf
--- /dev/null
@@ -0,0 +1,8 @@
+0 100
+1 101
+2 102
+3 103
+4 104
+5 105
+6 106
+7 107
diff --git a/apps/UDPEcho/README b/apps/UDPEcho/README
new file mode 100644 (file)
index 0000000..efeeae7
--- /dev/null
@@ -0,0 +1,11 @@
+
+A simple application which verifies the 6loWPAN stack is functioning
+correctly.  A mote running this will respond to ICMP Echo requests
+(0x80), and provide a UDP echo service on port 7 (a la rfc862).
+
+To build, use the 'blip' make target extra.  IE, 
+
+$ make <platform> blip ...
+
+For more information on setting up an IPv6 network, please see the tutorial:
+http://docs.tinyos.net/index.php/BLIP_Tutorial
diff --git a/apps/UDPEcho/UDPEchoC.nc b/apps/UDPEcho/UDPEchoC.nc
new file mode 100644 (file)
index 0000000..8cc47ab
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <6lowpan.h>
+#ifdef DBG_TRACK_FLOWS
+#include "TestDriver.h"
+#endif
+
+configuration UDPEchoC {
+
+} implementation {
+  components MainC, LedsC;
+  components UDPEchoP;
+
+  UDPEchoP.Boot -> MainC;
+  UDPEchoP.Leds -> LedsC;
+
+  components new TimerMilliC();
+  components IPDispatchC;
+
+  UDPEchoP.RadioControl -> IPDispatchC;
+  components new UdpSocketC() as Echo,
+    new UdpSocketC() as Status;
+  UDPEchoP.Echo -> Echo;
+
+  UDPEchoP.Status -> Status;
+
+  UDPEchoP.StatusTimer -> TimerMilliC;
+
+  components UdpC;
+  UDPEchoP.IPStats -> IPDispatchC.IPStats;
+  UDPEchoP.UDPStats -> UdpC;
+  UDPEchoP.RouteStats -> IPDispatchC.RouteStats;
+  UDPEchoP.ICMPStats -> IPDispatchC.ICMPStats;
+
+  components RandomC;
+  UDPEchoP.Random -> RandomC;
+
+  components UDPShellC;
+
+#ifdef SIM
+  components BaseStationC;
+#endif
+#ifdef DBG_TRACK_FLOWS
+  components TestDriverP, SerialActiveMessageC as Serial;
+  components ICMPResponderC, IPRoutingP;
+  TestDriverP.Boot -> MainC;
+  TestDriverP.SerialControl -> Serial;
+  TestDriverP.ICMPPing -> ICMPResponderC.ICMPPing[unique("PING")];
+  TestDriverP.CmdReceive -> Serial.Receive[AM_TESTDRIVER_MSG];
+  TestDriverP.IPRouting -> IPRoutingP;
+  TestDriverP.DoneSend -> Serial.AMSend[AM_TESTDRIVER_MSG];
+  TestDriverP.AckSend -> Serial.AMSend[AM_TESTDRIVER_ACK];
+  TestDriverP.RadioControl -> IPDispatchC;
+#endif
+#ifdef DBG_FLOWS_REPORT
+  components TrackFlowsC;
+#endif
+}
diff --git a/apps/UDPEcho/UDPEchoP.nc b/apps/UDPEcho/UDPEchoP.nc
new file mode 100644 (file)
index 0000000..eb10fc8
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <IPDispatch.h>
+#include <lib6lowpan.h>
+#include <ip.h>
+#include <lib6lowpan.h>
+#include <ip.h>
+
+#include "UDPReport.h"
+#include "PrintfUART.h"
+
+#define REPORT_PERIOD 75L
+
+module UDPEchoP {
+  uses {
+    interface Boot;
+    interface SplitControl as RadioControl;
+
+    interface UDP as Echo;
+    interface UDP as Status;
+
+    interface Leds;
+    
+    interface Timer<TMilli> as StatusTimer;
+   
+    interface Statistics<ip_statistics_t> as IPStats;
+    interface Statistics<udp_statistics_t> as UDPStats;
+    interface Statistics<route_statistics_t> as RouteStats;
+    interface Statistics<icmp_statistics_t> as ICMPStats;
+
+    interface Random;
+  }
+
+} implementation {
+
+  bool timerStarted;
+  nx_struct udp_report stats;
+  struct sockaddr_in6 route_dest;
+
+  event void Boot.booted() {
+    call RadioControl.start();
+    timerStarted = FALSE;
+
+    call IPStats.clear();
+    call RouteStats.clear();
+    call ICMPStats.clear();
+    printfUART_init();
+
+#ifdef REPORT_DEST
+    route_dest.sin6_port = hton16(7000);
+    inet_pton6(REPORT_DEST, &route_dest.sin6_addr);
+    call StatusTimer.startOneShot(call Random.rand16() % (1024 * REPORT_PERIOD));
+#endif
+
+    dbg("Boot", "booted: %i\n", TOS_NODE_ID);
+    call Echo.bind(7);
+    call Status.bind(7001);
+  }
+
+  event void RadioControl.startDone(error_t e) {
+
+  }
+
+  event void RadioControl.stopDone(error_t e) {
+
+  }
+
+  event void Status.recvfrom(struct sockaddr_in6 *from, void *data, 
+                             uint16_t len, struct ip_metadata *meta) {
+
+  }
+
+  event void Echo.recvfrom(struct sockaddr_in6 *from, void *data, 
+                           uint16_t len, struct ip_metadata *meta) {
+    call Echo.sendto(from, data, len);
+  }
+
+  event void StatusTimer.fired() {
+
+    if (!timerStarted) {
+      call StatusTimer.startPeriodic(1024 * REPORT_PERIOD);
+      timerStarted = TRUE;
+    }
+
+    stats.seqno++;
+    stats.sender = TOS_NODE_ID;
+
+    call IPStats.get(&stats.ip);
+    call UDPStats.get(&stats.udp);
+    call ICMPStats.get(&stats.icmp);
+    call RouteStats.get(&stats.route);
+
+    call Status.sendto(&route_dest, &stats, sizeof(stats));
+  }
+}
diff --git a/apps/UDPEcho/UDPReport.h b/apps/UDPEcho/UDPReport.h
new file mode 100644 (file)
index 0000000..2efaaa0
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _UDPREPORT_H
+#define _UDPREPORT_H
+
+#include <Statistics.h>
+
+nx_struct udp_report {
+  nx_uint16_t seqno;
+  nx_uint16_t sender;
+  ip_statistics_t    ip;
+  udp_statistics_t   udp;
+  icmp_statistics_t  icmp;
+  route_statistics_t route;
+} ;
+
+#endif
diff --git a/apps/UDPEcho/tests/echotest.pl b/apps/UDPEcho/tests/echotest.pl
new file mode 100644 (file)
index 0000000..30ae0d5
--- /dev/null
@@ -0,0 +1,46 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use FileHandle;
+use IPC::Open2;
+
+if (@ARGV != 1) {
+    print "Usage: echotest.pl <target ipv6>\n";
+    exit(1);
+}
+
+my $alpha = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+my $testbuf = "";
+while (length($testbuf) < 1280 - 40 - 8) {
+    $testbuf .= $alpha;
+}
+
+open2(*READER, *WRITER, "nc6 -u $ARGV[0] 7");
+
+my $trials = 0;
+while (1) {
+    my $len = int(rand(1000));
+    print $len . "\n";
+    print WRITER substr($testbuf, 0, $len) . "\n";
+
+    my $rin = '';
+    vec($rin,fileno(READER),1) = 1;
+    my $found = select($rin, undef, undef, "6");
+    if ($found == 1) {
+        my $foo;
+        sysread READER, $foo, 1280;
+        if ($foo eq $testbuf) {
+            print "WARNING: payload mismatch\n";
+        }
+    } else {
+        print "FAILURE: len: $len\n";
+    }
+
+    $trials++;
+    print "TRIAL: $trials\n";
+    sleep(.05);
+}
+# need to kill off the nc6 process
+print WRITER eof;
+
diff --git a/apps/UDPEcho/tests/seqtest.pl b/apps/UDPEcho/tests/seqtest.pl
new file mode 100755 (executable)
index 0000000..b3b170a
--- /dev/null
@@ -0,0 +1,50 @@
+#!/usr/bin/perl
+
+# make sure we don't break on any length boundaries
+
+use strict;
+use warnings;
+use FileHandle;
+use IPC::Open2;
+
+if (@ARGV != 1) {
+    print "Usage: seqtest.pl <target ipv6>\n";
+    exit(1);
+}
+
+my $alpha = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+my $testbuf = "";
+while (length($testbuf) < 1280 - 40 - 8) {
+    $testbuf .= $alpha;
+}
+
+open2(*READER, *WRITER, "nc6 -u $ARGV[0] 7");
+
+my $trials = 0;
+while (1) {
+    my $len;
+    for ($len = 1; $len < 1000; $len++) {
+        print $len . "\n";
+        print WRITER substr($testbuf, 0, $len) . "\n";
+        
+        my $rin = '';
+        vec($rin,fileno(READER),1) = 1;
+        my $found = select($rin, undef, undef, "6");
+        if ($found == 1) {
+            my $foo;
+            sysread READER, $foo, 1280;
+            if ($foo eq $testbuf) {
+                print "WARNING: payload mismatch\n";
+            }
+        } else {
+            print "FAILURE: len: $len\n";
+        }
+        
+        $trials++;
+        print "TRIAL: $trials\n";
+        sleep(.05);
+    }
+}
+# need to kill off the nc6 process
+print WRITER eof;
+
diff --git a/apps/UDPEcho/util/Listener.py b/apps/UDPEcho/util/Listener.py
new file mode 100644 (file)
index 0000000..cfe1206
--- /dev/null
@@ -0,0 +1,22 @@
+
+import socket
+import UdpReport
+import re
+import sys
+
+port = 7000
+
+if __name__ == '__main__':
+
+    s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
+    s.bind(('', port))
+
+    while True:
+        data, addr = s.recvfrom(1024)
+        if (len(data) > 0):
+
+            rpt = UdpReport.UdpReport(data=data, data_length=len(data))
+
+            print addr
+            print rpt
+
diff --git a/apps/UDPEcho/util/MySQLListener.py b/apps/UDPEcho/util/MySQLListener.py
new file mode 100644 (file)
index 0000000..4a240cf
--- /dev/null
@@ -0,0 +1,90 @@
+
+import socket
+import UdpReport
+import re
+import sys
+import MySQLdb
+
+port = 7000
+
+if __name__ == '__main__':
+    conn = MySQLdb.connect (host = "localhost",
+                            user = "b6lowpan",
+                            db = "b6lowpan")
+    cursor = conn.cursor()
+    s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
+    s.bind(('', port))
+    if len(sys.argv) < 2:
+        print "\tListener.py <tablename>"
+        sys.exit(1)
+
+    try:
+        drop = "DROP TABLE " + str(sys.argv[1])
+        cursor.execute(drop)
+    except:
+        print "Drop failed... continuing"
+
+    methods = []
+    create_table = "CREATE TABLE " + str(sys.argv[1]) + " ("
+    create_table += "ts TIMESTAMP, origin INT(4), "
+    insert = "INSERT INTO " + sys.argv[1] + " (origin, "
+
+
+    re = re.compile('^get_(.*)')
+    for method in dir(UdpReport.UdpReport):
+        result = re.search(method)
+        if result != None:
+            create_table += str(result.group(1)) + " INT(4), "
+            insert += str(result.group(1)) + ", "
+            methods.append(str(result.group(1)))
+
+    create_table = create_table[0:len(create_table) - 2]
+    insert = insert[0:len(insert) - 2]
+    create_table += ")"
+    insert += ") VALUES ("
+    print insert
+    print create_table
+
+    cursor.execute(create_table)
+
+    while True:
+        data, addr = s.recvfrom(1024)
+        if (len(data) > 0):
+
+
+            print
+            print str(len(data)) + ":", 
+            for i in data:
+                print "0x%x" % ord(i),
+            print
+            rpt = UdpReport.UdpReport(data=data, data_length=len(data))
+            addr = addr[0]
+            AA = addr.split(":")
+            print addr
+            print rpt
+
+
+            thisInsert = insert
+            thisInsert += "0x" + AA[-1] + ", "
+
+            
+
+            for m in methods:
+                try:
+                    getter = getattr(rpt, 'get_' + m, None)
+                    val = getter()
+                except:
+                    val = 0
+                if (isinstance(val, list)):
+                    val = val[0]
+                thisInsert += str(val) + ", "
+            thisInsert = thisInsert[0:len(thisInsert) - 2]
+            thisInsert += ")"
+
+            print thisInsert
+
+            cursor.execute(thisInsert)
+
+    conn.close()
+
diff --git a/apps/UDPEcho/util/UdpReport.py b/apps/UDPEcho/util/UdpReport.py
new file mode 100644 (file)
index 0000000..c42f817
--- /dev/null
@@ -0,0 +1,1452 @@
+#
+# This class is automatically generated by mig. DO NOT EDIT THIS FILE.
+# This class implements a Python interface to the 'UdpReport'
+# message type.
+#
+
+import tinyos.message.Message
+
+# The default size of this message type in bytes.
+DEFAULT_MESSAGE_SIZE = 35
+
+# The Active Message type associated with this message.
+AM_TYPE = -1
+
+class UdpReport(tinyos.message.Message.Message):
+    # Create a new UdpReport of size 35.
+    def __init__(self, data="", addr=None, gid=None, base_offset=0, data_length=35):
+        tinyos.message.Message.Message.__init__(self, data, addr, gid, base_offset, data_length)
+        self.amTypeSet(AM_TYPE)
+    
+    # Get AM_TYPE
+    def get_amType(cls):
+        return AM_TYPE
+    
+    get_amType = classmethod(get_amType)
+    
+    #
+    # Return a String representation of this message. Includes the
+    # message type name and the non-indexed field values.
+    #
+    def __str__(self):
+        s = "Message <UdpReport> \n"
+        try:
+            s += "  [ip.sent=0x%x]\n" % (self.get_ip_sent())
+        except:
+            pass
+        try:
+            s += "  [ip.forwarded=0x%x]\n" % (self.get_ip_forwarded())
+        except:
+            pass
+        try:
+            s += "  [ip.rx_drop=0x%x]\n" % (self.get_ip_rx_drop())
+        except:
+            pass
+        try:
+            s += "  [ip.tx_drop=0x%x]\n" % (self.get_ip_tx_drop())
+        except:
+            pass
+        try:
+            s += "  [ip.fw_drop=0x%x]\n" % (self.get_ip_fw_drop())
+        except:
+            pass
+        try:
+            s += "  [ip.rx_total=0x%x]\n" % (self.get_ip_rx_total())
+        except:
+            pass
+        try:
+            s += "  [ip.real_drop=0x%x]\n" % (self.get_ip_real_drop())
+        except:
+            pass
+        try:
+            s += "  [ip.hlim_drop=0x%x]\n" % (self.get_ip_hlim_drop())
+        except:
+            pass
+        try:
+            s += "  [ip.senddone_el=0x%x]\n" % (self.get_ip_senddone_el())
+        except:
+            pass
+        try:
+            s += "  [ip.fragpool=0x%x]\n" % (self.get_ip_fragpool())
+        except:
+            pass
+        try:
+            s += "  [ip.sendinfo=0x%x]\n" % (self.get_ip_sendinfo())
+        except:
+            pass
+        try:
+            s += "  [ip.sendentry=0x%x]\n" % (self.get_ip_sendentry())
+        except:
+            pass
+        try:
+            s += "  [ip.sndqueue=0x%x]\n" % (self.get_ip_sndqueue())
+        except:
+            pass
+        try:
+            s += "  [ip.encfail=0x%x]\n" % (self.get_ip_encfail())
+        except:
+            pass
+        try:
+            s += "  [ip.heapfree=0x%x]\n" % (self.get_ip_heapfree())
+        except:
+            pass
+        try:
+            s += "  [udp.total=0x%x]\n" % (self.get_udp_total())
+        except:
+            pass
+        try:
+            s += "  [udp.failed=0x%x]\n" % (self.get_udp_failed())
+        except:
+            pass
+        try:
+            s += "  [udp.seqno=0x%x]\n" % (self.get_udp_seqno())
+        except:
+            pass
+        try:
+            s += "  [udp.sender=0x%x]\n" % (self.get_udp_sender())
+        except:
+            pass
+        try:
+            s += "  [icmp.rx=0x%x]\n" % (self.get_icmp_rx())
+        except:
+            pass
+        try:
+            s += "  [route.hop_limit=0x%x]\n" % (self.get_route_hop_limit())
+        except:
+            pass
+        try:
+            s += "  [route.parent=0x%x]\n" % (self.get_route_parent())
+        except:
+            pass
+        try:
+            s += "  [route.parent_metric=0x%x]\n" % (self.get_route_parent_metric())
+        except:
+            pass
+        try:
+            s += "  [route.parent_etx=0x%x]\n" % (self.get_route_parent_etx())
+        except:
+            pass
+        return s
+
+    # Message-type-specific access methods appear below.
+
+    #
+    # Accessor methods for field: ip.sent
+    #   Field type: int
+    #   Offset (bits): 0
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'ip.sent' is signed (False).
+    #
+    def isSigned_ip_sent(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.sent' is an array (False).
+    #
+    def isArray_ip_sent(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.sent'
+    #
+    def offset_ip_sent(self):
+        return (0 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.sent'
+    #
+    def offsetBits_ip_sent(self):
+        return 0
+    
+    #
+    # Return the value (as a int) of the field 'ip.sent'
+    #
+    def get_ip_sent(self):
+        return self.getUIntElement(self.offsetBits_ip_sent(), 16, 1)
+    
+    #
+    # Set the value of the field 'ip.sent'
+    #
+    def set_ip_sent(self, value):
+        self.setUIntElement(self.offsetBits_ip_sent(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.sent'
+    #
+    def size_ip_sent(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.sent'
+    #
+    def sizeBits_ip_sent(self):
+        return 16
+    
+    #
+    # Accessor methods for field: ip.forwarded
+    #   Field type: int
+    #   Offset (bits): 16
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'ip.forwarded' is signed (False).
+    #
+    def isSigned_ip_forwarded(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.forwarded' is an array (False).
+    #
+    def isArray_ip_forwarded(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.forwarded'
+    #
+    def offset_ip_forwarded(self):
+        return (16 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.forwarded'
+    #
+    def offsetBits_ip_forwarded(self):
+        return 16
+    
+    #
+    # Return the value (as a int) of the field 'ip.forwarded'
+    #
+    def get_ip_forwarded(self):
+        return self.getUIntElement(self.offsetBits_ip_forwarded(), 16, 1)
+    
+    #
+    # Set the value of the field 'ip.forwarded'
+    #
+    def set_ip_forwarded(self, value):
+        self.setUIntElement(self.offsetBits_ip_forwarded(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.forwarded'
+    #
+    def size_ip_forwarded(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.forwarded'
+    #
+    def sizeBits_ip_forwarded(self):
+        return 16
+    
+    #
+    # Accessor methods for field: ip.rx_drop
+    #   Field type: short
+    #   Offset (bits): 32
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.rx_drop' is signed (False).
+    #
+    def isSigned_ip_rx_drop(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.rx_drop' is an array (False).
+    #
+    def isArray_ip_rx_drop(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.rx_drop'
+    #
+    def offset_ip_rx_drop(self):
+        return (32 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.rx_drop'
+    #
+    def offsetBits_ip_rx_drop(self):
+        return 32
+    
+    #
+    # Return the value (as a short) of the field 'ip.rx_drop'
+    #
+    def get_ip_rx_drop(self):
+        return self.getUIntElement(self.offsetBits_ip_rx_drop(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.rx_drop'
+    #
+    def set_ip_rx_drop(self, value):
+        self.setUIntElement(self.offsetBits_ip_rx_drop(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.rx_drop'
+    #
+    def size_ip_rx_drop(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.rx_drop'
+    #
+    def sizeBits_ip_rx_drop(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.tx_drop
+    #   Field type: short
+    #   Offset (bits): 40
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.tx_drop' is signed (False).
+    #
+    def isSigned_ip_tx_drop(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.tx_drop' is an array (False).
+    #
+    def isArray_ip_tx_drop(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.tx_drop'
+    #
+    def offset_ip_tx_drop(self):
+        return (40 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.tx_drop'
+    #
+    def offsetBits_ip_tx_drop(self):
+        return 40
+    
+    #
+    # Return the value (as a short) of the field 'ip.tx_drop'
+    #
+    def get_ip_tx_drop(self):
+        return self.getUIntElement(self.offsetBits_ip_tx_drop(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.tx_drop'
+    #
+    def set_ip_tx_drop(self, value):
+        self.setUIntElement(self.offsetBits_ip_tx_drop(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.tx_drop'
+    #
+    def size_ip_tx_drop(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.tx_drop'
+    #
+    def sizeBits_ip_tx_drop(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.fw_drop
+    #   Field type: short
+    #   Offset (bits): 48
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.fw_drop' is signed (False).
+    #
+    def isSigned_ip_fw_drop(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.fw_drop' is an array (False).
+    #
+    def isArray_ip_fw_drop(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.fw_drop'
+    #
+    def offset_ip_fw_drop(self):
+        return (48 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.fw_drop'
+    #
+    def offsetBits_ip_fw_drop(self):
+        return 48
+    
+    #
+    # Return the value (as a short) of the field 'ip.fw_drop'
+    #
+    def get_ip_fw_drop(self):
+        return self.getUIntElement(self.offsetBits_ip_fw_drop(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.fw_drop'
+    #
+    def set_ip_fw_drop(self, value):
+        self.setUIntElement(self.offsetBits_ip_fw_drop(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.fw_drop'
+    #
+    def size_ip_fw_drop(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.fw_drop'
+    #
+    def sizeBits_ip_fw_drop(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.rx_total
+    #   Field type: short
+    #   Offset (bits): 56
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.rx_total' is signed (False).
+    #
+    def isSigned_ip_rx_total(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.rx_total' is an array (False).
+    #
+    def isArray_ip_rx_total(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.rx_total'
+    #
+    def offset_ip_rx_total(self):
+        return (56 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.rx_total'
+    #
+    def offsetBits_ip_rx_total(self):
+        return 56
+    
+    #
+    # Return the value (as a short) of the field 'ip.rx_total'
+    #
+    def get_ip_rx_total(self):
+        return self.getUIntElement(self.offsetBits_ip_rx_total(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.rx_total'
+    #
+    def set_ip_rx_total(self, value):
+        self.setUIntElement(self.offsetBits_ip_rx_total(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.rx_total'
+    #
+    def size_ip_rx_total(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.rx_total'
+    #
+    def sizeBits_ip_rx_total(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.real_drop
+    #   Field type: short
+    #   Offset (bits): 64
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.real_drop' is signed (False).
+    #
+    def isSigned_ip_real_drop(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.real_drop' is an array (False).
+    #
+    def isArray_ip_real_drop(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.real_drop'
+    #
+    def offset_ip_real_drop(self):
+        return (64 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.real_drop'
+    #
+    def offsetBits_ip_real_drop(self):
+        return 64
+    
+    #
+    # Return the value (as a short) of the field 'ip.real_drop'
+    #
+    def get_ip_real_drop(self):
+        return self.getUIntElement(self.offsetBits_ip_real_drop(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.real_drop'
+    #
+    def set_ip_real_drop(self, value):
+        self.setUIntElement(self.offsetBits_ip_real_drop(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.real_drop'
+    #
+    def size_ip_real_drop(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.real_drop'
+    #
+    def sizeBits_ip_real_drop(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.hlim_drop
+    #   Field type: short
+    #   Offset (bits): 72
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.hlim_drop' is signed (False).
+    #
+    def isSigned_ip_hlim_drop(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.hlim_drop' is an array (False).
+    #
+    def isArray_ip_hlim_drop(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.hlim_drop'
+    #
+    def offset_ip_hlim_drop(self):
+        return (72 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.hlim_drop'
+    #
+    def offsetBits_ip_hlim_drop(self):
+        return 72
+    
+    #
+    # Return the value (as a short) of the field 'ip.hlim_drop'
+    #
+    def get_ip_hlim_drop(self):
+        return self.getUIntElement(self.offsetBits_ip_hlim_drop(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.hlim_drop'
+    #
+    def set_ip_hlim_drop(self, value):
+        self.setUIntElement(self.offsetBits_ip_hlim_drop(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.hlim_drop'
+    #
+    def size_ip_hlim_drop(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.hlim_drop'
+    #
+    def sizeBits_ip_hlim_drop(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.senddone_el
+    #   Field type: short
+    #   Offset (bits): 80
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.senddone_el' is signed (False).
+    #
+    def isSigned_ip_senddone_el(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.senddone_el' is an array (False).
+    #
+    def isArray_ip_senddone_el(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.senddone_el'
+    #
+    def offset_ip_senddone_el(self):
+        return (80 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.senddone_el'
+    #
+    def offsetBits_ip_senddone_el(self):
+        return 80
+    
+    #
+    # Return the value (as a short) of the field 'ip.senddone_el'
+    #
+    def get_ip_senddone_el(self):
+        return self.getUIntElement(self.offsetBits_ip_senddone_el(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.senddone_el'
+    #
+    def set_ip_senddone_el(self, value):
+        self.setUIntElement(self.offsetBits_ip_senddone_el(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.senddone_el'
+    #
+    def size_ip_senddone_el(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.senddone_el'
+    #
+    def sizeBits_ip_senddone_el(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.fragpool
+    #   Field type: short
+    #   Offset (bits): 88
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.fragpool' is signed (False).
+    #
+    def isSigned_ip_fragpool(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.fragpool' is an array (False).
+    #
+    def isArray_ip_fragpool(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.fragpool'
+    #
+    def offset_ip_fragpool(self):
+        return (88 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.fragpool'
+    #
+    def offsetBits_ip_fragpool(self):
+        return 88
+    
+    #
+    # Return the value (as a short) of the field 'ip.fragpool'
+    #
+    def get_ip_fragpool(self):
+        return self.getUIntElement(self.offsetBits_ip_fragpool(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.fragpool'
+    #
+    def set_ip_fragpool(self, value):
+        self.setUIntElement(self.offsetBits_ip_fragpool(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.fragpool'
+    #
+    def size_ip_fragpool(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.fragpool'
+    #
+    def sizeBits_ip_fragpool(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.sendinfo
+    #   Field type: short
+    #   Offset (bits): 96
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.sendinfo' is signed (False).
+    #
+    def isSigned_ip_sendinfo(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.sendinfo' is an array (False).
+    #
+    def isArray_ip_sendinfo(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.sendinfo'
+    #
+    def offset_ip_sendinfo(self):
+        return (96 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.sendinfo'
+    #
+    def offsetBits_ip_sendinfo(self):
+        return 96
+    
+    #
+    # Return the value (as a short) of the field 'ip.sendinfo'
+    #
+    def get_ip_sendinfo(self):
+        return self.getUIntElement(self.offsetBits_ip_sendinfo(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.sendinfo'
+    #
+    def set_ip_sendinfo(self, value):
+        self.setUIntElement(self.offsetBits_ip_sendinfo(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.sendinfo'
+    #
+    def size_ip_sendinfo(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.sendinfo'
+    #
+    def sizeBits_ip_sendinfo(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.sendentry
+    #   Field type: short
+    #   Offset (bits): 104
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.sendentry' is signed (False).
+    #
+    def isSigned_ip_sendentry(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.sendentry' is an array (False).
+    #
+    def isArray_ip_sendentry(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.sendentry'
+    #
+    def offset_ip_sendentry(self):
+        return (104 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.sendentry'
+    #
+    def offsetBits_ip_sendentry(self):
+        return 104
+    
+    #
+    # Return the value (as a short) of the field 'ip.sendentry'
+    #
+    def get_ip_sendentry(self):
+        return self.getUIntElement(self.offsetBits_ip_sendentry(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.sendentry'
+    #
+    def set_ip_sendentry(self, value):
+        self.setUIntElement(self.offsetBits_ip_sendentry(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.sendentry'
+    #
+    def size_ip_sendentry(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.sendentry'
+    #
+    def sizeBits_ip_sendentry(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.sndqueue
+    #   Field type: short
+    #   Offset (bits): 112
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.sndqueue' is signed (False).
+    #
+    def isSigned_ip_sndqueue(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.sndqueue' is an array (False).
+    #
+    def isArray_ip_sndqueue(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.sndqueue'
+    #
+    def offset_ip_sndqueue(self):
+        return (112 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.sndqueue'
+    #
+    def offsetBits_ip_sndqueue(self):
+        return 112
+    
+    #
+    # Return the value (as a short) of the field 'ip.sndqueue'
+    #
+    def get_ip_sndqueue(self):
+        return self.getUIntElement(self.offsetBits_ip_sndqueue(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.sndqueue'
+    #
+    def set_ip_sndqueue(self, value):
+        self.setUIntElement(self.offsetBits_ip_sndqueue(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.sndqueue'
+    #
+    def size_ip_sndqueue(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.sndqueue'
+    #
+    def sizeBits_ip_sndqueue(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.encfail
+    #   Field type: short
+    #   Offset (bits): 120
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ip.encfail' is signed (False).
+    #
+    def isSigned_ip_encfail(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.encfail' is an array (False).
+    #
+    def isArray_ip_encfail(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.encfail'
+    #
+    def offset_ip_encfail(self):
+        return (120 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.encfail'
+    #
+    def offsetBits_ip_encfail(self):
+        return 120
+    
+    #
+    # Return the value (as a short) of the field 'ip.encfail'
+    #
+    def get_ip_encfail(self):
+        return self.getUIntElement(self.offsetBits_ip_encfail(), 8, 1)
+    
+    #
+    # Set the value of the field 'ip.encfail'
+    #
+    def set_ip_encfail(self, value):
+        self.setUIntElement(self.offsetBits_ip_encfail(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.encfail'
+    #
+    def size_ip_encfail(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.encfail'
+    #
+    def sizeBits_ip_encfail(self):
+        return 8
+    
+    #
+    # Accessor methods for field: ip.heapfree
+    #   Field type: int
+    #   Offset (bits): 128
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'ip.heapfree' is signed (False).
+    #
+    def isSigned_ip_heapfree(self):
+        return False
+    
+    #
+    # Return whether the field 'ip.heapfree' is an array (False).
+    #
+    def isArray_ip_heapfree(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'ip.heapfree'
+    #
+    def offset_ip_heapfree(self):
+        return (128 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'ip.heapfree'
+    #
+    def offsetBits_ip_heapfree(self):
+        return 128
+    
+    #
+    # Return the value (as a int) of the field 'ip.heapfree'
+    #
+    def get_ip_heapfree(self):
+        return self.getUIntElement(self.offsetBits_ip_heapfree(), 16, 1)
+    
+    #
+    # Set the value of the field 'ip.heapfree'
+    #
+    def set_ip_heapfree(self, value):
+        self.setUIntElement(self.offsetBits_ip_heapfree(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'ip.heapfree'
+    #
+    def size_ip_heapfree(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'ip.heapfree'
+    #
+    def sizeBits_ip_heapfree(self):
+        return 16
+    
+    #
+    # Accessor methods for field: udp.total
+    #   Field type: int
+    #   Offset (bits): 144
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'udp.total' is signed (False).
+    #
+    def isSigned_udp_total(self):
+        return False
+    
+    #
+    # Return whether the field 'udp.total' is an array (False).
+    #
+    def isArray_udp_total(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'udp.total'
+    #
+    def offset_udp_total(self):
+        return (144 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'udp.total'
+    #
+    def offsetBits_udp_total(self):
+        return 144
+    
+    #
+    # Return the value (as a int) of the field 'udp.total'
+    #
+    def get_udp_total(self):
+        return self.getUIntElement(self.offsetBits_udp_total(), 16, 1)
+    
+    #
+    # Set the value of the field 'udp.total'
+    #
+    def set_udp_total(self, value):
+        self.setUIntElement(self.offsetBits_udp_total(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'udp.total'
+    #
+    def size_udp_total(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'udp.total'
+    #
+    def sizeBits_udp_total(self):
+        return 16
+    
+    #
+    # Accessor methods for field: udp.failed
+    #   Field type: int
+    #   Offset (bits): 160
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'udp.failed' is signed (False).
+    #
+    def isSigned_udp_failed(self):
+        return False
+    
+    #
+    # Return whether the field 'udp.failed' is an array (False).
+    #
+    def isArray_udp_failed(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'udp.failed'
+    #
+    def offset_udp_failed(self):
+        return (160 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'udp.failed'
+    #
+    def offsetBits_udp_failed(self):
+        return 160
+    
+    #
+    # Return the value (as a int) of the field 'udp.failed'
+    #
+    def get_udp_failed(self):
+        return self.getUIntElement(self.offsetBits_udp_failed(), 16, 1)
+    
+    #
+    # Set the value of the field 'udp.failed'
+    #
+    def set_udp_failed(self, value):
+        self.setUIntElement(self.offsetBits_udp_failed(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'udp.failed'
+    #
+    def size_udp_failed(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'udp.failed'
+    #
+    def sizeBits_udp_failed(self):
+        return 16
+    
+    #
+    # Accessor methods for field: udp.seqno
+    #   Field type: int
+    #   Offset (bits): 176
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'udp.seqno' is signed (False).
+    #
+    def isSigned_udp_seqno(self):
+        return False
+    
+    #
+    # Return whether the field 'udp.seqno' is an array (False).
+    #
+    def isArray_udp_seqno(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'udp.seqno'
+    #
+    def offset_udp_seqno(self):
+        return (176 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'udp.seqno'
+    #
+    def offsetBits_udp_seqno(self):
+        return 176
+    
+    #
+    # Return the value (as a int) of the field 'udp.seqno'
+    #
+    def get_udp_seqno(self):
+        return self.getUIntElement(self.offsetBits_udp_seqno(), 16, 1)
+    
+    #
+    # Set the value of the field 'udp.seqno'
+    #
+    def set_udp_seqno(self, value):
+        self.setUIntElement(self.offsetBits_udp_seqno(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'udp.seqno'
+    #
+    def size_udp_seqno(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'udp.seqno'
+    #
+    def sizeBits_udp_seqno(self):
+        return 16
+    
+    #
+    # Accessor methods for field: udp.sender
+    #   Field type: int
+    #   Offset (bits): 192
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'udp.sender' is signed (False).
+    #
+    def isSigned_udp_sender(self):
+        return False
+    
+    #
+    # Return whether the field 'udp.sender' is an array (False).
+    #
+    def isArray_udp_sender(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'udp.sender'
+    #
+    def offset_udp_sender(self):
+        return (192 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'udp.sender'
+    #
+    def offsetBits_udp_sender(self):
+        return 192
+    
+    #
+    # Return the value (as a int) of the field 'udp.sender'
+    #
+    def get_udp_sender(self):
+        return self.getUIntElement(self.offsetBits_udp_sender(), 16, 1)
+    
+    #
+    # Set the value of the field 'udp.sender'
+    #
+    def set_udp_sender(self, value):
+        self.setUIntElement(self.offsetBits_udp_sender(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'udp.sender'
+    #
+    def size_udp_sender(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'udp.sender'
+    #
+    def sizeBits_udp_sender(self):
+        return 16
+    
+    #
+    # Accessor methods for field: icmp.rx
+    #   Field type: int
+    #   Offset (bits): 208
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'icmp.rx' is signed (False).
+    #
+    def isSigned_icmp_rx(self):
+        return False
+    
+    #
+    # Return whether the field 'icmp.rx' is an array (False).
+    #
+    def isArray_icmp_rx(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'icmp.rx'
+    #
+    def offset_icmp_rx(self):
+        return (208 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'icmp.rx'
+    #
+    def offsetBits_icmp_rx(self):
+        return 208
+    
+    #
+    # Return the value (as a int) of the field 'icmp.rx'
+    #
+    def get_icmp_rx(self):
+        return self.getUIntElement(self.offsetBits_icmp_rx(), 16, 1)
+    
+    #
+    # Set the value of the field 'icmp.rx'
+    #
+    def set_icmp_rx(self, value):
+        self.setUIntElement(self.offsetBits_icmp_rx(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'icmp.rx'
+    #
+    def size_icmp_rx(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'icmp.rx'
+    #
+    def sizeBits_icmp_rx(self):
+        return 16
+    
+    #
+    # Accessor methods for field: route.hop_limit
+    #   Field type: short
+    #   Offset (bits): 224
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'route.hop_limit' is signed (False).
+    #
+    def isSigned_route_hop_limit(self):
+        return False
+    
+    #
+    # Return whether the field 'route.hop_limit' is an array (False).
+    #
+    def isArray_route_hop_limit(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'route.hop_limit'
+    #
+    def offset_route_hop_limit(self):
+        return (224 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'route.hop_limit'
+    #
+    def offsetBits_route_hop_limit(self):
+        return 224
+    
+    #
+    # Return the value (as a short) of the field 'route.hop_limit'
+    #
+    def get_route_hop_limit(self):
+        return self.getUIntElement(self.offsetBits_route_hop_limit(), 8, 1)
+    
+    #
+    # Set the value of the field 'route.hop_limit'
+    #
+    def set_route_hop_limit(self, value):
+        self.setUIntElement(self.offsetBits_route_hop_limit(), 8, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'route.hop_limit'
+    #
+    def size_route_hop_limit(self):
+        return (8 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'route.hop_limit'
+    #
+    def sizeBits_route_hop_limit(self):
+        return 8
+    
+    #
+    # Accessor methods for field: route.parent
+    #   Field type: int
+    #   Offset (bits): 232
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'route.parent' is signed (False).
+    #
+    def isSigned_route_parent(self):
+        return False
+    
+    #
+    # Return whether the field 'route.parent' is an array (False).
+    #
+    def isArray_route_parent(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'route.parent'
+    #
+    def offset_route_parent(self):
+        return (232 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'route.parent'
+    #
+    def offsetBits_route_parent(self):
+        return 232
+    
+    #
+    # Return the value (as a int) of the field 'route.parent'
+    #
+    def get_route_parent(self):
+        return self.getUIntElement(self.offsetBits_route_parent(), 16, 1)
+    
+    #
+    # Set the value of the field 'route.parent'
+    #
+    def set_route_parent(self, value):
+        self.setUIntElement(self.offsetBits_route_parent(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'route.parent'
+    #
+    def size_route_parent(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'route.parent'
+    #
+    def sizeBits_route_parent(self):
+        return 16
+    
+    #
+    # Accessor methods for field: route.parent_metric
+    #   Field type: int
+    #   Offset (bits): 248
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'route.parent_metric' is signed (False).
+    #
+    def isSigned_route_parent_metric(self):
+        return False
+    
+    #
+    # Return whether the field 'route.parent_metric' is an array (False).
+    #
+    def isArray_route_parent_metric(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'route.parent_metric'
+    #
+    def offset_route_parent_metric(self):
+        return (248 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'route.parent_metric'
+    #
+    def offsetBits_route_parent_metric(self):
+        return 248
+    
+    #
+    # Return the value (as a int) of the field 'route.parent_metric'
+    #
+    def get_route_parent_metric(self):
+        return self.getUIntElement(self.offsetBits_route_parent_metric(), 16, 1)
+    
+    #
+    # Set the value of the field 'route.parent_metric'
+    #
+    def set_route_parent_metric(self, value):
+        self.setUIntElement(self.offsetBits_route_parent_metric(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'route.parent_metric'
+    #
+    def size_route_parent_metric(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'route.parent_metric'
+    #
+    def sizeBits_route_parent_metric(self):
+        return 16
+    
+    #
+    # Accessor methods for field: route.parent_etx
+    #   Field type: int
+    #   Offset (bits): 264
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'route.parent_etx' is signed (False).
+    #
+    def isSigned_route_parent_etx(self):
+        return False
+    
+    #
+    # Return whether the field 'route.parent_etx' is an array (False).
+    #
+    def isArray_route_parent_etx(self):
+        return False
+    
+    #
+    # Return the offset (in bytes) of the field 'route.parent_etx'
+    #
+    def offset_route_parent_etx(self):
+        return (264 / 8)
+    
+    #
+    # Return the offset (in bits) of the field 'route.parent_etx'
+    #
+    def offsetBits_route_parent_etx(self):
+        return 264
+    
+    #
+    # Return the value (as a int) of the field 'route.parent_etx'
+    #
+    def get_route_parent_etx(self):
+        return self.getUIntElement(self.offsetBits_route_parent_etx(), 16, 1)
+    
+    #
+    # Set the value of the field 'route.parent_etx'
+    #
+    def set_route_parent_etx(self, value):
+        self.setUIntElement(self.offsetBits_route_parent_etx(), 16, value, 1)
+    
+    #
+    # Return the size, in bytes, of the field 'route.parent_etx'
+    #
+    def size_route_parent_etx(self):
+        return (16 / 8)
+    
+    #
+    # Return the size, in bits, of the field 'route.parent_etx'
+    #
+    def sizeBits_route_parent_etx(self):
+        return 16
+    
diff --git a/apps/UDPEcho/volumes-at45db.xml b/apps/UDPEcho/volumes-at45db.xml
new file mode 100644 (file)
index 0000000..8b22ebe
--- /dev/null
@@ -0,0 +1,6 @@
+<volume_table>
+  <volume name="GOLDENIMAGE" size="65536" base="0" />
+  <volume name="DELUGE1" size="65536"/>
+  <volume name="DELUGE2" size="65536"/>
+  <volume name="DELUGE3" size="65536"/>
+</volume_table>
\ No newline at end of file
diff --git a/apps/UDPEcho/volumes-stm25p.xml b/apps/UDPEcho/volumes-stm25p.xml
new file mode 100644 (file)
index 0000000..4210f08
--- /dev/null
@@ -0,0 +1,6 @@
+<volume_table>
+  <volume name="GOLDENIMAGE" size="65536" base="983040" />
+  <volume name="DELUGE1" size="65536"/>
+  <volume name="DELUGE2" size="65536"/>
+  <volume name="DELUGE3" size="65536"/>
+</volume_table>
\ No newline at end of file
diff --git a/apps/tests/NxFloat/.cvsignore b/apps/tests/NxFloat/.cvsignore
new file mode 100644 (file)
index 0000000..5abf788
--- /dev/null
@@ -0,0 +1,4 @@
+TestSerialMsg.java
+TestSerialMsg.class
+TestSerial.class
+build
diff --git a/apps/tests/NxFloat/Makefile b/apps/tests/NxFloat/Makefile
new file mode 100644 (file)
index 0000000..daf594a
--- /dev/null
@@ -0,0 +1,15 @@
+COMPONENT=TestSerialAppC
+BUILD_EXTRA_DEPS += TestSerial.class
+CLEAN_EXTRA = *.class TestSerialMsg.java
+
+CFLAGS += -I$(TOSDIR)/lib/T2Hack
+
+TestSerial.class: $(wildcard *.java) TestSerialMsg.java
+       javac -target 1.4 -source 1.4 *.java
+
+TestSerialMsg.java:
+       mig java -target=null $(CFLAGS) -java-classname=TestSerialMsg TestSerial.h test_serial_msg -o $@
+
+
+include $(MAKERULES)
+
diff --git a/apps/tests/NxFloat/README.txt b/apps/tests/NxFloat/README.txt
new file mode 100644 (file)
index 0000000..1b16c97
--- /dev/null
@@ -0,0 +1,29 @@
+README for NxFloat
+Author/Contact: tinyos-help@millennium.berkeley.edu
+
+Description:
+
+NxFloat is a version of the TestSerial application modified to use
+floating point numbers. It tests communication over the serial port
+and nx_float support. The java application sends packets to the serial
+port at 1Hz: the packet contains an incrementing counter. When the
+mote application receives a counter packet, it displays the bottom
+three bits on its LEDs. (This application is similar to
+RadioCountToLeds, except that it operates over the serial port.)
+Likewise, the mote also sends packets to the serial port at 1Hz, these
+packets contain a sequence number multiplied by 3.2. Upon reception of
+a packet, the java application prints the counter's value to standard
+out.
+
+Java Application Usage:
+  java TestSerial [-comm <packetsource>]
+
+  If not specified, the <packetsource> defaults to sf@localhost:9002 or
+  to your MOTECOM environment variable (if defined).
+
+Tools:
+
+Known bugs/limitations:
+
+None.
+
diff --git a/apps/tests/NxFloat/TestSerial.h b/apps/tests/NxFloat/TestSerial.h
new file mode 100644 (file)
index 0000000..6e0af1a
--- /dev/null
@@ -0,0 +1,13 @@
+
+#ifndef TEST_SERIAL_H
+#define TEST_SERIAL_H
+
+typedef nx_struct test_serial_msg {
+  nx_float counter;
+} test_serial_msg_t;
+
+enum {
+  AM_TEST_SERIAL_MSG = 0x89,
+};
+
+#endif
diff --git a/apps/tests/NxFloat/TestSerial.java b/apps/tests/NxFloat/TestSerial.java
new file mode 100644 (file)
index 0000000..873fdec
--- /dev/null
@@ -0,0 +1,106 @@
+/*                                                                     tab:4
+ * "Copyright (c) 2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY
+ * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
+ * DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * Java-side application for testing serial port communication.
+ * 
+ *
+ * @author Phil Levis <pal@cs.berkeley.edu>
+ * @date August 12 2005
+ */
+
+import java.io.IOException;
+
+import net.tinyos.message.*;
+import net.tinyos.packet.*;
+import net.tinyos.util.*;
+
+public class TestSerial implements MessageListener {
+
+  private MoteIF moteIF;
+  
+  public TestSerial(MoteIF moteIF) {
+    this.moteIF = moteIF;
+    this.moteIF.registerListener(new TestSerialMsg(), this);
+  }
+
+  public void sendPackets() {
+    int counter = 0;
+    TestSerialMsg payload = new TestSerialMsg();
+    
+    try {
+      while (true) {
+       System.out.println("Sending packet " + counter);
+       payload.set_counter(counter);
+       moteIF.send(0, payload);
+       counter++;
+       try {Thread.sleep(1000);}
+       catch (InterruptedException exception) {}
+      }
+    }
+    catch (IOException exception) {
+      System.err.println("Exception thrown when sending packets. Exiting.");
+      System.err.println(exception);
+    }
+  }
+
+  public void messageReceived(int to, Message message) {
+    TestSerialMsg msg = (TestSerialMsg)message;
+    System.out.println("Received packet sequence number " + msg.get_counter());
+  }
+  
+  private static void usage() {
+    System.err.println("usage: TestSerial [-comm <source>]");
+  }
+  
+  public static void main(String[] args) throws Exception {
+    String source = null;
+    if (args.length == 2) {
+      if (!args[0].equals("-comm")) {
+       usage();
+       System.exit(1);
+      }
+      source = args[1];
+    }
+    else if (args.length != 0) {
+      usage();
+      System.exit(1);
+    }
+    
+    PhoenixSource phoenix;
+    
+    if (source == null) {
+      phoenix = BuildSource.makePhoenix(PrintStreamMessenger.err);
+    }
+    else {
+      phoenix = BuildSource.makePhoenix(source, PrintStreamMessenger.err);
+    }
+
+    MoteIF mif = new MoteIF(phoenix);
+    TestSerial serial = new TestSerial(mif);
+    serial.sendPackets();
+  }
+
+
+}
diff --git a/apps/tests/NxFloat/TestSerialAppC.nc b/apps/tests/NxFloat/TestSerialAppC.nc
new file mode 100644 (file)
index 0000000..4383f64
--- /dev/null
@@ -0,0 +1,67 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ * Application to test that the TinyOS java toolchain can communicate
+ * with motes over the serial port. The application sends packets to
+ * the serial port at 1Hz: the packet contains an incrementing
+ * counter. When the application receives a counter packet, it
+ * displays the bottom three bits on its LEDs. This application is
+ * very similar to RadioCountToLeds, except that it operates over the
+ * serial port. There is Java application for testing the mote
+ * application: run TestSerial to print out the received packets and
+ * send packets to the mote.
+ *
+ *  @author Gilman Tolle
+ *  @author Philip Levis
+ *  
+ *  @date   Aug 12 2005
+ *
+ **/
+
+#include "TestSerial.h"
+
+configuration TestSerialAppC {}
+implementation {
+  components TestSerialC as App, LedsC, MainC;
+  components SerialActiveMessageC as AM;
+  components new TimerMilliC();
+
+  App.Boot -> MainC.Boot;
+  App.Control -> AM;
+  App.Receive -> AM.Receive[AM_TEST_SERIAL_MSG];
+  App.AMSend -> AM.AMSend[AM_TEST_SERIAL_MSG];
+  App.Leds -> LedsC;
+  App.MilliTimer -> TimerMilliC;
+  App.Packet -> AM;
+}
+
+
diff --git a/apps/tests/NxFloat/TestSerialC.nc b/apps/tests/NxFloat/TestSerialC.nc
new file mode 100644 (file)
index 0000000..3a40db6
--- /dev/null
@@ -0,0 +1,130 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ * Application to test that the TinyOS java toolchain can communicate
+ * with motes over the serial port. 
+ *
+ *  @author Gilman Tolle
+ *  @author Philip Levis
+ *  
+ *  @date   Aug 12 2005
+ *
+ **/
+
+#include "Timer.h"
+#include "TestSerial.h"
+
+module TestSerialC {
+  uses {
+    interface SplitControl as Control;
+    interface Leds;
+    interface Boot;
+    interface Receive;
+    interface AMSend;
+    interface Timer<TMilli> as MilliTimer;
+    interface Packet;
+  }
+}
+implementation {
+
+  message_t packet;
+
+  bool locked = FALSE;
+  uint16_t counter = 0;
+  
+  event void Boot.booted() {
+    call Control.start();
+  }
+  
+  event void MilliTimer.fired() {
+    counter++;
+    if (locked) {
+      return;
+    }
+    else {
+      test_serial_msg_t* rcm = (test_serial_msg_t*)call Packet.getPayload(&packet, sizeof(test_serial_msg_t));
+      if (rcm == NULL) {return;}
+      if (call Packet.maxPayloadLength() < sizeof(test_serial_msg_t)) {
+       return;
+      }
+
+      rcm->counter = counter * 3.2;
+      if (call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(test_serial_msg_t)) == SUCCESS) {
+       locked = TRUE;
+      }
+    }
+  }
+
+  event message_t* Receive.receive(message_t* bufPtr, 
+                                  void* payload, uint8_t len) {
+    if (len != sizeof(test_serial_msg_t)) {return bufPtr;}
+    else {
+      test_serial_msg_t* rcm = (test_serial_msg_t*)payload;
+      if ((int)rcm->counter & 0x1) {
+       call Leds.led0On();
+      }
+      else {
+       call Leds.led0Off();
+      }
+      if ((int)rcm->counter & 0x2) {
+       call Leds.led1On();
+      }
+      else {
+       call Leds.led1Off();
+      }
+      if ((int)rcm->counter & 0x4) {
+       call Leds.led2On();
+      }
+      else {
+       call Leds.led2Off();
+      }
+      return bufPtr;
+    }
+  }
+
+  event void AMSend.sendDone(message_t* bufPtr, error_t error) {
+    if (&packet == bufPtr) {
+      locked = FALSE;
+    }
+  }
+
+  event void Control.startDone(error_t err) {
+    if (err == SUCCESS) {
+      call MilliTimer.startPeriodic(1000);
+    }
+  }
+  event void Control.stopDone(error_t err) {}
+}
+
+
+
+
diff --git a/apps/tests/TestDhv/DhvInject.java b/apps/tests/TestDhv/DhvInject.java
new file mode 100644 (file)
index 0000000..5867b92
--- /dev/null
@@ -0,0 +1,71 @@
+
+import java.io.*;
+import net.tinyos.message.*;
+import net.tinyos.util.*;
+
+public class DhvInject implements MessageListener
+{
+    MoteIF mote;
+
+    DhvInject(DhvMsg dhvmsg) {
+        mote = new MoteIF(PrintStreamMessenger.err);
+        mote.registerListener(dhvmsg, this);
+    }
+
+    public synchronized void messageReceived(int dest_addr, Message message)
+    {
+       // do nothing for now
+    }
+
+    void sendDhvDataMsg(int key, long version, short[] data) {
+       int totalsize = DhvMsg.DEFAULT_MESSAGE_SIZE +
+           DhvDataMsg.DEFAULT_MESSAGE_SIZE +
+           DhvData.DEFAULT_MESSAGE_SIZE;
+       DhvMsg dm = new DhvMsg(totalsize);
+       dm.set_type((short)3);
+
+       DhvDataMsg ddm = new DhvDataMsg(dm, DhvMsg.DEFAULT_MESSAGE_SIZE);
+       ddm.set_key(key);
+        ddm.set_version(version << 16);
+        ddm.set_size((short)data.length);
+
+        DhvData dd = new DhvData(ddm, DhvDataMsg.DEFAULT_MESSAGE_SIZE); 
+        dd.set_data(data);
+
+        try {
+           mote.send(MoteIF.TOS_BCAST_ADDR, dd);
+       }
+        catch(IOException e) {
+           System.err.println("Cannot send message");
+       }
+    }
+
+    public static void main(String args[]) {
+       int i;
+
+        System.out.println("Usage: java DhvInject [key] [version] [hex data delimit space in quotes]");
+        int k = Integer.parseInt(args[0], 16);
+        long v = Long.parseLong(args[1]);
+        String hexdata[] = args[2].split(" ");
+       short d[];
+
+        if(hexdata.length > 16) {
+            System.err.println("Data too long, keep it <= 16 bytes please");
+       }
+
+       d = new short[hexdata.length];
+        for(i = 0; i < d.length; i++)
+            d[i] = Short.parseShort(hexdata[i], 16);
+
+        System.out.println("Key: " + k);
+        System.out.println("Version: " + v);
+        System.out.print("Data: ");
+        for(i = 0; i < d.length; i++) {
+            System.out.print(d[i] + " ");
+       }
+        System.out.println();
+
+        DhvInject dhvinject = new DhvInject(new DhvMsg());
+        dhvinject.sendDhvDataMsg(k, v, d);
+    }
+}
diff --git a/apps/tests/TestDhv/Makefile b/apps/tests/TestDhv/Makefile
new file mode 100644 (file)
index 0000000..7a8241c
--- /dev/null
@@ -0,0 +1,53 @@
+COMPONENT=TestDhvC
+BUILD_EXTRA_DEPS = DhvMsg.py DhvDataMsg.py DhvMsg.class DhvDataMsg.class DhvData.class DhvInject.class DhvTestMsg.class
+CFLAGS += -I$(TOSDIR)/lib/net
+#CFLAGS += -DLOW_POWER_LISTENING
+#CFLAGS += -DLPL_DEF_LOCAL_SLEEP=512
+#CFLAGS += -DLPL_DEF_RX_SLEEP=512
+#CFLAGS += -DDELAY_AFTER_RECEIVE=20
+CFLAGS += -I$(TOSDIR)/lib/net/dhv -I$(TOSDIR)/lib/net/dhv/interfaces
+#CFLAGS += -I$(TOSDIR)/lib/net/dhv -I$(TOSDIR)/lib/net/dhv/interfaces
+#CFLAGS += -I$(TOSDIR)/lib/net/drip
+
+CONSTANTS += -DTOSH_DATA_LENGTH=32
+CFLAGS += $(CONSTANTS)
+
+CLEAN_EXTRA += DhvMsg.py DhvDataMsg.py DhvData.py DhvMsg.java DhvDataMsg.java DhvData.java DhvMsg.class DhvDataMsg.class DhvData.class DhvInject.class DhvTestMsg.class DhvTestMsg.java
+
+DhvMsg.py:
+       mig python -target=$(PLATFORM) -python-classname=DhvMsg $(CFLAGS) $(TOSDIR)/lib/net/dhv/Dhv.h dhv_msg -o $@
+
+DhvDataMsg.py:
+       mig python -target=$(PLATFORM) -python-classname=DhvDataMsg -python-extends=DhvMsg $(CFLAGS) $(TOSDIR)/lib/net/dhv/Dhv.h dhv_data_msg -o $@
+
+DhvData.py:
+       mig python -target=$(PLATFORM) -python-classname=DhvData -python-extends=DhvDataMsg $(CFLAGS) $(TOSDIR)/lib/net/dhv/Dhv.h dhv_data -o $@
+
+DhvTestMsg.class: DhvTestMsg.java
+       javac DhvTestMsg.java
+
+DhvMsg.class: DhvMsg.java
+       javac  DhvMsg.java
+
+DhvDataMsg.class: DhvDataMsg.java
+       javac  DhvDataMsg.java
+
+DhvData.class: DhvData.java
+       javac  DhvData.java
+
+DhvTestMsg.java:
+       mig java -target=null -java-classname=DhvTestMsg $(CFLAGS) $(TOSDIR)/lib/net/dhv/Dhv.h dhv_test_msg -o $@
+
+DhvMsg.java:
+       mig java -target=null -java-classname=DhvMsg $(CFLAGS) $(TOSDIR)/lib/net/dhv/Dhv.h dhv_msg -o $@
+
+DhvDataMsg.java:
+       mig java -target=null -java-classname=DhvDataMsg -java-extends=DhvMsg $(CFLAGS) $(TOSDIR)/lib/net/dhv/Dhv.h dhv_data_msg -o $@
+
+DhvData.java:
+       mig java -target=null -java-classname=DhvData -java-extends=DhvDataMsg $(CFLAGS) $(TOSDIR)/lib/net/dhv/Dhv.h dhv_data -o $@
+
+DhvInject.class:
+       javac  DhvInject.java
+
+include $(MAKERULES)
diff --git a/apps/tests/TestDhv/README b/apps/tests/TestDhv/README
new file mode 100644 (file)
index 0000000..a1542d8
--- /dev/null
@@ -0,0 +1,59 @@
+
+Title: TestDhv Application
+Author: Thanh Dang, Sweungweon Park 
+adopted from TestDip
+
+1. SETTING UP THE TEST
+
+You need to first generate the code for compilation. The gentest.py
+script reads in the Master files and creates TestDhvC.nc (the
+configuration) and TestDhvP.nc (the module). It takes two parameters,
+the total number of items and the number of new items. The items that
+are random are chosen randomly.
+
+If you want 128 total items in the dissemination set, where 96 of
+those 128 items are new, you would type:
+
+python gentest.py 128 96
+
+After the configuration and module have been generated, you can use
+the normal compilation method (e.g. make telosb).
+
+2, READING THE LEDS
+
+When an node receives a new item, it toggles LED0. When a node
+completes all items, it turns all LEDs on.
+
+3. SERIAL MESSAGES
+
+typedef nx_struct dhv_test_msg_t {
+  nx_am_addr_t id;
+  nx_uint8_t count;
+  nx_uint8_t isOk;
+} dhv_test_msg_t;
+
+When a node receives a new item, it sends a dhv_test_msg_t through the
+serial interface.
+
+id is the node id
+count is how many new items it has received so far
+isOk will be true if the data value was as expected
+
+4. PACKET INJECTOR
+
+You can also use the injector to send data packets via a
+basestation. The syntax to do that is:
+
+java DhvInject [key] [version] [data in quotes delimited by space]
+
+key is the data key in hexadecimal
+version is the version number in decimal
+data is the actual data in quotes delimited by space
+
+For example, if you want to send key 10, version 2, and data "ab cd
+ef". You would type:
+
+java DipInject 0a 2 "ab cd ef"
+
+For this specific test application, your data needs to be "ef be". You
+will need a SerialForwarder running for this work.
diff --git a/apps/tests/TestDhv/TestDhv.h b/apps/tests/TestDhv/TestDhv.h
new file mode 100644 (file)
index 0000000..0553587
--- /dev/null
@@ -0,0 +1,8 @@
+#ifndef __TESTDHV_H__
+#define __TESTDHV_H__
+
+/*enum {
+  AM_DHV_TEST_MSG = 0xAB
+};*/
+
+#endif
diff --git a/apps/tests/TestDhv/TestDhvC-Master.nc b/apps/tests/TestDhv/TestDhvC-Master.nc
new file mode 100644 (file)
index 0000000..94cf293
--- /dev/null
@@ -0,0 +1,29 @@
+#include "TestDhv.h"
+
+configuration TestDhvC {
+
+}
+
+implementation {
+  components TestDhvP;
+  components LedsC as LedsC;
+  TestDhvP.Leds -> LedsC;
+
+  components DisseminationC;
+  TestDhvP.StdControl -> DisseminationC;
+  /*
+  components new DisseminatorC(uint32_t, 0x1) as Dissem1;
+  TestDhvP.DisseminationValue1 -> Dissem1;
+  TestDhvP.DisseminationUpdate1 -> Dissem1;
+  */
+
+  // ... DISSEMINATORS
+
+  components MainC;
+  TestDhvP.Boot -> MainC;
+
+  components SerialActiveMessageC;
+  components new SerialAMSenderC(AM_DHV_TEST_MSG);
+  TestDhvP.SerialSend -> SerialAMSenderC;
+  TestDhvP.SerialControl -> SerialActiveMessageC;
+}
diff --git a/apps/tests/TestDhv/TestDhvC.nc b/apps/tests/TestDhv/TestDhvC.nc
new file mode 100644 (file)
index 0000000..44ee2bc
--- /dev/null
@@ -0,0 +1,284 @@
+#include "TestDhv.h"
+
+configuration TestDhvC {
+
+}
+
+implementation {
+  components TestDhvP;
+  components LedsC as LedsC;
+  TestDhvP.Leds -> LedsC;
+
+  components DisseminationC;
+  TestDhvP.StdControl -> DisseminationC;
+  /*
+  components new DisseminatorC(uint32_t, 0x1) as Dissem1;
+  TestDhvP.DisseminationValue1 -> Dissem1;
+  TestDhvP.DisseminationUpdate1 -> Dissem1;
+  */
+
+  components new DisseminatorC(uint16_t, 1) as Dissem1;
+  TestDhvP.DisseminationUpdate1 -> Dissem1;
+  TestDhvP.DisseminationValue1 -> Dissem1;
+
+  components new DisseminatorC(uint16_t, 2) as Dissem2;
+  TestDhvP.DisseminationUpdate2 -> Dissem2;
+  TestDhvP.DisseminationValue2 -> Dissem2;
+
+  components new DisseminatorC(uint16_t, 3) as Dissem3;
+  TestDhvP.DisseminationUpdate3 -> Dissem3;
+  TestDhvP.DisseminationValue3 -> Dissem3;
+
+  components new DisseminatorC(uint16_t, 4) as Dissem4;
+  TestDhvP.DisseminationUpdate4 -> Dissem4;
+  TestDhvP.DisseminationValue4 -> Dissem4;
+
+  components new DisseminatorC(uint16_t, 5) as Dissem5;
+  TestDhvP.DisseminationUpdate5 -> Dissem5;
+  TestDhvP.DisseminationValue5 -> Dissem5;
+
+  components new DisseminatorC(uint16_t, 6) as Dissem6;
+  TestDhvP.DisseminationUpdate6 -> Dissem6;
+  TestDhvP.DisseminationValue6 -> Dissem6;
+
+  components new DisseminatorC(uint16_t, 7) as Dissem7;
+  TestDhvP.DisseminationUpdate7 -> Dissem7;
+  TestDhvP.DisseminationValue7 -> Dissem7;
+
+  components new DisseminatorC(uint16_t, 8) as Dissem8;
+  TestDhvP.DisseminationUpdate8 -> Dissem8;
+  TestDhvP.DisseminationValue8 -> Dissem8;
+
+  components new DisseminatorC(uint16_t, 9) as Dissem9;
+  TestDhvP.DisseminationUpdate9 -> Dissem9;
+  TestDhvP.DisseminationValue9 -> Dissem9;
+
+  components new DisseminatorC(uint16_t, 10) as Dissem10;
+  TestDhvP.DisseminationUpdate10 -> Dissem10;
+  TestDhvP.DisseminationValue10 -> Dissem10;
+
+  components new DisseminatorC(uint16_t, 11) as Dissem11;
+  TestDhvP.DisseminationUpdate11 -> Dissem11;
+  TestDhvP.DisseminationValue11 -> Dissem11;
+
+  components new DisseminatorC(uint16_t, 12) as Dissem12;
+  TestDhvP.DisseminationUpdate12 -> Dissem12;
+  TestDhvP.DisseminationValue12 -> Dissem12;
+
+  components new DisseminatorC(uint16_t, 13) as Dissem13;
+  TestDhvP.DisseminationUpdate13 -> Dissem13;
+  TestDhvP.DisseminationValue13 -> Dissem13;
+
+  components new DisseminatorC(uint16_t, 14) as Dissem14;
+  TestDhvP.DisseminationUpdate14 -> Dissem14;
+  TestDhvP.DisseminationValue14 -> Dissem14;
+
+  components new DisseminatorC(uint16_t, 15) as Dissem15;
+  TestDhvP.DisseminationUpdate15 -> Dissem15;
+  TestDhvP.DisseminationValue15 -> Dissem15;
+
+  components new DisseminatorC(uint16_t, 16) as Dissem16;
+  TestDhvP.DisseminationUpdate16 -> Dissem16;
+  TestDhvP.DisseminationValue16 -> Dissem16;
+
+  components new DisseminatorC(uint16_t, 17) as Dissem17;
+  TestDhvP.DisseminationUpdate17 -> Dissem17;
+  TestDhvP.DisseminationValue17 -> Dissem17;
+
+  components new DisseminatorC(uint16_t, 18) as Dissem18;
+  TestDhvP.DisseminationUpdate18 -> Dissem18;
+  TestDhvP.DisseminationValue18 -> Dissem18;
+
+  components new DisseminatorC(uint16_t, 19) as Dissem19;
+  TestDhvP.DisseminationUpdate19 -> Dissem19;
+  TestDhvP.DisseminationValue19 -> Dissem19;
+
+  components new DisseminatorC(uint16_t, 20) as Dissem20;
+  TestDhvP.DisseminationUpdate20 -> Dissem20;
+  TestDhvP.DisseminationValue20 -> Dissem20;
+
+  components new DisseminatorC(uint16_t, 21) as Dissem21;
+  TestDhvP.DisseminationUpdate21 -> Dissem21;
+  TestDhvP.DisseminationValue21 -> Dissem21;
+
+  components new DisseminatorC(uint16_t, 22) as Dissem22;
+  TestDhvP.DisseminationUpdate22 -> Dissem22;
+  TestDhvP.DisseminationValue22 -> Dissem22;
+
+  components new DisseminatorC(uint16_t, 23) as Dissem23;
+  TestDhvP.DisseminationUpdate23 -> Dissem23;
+  TestDhvP.DisseminationValue23 -> Dissem23;
+
+  components new DisseminatorC(uint16_t, 24) as Dissem24;
+  TestDhvP.DisseminationUpdate24 -> Dissem24;
+  TestDhvP.DisseminationValue24 -> Dissem24;
+
+  components new DisseminatorC(uint16_t, 25) as Dissem25;
+  TestDhvP.DisseminationUpdate25 -> Dissem25;
+  TestDhvP.DisseminationValue25 -> Dissem25;
+
+  components new DisseminatorC(uint16_t, 26) as Dissem26;
+  TestDhvP.DisseminationUpdate26 -> Dissem26;
+  TestDhvP.DisseminationValue26 -> Dissem26;
+
+  components new DisseminatorC(uint16_t, 27) as Dissem27;
+  TestDhvP.DisseminationUpdate27 -> Dissem27;
+  TestDhvP.DisseminationValue27 -> Dissem27;
+
+  components new DisseminatorC(uint16_t, 28) as Dissem28;
+  TestDhvP.DisseminationUpdate28 -> Dissem28;
+  TestDhvP.DisseminationValue28 -> Dissem28;
+
+  components new DisseminatorC(uint16_t, 29) as Dissem29;
+  TestDhvP.DisseminationUpdate29 -> Dissem29;
+  TestDhvP.DisseminationValue29 -> Dissem29;
+
+  components new DisseminatorC(uint16_t, 30) as Dissem30;
+  TestDhvP.DisseminationUpdate30 -> Dissem30;
+  TestDhvP.DisseminationValue30 -> Dissem30;
+
+  components new DisseminatorC(uint16_t, 31) as Dissem31;
+  TestDhvP.DisseminationUpdate31 -> Dissem31;
+  TestDhvP.DisseminationValue31 -> Dissem31;
+
+  components new DisseminatorC(uint16_t, 32) as Dissem32;
+  TestDhvP.DisseminationUpdate32 -> Dissem32;
+  TestDhvP.DisseminationValue32 -> Dissem32;
+
+  components new DisseminatorC(uint16_t, 33) as Dissem33;
+  TestDhvP.DisseminationUpdate33 -> Dissem33;
+  TestDhvP.DisseminationValue33 -> Dissem33;
+
+  components new DisseminatorC(uint16_t, 34) as Dissem34;
+  TestDhvP.DisseminationUpdate34 -> Dissem34;
+  TestDhvP.DisseminationValue34 -> Dissem34;
+
+  components new DisseminatorC(uint16_t, 35) as Dissem35;
+  TestDhvP.DisseminationUpdate35 -> Dissem35;
+  TestDhvP.DisseminationValue35 -> Dissem35;
+
+  components new DisseminatorC(uint16_t, 36) as Dissem36;
+  TestDhvP.DisseminationUpdate36 -> Dissem36;
+  TestDhvP.DisseminationValue36 -> Dissem36;
+
+  components new DisseminatorC(uint16_t, 37) as Dissem37;
+  TestDhvP.DisseminationUpdate37 -> Dissem37;
+  TestDhvP.DisseminationValue37 -> Dissem37;
+
+  components new DisseminatorC(uint16_t, 38) as Dissem38;
+  TestDhvP.DisseminationUpdate38 -> Dissem38;
+  TestDhvP.DisseminationValue38 -> Dissem38;
+
+  components new DisseminatorC(uint16_t, 39) as Dissem39;
+  TestDhvP.DisseminationUpdate39 -> Dissem39;
+  TestDhvP.DisseminationValue39 -> Dissem39;
+
+  components new DisseminatorC(uint16_t, 40) as Dissem40;
+  TestDhvP.DisseminationUpdate40 -> Dissem40;
+  TestDhvP.DisseminationValue40 -> Dissem40;
+
+  components new DisseminatorC(uint16_t, 41) as Dissem41;
+  TestDhvP.DisseminationUpdate41 -> Dissem41;
+  TestDhvP.DisseminationValue41 -> Dissem41;
+
+  components new DisseminatorC(uint16_t, 42) as Dissem42;
+  TestDhvP.DisseminationUpdate42 -> Dissem42;
+  TestDhvP.DisseminationValue42 -> Dissem42;
+
+  components new DisseminatorC(uint16_t, 43) as Dissem43;
+  TestDhvP.DisseminationUpdate43 -> Dissem43;
+  TestDhvP.DisseminationValue43 -> Dissem43;
+
+  components new DisseminatorC(uint16_t, 44) as Dissem44;
+  TestDhvP.DisseminationUpdate44 -> Dissem44;
+  TestDhvP.DisseminationValue44 -> Dissem44;
+
+  components new DisseminatorC(uint16_t, 45) as Dissem45;
+  TestDhvP.DisseminationUpdate45 -> Dissem45;
+  TestDhvP.DisseminationValue45 -> Dissem45;
+
+  components new DisseminatorC(uint16_t, 46) as Dissem46;
+  TestDhvP.DisseminationUpdate46 -> Dissem46;
+  TestDhvP.DisseminationValue46 -> Dissem46;
+
+  components new DisseminatorC(uint16_t, 47) as Dissem47;
+  TestDhvP.DisseminationUpdate47 -> Dissem47;
+  TestDhvP.DisseminationValue47 -> Dissem47;
+
+  components new DisseminatorC(uint16_t, 48) as Dissem48;
+  TestDhvP.DisseminationUpdate48 -> Dissem48;
+  TestDhvP.DisseminationValue48 -> Dissem48;
+
+  components new DisseminatorC(uint16_t, 49) as Dissem49;
+  TestDhvP.DisseminationUpdate49 -> Dissem49;
+  TestDhvP.DisseminationValue49 -> Dissem49;
+
+  components new DisseminatorC(uint16_t, 50) as Dissem50;
+  TestDhvP.DisseminationUpdate50 -> Dissem50;
+  TestDhvP.DisseminationValue50 -> Dissem50;
+
+  components new DisseminatorC(uint16_t, 51) as Dissem51;
+  TestDhvP.DisseminationUpdate51 -> Dissem51;
+  TestDhvP.DisseminationValue51 -> Dissem51;
+
+  components new DisseminatorC(uint16_t, 52) as Dissem52;
+  TestDhvP.DisseminationUpdate52 -> Dissem52;
+  TestDhvP.DisseminationValue52 -> Dissem52;
+
+  components new DisseminatorC(uint16_t, 53) as Dissem53;
+  TestDhvP.DisseminationUpdate53 -> Dissem53;
+  TestDhvP.DisseminationValue53 -> Dissem53;
+
+  components new DisseminatorC(uint16_t, 54) as Dissem54;
+  TestDhvP.DisseminationUpdate54 -> Dissem54;
+  TestDhvP.DisseminationValue54 -> Dissem54;
+
+  components new DisseminatorC(uint16_t, 55) as Dissem55;
+  TestDhvP.DisseminationUpdate55 -> Dissem55;
+  TestDhvP.DisseminationValue55 -> Dissem55;
+
+  components new DisseminatorC(uint16_t, 56) as Dissem56;
+  TestDhvP.DisseminationUpdate56 -> Dissem56;
+  TestDhvP.DisseminationValue56 -> Dissem56;
+
+  components new DisseminatorC(uint16_t, 57) as Dissem57;
+  TestDhvP.DisseminationUpdate57 -> Dissem57;
+  TestDhvP.DisseminationValue57 -> Dissem57;
+
+  components new DisseminatorC(uint16_t, 58) as Dissem58;
+  TestDhvP.DisseminationUpdate58 -> Dissem58;
+  TestDhvP.DisseminationValue58 -> Dissem58;
+
+  components new DisseminatorC(uint16_t, 59) as Dissem59;
+  TestDhvP.DisseminationUpdate59 -> Dissem59;
+  TestDhvP.DisseminationValue59 -> Dissem59;
+
+  components new DisseminatorC(uint16_t, 60) as Dissem60;
+  TestDhvP.DisseminationUpdate60 -> Dissem60;
+  TestDhvP.DisseminationValue60 -> Dissem60;
+
+  components new DisseminatorC(uint16_t, 61) as Dissem61;
+  TestDhvP.DisseminationUpdate61 -> Dissem61;
+  TestDhvP.DisseminationValue61 -> Dissem61;
+
+  components new DisseminatorC(uint16_t, 62) as Dissem62;
+  TestDhvP.DisseminationUpdate62 -> Dissem62;
+  TestDhvP.DisseminationValue62 -> Dissem62;
+
+  components new DisseminatorC(uint16_t, 63) as Dissem63;
+  TestDhvP.DisseminationUpdate63 -> Dissem63;
+  TestDhvP.DisseminationValue63 -> Dissem63;
+
+  components new DisseminatorC(uint16_t, 64) as Dissem64;
+  TestDhvP.DisseminationUpdate64 -> Dissem64;
+  TestDhvP.DisseminationValue64 -> Dissem64;
+
+
+  components MainC;
+  TestDhvP.Boot -> MainC;
+
+  components SerialActiveMessageC;
+  components new SerialAMSenderC(AM_DHV_TEST_MSG);
+  TestDhvP.SerialSend -> SerialAMSenderC;
+  TestDhvP.SerialControl -> SerialActiveMessageC;
+}
diff --git a/apps/tests/TestDhv/TestDhvP-Master.nc b/apps/tests/TestDhv/TestDhvP-Master.nc
new file mode 100644 (file)
index 0000000..d4cbdb2
--- /dev/null
@@ -0,0 +1,93 @@
+
+module TestDhvP {
+  uses interface Leds;
+  uses interface StdControl;
+
+  /*
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate1;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue1;
+  */
+
+  // ... INTERFACES
+
+  uses interface Boot;
+  uses interface AMSend as SerialSend;
+  uses interface SplitControl as SerialControl;
+}
+
+implementation {
+  typedef nx_struct dhv_test_msg_t {
+    nx_am_addr_t id;
+    nx_uint8_t count;
+    nx_uint8_t isOk;
+  } dhv_test_msg_t;
+
+  message_t testMsg;
+
+  uint8_t okBit = 1;
+  uint16_t data;
+  uint8_t count = 0;
+  /*
+  uint8_t newCount = N;
+  */
+  // ... NEWCOUNT
+
+  void bookkeep();
+
+  event void SerialControl.startDone(error_t err) {
+    call StdControl.start();
+    if(TOS_NODE_ID == 1) {
+      data = 0xBEEF;
+      dbg("TestDhvP","Updating data items\n");
+      /*
+      call DisseminationUpdate1.change(&data);
+      */
+      // ... CHANGES
+    }
+  }
+  
+  event void SerialControl.stopDone(error_t err) {
+    
+  }
+
+  event void Boot.booted() {
+    call SerialControl.start();
+    dbg("TestDhvP", "Booted at %s\n", sim_time_string());
+  }
+  /*
+  event void DisseminationValue1.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue1.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+  */
+
+  // ... EVENTS
+
+  void bookkeep() {
+    dhv_test_msg_t* dhvTestMsgPtr;
+
+    if(count < newCount) {
+      count++;
+    }
+    dbg("TestDhvP", "Got an update, %u complete now at %s\n", count, sim_time_string());
+    call Leds.led0Toggle();
+
+    dhvTestMsgPtr = (dhv_test_msg_t*) call SerialSend.getPayload(&testMsg, 0);
+    dhvTestMsgPtr->id = TOS_NODE_ID;
+    dhvTestMsgPtr->count = count;
+    dhvTestMsgPtr->isOk = okBit;
+    call SerialSend.send(0, &testMsg, sizeof(dhv_test_msg_t));
+    
+
+    if(newCount == count) {
+      dbg("TestDhvP","Dissemination COMPLETE!\n");
+      call Leds.set(7);
+    }
+    
+  }
+
+  event void SerialSend.sendDone(message_t* message, error_t err) {
+
+  }
+}
diff --git a/apps/tests/TestDhv/TestDhvP.nc b/apps/tests/TestDhv/TestDhvP.nc
new file mode 100644 (file)
index 0000000..5c75d2f
--- /dev/null
@@ -0,0 +1,674 @@
+
+module TestDhvP {
+  uses interface Leds;
+  uses interface StdControl;
+
+  /*
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate1;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue1;
+  */
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate1;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue1;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate2;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue2;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate3;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue3;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate4;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue4;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate5;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue5;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate6;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue6;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate7;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue7;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate8;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue8;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate9;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue9;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate10;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue10;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate11;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue11;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate12;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue12;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate13;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue13;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate14;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue14;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate15;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue15;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate16;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue16;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate17;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue17;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate18;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue18;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate19;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue19;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate20;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue20;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate21;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue21;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate22;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue22;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate23;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue23;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate24;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue24;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate25;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue25;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate26;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue26;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate27;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue27;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate28;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue28;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate29;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue29;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate30;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue30;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate31;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue31;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate32;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue32;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate33;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue33;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate34;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue34;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate35;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue35;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate36;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue36;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate37;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue37;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate38;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue38;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate39;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue39;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate40;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue40;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate41;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue41;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate42;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue42;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate43;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue43;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate44;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue44;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate45;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue45;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate46;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue46;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate47;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue47;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate48;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue48;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate49;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue49;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate50;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue50;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate51;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue51;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate52;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue52;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate53;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue53;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate54;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue54;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate55;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue55;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate56;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue56;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate57;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue57;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate58;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue58;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate59;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue59;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate60;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue60;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate61;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue61;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate62;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue62;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate63;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue63;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate64;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue64;
+
+
+  uses interface Boot;
+  uses interface AMSend as SerialSend;
+  uses interface SplitControl as SerialControl;
+}
+
+implementation {
+  typedef nx_struct dhv_test_msg_t {
+    nx_am_addr_t id;
+    nx_uint8_t count;
+    nx_uint8_t isOk;
+  } dhv_test_msg_t;
+
+  message_t testMsg;
+
+  uint8_t okBit = 1;
+  uint16_t data;
+  uint8_t count = 0;
+  /*
+  uint8_t newCount = N;
+  */
+  uint8_t newCount = 8;
+
+  void bookkeep();
+
+  event void SerialControl.startDone(error_t err) {
+    call StdControl.start();
+    if(TOS_NODE_ID == 1) {
+      data = 0xBEEF;
+      dbg("TestDhvP","Updating data items\n");
+      /*
+      call DisseminationUpdate1.change(&data);
+      */
+      call DisseminationUpdate18.change(&data);
+      call DisseminationUpdate61.change(&data);
+      call DisseminationUpdate21.change(&data);
+      call DisseminationUpdate53.change(&data);
+      call DisseminationUpdate17.change(&data);
+      call DisseminationUpdate19.change(&data);
+      call DisseminationUpdate11.change(&data);
+      call DisseminationUpdate36.change(&data);
+    }
+  }
+  
+  event void SerialControl.stopDone(error_t err) {
+    
+  }
+
+  event void Boot.booted() {
+    call SerialControl.start();
+    dbg("TestDhvP", "Booted at %s\n", sim_time_string());
+  }
+  /*
+  event void DisseminationValue1.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue1.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+  */
+
+  event void DisseminationValue1.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue1.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue2.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue2.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue3.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue3.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue4.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue4.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue5.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue5.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue6.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue6.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue7.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue7.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue8.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue8.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue9.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue9.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue10.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue10.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue11.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue11.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue12.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue12.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue13.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue13.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue14.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue14.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue15.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue15.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue16.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue16.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue17.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue17.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue18.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue18.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue19.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue19.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue20.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue20.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue21.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue21.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue22.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue22.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue23.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue23.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue24.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue24.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue25.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue25.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue26.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue26.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue27.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue27.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue28.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue28.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue29.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue29.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue30.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue30.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue31.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue31.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue32.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue32.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue33.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue33.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue34.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue34.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue35.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue35.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue36.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue36.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue37.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue37.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue38.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue38.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue39.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue39.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue40.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue40.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue41.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue41.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue42.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue42.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue43.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue43.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue44.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue44.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue45.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue45.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue46.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue46.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue47.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue47.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue48.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue48.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue49.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue49.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue50.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue50.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue51.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue51.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue52.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue52.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue53.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue53.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue54.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue54.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue55.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue55.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue56.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue56.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue57.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue57.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue58.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue58.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue59.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue59.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue60.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue60.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue61.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue61.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue62.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue62.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue63.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue63.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue64.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue64.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+
+  void bookkeep() {
+    dhv_test_msg_t* dhvTestMsgPtr;
+
+    if(count < newCount) {
+      count++;
+    }
+    dbg("TestDhvP", "Got an update, %u complete now at %s\n", count, sim_time_string());
+    call Leds.led0Toggle();
+
+    dhvTestMsgPtr = (dhv_test_msg_t*) call SerialSend.getPayload(&testMsg, 0);
+    dhvTestMsgPtr->id = TOS_NODE_ID;
+    dhvTestMsgPtr->count = count;
+    dhvTestMsgPtr->isOk = okBit;
+    call SerialSend.send(0, &testMsg, sizeof(dhv_test_msg_t));
+    
+
+    if(newCount == count) {
+      dbg("TestDhvP","Dissemination COMPLETE!\n");
+      call Leds.set(7);
+    }
+    
+  }
+
+  event void SerialSend.sendDone(message_t* message, error_t err) {
+
+  }
+}
diff --git a/apps/tests/TestDhv/TestDipP.nc b/apps/tests/TestDhv/TestDipP.nc
new file mode 100644 (file)
index 0000000..f26d652
--- /dev/null
@@ -0,0 +1,674 @@
+
+module TestDipP {
+  uses interface Leds;
+  uses interface StdControl;
+
+  /*
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate1;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue1;
+  */
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate1;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue1;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate2;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue2;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate3;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue3;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate4;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue4;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate5;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue5;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate6;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue6;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate7;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue7;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate8;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue8;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate9;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue9;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate10;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue10;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate11;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue11;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate12;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue12;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate13;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue13;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate14;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue14;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate15;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue15;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate16;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue16;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate17;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue17;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate18;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue18;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate19;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue19;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate20;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue20;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate21;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue21;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate22;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue22;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate23;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue23;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate24;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue24;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate25;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue25;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate26;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue26;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate27;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue27;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate28;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue28;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate29;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue29;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate30;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue30;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate31;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue31;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate32;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue32;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate33;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue33;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate34;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue34;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate35;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue35;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate36;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue36;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate37;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue37;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate38;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue38;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate39;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue39;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate40;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue40;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate41;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue41;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate42;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue42;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate43;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue43;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate44;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue44;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate45;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue45;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate46;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue46;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate47;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue47;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate48;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue48;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate49;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue49;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate50;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue50;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate51;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue51;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate52;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue52;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate53;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue53;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate54;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue54;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate55;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue55;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate56;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue56;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate57;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue57;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate58;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue58;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate59;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue59;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate60;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue60;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate61;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue61;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate62;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue62;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate63;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue63;
+
+  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate64;
+  uses interface DisseminationValue<uint16_t> as DisseminationValue64;
+
+
+  uses interface Boot;
+  uses interface AMSend as SerialSend;
+  uses interface SplitControl as SerialControl;
+}
+
+implementation {
+  typedef nx_struct dip_test_msg_t {
+    nx_am_addr_t id;
+    nx_uint8_t count;
+    nx_uint8_t isOk;
+  } dip_test_msg_t;
+
+  message_t testMsg;
+
+  uint8_t okBit = 1;
+  uint16_t data;
+  uint8_t count = 0;
+  /*
+  uint8_t newCount = N;
+  */
+  uint8_t newCount = 8;
+
+  void bookkeep();
+
+  event void SerialControl.startDone(error_t err) {
+    call StdControl.start();
+    if(TOS_NODE_ID == 1) {
+      data = 0xBEEF;
+      dbg("TestDipP","Updating data items\n");
+      /*
+      call DisseminationUpdate1.change(&data);
+      */
+      call DisseminationUpdate50.change(&data);
+      call DisseminationUpdate25.change(&data);
+      call DisseminationUpdate47.change(&data);
+      call DisseminationUpdate7.change(&data);
+      call DisseminationUpdate43.change(&data);
+      call DisseminationUpdate58.change(&data);
+      call DisseminationUpdate48.change(&data);
+      call DisseminationUpdate45.change(&data);
+    }
+  }
+  
+  event void SerialControl.stopDone(error_t err) {
+    
+  }
+
+  event void Boot.booted() {
+    call SerialControl.start();
+    dbg("TestDipP", "Booted at %s\n", sim_time_string());
+  }
+  /*
+  event void DisseminationValue1.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue1.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+  */
+
+  event void DisseminationValue1.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue1.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue2.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue2.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue3.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue3.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue4.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue4.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue5.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue5.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue6.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue6.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue7.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue7.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue8.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue8.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue9.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue9.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue10.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue10.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue11.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue11.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue12.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue12.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue13.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue13.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue14.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue14.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue15.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue15.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue16.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue16.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue17.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue17.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue18.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue18.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue19.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue19.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue20.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue20.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue21.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue21.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue22.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue22.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue23.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue23.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue24.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue24.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue25.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue25.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue26.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue26.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue27.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue27.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue28.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue28.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue29.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue29.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue30.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue30.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue31.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue31.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue32.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue32.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue33.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue33.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue34.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue34.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue35.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue35.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue36.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue36.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue37.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue37.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue38.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue38.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue39.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue39.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue40.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue40.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue41.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue41.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue42.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue42.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue43.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue43.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue44.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue44.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue45.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue45.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue46.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue46.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue47.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue47.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue48.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue48.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue49.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue49.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue50.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue50.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue51.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue51.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue52.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue52.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue53.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue53.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue54.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue54.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue55.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue55.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue56.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue56.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue57.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue57.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue58.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue58.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue59.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue59.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue60.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue60.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue61.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue61.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue62.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue62.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue63.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue63.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+  event void DisseminationValue64.changed() {
+    uint16_t val = *(uint16_t*) call DisseminationValue64.get();
+    if(val != 0xBEEF) { return; }
+    bookkeep();
+  }
+
+
+  void bookkeep() {
+    dip_test_msg_t* dipTestMsgPtr;
+
+    if(count < newCount) {
+      count++;
+    }
+    dbg("TestDipP", "Got an update, %u complete now at %s\n", count, sim_time_string());
+    call Leds.led0Toggle();
+
+    dipTestMsgPtr = (dip_test_msg_t*) call SerialSend.getPayload(&testMsg, 0);
+    dipTestMsgPtr->id = TOS_NODE_ID;
+    dipTestMsgPtr->count = count;
+    dipTestMsgPtr->isOk = okBit;
+    call SerialSend.send(0, &testMsg, sizeof(dip_test_msg_t));
+    
+
+    if(newCount == count) {
+      dbg("TestDipP","Dissemination COMPLETE!\n");
+      call Leds.set(7);
+    }
+    
+  }
+
+  event void SerialSend.sendDone(message_t* message, error_t err) {
+
+  }
+}
diff --git a/apps/tests/TestDhv/gentest.py b/apps/tests/TestDhv/gentest.py
new file mode 100644 (file)
index 0000000..ff3e217
--- /dev/null
@@ -0,0 +1,61 @@
+#!/usr/bin/python
+
+import sys
+import re
+import os
+import random
+
+print "Usage: python gentest.py [numitems] [newitems]"
+
+items = sys.argv[1]
+newitems = sys.argv[2]
+
+print "Generating Configurations"
+
+fin = open("TestDhvC-Master.nc", "r")
+fout = open("TestDhvC.nc", "w")
+lines = fin.readlines()
+for line in lines:
+    if(line.find("... DISSEMINATORS") != -1):
+        for i in range(1, int(items)+1):
+            fout.write("  components new DisseminatorC(uint16_t, ")
+            fout.write(str(i))
+            fout.write(") as Dissem" + str(i) + ";\n")
+            fout.write("  TestDhvP.DisseminationUpdate" + str(i))
+            fout.write(" -> Dissem" + str(i) + ";\n")
+            fout.write("  TestDhvP.DisseminationValue" + str(i))
+            fout.write(" -> Dissem" + str(i) + ";\n\n")
+    else:
+        fout.write(line)
+
+fin.close()
+fout.close()
+
+print "Generating Modules"
+
+fin = open("TestDhvP-Master.nc", "r")
+fout = open("TestDhvP.nc", "w")
+lines = fin.readlines()
+for line in lines:
+    if(line.find("... INTERFACES") != -1):
+        for i in range(1, int(items)+1):
+            fout.write("  uses interface DisseminationUpdate<uint16_t> as DisseminationUpdate")
+            fout.write(str(i) + ";\n")
+            fout.write("  uses interface DisseminationValue<uint16_t> as DisseminationValue")
+            fout.write(str(i) + ";\n\n")
+    elif(line.find("... NEWCOUNT") != -1):
+        fout.write("  uint8_t newCount = " + str(newitems) + ";\n")
+    elif(line.find("... CHANGES") != -1):
+        for i in random.sample(range(1, int(items)+1), int(newitems)):
+            fout.write("      call DisseminationUpdate" + str(i) + ".change(&data);\n")
+    elif(line.find("... EVENTS") != -1):
+        for i in range(1, int(items)+1):
+            fout.write("  event void DisseminationValue" + str(i))
+            fout.write(".changed() {\n")
+            fout.write("    uint16_t val = *(uint16_t*) call DisseminationValue" + str(i) + ".get();\n")
+            fout.write("    if(val != 0xBEEF) { return; }\n")
+            fout.write("    bookkeep();\n")
+            fout.write("  }\n\n")
+    else:
+        fout.write(line)
+
index ed0305abba9929829147c8f2cd8a4b222e85e405..1576ee72f6d94db238fcb9b6418ebf12648fd448 100644 (file)
@@ -5,8 +5,15 @@ CFLAGS += -I$(TOSDIR)/lib/net/dip -I$(TOSDIR)/lib/net/dip/interfaces
 #CFLAGS += -I$(TOSDIR)/lib/net/drip
 
 CONSTANTS += -DTOSH_DATA_LENGTH=32
+#CONSTANTS += -DDIP_JOINTEST
 CFLAGS += $(CONSTANTS)
 
+# LPL FLAGS
+#CFLAGS += -DLOW_POWER_LISTENING
+#CFLAGS += -DLPL_DEF_LOCAL_WAKEUP=512
+#CFLAGS += -DLPL_DEF_REMOTE_WAKEUP=512
+#CFLAGS += -DDELAY_AFTER_RECEIVE=20
+
 CLEAN_EXTRA += DipMsg.py DipDataMsg.py DipData.py DipMsg.java DipDataMsg.java DipData.java DipMsg.class DipDataMsg.class DipData.class DipInject.class
 
 DipMsg.py:
index b56aeaff4465b5808d0926f3c9c8d99b47c63701..d01236a643bf3a60193f07053875ed13d050724d 100644 (file)
@@ -1,6 +1,6 @@
 
 Title: TestDip Application
-Author: Kaisen Lin
+Author: Kaisen Lin (kaisenl@cs.ucsd.edu)
 
 1. SETTING UP THE TEST
 
@@ -70,3 +70,13 @@ approximately:
 
 2 minutes for both nodes to receive 96 out of 96 items.
 With 128 items or more, MicaZ nodes don't receive anything. Memory limitation?
+
+6. BASESTATION
+
+If you are using the Basestation application to sniff what packets are
+being sent in the air, you will need to adjust the packet size to match
+the test application. You can add the following to your Makefile:
+
+CFLAGS += -DTOSH_DATA_LENGTH=XX
+
+where XX is your payload size
index f2c673a24903543de4710c451e368305669eaae7..45119ee7500cc5ffd183cba23f6374afc8b18164 100644 (file)
@@ -1,4 +1,4 @@
-#include <TestDip.h>
+#include "TestDip.h"
 
 configuration TestDipC {
 
@@ -26,4 +26,7 @@ implementation {
   components new SerialAMSenderC(AM_TESTDIP);
   TestDipP.SerialSend -> SerialAMSenderC;
   TestDipP.SerialControl -> SerialActiveMessageC;
+
+  components ActiveMessageC;
+  TestDipP.AMControl -> ActiveMessageC;
 }
index e5404619d0dcd76681a59b2cea15dcb89708ddd8..ec3d7bebb860ae185c88245fd2488ab8c3675dd1 100644 (file)
@@ -13,6 +13,7 @@ module TestDipP {
   uses interface Boot;
   uses interface AMSend as SerialSend;
   uses interface SplitControl as SerialControl;
+  uses interface SplitControl as AMControl;
 }
 
 implementation {
@@ -35,8 +36,20 @@ implementation {
   void bookkeep();
 
   event void SerialControl.startDone(error_t err) {
+    if(err != SUCCESS) {
+      call SerialControl.start();
+      return;
+    }
+    call AMControl.start();
+  }
+
+  event void AMControl.startDone(error_t err) {
+    if(err != SUCCESS) {
+      call AMControl.start();
+      return;
+    }
     call StdControl.start();
-    if(TOS_NODE_ID == 0) {
+    if(TOS_NODE_ID == 1) {
       data = 0xBEEF;
       dbg("TestDipP","Updating data items\n");
       /*
@@ -46,14 +59,14 @@ implementation {
     }
   }
   
-  event void SerialControl.stopDone(error_t err) {
-    
-  }
+  event void SerialControl.stopDone(error_t err) { }
+  event void AMControl.stopDone(error_t err) { }
 
   event void Boot.booted() {
     call SerialControl.start();
     dbg("TestDipP", "Booted at %s\n", sim_time_string());
   }
+
   /*
   event void DisseminationValue1.changed() {
     uint16_t val = *(uint16_t*) call DisseminationValue1.get();
@@ -70,7 +83,7 @@ implementation {
     if(count < newCount) {
       count++;
     }
-    dbg("TestDIPP", "Got an update, %u complete now at %s\n", count, sim_time_string());
+    dbg("TestDipP", "Got an update, %u complete now at %s\n", count, sim_time_string());
     call Leds.led0Toggle();
 
     dipTestMsgPtr = (dip_test_msg_t*) call SerialSend.getPayload(&testMsg, 0);
@@ -81,6 +94,7 @@ implementation {
     
 
     if(newCount == count) {
+      dbg("TestDipP","Dissemination COMPLETE!\n");
       call Leds.set(7);
     }
     
index dcb1052931ab9b3db4b021106d19557851330674..a2d78af8ca0942c8687b63e2747c811ba1d3f208 100644 (file)
@@ -6,6 +6,8 @@ CFLAGS += -I$(TOSDIR)/lib/net -I%T/lib/net/drip
 ### For DIP:
 #CFLAGS += -I$(TOSDIR)/lib/net -I%T/lib/net/dip -I%T/lib/net/dip/interfaces
 
+### For Dhv
+#CFLAGS += -I$(TOSDIR)/lib/net -I%T/lib/net/dhv -I%T/lib/net/dhv/interfaces
 
 include $(MAKERULES)
 
diff --git a/apps/tests/TestEui/Makefile b/apps/tests/TestEui/Makefile
new file mode 100644 (file)
index 0000000..174baa2
--- /dev/null
@@ -0,0 +1,4 @@
+COMPONENT=TestEuiAppC
+CFLAGS += -I$(TOSDIR)/lib/printf
+include $(MAKERULES)
+
diff --git a/apps/tests/TestEui/README.txt b/apps/tests/TestEui/README.txt
new file mode 100644 (file)
index 0000000..d918ef0
--- /dev/null
@@ -0,0 +1,23 @@
+$Id$
+
+README for TestEui
+Author/Contact: tinyos-help@millennium.berkeley.edu
+
+Description:
+
+The TestEui application prints out the IEEE EUI64 of the device periodically
+using printf. Currently supported platforms: iris.
+
+Tools:
+
+net.tinyos.tools.PrintfClient is a Java application that displays the output on
+the PC.
+
+Usage:
+
+java net.tinyos.tools.PrintfClient -comm serial@<serial port>:<mote>
+
+Known bugs/limitations:
+
+None.
\ No newline at end of file
diff --git a/apps/tests/TestEui/TestEuiAppC.nc b/apps/tests/TestEui/TestEuiAppC.nc
new file mode 100644 (file)
index 0000000..5dba893
--- /dev/null
@@ -0,0 +1,43 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+#include "printf.h"
+
+/**
+ * This application reads the 64-bit EUI of the device at initialization time
+ * and then periodically prints it out using printf.
+ *
+ */
+configuration TestEuiAppC{}
+implementation {
+  components MainC, TestEuiC, LedsC, LocalIeeeEui64C, new TimerMilliC();
+
+  MainC.Boot <- TestEuiC;
+  TestEuiC.Timer -> TimerMilliC;
+
+  TestEuiC -> LedsC.Leds;
+
+  TestEuiC.LocalIeeeEui64 -> LocalIeeeEui64C;
+}
+
diff --git a/apps/tests/TestEui/TestEuiC.nc b/apps/tests/TestEui/TestEuiC.nc
new file mode 100644 (file)
index 0000000..79c0bed
--- /dev/null
@@ -0,0 +1,63 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+/**
+ * This application reads the 64-bit EUI of the device at initialization time
+ * and then periodically, and prints it out using printf.
+ *
+ */
+module TestEuiC
+{
+  uses interface Boot;
+  uses interface Timer<TMilli>;
+  uses interface Leds;
+  uses interface LocalIeeeEui64;
+}
+implementation
+{
+  void print() {
+  }
+
+  event void Boot.booted()  {
+    call Timer.startPeriodic(1000);
+  }
+
+  event void Timer.fired() {
+    int i;
+    ieee_eui64_t id;
+
+    call Leds.led0Toggle();
+
+    id = call LocalIeeeEui64.getId();
+
+    printf("IEEE 64-bit UID: ");
+    for(i=0;i<8;i++) {
+      printf("%d ", id.data[i]);
+    }
+    printf("\n");
+       printfflush();
+
+  }
+}
+
diff --git a/apps/tests/TestFtsp/Ftsp/FtspDataAnalyzer.m b/apps/tests/TestFtsp/Ftsp/FtspDataAnalyzer.m
new file mode 100755 (executable)
index 0000000..94dda15
--- /dev/null
@@ -0,0 +1,60 @@
+%load file written out by FtspDataLogger.java class\r
+%arg0 - filename, e.g. '1205543689171.report'\r
+function FTSPDataAnalyzer(file, varargin)\r
+[c1 c2 c3 c4 c5]= textread(file, '%u %u %u %u %u', 'commentstyle', 'shell');\r
+data = [c2 c3 c4 c5]; %skipping the first column (java time)\r
+data1 = sortrows(sortrows(data,1),2);\r
+newdata = [];\r
+\r
+row=1;\r
+newrow=1;\r
+unsynced=0;\r
+while (row<=size(data1,1))\r
+\r
+    seqnum=data1(row,2);\r
+\r
+    data2=[];\r
+    row2=1;\r
+    tmprow1=row;\r
+    while (row <= size(data1,1) && data1(row,2)==seqnum)\r
+        if (data1(row,4)==0)\r
+            data2(row2,1)=data1(row,3);\r
+            row2= row2+ 1;\r
+        else\r
+            unsynced=unsynced+1;\r
+        end\r
+        row = row + 1;\r
+    end\r
+    \r
+    if (row2>1)\r
+        row2size=row2-1;\r
+        rcvdsize=row-tmprow1;\r
+        newdata(newrow,1) = seqnum;\r
+        newdata(newrow,2) = mad(data2(1:row2size,1));\r
+        newdata(newrow,3) = mean(data2(1:row2size,1));\r
+        newdata(newrow,4) = row2size/rcvdsize;\r
+        newrow = newrow + 1;\r
+    end\r
+end\r
+\r
+if (length(newdata)==0)\r
+    disp('no data found (at least one data point from a synchronized mote is required)!');\r
+else\r
+    newsize=newrow-1;\r
+    subplot(3,1,1);\r
+    plot(newdata(1:newsize,1),newdata(1:newsize,2));\r
+    title(sprintf('TimeSync Errors'));\r
+    subplot(3,1,2);\r
+    plot(newdata(1:newsize,1),newdata(1:newsize,3));\r
+    title(sprintf('Avg Glob Time'));\r
+    subplot(3,1,3);\r
+    plot(newdata(1:newsize,1),newdata(1:newsize,4),'b-');\r
+    title(sprintf('%% Synced Motes'));\r
+\r
+    disp(sprintf('total unsycned num %d (all %d)',unsynced,newsize));\r
+    disp(sprintf('avg %0.3f',mean(newdata(1:newsize,2))));\r
+    disp(sprintf('max %d',max(newdata(1:newsize,2))));\r
+    savedata = newdata(1:newsize,:);\r
+    save data.out savedata -ASCII;\r
+end\r
+    
\ No newline at end of file
diff --git a/apps/tests/TestFtsp/Ftsp/FtspDataLogger.java b/apps/tests/TestFtsp/Ftsp/FtspDataLogger.java
new file mode 100755 (executable)
index 0000000..168fa0f
--- /dev/null
@@ -0,0 +1,120 @@
+/*                  tab:4
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2007 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+
+/**
+ * @author Brano Kusy
+ */
+
+import java.io.FileOutputStream;
+import java.io.PrintStream;
+import net.tinyos.message.*;
+import net.tinyos.util.*;
+
+public class FtspDataLogger implements MessageListener {
+        public class RunWhenShuttingDown extends Thread {
+                public void run()
+                {
+                        System.out.println("Control-C caught. Shutting down...");
+                        if (outReport!=null)
+                        outReport.close();
+                }
+        }
+
+  MoteIF mote;    // For talking to the antitheft root node
+
+        void connect()
+        {
+                try {
+                        mote = new MoteIF(PrintStreamMessenger.err);
+                        mote.registerListener(new TestFtspMsg(), this);
+                        System.out.println("Connection ok!");
+                }
+                catch(Exception e) {
+                        e.printStackTrace();
+                        System.exit(2);
+                }
+        }
+        PrintStream outReport = null;
+
+        public FtspDataLogger() {
+                connect();
+                Runtime.getRuntime().addShutdownHook(new RunWhenShuttingDown());
+                String name=""+System.currentTimeMillis();
+                try
+                {
+                        outReport = new PrintStream(new FileOutputStream(name+".report"));
+                        outReport.println("#[JAVA_TIME] [NODE_ID] [SEQ_NUM] [GLOB_TIME] [IS_TIME_VALID]");
+                }
+                catch (Exception e)
+                {
+                        System.out.println("FtspDataLogger.FtspDataLogger(): "+e.toString());
+                }
+        }
+
+        public void writeReprot(TestFtspMsg tspr)
+        {
+                String foo = (System.currentTimeMillis()
+                               +" "+tspr.get_src_addr()+" "+tspr.get_counter()
+                        +" "+tspr.get_global_rx_timestamp()+" "+tspr.get_is_synced());
+                outReport.println(foo);
+                System.out.println(foo);
+                outReport.flush();
+        }
+
+        public void writeFullReprot(TestFtspMsg tspr)
+        {
+                String foo = (System.currentTimeMillis()
+                               +" "+tspr.get_src_addr()
+                        +" "+tspr.get_counter()
+                        +" "+tspr.get_local_rx_timestamp()
+                        +" "+tspr.get_global_rx_timestamp()
+                        +" "+tspr.get_skew_times_1000000()
+                        +" "+tspr.get_is_synced()
+                        +" "+tspr.get_ftsp_root_addr()
+                        +" "+tspr.get_ftsp_seq()
+                        +" "+tspr.get_ftsp_table_entries());
+                outReport.println(foo);
+                System.out.println(foo);
+                outReport.flush();
+        }
+
+        public void messageReceived(int dest_addr, Message msg)
+        {
+                if (msg instanceof TestFtspMsg)
+                        //writeFullReprot((TestFtspMsg)msg);
+                        writeReprot((TestFtspMsg)msg);
+        }
+
+        /* Just start the app... */
+        public static void main(String[] args)
+        {
+                new FtspDataLogger();
+        }
+}
\ No newline at end of file
diff --git a/apps/tests/TestFtsp/Ftsp/FtspDataLogger.py b/apps/tests/TestFtsp/Ftsp/FtspDataLogger.py
new file mode 100755 (executable)
index 0000000..0c5687b
--- /dev/null
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+
+import sys, time
+import tos
+
+AM_TEST_FTSP_MSG = 137
+
+class FtspMsg(tos.Packet):
+    def __init__(self, packet = None):
+        tos.Packet.__init__(self,
+                            [('src_addr',            'int', 2),
+                             ('counter',             'int', 2),
+                             ('local_rx_timestamp',  'int', 4),
+                             ('global_rx_timestamp', 'int', 4),
+                             ('skew_times_1000000',  'int', 4),
+                             ('is_synced',           'int', 1),
+                             ('ftsp_root_addr',      'int', 2),
+                             ('ftsp_seq',            'int', 1),
+                             ('ftsp_table_entries',  'int', 2)],
+                            packet)
+
+if '-h' in sys.argv:
+    print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:57600"
+    sys.exit()
+
+am = tos.AM()
+
+while True:
+    p = am.read()
+    if p and p.type == AM_TEST_FTSP_MSG:
+        msg = FtspMsg(p.data)
+        print int(time.time()), msg.src_addr, msg.counter, msg.global_rx_timestamp, msg.is_synced
+        #print msg
diff --git a/apps/tests/TestFtsp/Ftsp/Makefile b/apps/tests/TestFtsp/Ftsp/Makefile
new file mode 100755 (executable)
index 0000000..25cb720
--- /dev/null
@@ -0,0 +1,17 @@
+BUILD_EXTRA_DEPS = FtspDataLogger.class
+CLEAN_EXTRA = *.class TestFtspMsg.java
+
+FtspDataLogger.class: TestFtspMsg.java
+       javac *.java
+
+TestFtspMsg.java: TestFtsp.h
+       mig java -target=$(PLATFORM) $(CFLAGS) -java-classname=TestFtspMsg TestFtsp.h test_ftsp_msg -o $@
+
+COMPONENT=TestFtspAppC
+
+PFLAGS += -DTIMESYNC_RATE=3
+#PFLAGS += -DTIMESYNC_DEBUG
+
+PFLAGS += -I$(TOSDIR)/lib/ftsp -I$(TOSDIR)/../apps/RadioCountToLeds
+
+include $(MAKERULES)
diff --git a/apps/tests/TestFtsp/Ftsp/README.MATLAB.txt b/apps/tests/TestFtsp/Ftsp/README.MATLAB.txt
new file mode 100755 (executable)
index 0000000..0535549
--- /dev/null
@@ -0,0 +1,46 @@
+FtspDataAnalyzer.m\r
+\r
+-------------------------------------------------------------------------------\r
+Author/Contact:\r
+---------------\r
+ Brano Kusy: branislav.kusy@gmail.com\r
+\r
+-------------------------------------------------------------------------------\r
+DESCRIPTION:\r
+------------\r
+\r
+FtspDataAnalyzer.m works with data logs collected by FtspDataLogger.java and\r
+calculates the maximum and average timesync error over time.\r
+\r
+-------------------------------------------------------------------------------\r
+STEP BY STEP GUIDE TO RUN OUR TEST SCENARIO:\r
+--------------------------------------------\r
+1. program and start motes as described in ./README.txt\r
+2. start SerialForwarder and FtspDataLogger.java as described in ./README.txt\r
+3. 'current_time.report' file (where current_time is a number) is created in ./\r
+   this file is updated with data in the real time\r
+4. let the experiment run for some time\r
+5. start matlab and enter (assuming your current_time was 1206126224593)\r
+    FTSPDataAnalyzer('1206126224593.report')\r
+    this will plot the mean absolute timesync error, global time, and number of\r
+    synced motes; this can be done while experiment is running\r
+6. Matlab also creates data.out file which contains data in the following format\r
+    #seqNum mean_abs_error global_time num_synced_motes\r
+    mean_abs_error is calculated as mean absolute deviation from the mean (mad)\r
+\r
+Simulating multi-hop:\r
+1. define TIMESYNC_DEBUG in the Makefile\r
+2. recompile and upload TestFTSP app to n motes with special NODE_IDs:\r
+     using 'make micaz reinstall.0xAB', nodes 0xAB and 0xCD can communicate\r
+     iff 2D grid coordinates (A,B) and (C,D) are neighbors in a 2D grid\r
\r
+-------------------------------------------------------------------------------\r
+EVALUATION:\r
+--------------------------------------------\r
+ - deployment setup: 11 nodes in a 5x3 grid using simulated multi-hop (4 points\r
+   were vacant as we only used 11 nodes). the max number of hops was 5.\r
+ - parameters: sync period 10sec, polling period 3 sec\r
+ - experiment length: 100 minutes\r
+ - results (1 jiffy is ~30.5 us)\r
+    1.53 jiffy avg error (~50us)\r
+    3.5 jiffy max error (~100us)
\ No newline at end of file
diff --git a/apps/tests/TestFtsp/Ftsp/README.txt b/apps/tests/TestFtsp/Ftsp/README.txt
new file mode 100755 (executable)
index 0000000..b011bc3
--- /dev/null
@@ -0,0 +1,93 @@
+TestFtsp
+
+-------------------------------------------------------------------------------
+Author/Contact:
+---------------
+ Brano Kusy: branislav.kusy@gmail.com
+ Janos Sallai: janos.sallai@vanderbilt.edu
+ Miklos Maroti: mmaroti@gmail.com
+
+-------------------------------------------------------------------------------
+DESCRIPTION:
+------------
+ The TestFtsp application tests the Flooding Time Synchronization Protocol
+ (FTSP) implementation. A network of motes programmed with TestFtsp run the
+ FTSP protocol to time synchronize, and sends to the base station the global
+ reception timestamps of messages broadcast by a dedicated beacon mote
+ programmed with RadioCountToLeds. Ideally, the global reception timestamps of
+ the same RadioCountToLeds message should agree for all TestFtsp motes (with a
+ small synchronization error).
+
+-------------------------------------------------------------------------------
+SUPPORTED PLATFORMS:
+--------------------------------------------
+ The supported platforms are micaz, telosb and iris.
+
+-------------------------------------------------------------------------------
+STEP BY STEP GUIDE TO RUN OUR TEST SCENARIO:
+--------------------------------------------
+ - program one mote with apps/RadioCountToLeds
+ - program multiple motes with TestFtsp
+ - program a mote with apps/BaseStation, leave it on the programming board
+ - turn on all the motes
+ - start the FtspDataLogger java application (type "java FtspDataLogger")
+
+-------------------------------------------------------------------------------
+REPORTED DATA:
+--------------
+ The most important reported data is the global time of arrival of the beacons.
+ The beacon msg arrives to all clients at the same time instant, thus reported
+ global times should be the same for all clients for the same sequence number.
+
+ Each message contains:
+ - the time of message reception by the java app [JAVA_TIME]
+ - the node ID of the mote that is sending this report [NODE_ID]
+ - the  sequence number of the RadioCountToLeds message that is increased
+   for each new polling msg [SEQ_NUM]
+ - the global time when the polling message arrived [GLOB_TIME]
+ - a result_t value indicating if the timestamp is valid [IS_TIME_VALID]
+   (a result_t of 0 denotes a valid timestamp)
+
+If the application is running correctly, then the output should show
+reports from the different FTSP nodes with valid timestamps and similar
+global time values. For example, this is a trace with two FTSP nodes,
+with IDs 1 and 5:
+
+1214516486569 1 10916 433709 0
+1214516486569 5 10916 433709 0
+1214516486809 5 10917 433964 0
+1214516486809 1 10917 433963 0
+1214516487045 5 10918 434210 0
+1214516487053 1 10918 434210 0
+1214516487285 1 10919 434454 0
+1214516487293 5 10919 434455 0
+
+One way to test if FTSP is operating correctly is to turn off one of
+the FTSP nodes. For a short time, that node's global times will differ
+significantly and its valid flag will not be 0. For example, this
+is what it looks like when node 1 in the earlier trace is reset:
+
+1214516490953 5 10934 438208 0
+1214516491201 5 10935 438460 0
+1214516491441 5 10936 438712 0
+1214516491685 5 10937 438964 0
+1214516492169 5 10939 439455 0
+1214516492417 1 10940 243 1
+1214516492421 5 10940 439706 0
+1214516492665 5 10941 439960 0
+1214516492669 1 10941 497 1
+1214516492905 5 10942 440213 0
+...
+1214516497541 1 10961 5495 1
+1214516497549 5 10961 444958 0
+1214516497793 1 10962 5747 1
+1214516498025 1 10963 445456 0
+1214516498033 5 10963 445455 0
+1214516498277 5 10964 445705 0
+1214516498285 1 10964 445707 0
+1214516498521 1 10965 445964 0
+
+This output is also saved in a file named 'current_timestamp.report'.
+'.report' files can be used with the FtspDataAnalyzer.m Matlab
+application. Mean absolute timesync error, global time, and % of
+synced motes will be plotted.
diff --git a/apps/tests/TestFtsp/Ftsp/TestFtsp.h b/apps/tests/TestFtsp/Ftsp/TestFtsp.h
new file mode 100755 (executable)
index 0000000..cc241ab
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2002, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * @author: Miklos Maroti, Brano Kusy (kusy@isis.vanderbilt.edu)
+ * Ported to T2: 3/17/08 by Brano Kusy (branislav.kusy@gmail.com)
+ */
+
+#ifndef TEST_FTSP_H
+#define TEST_FTSP_H
+
+typedef nx_struct test_ftsp_msg
+{
+  nx_uint16_t    src_addr;
+  nx_uint16_t    counter;
+  nx_uint32_t    local_rx_timestamp;
+  nx_uint32_t    global_rx_timestamp;
+  nx_int32_t     skew_times_1000000;
+  nx_uint8_t     is_synced;
+  nx_uint16_t    ftsp_root_addr;
+  nx_uint8_t     ftsp_seq;
+  nx_uint8_t     ftsp_table_entries;
+} test_ftsp_msg_t;
+
+enum
+{
+       AM_TEST_FTSP_MSG = 137
+};
+
+#endif
diff --git a/apps/tests/TestFtsp/Ftsp/TestFtspAppC.nc b/apps/tests/TestFtsp/Ftsp/TestFtspAppC.nc
new file mode 100755 (executable)
index 0000000..d30adcd
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2002, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * @author: Miklos Maroti, Brano Kusy (kusy@isis.vanderbilt.edu)
+ * Ported to T2: 3/17/08 by Brano Kusy (branislav.kusy@gmail.com)
+ */
+
+#include "TestFtsp.h"
+#include "RadioCountToLeds.h"
+
+configuration TestFtspAppC {
+}
+
+implementation {
+  components MainC, TimeSyncC;
+
+  MainC.SoftwareInit -> TimeSyncC;
+  TimeSyncC.Boot -> MainC;
+
+  components TestFtspC as App;
+  App.Boot -> MainC;
+
+  components ActiveMessageC;
+  App.RadioControl -> ActiveMessageC;
+  App.Receive -> ActiveMessageC.Receive[AM_RADIO_COUNT_MSG];
+  App.AMSend -> ActiveMessageC.AMSend[AM_TEST_FTSP_MSG];
+  App.Packet -> ActiveMessageC;
+  App.PacketTimeStamp -> ActiveMessageC;
+
+  components LedsC;
+
+  App.GlobalTime -> TimeSyncC;
+  App.TimeSyncInfo -> TimeSyncC;
+  App.Leds -> LedsC;
+
+}
diff --git a/apps/tests/TestFtsp/Ftsp/TestFtspC.nc b/apps/tests/TestFtsp/Ftsp/TestFtspC.nc
new file mode 100755 (executable)
index 0000000..304da1b
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2002, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * @author: Miklos Maroti, Brano Kusy (kusy@isis.vanderbilt.edu)
+ * Ported to T2: 3/17/08 by Brano Kusy (branislav.kusy@gmail.com)
+ */
+
+#include "TestFtsp.h"
+#include "RadioCountToLeds.h"
+
+module TestFtspC
+{
+    uses
+    {
+        interface GlobalTime<TMilli>;
+        interface TimeSyncInfo;
+        interface Receive;
+        interface AMSend;
+        interface Packet;
+        interface Leds;
+        interface PacketTimeStamp<TMilli,uint32_t>;
+        interface Boot;
+        interface SplitControl as RadioControl;
+    }
+}
+
+implementation
+{
+    message_t msg;
+    bool locked = FALSE;
+
+    event void Boot.booted() {
+        call RadioControl.start();
+    }
+
+    event message_t* Receive.receive(message_t* msgPtr, void* payload, uint8_t len)
+    {
+        call Leds.led0Toggle();
+        if (!locked && call PacketTimeStamp.isValid(msgPtr)) {
+            radio_count_msg_t* rcm = (radio_count_msg_t*)call Packet.getPayload(msgPtr, sizeof(radio_count_msg_t));
+            test_ftsp_msg_t* report = (test_ftsp_msg_t*)call Packet.getPayload(&msg, sizeof(test_ftsp_msg_t));
+
+            uint32_t rxTimestamp = call PacketTimeStamp.timestamp(msgPtr);
+
+            report->src_addr = TOS_NODE_ID;
+            report->counter = rcm->counter;
+            report->local_rx_timestamp = rxTimestamp;
+            report->is_synced = call GlobalTime.local2Global(&rxTimestamp);
+            report->global_rx_timestamp = rxTimestamp;
+            report->skew_times_1000000 = (uint32_t)call TimeSyncInfo.getSkew()*1000000UL;
+            report->ftsp_root_addr = call TimeSyncInfo.getRootID();
+            report->ftsp_seq = call TimeSyncInfo.getSeqNum();
+            report->ftsp_table_entries = call TimeSyncInfo.getNumEntries();
+
+            if (call AMSend.send(AM_BROADCAST_ADDR, &msg, sizeof(test_ftsp_msg_t)) == SUCCESS) {
+              locked = TRUE;
+            }
+        }
+
+        return msgPtr;
+    }
+
+    event void AMSend.sendDone(message_t* ptr, error_t success) {
+        locked = FALSE;
+        return;
+    }
+
+    event void RadioControl.startDone(error_t err) {}
+    event void RadioControl.stopDone(error_t error){}
+}
diff --git a/apps/tests/TestFtsp/FtspDataAnalyzer.m b/apps/tests/TestFtsp/FtspDataAnalyzer.m
deleted file mode 100644 (file)
index 94dda15..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-%load file written out by FtspDataLogger.java class\r
-%arg0 - filename, e.g. '1205543689171.report'\r
-function FTSPDataAnalyzer(file, varargin)\r
-[c1 c2 c3 c4 c5]= textread(file, '%u %u %u %u %u', 'commentstyle', 'shell');\r
-data = [c2 c3 c4 c5]; %skipping the first column (java time)\r
-data1 = sortrows(sortrows(data,1),2);\r
-newdata = [];\r
-\r
-row=1;\r
-newrow=1;\r
-unsynced=0;\r
-while (row<=size(data1,1))\r
-\r
-    seqnum=data1(row,2);\r
-\r
-    data2=[];\r
-    row2=1;\r
-    tmprow1=row;\r
-    while (row <= size(data1,1) && data1(row,2)==seqnum)\r
-        if (data1(row,4)==0)\r
-            data2(row2,1)=data1(row,3);\r
-            row2= row2+ 1;\r
-        else\r
-            unsynced=unsynced+1;\r
-        end\r
-        row = row + 1;\r
-    end\r
-    \r
-    if (row2>1)\r
-        row2size=row2-1;\r
-        rcvdsize=row-tmprow1;\r
-        newdata(newrow,1) = seqnum;\r
-        newdata(newrow,2) = mad(data2(1:row2size,1));\r
-        newdata(newrow,3) = mean(data2(1:row2size,1));\r
-        newdata(newrow,4) = row2size/rcvdsize;\r
-        newrow = newrow + 1;\r
-    end\r
-end\r
-\r
-if (length(newdata)==0)\r
-    disp('no data found (at least one data point from a synchronized mote is required)!');\r
-else\r
-    newsize=newrow-1;\r
-    subplot(3,1,1);\r
-    plot(newdata(1:newsize,1),newdata(1:newsize,2));\r
-    title(sprintf('TimeSync Errors'));\r
-    subplot(3,1,2);\r
-    plot(newdata(1:newsize,1),newdata(1:newsize,3));\r
-    title(sprintf('Avg Glob Time'));\r
-    subplot(3,1,3);\r
-    plot(newdata(1:newsize,1),newdata(1:newsize,4),'b-');\r
-    title(sprintf('%% Synced Motes'));\r
-\r
-    disp(sprintf('total unsycned num %d (all %d)',unsynced,newsize));\r
-    disp(sprintf('avg %0.3f',mean(newdata(1:newsize,2))));\r
-    disp(sprintf('max %d',max(newdata(1:newsize,2))));\r
-    savedata = newdata(1:newsize,:);\r
-    save data.out savedata -ASCII;\r
-end\r
-    
\ No newline at end of file
diff --git a/apps/tests/TestFtsp/FtspDataLogger.java b/apps/tests/TestFtsp/FtspDataLogger.java
deleted file mode 100644 (file)
index 168fa0f..0000000
+++ /dev/null
@@ -1,120 +0,0 @@
-/*                  tab:4
- * "Copyright (c) 2000-2003 The Regents of the University  of California.
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- *
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- * Copyright (c) 2002-2007 Intel Corporation
- * All rights reserved.
- *
- * This file is distributed under the terms in the attached INTEL-LICENSE
- * file. If you do not find these files, copies can be found by writing to
- * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
- * 94704.  Attention:  Intel License Inquiry.
- */
-
-
-/**
- * @author Brano Kusy
- */
-
-import java.io.FileOutputStream;
-import java.io.PrintStream;
-import net.tinyos.message.*;
-import net.tinyos.util.*;
-
-public class FtspDataLogger implements MessageListener {
-        public class RunWhenShuttingDown extends Thread {
-                public void run()
-                {
-                        System.out.println("Control-C caught. Shutting down...");
-                        if (outReport!=null)
-                        outReport.close();
-                }
-        }
-
-  MoteIF mote;    // For talking to the antitheft root node
-
-        void connect()
-        {
-                try {
-                        mote = new MoteIF(PrintStreamMessenger.err);
-                        mote.registerListener(new TestFtspMsg(), this);
-                        System.out.println("Connection ok!");
-                }
-                catch(Exception e) {
-                        e.printStackTrace();
-                        System.exit(2);
-                }
-        }
-        PrintStream outReport = null;
-
-        public FtspDataLogger() {
-                connect();
-                Runtime.getRuntime().addShutdownHook(new RunWhenShuttingDown());
-                String name=""+System.currentTimeMillis();
-                try
-                {
-                        outReport = new PrintStream(new FileOutputStream(name+".report"));
-                        outReport.println("#[JAVA_TIME] [NODE_ID] [SEQ_NUM] [GLOB_TIME] [IS_TIME_VALID]");
-                }
-                catch (Exception e)
-                {
-                        System.out.println("FtspDataLogger.FtspDataLogger(): "+e.toString());
-                }
-        }
-
-        public void writeReprot(TestFtspMsg tspr)
-        {
-                String foo = (System.currentTimeMillis()
-                               +" "+tspr.get_src_addr()+" "+tspr.get_counter()
-                        +" "+tspr.get_global_rx_timestamp()+" "+tspr.get_is_synced());
-                outReport.println(foo);
-                System.out.println(foo);
-                outReport.flush();
-        }
-
-        public void writeFullReprot(TestFtspMsg tspr)
-        {
-                String foo = (System.currentTimeMillis()
-                               +" "+tspr.get_src_addr()
-                        +" "+tspr.get_counter()
-                        +" "+tspr.get_local_rx_timestamp()
-                        +" "+tspr.get_global_rx_timestamp()
-                        +" "+tspr.get_skew_times_1000000()
-                        +" "+tspr.get_is_synced()
-                        +" "+tspr.get_ftsp_root_addr()
-                        +" "+tspr.get_ftsp_seq()
-                        +" "+tspr.get_ftsp_table_entries());
-                outReport.println(foo);
-                System.out.println(foo);
-                outReport.flush();
-        }
-
-        public void messageReceived(int dest_addr, Message msg)
-        {
-                if (msg instanceof TestFtspMsg)
-                        //writeFullReprot((TestFtspMsg)msg);
-                        writeReprot((TestFtspMsg)msg);
-        }
-
-        /* Just start the app... */
-        public static void main(String[] args)
-        {
-                new FtspDataLogger();
-        }
-}
\ No newline at end of file
diff --git a/apps/tests/TestFtsp/FtspLpl/FtspDataLogger.py b/apps/tests/TestFtsp/FtspLpl/FtspDataLogger.py
new file mode 100755 (executable)
index 0000000..0c5687b
--- /dev/null
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+
+import sys, time
+import tos
+
+AM_TEST_FTSP_MSG = 137
+
+class FtspMsg(tos.Packet):
+    def __init__(self, packet = None):
+        tos.Packet.__init__(self,
+                            [('src_addr',            'int', 2),
+                             ('counter',             'int', 2),
+                             ('local_rx_timestamp',  'int', 4),
+                             ('global_rx_timestamp', 'int', 4),
+                             ('skew_times_1000000',  'int', 4),
+                             ('is_synced',           'int', 1),
+                             ('ftsp_root_addr',      'int', 2),
+                             ('ftsp_seq',            'int', 1),
+                             ('ftsp_table_entries',  'int', 2)],
+                            packet)
+
+if '-h' in sys.argv:
+    print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:57600"
+    sys.exit()
+
+am = tos.AM()
+
+while True:
+    p = am.read()
+    if p and p.type == AM_TEST_FTSP_MSG:
+        msg = FtspMsg(p.data)
+        print int(time.time()), msg.src_addr, msg.counter, msg.global_rx_timestamp, msg.is_synced
+        #print msg
diff --git a/apps/tests/TestFtsp/FtspLpl/Makefile b/apps/tests/TestFtsp/FtspLpl/Makefile
new file mode 100755 (executable)
index 0000000..9962988
--- /dev/null
@@ -0,0 +1,16 @@
+SENSORBOARD=quantoplus
+
+COMPONENT=TestFtspAppC
+
+PFLAGS += -DTIMESYNC_RATE=10
+#PFLAGS += -DTIMESYNC_DEBUG
+#PFLAGS += -DCC2420_CHANNEL=26
+CFLAGS += -DTOSH_DATA_LENGTH=50
+#CFLAGS += -DCOUNT_LOG
+
+PFLAGS += -I$(TOSDIR)/lib/ftsp -I$(TOSDIR)/../apps/RadioCountToLeds -I$(TOSDIR)/lib/printf
+
+CFLAGS += -DLPL_INTERVAL=200
+CFLAGS += -DLOW_POWER_LISTENING
+
+include $(MAKERULES)
diff --git a/apps/tests/TestFtsp/FtspLpl/README b/apps/tests/TestFtsp/FtspLpl/README
new file mode 100755 (executable)
index 0000000..24c080c
--- /dev/null
@@ -0,0 +1,31 @@
+First, program several nodes with this TestFtsp application. In addition,
+you will need one TinyOS Basestation that listens for messages, and one
+beacon node. Program the beacon node with the RadioCountToLed application
+from the TestFtsp32kLplBeaconer directory. This is a special modification of
+the RadioCountToLed code which allows to evaluate a duty-cycled ftsp
+network. The regular RadioCountToLed code doesn't work, since a LPL
+broadcast message gets transmitted more than just once. Thus, there is a
+disambiguity in which precise broadcast message was actually timestamped by
+the TestFtsp application. The modifications take care of this by using the
+TimeSyncAMSend interface and setting an arbitrary event time. Thus, on
+reception, the TestFtsp code can account for this delayed send.
+
+To evaluate the synchronization precision, use the FtspDataLogger.py
+application. First, you will need a serial forwarder that connects to the
+BaseStation node. Then, run the python application like this:
+python FtspDataLogger.py sf@localhost:9002
+
+You should now see messages coming in, one per line. The first value is the
+current time as a unix timestamp. The last line is a binary value indicating
+if there was some missed data, and thus the values are not good (indicated
+by a 1), or if all the nodes are synchronized and we received a value for
+each and every one of them (indicated by a 0).
+
+Note!!!!!
+- the basestation should also define
+    CFLAGS += -DTOSH_DATA_LENGTH=50
+    in the makefile. Else, the reports will not fit into 1 tinyos message, and
+    they will get silently dropped.
+- 32k timesync only works for certain platforms (those that provide 32khz
+    counter), if your platform does not support the counter, LPL still works,
+    but you need to use TMilli timesync
diff --git a/apps/tests/TestFtsp/FtspLpl/TestFtsp.h b/apps/tests/TestFtsp/FtspLpl/TestFtsp.h
new file mode 100755 (executable)
index 0000000..57cd25c
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2002, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * @author: Miklos Maroti, Brano Kusy (kusy@isis.vanderbilt.edu)
+ * Ported to T2: 3/17/08 by Brano Kusy (branislav.kusy@gmail.com)
+ */
+
+#ifndef TEST_FTSP_H
+#define TEST_FTSP_H
+
+typedef nx_struct test_ftsp_msg
+{
+  nx_uint16_t    src_addr;
+  nx_uint16_t    counter;
+  nx_uint32_t    local_rx_timestamp;
+  nx_uint32_t    global_rx_timestamp;
+  nx_int32_t     skew_times_1000000;
+  nx_float       skew;
+  nx_uint8_t     is_synced;
+  nx_uint16_t    ftsp_root_addr;
+  nx_uint8_t     ftsp_seq;
+  nx_uint8_t     ftsp_table_entries;
+  nx_uint32_t    localAverage;
+  nx_int32_t     offsetAverage;
+} test_ftsp_msg_t;
+
+enum
+{
+       AM_TEST_FTSP_MSG = 137
+};
+
+#endif
diff --git a/apps/tests/TestFtsp/FtspLpl/TestFtspAppC.nc b/apps/tests/TestFtsp/FtspLpl/TestFtspAppC.nc
new file mode 100755 (executable)
index 0000000..1d52625
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2002, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * @author: Miklos Maroti, Brano Kusy (kusy@isis.vanderbilt.edu)
+ * Ported to T2: 3/17/08 by Brano Kusy (branislav.kusy@gmail.com)
+ * Adapted for LPL: 6/16/09 by Thomas Schmid (thomas.schmid@ucla.edu)
+ */
+
+#include "TestFtsp.h"
+#include "RadioCountToLeds.h"
+
+configuration TestFtspAppC {
+}
+
+implementation {
+  components MainC, TestFtspC as App;
+  App.Boot -> MainC;
+
+  components ActiveMessageC;
+  components TimeSyncMessageC;
+  App.RadioControl -> ActiveMessageC;
+  App.Receive -> TimeSyncMessageC.Receive[AM_RADIO_COUNT_MSG];
+  App.TimeSyncPacket -> TimeSyncMessageC;
+  App.AMSend -> ActiveMessageC.AMSend[AM_TEST_FTSP_MSG];
+  App.Packet -> ActiveMessageC;
+  App.PacketTimeStamp -> ActiveMessageC;
+  App.LowPowerListening -> ActiveMessageC;
+
+
+  components RandomC;
+  App.Random -> RandomC;
+
+  components new TimerMilliC() as Timer0;
+  App.RandomTimer -> Timer0;
+
+  components LedsC;
+
+#if defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB)
+  components TimeSync32kC;
+  MainC.SoftwareInit -> TimeSync32kC;
+  TimeSync32kC.Boot -> MainC;
+  App.GlobalTime -> TimeSync32kC;
+  App.TimeSyncInfo -> TimeSync32kC;
+#else
+#error "LPL timesync is not available for your platform"
+#endif
+  App.Leds -> LedsC;
+  
+}
diff --git a/apps/tests/TestFtsp/FtspLpl/TestFtspC.nc b/apps/tests/TestFtsp/FtspLpl/TestFtspC.nc
new file mode 100755 (executable)
index 0000000..58b58ee
--- /dev/null
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2002, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * @author: Miklos Maroti, Brano Kusy (kusy@isis.vanderbilt.edu)
+ * Ported to T2: 3/17/08 by Brano Kusy (branislav.kusy@gmail.com)
+ * Ported for LPL: Thomas Schmid (thomas.schmid@ucla.edu)
+ */
+
+#include "TestFtsp.h"
+#include "RadioCountToLeds.h"
+
+module TestFtspC
+{
+    uses
+    {
+        interface GlobalTime<T32khz>;
+        interface TimeSyncInfo;
+        interface Receive;
+        interface AMSend;
+        interface Packet;
+        interface Leds;
+        interface PacketTimeStamp<T32khz,uint32_t>;
+        interface Boot;
+        interface SplitControl as RadioControl;
+        interface Timer<TMilli> as RandomTimer;
+        interface Random;
+
+        interface TimeSyncPacket<T32khz,uint32_t>;
+
+        interface LowPowerListening;
+
+    }
+}
+
+implementation
+{
+    enum {
+        ACT_TESTFTSP = 0x11,
+    };
+
+    message_t msg;
+    bool locked = FALSE;
+    test_ftsp_msg_t* report;
+
+    event void Boot.booted() {
+        call RadioControl.start();
+    }
+
+    event message_t* Receive.receive(message_t* msgPtr, void* payload, uint8_t len)
+    {
+        if (!(call PacketTimeStamp.isValid(msgPtr))){
+            call Leds.led1Toggle();
+        }
+        if (!locked && call PacketTimeStamp.isValid(msgPtr)) {
+            radio_count_msg_t* rcm = (radio_count_msg_t*)call Packet.getPayload(msgPtr, sizeof(radio_count_msg_t));
+            if(call TimeSyncPacket.isValid(msgPtr)) {
+                uint32_t rxTimestamp = call TimeSyncPacket.eventTime(msgPtr);
+                report = (test_ftsp_msg_t*)call Packet.getPayload(&msg, sizeof(test_ftsp_msg_t));
+
+                report->src_addr = TOS_NODE_ID;
+                report->counter = rcm->counter;
+                report->local_rx_timestamp = rxTimestamp;
+                report->is_synced = call GlobalTime.local2Global(&rxTimestamp);
+                report->global_rx_timestamp = rxTimestamp;
+                report->skew_times_1000000 = (uint32_t)call TimeSyncInfo.getSkew()*1000000UL;
+                report->skew = call TimeSyncInfo.getSkew();
+                report->ftsp_root_addr = call TimeSyncInfo.getRootID();
+                report->ftsp_seq = call TimeSyncInfo.getSeqNum();
+                report->ftsp_table_entries = call TimeSyncInfo.getNumEntries();
+                report->localAverage = call TimeSyncInfo.getSyncPoint();
+                report->offsetAverage = call TimeSyncInfo.getOffset();
+
+                locked = TRUE;
+                call RandomTimer.startOneShot(call Random.rand16() % (64));
+            }
+        }
+
+        return msgPtr;
+    }
+
+    event void RandomTimer.fired()
+    {
+#ifdef LOW_POWER_LISTENING
+        call LowPowerListening.setRemoteWakeupInterval(&msg, LPL_INTERVAL);
+#endif
+        if(locked && (call AMSend.send(4000, &msg, sizeof(test_ftsp_msg_t)) == SUCCESS)){
+            call Leds.led2On();
+        } else {
+            locked = FALSE;
+        }
+    }
+
+    event void AMSend.sendDone(message_t* ptr, error_t success) {
+        locked = FALSE;
+        call Leds.led2Off();
+        return;
+    }
+
+    event void RadioControl.startDone(error_t err) {
+        call LowPowerListening.setLocalWakeupInterval(LPL_INTERVAL);
+    }
+    event void RadioControl.stopDone(error_t error){}
+}
diff --git a/apps/tests/TestFtsp/FtspLpl/TestFtspMsg.py b/apps/tests/TestFtsp/FtspLpl/TestFtspMsg.py
new file mode 100755 (executable)
index 0000000..0223c4d
--- /dev/null
@@ -0,0 +1,744 @@
+#
+# This class is automatically generated by mig. DO NOT EDIT THIS FILE.
+# This class implements a Python interface to the 'TestFtspMsg'
+# message type.
+#
+
+import tinyos.message.Message
+
+# The default size of this message type in bytes.
+DEFAULT_MESSAGE_SIZE = 33
+
+# The Active Message type associated with this message.
+AM_TYPE = 137
+
+class TestFtspMsg(tinyos.message.Message.Message):
+    # Create a new TestFtspMsg of size 33.
+    def __init__(self, data="", addr=None, gid=None, base_offset=0, data_length=33):
+        tinyos.message.Message.Message.__init__(self, data, addr, gid, base_offset, data_length)
+        self.amTypeSet(AM_TYPE)
+
+    # Get AM_TYPE
+    def get_amType(cls):
+        return AM_TYPE
+
+    get_amType = classmethod(get_amType)
+
+    #
+    # Return a String representation of this message. Includes the
+    # message type name and the non-indexed field values.
+    #
+    def __str__(self):
+        s = "Message <TestFtspMsg> \n"
+        try:
+            s += "  [src_addr=0x%x]\n" % (self.get_src_addr())
+        except:
+            pass
+        try:
+            s += "  [counter=0x%x]\n" % (self.get_counter())
+        except:
+            pass
+        try:
+            s += "  [local_rx_timestamp=0x%x]\n" % (self.get_local_rx_timestamp())
+        except:
+            pass
+        try:
+            s += "  [global_rx_timestamp=0x%x]\n" % (self.get_global_rx_timestamp())
+        except:
+            pass
+        try:
+            s += "  [skew_times_1000000=0x%x]\n" % (self.get_skew_times_1000000())
+        except:
+            pass
+        try:
+            s += "  [skew=0x%x]\n" % (self.get_skew())
+        except:
+            pass
+        try:
+            s += "  [is_synced=0x%x]\n" % (self.get_is_synced())
+        except:
+            pass
+        try:
+            s += "  [ftsp_root_addr=0x%x]\n" % (self.get_ftsp_root_addr())
+        except:
+            pass
+        try:
+            s += "  [ftsp_seq=0x%x]\n" % (self.get_ftsp_seq())
+        except:
+            pass
+        try:
+            s += "  [ftsp_table_entries=0x%x]\n" % (self.get_ftsp_table_entries())
+        except:
+            pass
+        try:
+            s += "  [localAverage=0x%x]\n" % (self.get_localAverage())
+        except:
+            pass
+        try:
+            s += "  [offsetAverage=0x%x]\n" % (self.get_offsetAverage())
+        except:
+            pass
+        return s
+
+    # Message-type-specific access methods appear below.
+
+    #
+    # Accessor methods for field: src_addr
+    #   Field type: int
+    #   Offset (bits): 0
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'src_addr' is signed (False).
+    #
+    def isSigned_src_addr(self):
+        return False
+
+    #
+    # Return whether the field 'src_addr' is an array (False).
+    #
+    def isArray_src_addr(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'src_addr'
+    #
+    def offset_src_addr(self):
+        return (0 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'src_addr'
+    #
+    def offsetBits_src_addr(self):
+        return 0
+
+    #
+    # Return the value (as a int) of the field 'src_addr'
+    #
+    def get_src_addr(self):
+        return self.getUIntElement(self.offsetBits_src_addr(), 16, 1)
+
+    #
+    # Set the value of the field 'src_addr'
+    #
+    def set_src_addr(self, value):
+        self.setUIntElement(self.offsetBits_src_addr(), 16, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'src_addr'
+    #
+    def size_src_addr(self):
+        return (16 / 8)
+
+    #
+    # Return the size, in bits, of the field 'src_addr'
+    #
+    def sizeBits_src_addr(self):
+        return 16
+
+    #
+    # Accessor methods for field: counter
+    #   Field type: int
+    #   Offset (bits): 16
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'counter' is signed (False).
+    #
+    def isSigned_counter(self):
+        return False
+
+    #
+    # Return whether the field 'counter' is an array (False).
+    #
+    def isArray_counter(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'counter'
+    #
+    def offset_counter(self):
+        return (16 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'counter'
+    #
+    def offsetBits_counter(self):
+        return 16
+
+    #
+    # Return the value (as a int) of the field 'counter'
+    #
+    def get_counter(self):
+        return self.getUIntElement(self.offsetBits_counter(), 16, 1)
+
+    #
+    # Set the value of the field 'counter'
+    #
+    def set_counter(self, value):
+        self.setUIntElement(self.offsetBits_counter(), 16, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'counter'
+    #
+    def size_counter(self):
+        return (16 / 8)
+
+    #
+    # Return the size, in bits, of the field 'counter'
+    #
+    def sizeBits_counter(self):
+        return 16
+
+    #
+    # Accessor methods for field: local_rx_timestamp
+    #   Field type: long
+    #   Offset (bits): 32
+    #   Size (bits): 32
+    #
+
+    #
+    # Return whether the field 'local_rx_timestamp' is signed (False).
+    #
+    def isSigned_local_rx_timestamp(self):
+        return False
+
+    #
+    # Return whether the field 'local_rx_timestamp' is an array (False).
+    #
+    def isArray_local_rx_timestamp(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'local_rx_timestamp'
+    #
+    def offset_local_rx_timestamp(self):
+        return (32 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'local_rx_timestamp'
+    #
+    def offsetBits_local_rx_timestamp(self):
+        return 32
+
+    #
+    # Return the value (as a long) of the field 'local_rx_timestamp'
+    #
+    def get_local_rx_timestamp(self):
+        return self.getUIntElement(self.offsetBits_local_rx_timestamp(), 32, 1)
+
+    #
+    # Set the value of the field 'local_rx_timestamp'
+    #
+    def set_local_rx_timestamp(self, value):
+        self.setUIntElement(self.offsetBits_local_rx_timestamp(), 32, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'local_rx_timestamp'
+    #
+    def size_local_rx_timestamp(self):
+        return (32 / 8)
+
+    #
+    # Return the size, in bits, of the field 'local_rx_timestamp'
+    #
+    def sizeBits_local_rx_timestamp(self):
+        return 32
+
+    #
+    # Accessor methods for field: global_rx_timestamp
+    #   Field type: long
+    #   Offset (bits): 64
+    #   Size (bits): 32
+    #
+
+    #
+    # Return whether the field 'global_rx_timestamp' is signed (False).
+    #
+    def isSigned_global_rx_timestamp(self):
+        return False
+
+    #
+    # Return whether the field 'global_rx_timestamp' is an array (False).
+    #
+    def isArray_global_rx_timestamp(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'global_rx_timestamp'
+    #
+    def offset_global_rx_timestamp(self):
+        return (64 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'global_rx_timestamp'
+    #
+    def offsetBits_global_rx_timestamp(self):
+        return 64
+
+    #
+    # Return the value (as a long) of the field 'global_rx_timestamp'
+    #
+    def get_global_rx_timestamp(self):
+        return self.getUIntElement(self.offsetBits_global_rx_timestamp(), 32, 1)
+
+    #
+    # Set the value of the field 'global_rx_timestamp'
+    #
+    def set_global_rx_timestamp(self, value):
+        self.setUIntElement(self.offsetBits_global_rx_timestamp(), 32, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'global_rx_timestamp'
+    #
+    def size_global_rx_timestamp(self):
+        return (32 / 8)
+
+    #
+    # Return the size, in bits, of the field 'global_rx_timestamp'
+    #
+    def sizeBits_global_rx_timestamp(self):
+        return 32
+
+    #
+    # Accessor methods for field: skew_times_1000000
+    #   Field type: int
+    #   Offset (bits): 96
+    #   Size (bits): 32
+    #
+
+    #
+    # Return whether the field 'skew_times_1000000' is signed (False).
+    #
+    def isSigned_skew_times_1000000(self):
+        return False
+
+    #
+    # Return whether the field 'skew_times_1000000' is an array (False).
+    #
+    def isArray_skew_times_1000000(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'skew_times_1000000'
+    #
+    def offset_skew_times_1000000(self):
+        return (96 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'skew_times_1000000'
+    #
+    def offsetBits_skew_times_1000000(self):
+        return 96
+
+    #
+    # Return the value (as a int) of the field 'skew_times_1000000'
+    #
+    def get_skew_times_1000000(self):
+        return self.getSIntElement(self.offsetBits_skew_times_1000000(), 32, 1)
+
+    #
+    # Set the value of the field 'skew_times_1000000'
+    #
+    def set_skew_times_1000000(self, value):
+        self.setSIntElement(self.offsetBits_skew_times_1000000(), 32, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'skew_times_1000000'
+    #
+    def size_skew_times_1000000(self):
+        return (32 / 8)
+
+    #
+    # Return the size, in bits, of the field 'skew_times_1000000'
+    #
+    def sizeBits_skew_times_1000000(self):
+        return 32
+
+    #
+    # Accessor methods for field: skew
+    #   Field type: int
+    #   Offset (bits): 128
+    #   Size (bits): 32
+    #
+
+    #
+    # Return whether the field 'skew' is signed (False).
+    #
+    def isSigned_skew(self):
+        return False
+
+    #
+    # Return whether the field 'skew' is an array (False).
+    #
+    def isArray_skew(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'skew'
+    #
+    def offset_skew(self):
+        return (128 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'skew'
+    #
+    def offsetBits_skew(self):
+        return 128
+
+    #
+    # Return the value (as a int) of the field 'skew'
+    #
+    def get_skew(self):
+        return self.getFloatElement(self.offsetBits_skew(), 32, 0)
+
+    #
+    # Set the value of the field 'skew'
+    #
+    def set_skew(self, value):
+        self.setSIntElement(self.offsetBits_skew(), 32, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'skew'
+    #
+    def size_skew(self):
+        return (32 / 8)
+
+    #
+    # Return the size, in bits, of the field 'skew'
+    #
+    def sizeBits_skew(self):
+        return 32
+
+    #
+    # Accessor methods for field: is_synced
+    #   Field type: short
+    #   Offset (bits): 160
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'is_synced' is signed (False).
+    #
+    def isSigned_is_synced(self):
+        return False
+
+    #
+    # Return whether the field 'is_synced' is an array (False).
+    #
+    def isArray_is_synced(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'is_synced'
+    #
+    def offset_is_synced(self):
+        return (160 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'is_synced'
+    #
+    def offsetBits_is_synced(self):
+        return 160
+
+    #
+    # Return the value (as a short) of the field 'is_synced'
+    #
+    def get_is_synced(self):
+        return self.getUIntElement(self.offsetBits_is_synced(), 8, 1)
+
+    #
+    # Set the value of the field 'is_synced'
+    #
+    def set_is_synced(self, value):
+        self.setUIntElement(self.offsetBits_is_synced(), 8, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'is_synced'
+    #
+    def size_is_synced(self):
+        return (8 / 8)
+
+    #
+    # Return the size, in bits, of the field 'is_synced'
+    #
+    def sizeBits_is_synced(self):
+        return 8
+
+    #
+    # Accessor methods for field: ftsp_root_addr
+    #   Field type: int
+    #   Offset (bits): 168
+    #   Size (bits): 16
+    #
+
+    #
+    # Return whether the field 'ftsp_root_addr' is signed (False).
+    #
+    def isSigned_ftsp_root_addr(self):
+        return False
+
+    #
+    # Return whether the field 'ftsp_root_addr' is an array (False).
+    #
+    def isArray_ftsp_root_addr(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'ftsp_root_addr'
+    #
+    def offset_ftsp_root_addr(self):
+        return (168 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'ftsp_root_addr'
+    #
+    def offsetBits_ftsp_root_addr(self):
+        return 168
+
+    #
+    # Return the value (as a int) of the field 'ftsp_root_addr'
+    #
+    def get_ftsp_root_addr(self):
+        return self.getUIntElement(self.offsetBits_ftsp_root_addr(), 16, 1)
+
+    #
+    # Set the value of the field 'ftsp_root_addr'
+    #
+    def set_ftsp_root_addr(self, value):
+        self.setUIntElement(self.offsetBits_ftsp_root_addr(), 16, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'ftsp_root_addr'
+    #
+    def size_ftsp_root_addr(self):
+        return (16 / 8)
+
+    #
+    # Return the size, in bits, of the field 'ftsp_root_addr'
+    #
+    def sizeBits_ftsp_root_addr(self):
+        return 16
+
+    #
+    # Accessor methods for field: ftsp_seq
+    #   Field type: short
+    #   Offset (bits): 184
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ftsp_seq' is signed (False).
+    #
+    def isSigned_ftsp_seq(self):
+        return False
+
+    #
+    # Return whether the field 'ftsp_seq' is an array (False).
+    #
+    def isArray_ftsp_seq(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'ftsp_seq'
+    #
+    def offset_ftsp_seq(self):
+        return (184 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'ftsp_seq'
+    #
+    def offsetBits_ftsp_seq(self):
+        return 184
+
+    #
+    # Return the value (as a short) of the field 'ftsp_seq'
+    #
+    def get_ftsp_seq(self):
+        return self.getUIntElement(self.offsetBits_ftsp_seq(), 8, 1)
+
+    #
+    # Set the value of the field 'ftsp_seq'
+    #
+    def set_ftsp_seq(self, value):
+        self.setUIntElement(self.offsetBits_ftsp_seq(), 8, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'ftsp_seq'
+    #
+    def size_ftsp_seq(self):
+        return (8 / 8)
+
+    #
+    # Return the size, in bits, of the field 'ftsp_seq'
+    #
+    def sizeBits_ftsp_seq(self):
+        return 8
+
+    #
+    # Accessor methods for field: ftsp_table_entries
+    #   Field type: short
+    #   Offset (bits): 192
+    #   Size (bits): 8
+    #
+
+    #
+    # Return whether the field 'ftsp_table_entries' is signed (False).
+    #
+    def isSigned_ftsp_table_entries(self):
+        return False
+
+    #
+    # Return whether the field 'ftsp_table_entries' is an array (False).
+    #
+    def isArray_ftsp_table_entries(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'ftsp_table_entries'
+    #
+    def offset_ftsp_table_entries(self):
+        return (192 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'ftsp_table_entries'
+    #
+    def offsetBits_ftsp_table_entries(self):
+        return 192
+
+    #
+    # Return the value (as a short) of the field 'ftsp_table_entries'
+    #
+    def get_ftsp_table_entries(self):
+        return self.getUIntElement(self.offsetBits_ftsp_table_entries(), 8, 1)
+
+    #
+    # Set the value of the field 'ftsp_table_entries'
+    #
+    def set_ftsp_table_entries(self, value):
+        self.setUIntElement(self.offsetBits_ftsp_table_entries(), 8, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'ftsp_table_entries'
+    #
+    def size_ftsp_table_entries(self):
+        return (8 / 8)
+
+    #
+    # Return the size, in bits, of the field 'ftsp_table_entries'
+    #
+    def sizeBits_ftsp_table_entries(self):
+        return 8
+
+    #
+    # Accessor methods for field: localAverage
+    #   Field type: long
+    #   Offset (bits): 200
+    #   Size (bits): 32
+    #
+
+    #
+    # Return whether the field 'localAverage' is signed (False).
+    #
+    def isSigned_localAverage(self):
+        return False
+
+    #
+    # Return whether the field 'localAverage' is an array (False).
+    #
+    def isArray_localAverage(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'localAverage'
+    #
+    def offset_localAverage(self):
+        return (200 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'localAverage'
+    #
+    def offsetBits_localAverage(self):
+        return 200
+
+    #
+    # Return the value (as a long) of the field 'localAverage'
+    #
+    def get_localAverage(self):
+        return self.getUIntElement(self.offsetBits_localAverage(), 32, 1)
+
+    #
+    # Set the value of the field 'localAverage'
+    #
+    def set_localAverage(self, value):
+        self.setUIntElement(self.offsetBits_localAverage(), 32, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'localAverage'
+    #
+    def size_localAverage(self):
+        return (32 / 8)
+
+    #
+    # Return the size, in bits, of the field 'localAverage'
+    #
+    def sizeBits_localAverage(self):
+        return 32
+
+    #
+    # Accessor methods for field: offsetAverage
+    #   Field type: int
+    #   Offset (bits): 232
+    #   Size (bits): 32
+    #
+
+    #
+    # Return whether the field 'offsetAverage' is signed (False).
+    #
+    def isSigned_offsetAverage(self):
+        return False
+
+    #
+    # Return whether the field 'offsetAverage' is an array (False).
+    #
+    def isArray_offsetAverage(self):
+        return False
+
+    #
+    # Return the offset (in bytes) of the field 'offsetAverage'
+    #
+    def offset_offsetAverage(self):
+        return (232 / 8)
+
+    #
+    # Return the offset (in bits) of the field 'offsetAverage'
+    #
+    def offsetBits_offsetAverage(self):
+        return 232
+
+    #
+    # Return the value (as a int) of the field 'offsetAverage'
+    #
+    def get_offsetAverage(self):
+        return self.getSIntElement(self.offsetBits_offsetAverage(), 32, 1)
+
+    #
+    # Set the value of the field 'offsetAverage'
+    #
+    def set_offsetAverage(self, value):
+        self.setSIntElement(self.offsetBits_offsetAverage(), 32, value, 1)
+
+    #
+    # Return the size, in bytes, of the field 'offsetAverage'
+    #
+    def size_offsetAverage(self):
+        return (32 / 8)
+
+    #
+    # Return the size, in bits, of the field 'offsetAverage'
+    #
+    def sizeBits_offsetAverage(self):
+        return 32
+
diff --git a/apps/tests/TestFtsp/FtspLplBeaconer/Makefile b/apps/tests/TestFtsp/FtspLplBeaconer/Makefile
new file mode 100755 (executable)
index 0000000..a935c01
--- /dev/null
@@ -0,0 +1,7 @@
+COMPONENT=RadioCountToLedsAppC
+
+CFLAGS += -DLPL_INTERVAL=200
+CFLAGS += -DLOW_POWER_LISTENING
+
+include $(MAKERULES)
+
diff --git a/apps/tests/TestFtsp/FtspLplBeaconer/RadioCountToLeds.h b/apps/tests/TestFtsp/FtspLplBeaconer/RadioCountToLeds.h
new file mode 100755 (executable)
index 0000000..8d29f3f
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * "Copyright (c) 2004-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+#ifndef RADIO_COUNT_TO_LEDS_H
+#define RADIO_COUNT_TO_LEDS_H
+
+typedef nx_struct radio_count_msg {
+  nx_uint16_t counter;
+} radio_count_msg_t;
+
+enum {
+  AM_RADIO_COUNT_MSG = 6,
+};
+
+#endif
diff --git a/apps/tests/TestFtsp/FtspLplBeaconer/RadioCountToLedsAppC.nc b/apps/tests/TestFtsp/FtspLplBeaconer/RadioCountToLedsAppC.nc
new file mode 100755 (executable)
index 0000000..13f3667
--- /dev/null
@@ -0,0 +1,74 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+#include "RadioCountToLeds.h"
+#include "Timer.h"
+
+/**
+ * Configuration for the RadioCountToLeds application. RadioCountToLeds 
+ * maintains a 4Hz counter, broadcasting its value in an AM packet 
+ * every time it gets updated. A RadioCountToLeds node that hears a counter 
+ * displays the bottom three bits on its LEDs. This application is a useful 
+ * test to show that basic AM communication and timers work.
+ *
+ * @author Philip Levis
+ * @date   June 6 2005
+ */
+
+configuration RadioCountToLedsAppC {}
+implementation {
+  components MainC, new RadioCountToLedsC(T32khz) as App, LedsC;
+  components new AMReceiverC(AM_RADIO_COUNT_MSG);
+  components new TimerMilliC();
+  components TimeSyncMessageC as ActiveMessageC;
+  
+  App.Boot -> MainC.Boot;
+  
+  App.Receive -> AMReceiverC;
+  App.AMSend -> ActiveMessageC.TimeSyncAMSend32khz[AM_RADIO_COUNT_MSG];
+  App.AMControl -> ActiveMessageC;
+  App.Leds -> LedsC;
+  App.MilliTimer -> TimerMilliC;
+  App.Packet -> ActiveMessageC;
+
+  components Counter32khz32C, new CounterToLocalTimeC(T32khz) as LocalTime32khzC;
+  LocalTime32khzC.Counter -> Counter32khz32C;
+  App.LocalTime     -> LocalTime32khzC;
+
+
+#ifdef LOW_POWER_LISTENING
+  components CC2420ActiveMessageC;
+  App.LowPowerListening -> CC2420ActiveMessageC;
+#endif
+
+}
+
+
diff --git a/apps/tests/TestFtsp/FtspLplBeaconer/RadioCountToLedsC.nc b/apps/tests/TestFtsp/FtspLplBeaconer/RadioCountToLedsC.nc
new file mode 100755 (executable)
index 0000000..02b613b
--- /dev/null
@@ -0,0 +1,148 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+#include "Timer.h"
+#include "RadioCountToLeds.h"
+/**
+ * Implementation of the RadioCountToLeds application. RadioCountToLeds 
+ * maintains a 4Hz counter, broadcasting its value in an AM packet 
+ * every time it gets updated. A RadioCountToLeds node that hears a counter 
+ * displays the bottom three bits on its LEDs. This application is a useful 
+ * test to show that basic AM communication and timers work.
+ *
+ * @author Philip Levis
+ * @date   June 6 2005
+ */
+
+generic module RadioCountToLedsC(typedef precision_tag) @safe() {
+  uses {
+    interface Leds;
+    interface Boot;
+    interface Receive;
+    interface TimeSyncAMSend<precision_tag,uint32_t> as AMSend;
+    interface Timer<TMilli> as MilliTimer;
+    interface SplitControl as AMControl;
+    interface Packet;
+
+    interface LocalTime<precision_tag> as LocalTime;
+
+
+#ifdef LOW_POWER_LISTENING
+    interface LowPowerListening;
+#endif
+
+  }
+}
+implementation {
+
+  message_t packet;
+
+  bool locked;
+  uint16_t counter = 0;
+  
+  event void Boot.booted() {
+    call AMControl.start();
+  }
+
+  event void AMControl.startDone(error_t err) {
+    if (err == SUCCESS) {
+      call MilliTimer.startPeriodic(2*1024);
+    }
+    else {
+      call AMControl.start();
+    }
+  }
+
+  event void AMControl.stopDone(error_t err) {
+    // do nothing
+  }
+  
+  event void MilliTimer.fired() {
+      uint32_t time = call LocalTime.get();
+    counter++;
+    dbg("RadioCountToLedsC", "RadioCountToLedsC: timer fired, counter is %hu.\n", counter);
+    if (locked) {
+      return;
+    }
+    else {
+      radio_count_msg_t* rcm = (radio_count_msg_t*)call Packet.getPayload(&packet, sizeof(radio_count_msg_t));
+      if (rcm == NULL) {
+       return;
+      }
+
+      rcm->counter = counter;
+#ifdef LOW_POWER_LISTENING
+      call LowPowerListening.setRemoteWakeupInterval(&packet, LPL_INTERVAL);
+#endif
+      
+      if (call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(radio_count_msg_t), time) == SUCCESS) {
+       dbg("RadioCountToLedsC", "RadioCountToLedsC: packet sent.\n", counter); 
+       locked = TRUE;
+      }
+    }
+  }
+
+  event message_t* Receive.receive(message_t* bufPtr, 
+                                  void* payload, uint8_t len) {
+    dbg("RadioCountToLedsC", "Received packet of length %hhu.\n", len);
+    if (len != sizeof(radio_count_msg_t)) {return bufPtr;}
+    else {
+      radio_count_msg_t* rcm = (radio_count_msg_t*)payload;
+      if (rcm->counter & 0x1) {
+       call Leds.led0On();
+      }
+      else {
+       call Leds.led0Off();
+      }
+      if (rcm->counter & 0x2) {
+       call Leds.led1On();
+      }
+      else {
+       call Leds.led1Off();
+      }
+      if (rcm->counter & 0x4) {
+       call Leds.led2On();
+      }
+      else {
+       call Leds.led2Off();
+      }
+      return bufPtr;
+    }
+  }
+
+  event void AMSend.sendDone(message_t* bufPtr, error_t error) {
+    if (&packet == bufPtr) {
+      locked = FALSE;
+    }
+  }
+
+}
diff --git a/apps/tests/TestFtsp/Makefile b/apps/tests/TestFtsp/Makefile
deleted file mode 100644 (file)
index 25cb720..0000000
+++ /dev/null
@@ -1,17 +0,0 @@
-BUILD_EXTRA_DEPS = FtspDataLogger.class
-CLEAN_EXTRA = *.class TestFtspMsg.java
-
-FtspDataLogger.class: TestFtspMsg.java
-       javac *.java
-
-TestFtspMsg.java: TestFtsp.h
-       mig java -target=$(PLATFORM) $(CFLAGS) -java-classname=TestFtspMsg TestFtsp.h test_ftsp_msg -o $@
-
-COMPONENT=TestFtspAppC
-
-PFLAGS += -DTIMESYNC_RATE=3
-#PFLAGS += -DTIMESYNC_DEBUG
-
-PFLAGS += -I$(TOSDIR)/lib/ftsp -I$(TOSDIR)/../apps/RadioCountToLeds
-
-include $(MAKERULES)
diff --git a/apps/tests/TestFtsp/README.txt b/apps/tests/TestFtsp/README.txt
deleted file mode 100644 (file)
index b011bc3..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-TestFtsp
-
--------------------------------------------------------------------------------
-Author/Contact:
----------------
- Brano Kusy: branislav.kusy@gmail.com
- Janos Sallai: janos.sallai@vanderbilt.edu
- Miklos Maroti: mmaroti@gmail.com
-
--------------------------------------------------------------------------------
-DESCRIPTION:
-------------
- The TestFtsp application tests the Flooding Time Synchronization Protocol
- (FTSP) implementation. A network of motes programmed with TestFtsp run the
- FTSP protocol to time synchronize, and sends to the base station the global
- reception timestamps of messages broadcast by a dedicated beacon mote
- programmed with RadioCountToLeds. Ideally, the global reception timestamps of
- the same RadioCountToLeds message should agree for all TestFtsp motes (with a
- small synchronization error).
-
--------------------------------------------------------------------------------
-SUPPORTED PLATFORMS:
---------------------------------------------
- The supported platforms are micaz, telosb and iris.
-
--------------------------------------------------------------------------------
-STEP BY STEP GUIDE TO RUN OUR TEST SCENARIO:
---------------------------------------------
- - program one mote with apps/RadioCountToLeds
- - program multiple motes with TestFtsp
- - program a mote with apps/BaseStation, leave it on the programming board
- - turn on all the motes
- - start the FtspDataLogger java application (type "java FtspDataLogger")
-
--------------------------------------------------------------------------------
-REPORTED DATA:
---------------
- The most important reported data is the global time of arrival of the beacons.
- The beacon msg arrives to all clients at the same time instant, thus reported
- global times should be the same for all clients for the same sequence number.
-
- Each message contains:
- - the time of message reception by the java app [JAVA_TIME]
- - the node ID of the mote that is sending this report [NODE_ID]
- - the  sequence number of the RadioCountToLeds message that is increased
-   for each new polling msg [SEQ_NUM]
- - the global time when the polling message arrived [GLOB_TIME]
- - a result_t value indicating if the timestamp is valid [IS_TIME_VALID]
-   (a result_t of 0 denotes a valid timestamp)
-
-If the application is running correctly, then the output should show
-reports from the different FTSP nodes with valid timestamps and similar
-global time values. For example, this is a trace with two FTSP nodes,
-with IDs 1 and 5:
-
-1214516486569 1 10916 433709 0
-1214516486569 5 10916 433709 0
-1214516486809 5 10917 433964 0
-1214516486809 1 10917 433963 0
-1214516487045 5 10918 434210 0
-1214516487053 1 10918 434210 0
-1214516487285 1 10919 434454 0
-1214516487293 5 10919 434455 0
-
-One way to test if FTSP is operating correctly is to turn off one of
-the FTSP nodes. For a short time, that node's global times will differ
-significantly and its valid flag will not be 0. For example, this
-is what it looks like when node 1 in the earlier trace is reset:
-
-1214516490953 5 10934 438208 0
-1214516491201 5 10935 438460 0
-1214516491441 5 10936 438712 0
-1214516491685 5 10937 438964 0
-1214516492169 5 10939 439455 0
-1214516492417 1 10940 243 1
-1214516492421 5 10940 439706 0
-1214516492665 5 10941 439960 0
-1214516492669 1 10941 497 1
-1214516492905 5 10942 440213 0
-...
-1214516497541 1 10961 5495 1
-1214516497549 5 10961 444958 0
-1214516497793 1 10962 5747 1
-1214516498025 1 10963 445456 0
-1214516498033 5 10963 445455 0
-1214516498277 5 10964 445705 0
-1214516498285 1 10964 445707 0
-1214516498521 1 10965 445964 0
-
-This output is also saved in a file named 'current_timestamp.report'.
-'.report' files can be used with the FtspDataAnalyzer.m Matlab
-application. Mean absolute timesync error, global time, and % of
-synced motes will be plotted.
diff --git a/apps/tests/TestFtsp/TestFtsp.h b/apps/tests/TestFtsp/TestFtsp.h
deleted file mode 100644 (file)
index c5ded36..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2002, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- *
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * @author: Miklos Maroti, Brano Kusy (kusy@isis.vanderbilt.edu)
- * Ported to T2: 3/17/08 by Brano Kusy (branislav.kusy@gmail.com)
- */
-
-#ifndef TEST_FTSP_H
-#define TEST_FTSP_H
-
-typedef nx_struct test_ftsp_msg
-{
-  nx_uint16_t    src_addr;
-  nx_uint16_t    counter;
-  nx_uint32_t    local_rx_timestamp;
-  nx_uint32_t    global_rx_timestamp;
-  nx_uint32_t    skew_times_1000000;
-  nx_uint8_t     is_synced;
-  nx_uint16_t    ftsp_root_addr;
-  nx_uint8_t     ftsp_seq;
-  nx_uint8_t     ftsp_table_entries;
-} test_ftsp_msg_t;
-
-enum
-{
-       AM_TEST_FTSP_MSG = 137
-};
-
-#endif
diff --git a/apps/tests/TestFtsp/TestFtspAppC.nc b/apps/tests/TestFtsp/TestFtspAppC.nc
deleted file mode 100644 (file)
index d30adcd..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2002, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- *
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * @author: Miklos Maroti, Brano Kusy (kusy@isis.vanderbilt.edu)
- * Ported to T2: 3/17/08 by Brano Kusy (branislav.kusy@gmail.com)
- */
-
-#include "TestFtsp.h"
-#include "RadioCountToLeds.h"
-
-configuration TestFtspAppC {
-}
-
-implementation {
-  components MainC, TimeSyncC;
-
-  MainC.SoftwareInit -> TimeSyncC;
-  TimeSyncC.Boot -> MainC;
-
-  components TestFtspC as App;
-  App.Boot -> MainC;
-
-  components ActiveMessageC;
-  App.RadioControl -> ActiveMessageC;
-  App.Receive -> ActiveMessageC.Receive[AM_RADIO_COUNT_MSG];
-  App.AMSend -> ActiveMessageC.AMSend[AM_TEST_FTSP_MSG];
-  App.Packet -> ActiveMessageC;
-  App.PacketTimeStamp -> ActiveMessageC;
-
-  components LedsC;
-
-  App.GlobalTime -> TimeSyncC;
-  App.TimeSyncInfo -> TimeSyncC;
-  App.Leds -> LedsC;
-
-}
diff --git a/apps/tests/TestFtsp/TestFtspC.nc b/apps/tests/TestFtsp/TestFtspC.nc
deleted file mode 100644 (file)
index 304da1b..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2002, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- *
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * @author: Miklos Maroti, Brano Kusy (kusy@isis.vanderbilt.edu)
- * Ported to T2: 3/17/08 by Brano Kusy (branislav.kusy@gmail.com)
- */
-
-#include "TestFtsp.h"
-#include "RadioCountToLeds.h"
-
-module TestFtspC
-{
-    uses
-    {
-        interface GlobalTime<TMilli>;
-        interface TimeSyncInfo;
-        interface Receive;
-        interface AMSend;
-        interface Packet;
-        interface Leds;
-        interface PacketTimeStamp<TMilli,uint32_t>;
-        interface Boot;
-        interface SplitControl as RadioControl;
-    }
-}
-
-implementation
-{
-    message_t msg;
-    bool locked = FALSE;
-
-    event void Boot.booted() {
-        call RadioControl.start();
-    }
-
-    event message_t* Receive.receive(message_t* msgPtr, void* payload, uint8_t len)
-    {
-        call Leds.led0Toggle();
-        if (!locked && call PacketTimeStamp.isValid(msgPtr)) {
-            radio_count_msg_t* rcm = (radio_count_msg_t*)call Packet.getPayload(msgPtr, sizeof(radio_count_msg_t));
-            test_ftsp_msg_t* report = (test_ftsp_msg_t*)call Packet.getPayload(&msg, sizeof(test_ftsp_msg_t));
-
-            uint32_t rxTimestamp = call PacketTimeStamp.timestamp(msgPtr);
-
-            report->src_addr = TOS_NODE_ID;
-            report->counter = rcm->counter;
-            report->local_rx_timestamp = rxTimestamp;
-            report->is_synced = call GlobalTime.local2Global(&rxTimestamp);
-            report->global_rx_timestamp = rxTimestamp;
-            report->skew_times_1000000 = (uint32_t)call TimeSyncInfo.getSkew()*1000000UL;
-            report->ftsp_root_addr = call TimeSyncInfo.getRootID();
-            report->ftsp_seq = call TimeSyncInfo.getSeqNum();
-            report->ftsp_table_entries = call TimeSyncInfo.getNumEntries();
-
-            if (call AMSend.send(AM_BROADCAST_ADDR, &msg, sizeof(test_ftsp_msg_t)) == SUCCESS) {
-              locked = TRUE;
-            }
-        }
-
-        return msgPtr;
-    }
-
-    event void AMSend.sendDone(message_t* ptr, error_t success) {
-        locked = FALSE;
-        return;
-    }
-
-    event void RadioControl.startDone(error_t err) {}
-    event void RadioControl.stopDone(error_t error){}
-}
index 5fac5fae78755b805b362bf5a8712433d6ea532b..825967f4979abf6dc0760a70e58cc5a673d57815 100644 (file)
@@ -6,6 +6,9 @@ Description:
 TestLocalTime is a simple application that tests the LocalTimeMilliC component
 by sending the current time over the serial port once per second.
 
+dump.py is a Python script that can be used to read and format the values from
+the serial port.
+
 Tools:
 
 None.
diff --git a/apps/tests/TestLocalTime/dump.py b/apps/tests/TestLocalTime/dump.py
new file mode 100644 (file)
index 0000000..e8dea05
--- /dev/null
@@ -0,0 +1,22 @@
+#!/usr/bin/env python
+
+import sys
+import tos
+
+class Localtime(tos.Packet):
+    def __init__(self, packet = None):
+        tos.Packet.__init__(self,
+                            [('time', 'int', 4)],
+                            packet)
+
+if '-h' in sys.argv:
+    print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:57600"
+    sys.exit()
+
+am = tos.AM()
+
+while True:
+    p = am.read()
+    if p:
+        msg = Localtime(p.data)
+        print msg
index 1add1755a7163a15b5ff7f843d452534bfc89850..d0092953c8571dc1ccfddc2745540b0dce382510 100644 (file)
@@ -4,7 +4,7 @@ Author/Contact: tinyos-help@millennium.berkeley.edu
 Description:
 
 A simple low-power-listening test app, which cycles through different
-low-power-listening settings every ~32s, repeating every ~256s. 
+low-power-listening settings every ~32s, repeating every ~192s. 
 
 This application currently runs on motes using the CC1000, CC2420 and
 RF230 radios. To compile for motes with CC2420 or RF230 radios, you
@@ -36,16 +36,10 @@ Its low-power-listening settings are as follows (repeating every 256s):
 160-192s:  receive: low-power-listening with 2000ms interval
           send: every 7 seconds, to low-power-listeners with 2000ms interval
 
-192-224s:  receive: low-power-listening with 1% duty cycle
-          send: every 7 seconds, to low-power-listeners with 1% duty cycle
-
-224-256s:  receive: low-power-listening with 0.1% duty cycle
-          send: every 7 seconds, to low-power-listeners with 0.1% duty cycle
-
 Whether two motes running TestLPL can receive each others messages depends
 on their current send and receive low-power-listening settings. If you reset
 two such motes at the same time, they will be able to receive each other's
-messages in the following intervals: 0-96s and 128-256s.
+messages in the following intervals: 0-96s and 128-192s.
 
 Tools:
 
index 46724370dcf9fee1e449838c088b9352060f78dd..af7a5975d7af9f1e4bcea06012fe76db028ee5ff 100644 (file)
@@ -45,9 +45,9 @@ implementation {
   components new TimerMilliC();
 #if defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
   components CC1000CsmaRadioC as LplRadio;
-#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB) || defined(PLATFORM_SHIMMER) || defined(PLATFORM_INTELMOTE2)
+#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB) || defined(PLATFORM_SHIMMER) || defined(PLATFORM_SHIMMER2) || defined(PLATFORM_INTELMOTE2) || defined(PLATFORM_EPIC)
   components CC2420ActiveMessageC as LplRadio;
-#elif defined(PLATFORM_IRIS)
+#elif defined(PLATFORM_IRIS) || defined(PLATFORM_MULLE)
   components RF230ActiveMessageC as LplRadio;
 #elif defined(PLATFORM_EYESIFXV1) || defined(PLATFORM_EYESIFXV2)
   components LplC as LplRadio;
index 0920f1364da86ed399b326138f74451627877452..b186e65d1337d7583cd46d60c3a941440fd62a4d 100644 (file)
@@ -68,31 +68,25 @@ implementation
     case 0:
       sendSkip = 0;
       sendInterval = 0;
-      call LowPowerListening.setLocalSleepInterval(0);
+      call LowPowerListening.setLocalWakeupInterval(0);
       break;
     case 1:
       sendInterval = 100; /* Send to sleepy listener */
       break;
     case 2:
       sendInterval = -1; /* Send to listener like us */
-      call LowPowerListening.setLocalSleepInterval(250);
+      call LowPowerListening.setLocalWakeupInterval(250);
       break;
     case 3:
       sendInterval = 0; /* Send to awake listener */
       break;
     case 4:
       sendInterval = -1; /* Send to listener like us */
-      call LowPowerListening.setLocalSleepInterval(10);
+      call LowPowerListening.setLocalWakeupInterval(10);
       break;
     case 5:
       sendSkip = 7; /* Send every 7s */
-      call LowPowerListening.setLocalSleepInterval(2000);
-      break;
-    case 6:
-      call LowPowerListening.setLocalDutyCycle(100);
-      break;
-    case 7:
-      call LowPowerListening.setLocalDutyCycle(10);
+      call LowPowerListening.setLocalWakeupInterval(2000);
       break;
     }
   }
@@ -106,7 +100,7 @@ implementation
     if (!locked && ((counter & sendSkip) == sendSkip))
       {
        if (sendInterval >= 0)
-         call LowPowerListening.setRxSleepInterval(&packet, sendInterval);
+         call LowPowerListening.setRemoteWakeupInterval(&packet, sendInterval);
        if (call AMSend.send(AM_BROADCAST_ADDR, &packet, 0) == SUCCESS)
          {
            call Leds.led0On();
index ed52205076f267e36aa3ab6974127e4b7c593c97..b533acdc7bea27d38a88a6eba93ac102d338ef6d 100644 (file)
@@ -14,6 +14,24 @@ Collection Tree Protocol for details.
 There are scripts on net2 website to parse the debug messages sent by
 the nodes.
 
+To test, start with two motes with no program that transmits
+packets. Example., erase the mote or install Blink. Program a mote with
+node id 0. The mote will toggle led1 (green on TelosB) approximately
+every 8s. Then program the second mote with id 1. Once programming is
+complete, the mote with id 0 will toggle led1 twice every 8s. Each
+toggle corresponds to the reception of collection message (once from
+itself, and once from the mote with id 1).
+
+Errors indications:
+
+Motes 0 and 1 will set led0 (red on TelosB) if there are errors while
+sending the packet.
+
+Mote 0 will set led2 (blue on TelosB) if the gap in sequence number on
+consecutive packet reception from node 1 is greater than 1. This is
+expected to be a rare event while doing experiment on a desk.
+
+
 Known bugs/limitations:
 
 None.
index b64adf2d82814a542922630a24a4b4a7a01aa18b..337b8d2e7629e87003be334420b3cac5969cf62b 100644 (file)
@@ -17,7 +17,7 @@ configuration TestNetworkAppC {}
 implementation {
   components TestNetworkC, MainC, LedsC, ActiveMessageC;
   components DisseminationC;
-  components new DisseminatorC(uint16_t, SAMPLE_RATE_KEY) as Object16C;
+  components new DisseminatorC(uint32_t, SAMPLE_RATE_KEY) as Object32C;
   components CollectionC as Collector;
   components new CollectionSenderC(CL_TEST);
   components new TimerMilliC();
@@ -39,7 +39,7 @@ implementation {
   TestNetworkC.DisseminationControl -> DisseminationC;
   TestNetworkC.Leds -> LedsC;
   TestNetworkC.Timer -> TimerMilliC;
-  TestNetworkC.DisseminationPeriod -> Object16C;
+  TestNetworkC.DisseminationPeriod -> Object32C;
   TestNetworkC.Send -> CollectionSenderC;
   TestNetworkC.ReadSensor -> DemoSensorC;
   TestNetworkC.RootControl -> Collector;
index 28e248f0d3e42589b593df059c1a1ee2a278b88c..05e44d2fbf2ca1b41a5fc246a7d4864d233e1e0c 100644 (file)
@@ -20,7 +20,7 @@ module TestNetworkC {
   uses interface SplitControl as SerialControl;
   uses interface StdControl as RoutingControl;
   uses interface StdControl as DisseminationControl;
-  uses interface DisseminationValue<uint16_t> as DisseminationPeriod;
+  uses interface DisseminationValue<uint32_t> as DisseminationPeriod;
   uses interface Send;
   uses interface Leds;
   uses interface Read<uint16_t> as ReadSensor;
@@ -87,7 +87,7 @@ implementation {
   void sendMessage() {
     TestNetworkMsg* msg = (TestNetworkMsg*)call Send.getPayload(&packet, sizeof(TestNetworkMsg));
     uint16_t metric;
-    am_addr_t parent;
+    am_addr_t parent = 0;
 
     call CtpInfo.getParent(&parent);
     call CtpInfo.getEtx(&metric);
@@ -113,10 +113,9 @@ implementation {
 
  
   event void Timer.fired() {
-    uint16_t nextInt;
-    call Leds.led0Toggle();
+    uint32_t nextInt;
     dbg("TestNetworkC", "TestNetworkC: Timer fired.\n");
-    nextInt = call Random.rand16() % SEND_INTERVAL;
+    nextInt = call Random.rand32() % SEND_INTERVAL;
     nextInt += SEND_INTERVAL >> 1;
     call Timer.startOneShot(nextInt);
     if (!sendBusy)
@@ -125,25 +124,38 @@ implementation {
 
   event void Send.sendDone(message_t* m, error_t err) {
     if (err != SUCCESS) {
-       //      call Leds.led0On();
+      call Leds.led0On();
     }
     sendBusy = FALSE;
     dbg("TestNetworkC", "Send completed.\n");
   }
   
   event void DisseminationPeriod.changed() {
-    const uint16_t* newVal = call DisseminationPeriod.get();
+    const uint32_t* newVal = call DisseminationPeriod.get();
     call Timer.stop();
     call Timer.startPeriodic(*newVal);
   }
 
+
+  uint8_t prevSeq = 0;
+  uint8_t firstMsg = 0;
+
   event message_t* 
   Receive.receive(message_t* msg, void* payload, uint8_t len) {
     dbg("TestNetworkC", "Received packet at %s from node %hhu.\n", sim_time_string(), call CollectionPacket.getOrigin(msg));
-    call Leds.led1Toggle();    
-    if (!call Pool.size() <= (TEST_NETWORK_QUEUE_SIZE < 4)? 1:3)  {
-      //      call CtpCongestion.setClientCongested(TRUE);
+    call Leds.led1Toggle();
+
+    if (call CollectionPacket.getOrigin(msg) == 1) {
+      if (firstMsg == 1) {
+       if (call CollectionPacket.getSequenceNumber(msg) - prevSeq > 1) {
+         call Leds.led2On();
+       }
+      } else {
+       firstMsg = 1;
+      }
+      prevSeq = call CollectionPacket.getSequenceNumber(msg);
     }
+
     if (!call Pool.empty() && call Queue.size() < call Queue.maxSize()) {
       message_t* tmp = call Pool.get();
       call Queue.enqueue(msg);
diff --git a/apps/tests/TestNetworkLpl/Makefile b/apps/tests/TestNetworkLpl/Makefile
new file mode 100644 (file)
index 0000000..af118ab
--- /dev/null
@@ -0,0 +1,73 @@
+COMPONENT=TestNetworkLplAppC
+
+CFLAGS += -DLOW_POWER_LISTENING
+CFLAGS += -DLPL_DEF_LOCAL_WAKEUP=512
+CFLAGS += -DLPL_DEF_REMOTE_WAKEUP=512
+CFLAGS += -DDELAY_AFTER_RECEIVE=20
+
+# CFLAGS += -DCC2420_DEF_CHANNEL=12
+CFLAGS += -I.
+CFLAGS += -I../TestNetwork
+
+CFLAGS += -I$(TOSDIR)/lib/net \
+          -I$(TOSDIR)/lib/net/drip \
+          -I$(TOSDIR)/lib/net/4bitle \
+          -I$(TOSDIR)/lib/net/ctp -DNO_DEBUG
+
+TFLAGS += -I$(TOSDIR)/../apps/tests/TestDissemination \
+          -I$(TOSDIR)/../support/sdk/c \
+          -I$(TOSDIR)/types \
+          -I.
+
+LIBMOTE = $(TOSDIR)/../support/sdk/c/libmote.a
+#BUILD_EXTRA_DEPS += tn-injector #tn-listener
+LISTEN_OBJS = collection_msg.o test_network_msg.o tn-listener.o $(LIBMOTE)
+INJECT_OBJS = set_rate_msg.o tn-injector.o collection_debug_msg.o $(LIBMOTE)
+
+# arguments: output filename stem, input filename, struct name
+define mig_templ
+MIGFILES += $(1).c $(1).h $(1).java $(1).o
+$(1).c:
+       mig -o $(1).h c -target=$$(PLATFORM) $$(CFLAGS) $$(TFLAGS) $(2) $(3)
+$(1).java:
+       mig -o $(1).java java -target=$$(PLATFORM) $$(CFLAGS) $$(TFLAGS) $(2) $(3)
+endef
+
+$(eval $(call mig_templ,test_network_msg,TestNetwork.h,TestNetworkMsg))
+$(eval $(call mig_templ,set_rate_msg,$(TOSDIR)/lib/net/DisseminationEngine.h,dissemination_message))
+$(eval $(call mig_templ,collection_debug_msg,$(TOSDIR)/lib/net/collection/CollectionDebugMsg.h,CollectionDebugMsg))
+
+%.o: %.c
+       gcc -v  $(TFLAGS) $(CFLAGS) -c -o $@ $<
+
+tn-listener: $(LISTEN_OBJS)
+       gcc -v $(TFLAGS) $(CFLAGS) -o $@ $(LISTEN_OBJS)
+
+tn-injector: $(INJECT_OBJS)
+       gcc -v $(TFLAGS) $(CFLAGS) -o $@ $(INJECT_OBJS)
+
+#tn-listener.o: tn-listener.c
+#      gcc $(TFLAGS) $(CFLAGS) -c -o $@ $<
+
+tn-injector.o: tn-injector.c test_network_msg.c
+       gcc $(TFLAGS) $(CFLAGS) -c -o $@ $<
+
+#test_network_msg.c:
+#      mig -o test_network_msg.h c -target=$(PLATFORM) $(CFLAGS) $(TFLAGS) TestNetwork.h TestNetworkMsg 
+
+#set_rate_msg.c:
+#      mig -o set_rate_msg.h c -target=$(PLATFORM) $(CFLAGS) $(TFLAGS) $(TOSDIR)/lib/net/DisseminationEngine.h dissemination_message
+
+#set_rate_msg.o: set_rate_msg.c
+#      gcc $(CFLAGS) $(TFLAGS) -c -o $@ $<
+
+#test_network_msg.o: test_network_msg.c
+#      gcc $(CFLAGS) $(TFLAGS) -c -o $@ $<
+
+#collection_msg.c:
+#      mig -o collection_msg.h c -target=$(PLATFORM) $(CFLAGS) $(TFLAGS) $(TOSDIR)/lib/net/collection/ForwardingEngine.h collection_header
+
+include $(MAKERULES)
+
+migclean:
+       rm -rf $(MIGFILES)
diff --git a/apps/tests/TestNetworkLpl/README.txt b/apps/tests/TestNetworkLpl/README.txt
new file mode 100644 (file)
index 0000000..3029a6a
--- /dev/null
@@ -0,0 +1,19 @@
+README for TestNetworkLpl
+Author/Contact: tinyos-help@millennium.berkeley.edu
+
+Description:
+
+This is a version of the TestNetworkLpl application that is using the
+default LowPowerListening mechanism to reduce the power consumption.
+
+The settings for default lpl are controlled by the following lines
+from the Makefile:
+
+  CFLAGS += -DLOW_POWER_LISTENING
+  CFLAGS += -DLPL_DEF_LOCAL_WAKEUP=512
+  CFLAGS += -DLPL_DEF_REMOTE_WAKEUP=512
+  CFLAGS += -DDELAY_AFTER_RECEIVE=20
+
+Known bugs/limitations:
+
+None.
diff --git a/apps/tests/TestNetworkLpl/TestNetworkLplAppC.nc b/apps/tests/TestNetworkLpl/TestNetworkLplAppC.nc
new file mode 100644 (file)
index 0000000..590785b
--- /dev/null
@@ -0,0 +1,68 @@
+/**
+ * TestNetworkLplC exercises the basic networking layers, collection and
+ * dissemination. The application samples DemoSensorC at a basic rate
+ * and sends packets up a collection tree. The rate is configurable
+ * through dissemination.
+ *
+ * See TEP118: Dissemination, TEP 119: Collection, and TEP 123: The
+ * Collection Tree Protocol for details.
+ * 
+ * @author Philip Levis
+ * @version $Revision$ $Date$
+ */
+#include "TestNetwork.h"
+#include "Ctp.h"
+
+configuration TestNetworkLplAppC {}
+implementation {
+  components TestNetworkLplC, MainC, LedsC, ActiveMessageC;
+  components DisseminationC;
+  components new DisseminatorC(uint32_t, SAMPLE_RATE_KEY) as Object32C;
+  components CollectionC as Collector;
+  components new CollectionSenderC(CL_TEST);
+  components new TimerMilliC();
+  components new DemoSensorC();
+  components new SerialAMSenderC(CL_TEST);
+  components SerialActiveMessageC;
+#ifndef NO_DEBUG
+  components new SerialAMSenderC(AM_COLLECTION_DEBUG) as UARTSender;
+  components UARTDebugSenderP as DebugSender;
+#endif
+  components RandomC;
+  components new QueueC(message_t*, 12);
+  components new PoolC(message_t, 12);
+
+  TestNetworkLplC.Boot -> MainC;
+  TestNetworkLplC.RadioControl -> ActiveMessageC;
+  TestNetworkLplC.SerialControl -> SerialActiveMessageC;
+  TestNetworkLplC.RoutingControl -> Collector;
+  TestNetworkLplC.DisseminationControl -> DisseminationC;
+  TestNetworkLplC.Leds -> LedsC;
+  TestNetworkLplC.Timer -> TimerMilliC;
+  TestNetworkLplC.DisseminationPeriod -> Object32C;
+  TestNetworkLplC.Send -> CollectionSenderC;
+  TestNetworkLplC.ReadSensor -> DemoSensorC;
+  TestNetworkLplC.RootControl -> Collector;
+  TestNetworkLplC.Receive -> Collector.Receive[CL_TEST];
+  TestNetworkLplC.UARTSend -> SerialAMSenderC.AMSend;
+  TestNetworkLplC.CollectionPacket -> Collector;
+  TestNetworkLplC.CtpInfo -> Collector;
+  TestNetworkLplC.CtpCongestion -> Collector;
+  TestNetworkLplC.Random -> RandomC;
+  TestNetworkLplC.Pool -> PoolC;
+  TestNetworkLplC.Queue -> QueueC;
+  TestNetworkLplC.RadioPacket -> ActiveMessageC;
+  TestNetworkLplC.LowPowerListening -> ActiveMessageC;
+  
+#ifndef NO_DEBUG
+  components new PoolC(message_t, 10) as DebugMessagePool;
+  components new QueueC(message_t*, 10) as DebugSendQueue;
+  DebugSender.Boot -> MainC;
+  DebugSender.UARTSend -> UARTSender;
+  DebugSender.MessagePool -> DebugMessagePool;
+  DebugSender.SendQueue -> DebugSendQueue;
+  Collector.CollectionDebug -> DebugSender;
+  TestNetworkLplC.CollectionDebug -> DebugSender;
+#endif
+  TestNetworkLplC.AMPacket -> ActiveMessageC;
+}
diff --git a/apps/tests/TestNetworkLpl/TestNetworkLplC.nc b/apps/tests/TestNetworkLpl/TestNetworkLplC.nc
new file mode 100644 (file)
index 0000000..110c9fe
--- /dev/null
@@ -0,0 +1,214 @@
+/**
+ * TestNetworkC exercises the basic networking layers, collection and
+ * dissemination. The application samples DemoSensorC at a basic rate
+ * and sends packets up a collection tree. The rate is configurable
+ * through dissemination. The default send rate is every 10s.
+ *
+ * See TEP118: Dissemination and TEP 119: Collection for details.
+ * 
+ * @author Philip Levis
+ * @version $Revision$ $Date$
+ */
+
+#include <Timer.h>
+#include "TestNetwork.h"
+#include "CtpDebugMsg.h"
+
+module TestNetworkLplC {
+  uses interface Boot;
+  uses interface SplitControl as RadioControl;
+  uses interface SplitControl as SerialControl;
+  uses interface StdControl as RoutingControl;
+  uses interface StdControl as DisseminationControl;
+  uses interface DisseminationValue<uint32_t> as DisseminationPeriod;
+  uses interface Send;
+  uses interface Leds;
+  uses interface Read<uint16_t> as ReadSensor;
+  uses interface Timer<TMilli>;
+  uses interface RootControl;
+  uses interface Receive;
+  uses interface AMSend as UARTSend;
+  uses interface CollectionPacket;
+  uses interface CtpInfo;
+  uses interface CtpCongestion;
+  uses interface Random;
+  uses interface Queue<message_t*>;
+  uses interface Pool<message_t>;
+  uses interface CollectionDebug;
+  uses interface AMPacket;
+  uses interface Packet as RadioPacket;
+  uses interface LowPowerListening;
+}
+implementation {
+  task void uartEchoTask();
+  message_t packet;
+  message_t uartpacket;
+  message_t* recvPtr = &uartpacket;
+  uint8_t msglen;
+  bool sendBusy = FALSE;
+  bool uartbusy = FALSE;
+  bool firstTimer = TRUE;
+  uint16_t seqno;
+  enum {
+    SEND_INTERVAL = 60*1024U,
+  };
+
+  event void ReadSensor.readDone(error_t err, uint16_t val) { }  
+
+  event void Boot.booted() {
+    call SerialControl.start();
+  }
+  event void SerialControl.startDone(error_t err) {
+    if (TOS_NODE_ID % 500 == 0) {
+      call LowPowerListening.setLocalWakeupInterval(0);
+    }
+    call RadioControl.start();
+  }
+  event void RadioControl.startDone(error_t err) {
+    if (err != SUCCESS) {
+      call RadioControl.start();
+    }
+    else {
+      //call DisseminationControl.start();
+      call RoutingControl.start();
+      if (TOS_NODE_ID % 500 == 0) {
+       call RootControl.setRoot();
+      }
+      seqno = 0;
+        call Timer.startOneShot(call Random.rand32() % SEND_INTERVAL);
+    }
+  }
+
+  event void RadioControl.stopDone(error_t err) {}
+  event void SerialControl.stopDone(error_t err) {}    
+
+  void failedSend() {
+    dbg("App", "%s: Send failed.\n", __FUNCTION__);
+    call CollectionDebug.logEvent(NET_C_DBG_1);
+  }
+
+   
+  void sendMessage() {
+    TestNetworkMsg* msg = (TestNetworkMsg*)call Send.getPayload(&packet, sizeof(TestNetworkMsg));
+    uint16_t metric;
+    am_addr_t parent = 0;
+
+    call CtpInfo.getParent(&parent);
+    call CtpInfo.getEtx(&metric);
+
+    msg->source = TOS_NODE_ID;
+    msg->seqno = seqno;
+    msg->data = 0xCAFE;
+    msg->parent = parent;
+    msg->hopcount = 0;
+    msg->metric = metric;
+
+    if (call Send.send(&packet, sizeof(TestNetworkMsg)) != SUCCESS) {
+      failedSend();
+      call Leds.led0On();
+      dbg("TestNetworkC", "%s: Transmission failed.\n", __FUNCTION__);
+    }
+    else {
+      sendBusy = TRUE;
+      seqno++; 
+      dbg("TestNetworkC", "%s: Transmission succeeded.\n", __FUNCTION__);
+    }
+  }
+
+  event void Timer.fired() {
+    uint32_t nextInt;
+    call Leds.led0Toggle();
+    dbg("TestNetworkC", "TestNetworkC: Timer fired.\n");
+    nextInt = call Random.rand32() % SEND_INTERVAL;
+    nextInt += SEND_INTERVAL >> 1;
+    call Timer.startOneShot(nextInt);
+    if (!sendBusy)
+       sendMessage();
+  }
+
+  event void Send.sendDone(message_t* m, error_t err) {
+    if (err != SUCCESS) {
+       //      call Leds.led0On();
+    }
+    sendBusy = FALSE;
+    dbg("TestNetworkC", "Send completed.\n");
+  }
+  
+  event void DisseminationPeriod.changed() {
+    const uint32_t* newVal = call DisseminationPeriod.get();
+    call Timer.stop();
+    call Timer.startPeriodic(*newVal);
+  }
+
+  event message_t* 
+  Receive.receive(message_t* msg, void* payload, uint8_t len) {
+    dbg("TestNetworkC", "Received packet at %s from node %hhu.\n", sim_time_string(), call CollectionPacket.getOrigin(msg));
+    call Leds.led1Toggle();    
+    if (!call Pool.size() <= (TEST_NETWORK_QUEUE_SIZE < 4)? 1:3)  {
+      //      call CtpCongestion.setClientCongested(TRUE);
+    }
+    if (!call Pool.empty() && call Queue.size() < call Queue.maxSize()) {
+      message_t* tmp = call Pool.get();
+      call Queue.enqueue(msg);
+      if (!uartbusy) {
+        post uartEchoTask();
+      }
+      return tmp;
+    }
+    return msg;
+ }
+
+ task void uartEchoTask() {
+    dbg("Traffic", "Sending packet to UART.\n");
+   if (call Queue.empty()) {
+     return;
+   }
+   else if (!uartbusy) {
+     message_t* msg = call Queue.dequeue();
+     dbg("Traffic", "Sending packet to UART.\n");
+     if (call UARTSend.send(0xffff, msg, call RadioPacket.payloadLength(msg)) == SUCCESS) {
+       uartbusy = TRUE;
+     }
+     else {
+      call CollectionDebug.logEventMsg(NET_C_DBG_2,
+                                      call CollectionPacket.getSequenceNumber(msg),
+                                      call CollectionPacket.getOrigin(msg),
+                                      call AMPacket.destination(msg));
+     }
+   }
+ }
+
+  event void UARTSend.sendDone(message_t *msg, error_t error) {
+    dbg("Traffic", "UART send done.\n");
+    uartbusy = FALSE;
+    call Pool.put(msg);
+    if (!call Queue.empty()) {
+      post uartEchoTask();
+    } 
+    else {
+      //        call CtpCongestion.setClientCongested(FALSE);
+    }
+  }
+
+  /* Default implementations for CollectionDebug calls.
+   * These allow CollectionDebug not to be wired to anything if debugging
+   * is not desired. */
+
+    default command error_t CollectionDebug.logEvent(uint8_t type) {
+        return SUCCESS;
+    }
+    default command error_t CollectionDebug.logEventSimple(uint8_t type, uint16_t arg) {
+        return SUCCESS;
+    }
+    default command error_t CollectionDebug.logEventDbg(uint8_t type, uint16_t arg1, uint16_t arg2, uint16_t arg3) {
+        return SUCCESS;
+    }
+    default command error_t CollectionDebug.logEventMsg(uint8_t type, uint16_t msg, am_addr_t origin, am_addr_t node) {
+        return SUCCESS;
+    }
+    default command error_t CollectionDebug.logEventRoute(uint8_t type, am_addr_t parent, uint8_t hopcount, uint16_t metric) {
+        return SUCCESS;
+    }
+}
diff --git a/apps/tests/TestNetworkLpl/ctp-dump.py b/apps/tests/TestNetworkLpl/ctp-dump.py
new file mode 100644 (file)
index 0000000..6fdef40
--- /dev/null
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+
+import sys, time
+import tos
+
+class Test(tos.Packet):
+    def __init__(self, payload = None):
+        tos.Packet.__init__(self,
+                               [('source',   'int', 2),
+                                ('seqno',    'int', 2),
+                                ('parent',   'int', 2),
+                                ('metric',   'int', 2),
+                                ('data',     'int', 2),
+                                ('hopcount', 'int', 1),
+                                ('sendCount','int', 2),
+                                ('sendSuccessCount','int', 2)],
+                               payload)
+
+class CtpData(tos.Packet):
+    def __init__(self, payload = None):
+        tos.Packet.__init__(self,
+                               [('options',     'int', 1),
+                                ('thl',         'int', 1),
+                                ('etx',         'int', 2),
+                                ('origin',      'int', 2),
+                                ('originSeqNo', 'int', 1),
+                                ('collectionId','int', 1),
+                                ('data',  'blob', None)],
+                               payload)
+
+if len(sys.argv) < 2:
+    print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:57600"
+    sys.exit()
+
+#s = tos.Serial(sys.argv[1], int(sys.argv[2]), debug=False)
+am = tos.AM()
+
+while True:
+    p = am.read()
+    if p:
+        if p.type == 238:
+            ts = "%.4f" % time.time()
+            ctp = CtpData(p.data)
+            test = Test(ctp.data)
+            print ts, '\t', ctp
+            print ts, '\t', test
+        else:
+            print p
+
index 31cba7b289bf95abe394b3598f5c87d016f9efde..1a8e56d5667b1735304964887b77b1b747f5a847 100644 (file)
@@ -16,9 +16,12 @@ application prints the counter's value to standard out.
 Java Application Usage:
   java TestSerial [-comm <packetsource>]
 
-  If not specified, the <packetsource> defaults to sf@localhost:9001 or
+  If not specified, the <packetsource> defaults to sf@localhost:9002 or
   to your MOTECOM environment variable (if defined).
 
+Python Usage:
+  tos-dump /dev/ttyUSB0 57600
+
 Tools:
 
 Known bugs/limitations:
index b0aae0547680874ebd4592e3d3fb7a8ae679cbcd..c7603bf069b7b67571bef0f8f181258c96a9d793 100644 (file)
@@ -1,6 +1,7 @@
 COMPONENT=TestSerialAppC
 BUILD_EXTRA_DEPS += TestSerialMsg.class TestSerial.class
 CFLAGS += -DTOSH_DATA_LENGTH=100
+CLEAN_EXTRA = *.class TestSerialMsg.java
 
 %.class: %.java
        javac $<
diff --git a/apps/tests/TestSerialBandwidth/TestSerialMsg.java b/apps/tests/TestSerialBandwidth/TestSerialMsg.java
deleted file mode 100644 (file)
index 257e8cd..0000000
+++ /dev/null
@@ -1,318 +0,0 @@
-/**
- * This class is automatically generated by mig. DO NOT EDIT THIS FILE.
- * This class implements a Java interface to the 'TestSerialMsg'
- * message type.
- */
-
-public class TestSerialMsg extends net.tinyos.message.Message {
-
-    /** The default size of this message type in bytes. */
-    public static final int DEFAULT_MESSAGE_SIZE = 100;
-
-    /** The Active Message type associated with this message. */
-    public static final int AM_TYPE = 9;
-
-    /** Create a new TestSerialMsg of size 100. */
-    public TestSerialMsg() {
-        super(DEFAULT_MESSAGE_SIZE);
-        amTypeSet(AM_TYPE);
-    }
-
-    /** Create a new TestSerialMsg of the given data_length. */
-    public TestSerialMsg(int data_length) {
-        super(data_length);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new TestSerialMsg with the given data_length
-     * and base offset.
-     */
-    public TestSerialMsg(int data_length, int base_offset) {
-        super(data_length, base_offset);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new TestSerialMsg using the given byte array
-     * as backing store.
-     */
-    public TestSerialMsg(byte[] data) {
-        super(data);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new TestSerialMsg using the given byte array
-     * as backing store, with the given base offset.
-     */
-    public TestSerialMsg(byte[] data, int base_offset) {
-        super(data, base_offset);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new TestSerialMsg using the given byte array
-     * as backing store, with the given base offset and data length.
-     */
-    public TestSerialMsg(byte[] data, int base_offset, int data_length) {
-        super(data, base_offset, data_length);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new TestSerialMsg embedded in the given message
-     * at the given base offset.
-     */
-    public TestSerialMsg(net.tinyos.message.Message msg, int base_offset) {
-        super(msg, base_offset, DEFAULT_MESSAGE_SIZE);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new TestSerialMsg embedded in the given message
-     * at the given base offset and length.
-     */
-    public TestSerialMsg(net.tinyos.message.Message msg, int base_offset, int data_length) {
-        super(msg, base_offset, data_length);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-    /* Return a String representation of this message. Includes the
-     * message type name and the non-indexed field values.
-     */
-    public String toString() {
-      String s = "Message <TestSerialMsg> \n";
-      try {
-        s += "  [counter=0x"+Long.toHexString(get_counter())+"]\n";
-      } catch (ArrayIndexOutOfBoundsException aioobe) { /* Skip field */ }
-      try {
-        s += "  [x=";
-        for (int i = 0; i < 98; i++) {
-          s += "0x"+Long.toHexString(getElement_x(i) & 0xff)+" ";
-        }
-        s += "]\n";
-      } catch (ArrayIndexOutOfBoundsException aioobe) { /* Skip field */ }
-      return s;
-    }
-
-    // Message-type-specific access methods appear below.
-
-    /////////////////////////////////////////////////////////
-    // Accessor methods for field: counter
-    //   Field type: int, unsigned
-    //   Offset (bits): 0
-    //   Size (bits): 16
-    /////////////////////////////////////////////////////////
-
-    /**
-     * Return whether the field 'counter' is signed (false).
-     */
-    public static boolean isSigned_counter() {
-        return false;
-    }
-
-    /**
-     * Return whether the field 'counter' is an array (false).
-     */
-    public static boolean isArray_counter() {
-        return false;
-    }
-
-    /**
-     * Return the offset (in bytes) of the field 'counter'
-     */
-    public static int offset_counter() {
-        return (0 / 8);
-    }
-
-    /**
-     * Return the offset (in bits) of the field 'counter'
-     */
-    public static int offsetBits_counter() {
-        return 0;
-    }
-
-    /**
-     * Return the value (as a int) of the field 'counter'
-     */
-    public int get_counter() {
-        return (int)getUIntBEElement(offsetBits_counter(), 16);
-    }
-
-    /**
-     * Set the value of the field 'counter'
-     */
-    public void set_counter(int value) {
-        setUIntBEElement(offsetBits_counter(), 16, value);
-    }
-
-    /**
-     * Return the size, in bytes, of the field 'counter'
-     */
-    public static int size_counter() {
-        return (16 / 8);
-    }
-
-    /**
-     * Return the size, in bits, of the field 'counter'
-     */
-    public static int sizeBits_counter() {
-        return 16;
-    }
-
-    /////////////////////////////////////////////////////////
-    // Accessor methods for field: x
-    //   Field type: short[], unsigned
-    //   Offset (bits): 16
-    //   Size of each element (bits): 8
-    /////////////////////////////////////////////////////////
-
-    /**
-     * Return whether the field 'x' is signed (false).
-     */
-    public static boolean isSigned_x() {
-        return false;
-    }
-
-    /**
-     * Return whether the field 'x' is an array (true).
-     */
-    public static boolean isArray_x() {
-        return true;
-    }
-
-    /**
-     * Return the offset (in bytes) of the field 'x'
-     */
-    public static int offset_x(int index1) {
-        int offset = 16;
-        if (index1 < 0 || index1 >= 98) throw new ArrayIndexOutOfBoundsException();
-        offset += 0 + index1 * 8;
-        return (offset / 8);
-    }
-
-    /**
-     * Return the offset (in bits) of the field 'x'
-     */
-    public static int offsetBits_x(int index1) {
-        int offset = 16;
-        if (index1 < 0 || index1 >= 98) throw new ArrayIndexOutOfBoundsException();
-        offset += 0 + index1 * 8;
-        return offset;
-    }
-
-    /**
-     * Return the entire array 'x' as a short[]
-     */
-    public short[] get_x() {
-        short[] tmp = new short[98];
-        for (int index0 = 0; index0 < numElements_x(0); index0++) {
-            tmp[index0] = getElement_x(index0);
-        }
-        return tmp;
-    }
-
-    /**
-     * Set the contents of the array 'x' from the given short[]
-     */
-    public void set_x(short[] value) {
-        for (int index0 = 0; index0 < value.length; index0++) {
-            setElement_x(index0, value[index0]);
-        }
-    }
-
-    /**
-     * Return an element (as a short) of the array 'x'
-     */
-    public short getElement_x(int index1) {
-        return (short)getUIntBEElement(offsetBits_x(index1), 8);
-    }
-
-    /**
-     * Set an element of the array 'x'
-     */
-    public void setElement_x(int index1, short value) {
-        setUIntBEElement(offsetBits_x(index1), 8, value);
-    }
-
-    /**
-     * Return the total size, in bytes, of the array 'x'
-     */
-    public static int totalSize_x() {
-        return (784 / 8);
-    }
-
-    /**
-     * Return the total size, in bits, of the array 'x'
-     */
-    public static int totalSizeBits_x() {
-        return 784;
-    }
-
-    /**
-     * Return the size, in bytes, of each element of the array 'x'
-     */
-    public static int elementSize_x() {
-        return (8 / 8);
-    }
-
-    /**
-     * Return the size, in bits, of each element of the array 'x'
-     */
-    public static int elementSizeBits_x() {
-        return 8;
-    }
-
-    /**
-     * Return the number of dimensions in the array 'x'
-     */
-    public static int numDimensions_x() {
-        return 1;
-    }
-
-    /**
-     * Return the number of elements in the array 'x'
-     */
-    public static int numElements_x() {
-        return 98;
-    }
-
-    /**
-     * Return the number of elements in the array 'x'
-     * for the given dimension.
-     */
-    public static int numElements_x(int dimension) {
-      int array_dims[] = { 98,  };
-        if (dimension < 0 || dimension >= 1) throw new ArrayIndexOutOfBoundsException();
-        if (array_dims[dimension] == 0) throw new IllegalArgumentException("Array dimension "+dimension+" has unknown size");
-        return array_dims[dimension];
-    }
-
-    /**
-     * Fill in the array 'x' with a String
-     */
-    public void setString_x(String s) { 
-         int len = s.length();
-         int i;
-         for (i = 0; i < len; i++) {
-             setElement_x(i, (short)s.charAt(i));
-         }
-         setElement_x(i, (short)0); //null terminate
-    }
-
-    /**
-     * Read the array 'x' as a String
-     */
-    public String getString_x() { 
-         char carr[] = new char[Math.min(net.tinyos.message.Message.MAX_CONVERTED_STRING_LENGTH,98)];
-         int i;
-         for (i = 0; i < carr.length; i++) {
-             if ((char)getElement_x(i) == (char)0) break;
-             carr[i] = (char)getElement_x(i);
-         }
-         return new String(carr,0,i);
-    }
-
-}
index 5780b33c299a1d42afbe006f7428635ffdbc837e..dda666e2d3a0b1768934e9fea023e38ec761c300 100644 (file)
@@ -30,29 +30,34 @@ quality links (-60 dBm) to node 2, but the reverse links (2 to 1 and
 like test-equal.py but few acknowledgements.
 
 The ./run script runs all the three tests and counts the number of
-ACKed and non-ACKed send packets. The output look like this:
+ACKed and non-ACKed send packets. The output will look something
+like this:
 
-test-asym.log
-           ACK           NOACK   total
-         1 4930          35923   40853
-         3 4983          35870   40853
 test-equal.log
            ACK           NOACK   total
          1 21197         19666   40863
          3 21320         19543   40863
+test-asym.log
+           ACK           NOACK   total
+         1 4930          35923   40853
+         3 4983          35870   40853
 test-unequal.log
            ACK           NOACK   total
          1 27619         12966   40585
          3 21040         19545   40585
 
-This output shows several this:
-- the number of ACKs in the asymmetric links case is much less than in
-  the equal case which proves the fact that the reverse links are indeed
-  poor.
-- in the unequal case the number on ACKs for node 1 is higher than
-  node 3 which is expected because node 1 has a better link to 2 than 3.
-- in the equal case both nodes perform similar, each of them loosing
-  about half of their packets.
+ACK is the number of acknowledged packets from that node to node 2;
+NOACK is the number of unacknowledged packets. Total is the sum.
+The output should show three things:
+
+  1) In test-equal, both node 1 and node 3 have very
+  similar delivery ratios, losing about half of their packets.
+
+  2) In test-asym, the number of ACKs is much less than in
+  test-equal because the reverse links are poor.
+
+  3) In test-unequal, node 1 has more acknowledged packets
+  than node 3, because it has a higher SNR link.
 
 Philip Levis
 
index d1720eeeba8c7f004fd30fc6ac2e07ca5e1644b2..7cd6667bc0b360f44cd7853ab226be1ffb68a17e 100755 (executable)
@@ -2,7 +2,7 @@
 
 make micaz sim
 
-for t in test*.py
+for t in test-equal.py test-asym.py test-unequal.py
 do
  echo Running $t...
  python $t > `basename $t .py`.log
@@ -10,7 +10,7 @@ done
 
 make clean
 
-for l in test*.log
+for l in test-equal.log test-asym.log test-unequal.log
 do
     echo $l
     echo -e '\t   ACK \t\t NOACK \t total'
index a84c454475011746e0c145f40129b3809d7992a5..31d87990abf3798d6c0645cd68a78bc9731b171b 100644 (file)
@@ -43,7 +43,7 @@ m1.createNoiseModel()
 m2.createNoiseModel()
 m3.createNoiseModel()
 
-for i in range(0, 1000000):
+for i in range(0, 200000):
     t.runNextEvent();
 
     
index a734f9b6aec169d507cfb73aa6a08483e1d992ca..bd7e84c87b2cc0b6aab500e9faae0c103ad838d5 100644 (file)
@@ -43,7 +43,7 @@ m1.createNoiseModel()
 m2.createNoiseModel()
 m3.createNoiseModel()
 
-for i in range(0, 1000000):
+for i in range(0, 200000):
     t.runNextEvent();
 
     
index 8b2da5fa2f31854ce293eda487de233d03b2ec86..a5bcc1e841d5589777def39c0428274d5028a87c 100644 (file)
@@ -42,7 +42,7 @@ m1.createNoiseModel()
 m2.createNoiseModel()
 m3.createNoiseModel()
 
-for i in range(0, 1000000):
+for i in range(0, 200000):
     t.runNextEvent();
 
     
index 3f25018c3d12bcb50df2d83a7c26335423ce6e63..65f8f369af05e7e11f0dccc4cefb5b57cb8545ec 100644 (file)
@@ -23,10 +23,14 @@ DEBUG (0): Timer A is good @ 0:10:1.837925167.
 DEBUG (0): Timer A is good @ 0:10:2.837925167.
 DEBUG (0): Timer A is good @ 0:10:3.837925167.
 
-If there is a timer bug, then the output will read
+If a timer is off, then the output will read
 
 DEBUG (0): Timer A is off. Should have fired in X, fired in Y @ Z.
 
+Note that if a timer is off by 1, the timer is still operating
+correctly. The way the atm128 counter registers work mean that you
+can't schedule very short timers, so sometimes the code needs to
+make it one tick longer.
 
 Tools:
 
index b2e3f776d431d5e781af752db355e31637e48449..ca39ca0814c5579b336fe0c795a64e5bb1b67418 100644 (file)
@@ -39,7 +39,7 @@ implementation {
   components new TimerMilliC();
   components new BitVectorC(1) as PendingVector;
   components new BitVectorC(1) as ChangeVector;
-
+  
   //  Timer.Timer -> TimerMilliC;
   //Timer.Random -> RandomC;
   //Timer.Changed -> ChangeVector;
@@ -52,7 +52,7 @@ implementation {
   TestTrickleTimerAppP.TimerB -> TimerB;
   TestTrickleTimerAppP.TimerC -> TimerC;
   TestTrickleTimerAppP.TimerD -> TimerD;
-  
+  TestTrickleTimerAppP.Random -> RandomC;
 }
 
   
index 35d872776fefd52ce0b7e3e5909bdac41a21a70d..0b456e97365ecd934a7b9549b4eb83b82a8ca8d4 100644 (file)
@@ -36,6 +36,7 @@ module TestTrickleTimerAppP {
     interface TrickleTimer as TimerB;
     interface TrickleTimer as TimerC;
     interface TrickleTimer as TimerD;
+    interface Random;
   }
 }
 implementation {
@@ -82,17 +83,17 @@ implementation {
     }
   }
 
-  uint8_t i = 0;
+  uint16_t i = 0;
   event void TimerD.fired() {
     dbg("TestTrickle", "Timer D fired at %s\n", sim_time_string());
-    i++;
-    i = i % 3;
+    i = call Random.rand16();
+    i = i % 4;
     switch (i) {
     case 0:
-      //      call TimerA.reset();
+      call TimerA.reset();
       break;
     case 1:
-      //      call TimerB.reset();
+      call TimerB.reset();
       break;
     case 2:
       call TimerC.reset();
index 9523a3fc7f6ec084477994b2d93a29cc097afec8..549f8b8207fdf9f334a1aaf0c32f8b4d356c45a5 100644 (file)
@@ -5,11 +5,11 @@ t = Tossim([]);
 t.init()
 t.addChannel("Trickle", sys.stdout);
 
-for i in range(0, 10):
+for i in range(0, 1):
     m = t.getNode(i)
     m.bootAtTime(i * 5023211 + 10002322)
 
-for i in range(0, 100):
+for i in range(0, 1000000):
     t.runNextEvent()
 
     
index 0ef3d460af727a5e2efc48d41387874b9ef309db..61658d3801199170818fb0cef7e083b48a46be02 100644 (file)
@@ -1,6 +1,6 @@
 README for TestFcfsArbiter
 Author/Contact: tinyos-help@millennium.berkeley.edu
-@author Kevin Klues <klues@tkn.tu-berlin.de>
+@author Kevin Klues <klueska@cs.berkeley.edu>
 
 Description:
 
index aa897643a59a24648c1d31b0d92320793b669b43..6f949eb3a87a323ed1e7c9d06595c8faf7e1ed36 100644 (file)
@@ -54,7 +54,7 @@
  * <li> Led 2 -> Resource 2
  * <br>
  *
- * @author Kevin Klues <klues@tkn.tu-berlin.de>
+ * @author Kevin Klues <klueska@cs.berkeley.edu>
  * @version  $Revision$
  * @date $Date$
  */
index 8a09308871feea6837f69d194047f8d4fa4cae21..46005bdbc84066e240950f008a3d26e04327cd41 100644 (file)
@@ -56,7 +56,7 @@
  * <li> Led 2 -> Resource 2
  * <br>
  *
- * @author Kevin Klues <klues@tkn.tu-berlin.de>
+ * @author Kevin Klues <klueska@cs.berkeley.edu>
  * @version  $Revision$
  * @date $Date$
  */
index 3b42da3b2467a1557047c638d4f81f1528c8168f..85a589d135d7e0406f2bdfd9546d5a8c78248fa9 100644 (file)
@@ -1,6 +1,6 @@
 README for TestRoundRobinArbiter
 Author/Contact: tinyos-help@millennium.berkeley.edu
-@author Kevin Klues <klues@tkn.tu-berlin.de>
+@author Kevin Klues <klueska@cs.berkeley.edu>
 
 Description:
 
index 593fea7b1eec4561c3147a0be507e59261edd65b..7d6b56184cf2cda9a86ff326b5436e03d80c2d41 100644 (file)
@@ -54,7 +54,7 @@
  * <li> Led 2 -> Resource 2
  * <br>
  *
- * @author Kevin Klues <klues@tkn.tu-berlin.de>
+ * @author Kevin Klues <klueska@cs.berkeley.edu>
  * @version  $Revision$
  * @date $Date$
  */
index de621148094f5cc3936a7ab63f073512bb1183eb..cf7cbf4a1b87eab75dde8b9664703e715e6df884 100644 (file)
@@ -56,7 +56,7 @@
  * <li> Led 2 -> Resource 2
  * <br>
  *
- * @author Kevin Klues <klues@tkn.tu-berlin.de>
+ * @author Kevin Klues <klueska@cs.berkeley.edu>
  * @version  $Revision$
  * @date $Date$
  */
index 6e62a3794338e836a03169370ac71e774811f981..139d6aeae4340a926a8fb41d212ec8a05fbec17f 100644 (file)
@@ -4,6 +4,7 @@ CFLAGS += -DACK_LOW_POWER_LISTENING
 #CFLAGS += -DNOACK_LOW_POWER_LISTENING
 
 BUILD_EXTRA_DEPS = RadioCountMsg.py RadioCountMsg.class
+CLEAN_EXTRA = *.class *.pyc RadioCountMsg.py RadioCountMsg.java
 
 RadioCountMsg.py: RadioCountToLeds.h
        mig python -target=$(PLATFORM) $(CFLAGS) -python-classname=RadioCountMsg RadioCountToLeds.h radio_count_msg -o $@
diff --git a/apps/tests/cc2420/LplBroadcastCountToLeds/RadioCountMsg.java b/apps/tests/cc2420/LplBroadcastCountToLeds/RadioCountMsg.java
deleted file mode 100644 (file)
index 46f7c7a..0000000
+++ /dev/null
@@ -1,158 +0,0 @@
-/**
- * This class is automatically generated by mig. DO NOT EDIT THIS FILE.
- * This class implements a Java interface to the 'RadioCountMsg'
- * message type.
- */
-
-public class RadioCountMsg extends net.tinyos.message.Message {
-
-    /** The default size of this message type in bytes. */
-    public static final int DEFAULT_MESSAGE_SIZE = 2;
-
-    /** The Active Message type associated with this message. */
-    public static final int AM_TYPE = 134;
-
-    /** Create a new RadioCountMsg of size 2. */
-    public RadioCountMsg() {
-        super(DEFAULT_MESSAGE_SIZE);
-        amTypeSet(AM_TYPE);
-    }
-
-    /** Create a new RadioCountMsg of the given data_length. */
-    public RadioCountMsg(int data_length) {
-        super(data_length);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new RadioCountMsg with the given data_length
-     * and base offset.
-     */
-    public RadioCountMsg(int data_length, int base_offset) {
-        super(data_length, base_offset);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new RadioCountMsg using the given byte array
-     * as backing store.
-     */
-    public RadioCountMsg(byte[] data) {
-        super(data);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new RadioCountMsg using the given byte array
-     * as backing store, with the given base offset.
-     */
-    public RadioCountMsg(byte[] data, int base_offset) {
-        super(data, base_offset);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new RadioCountMsg using the given byte array
-     * as backing store, with the given base offset and data length.
-     */
-    public RadioCountMsg(byte[] data, int base_offset, int data_length) {
-        super(data, base_offset, data_length);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new RadioCountMsg embedded in the given message
-     * at the given base offset.
-     */
-    public RadioCountMsg(net.tinyos.message.Message msg, int base_offset) {
-        super(msg, base_offset, DEFAULT_MESSAGE_SIZE);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-     * Create a new RadioCountMsg embedded in the given message
-     * at the given base offset and length.
-     */
-    public RadioCountMsg(net.tinyos.message.Message msg, int base_offset, int data_length) {
-        super(msg, base_offset, data_length);
-        amTypeSet(AM_TYPE);
-    }
-
-    /**
-    /* Return a String representation of this message. Includes the
-     * message type name and the non-indexed field values.
-     */
-    public String toString() {
-      String s = "Message <RadioCountMsg> \n";
-      try {
-        s += "  [counter=0x"+Long.toHexString(get_counter())+"]\n";
-      } catch (ArrayIndexOutOfBoundsException aioobe) { /* Skip field */ }
-      return s;
-    }
-
-    // Message-type-specific access methods appear below.
-
-    /////////////////////////////////////////////////////////
-    // Accessor methods for field: counter
-    //   Field type: int, unsigned
-    //   Offset (bits): 0
-    //   Size (bits): 16
-    /////////////////////////////////////////////////////////
-
-    /**
-     * Return whether the field 'counter' is signed (false).
-     */
-    public static boolean isSigned_counter() {
-        return false;
-    }
-
-    /**
-     * Return whether the field 'counter' is an array (false).
-     */
-    public static boolean isArray_counter() {
-        return false;
-    }
-
-    /**
-     * Return the offset (in bytes) of the field 'counter'
-     */
-    public static int offset_counter() {
-        return (0 / 8);
-    }
-
-    /**
-     * Return the offset (in bits) of the field 'counter'
-     */
-    public static int offsetBits_counter() {
-        return 0;
-    }
-
-    /**
-     * Return the value (as a int) of the field 'counter'
-     */
-    public int get_counter() {
-        return (int)getUIntBEElement(offsetBits_counter(), 16);
-    }
-
-    /**
-     * Set the value of the field 'counter'
-     */
-    public void set_counter(int value) {
-        setUIntBEElement(offsetBits_counter(), 16, value);
-    }
-
-    /**
-     * Return the size, in bytes, of the field 'counter'
-     */
-    public static int size_counter() {
-        return (16 / 8);
-    }
-
-    /**
-     * Return the size, in bits, of the field 'counter'
-     */
-    public static int sizeBits_counter() {
-        return 16;
-    }
-
-}
index 7e33328f38bfe155bbb3dc2defc1570d3a1b54dd..20f16ebc23f00f67f9d9d4687294422b710189c8 100644 (file)
@@ -49,7 +49,7 @@ implementation {
 
 #if defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
   components CC1000ActiveMessageC as LplC;
-#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB) || defined(PLATFORM_SHIMMER) || defined(PLATFORM_INTELMOTE2)
+#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB) || defined(PLATFORM_SHIMMER) || defined(PLATFORM_SHIMMER2) || defined(PLATFORM_INTELMOTE2) || defined(PLATFORM_EPIC) 
   components CC2420ActiveMessageC as LplC;
 #else
 #error "LPL testing not supported on this platform"
index 71fd0279aeb0a6b67d79209ccdfd5bce9f6835f7..96205b7c96d94486ea15bd8803b4fb1aabf444dd 100644 (file)
@@ -71,7 +71,7 @@ implementation {
   event void AMControl.startDone(error_t err) {
     if (err == SUCCESS) {
       // Note we can setup LPL before or after the radio turns on
-      call LowPowerListening.setLocalSleepInterval(1000);
+      call LowPowerListening.setLocalWakeupInterval(1000);
       call MilliTimer.startOneShot(1500);
     }
     else {
@@ -96,7 +96,7 @@ implementation {
       }
 
       rcm->counter = counter;
-      call LowPowerListening.setRxSleepInterval(&packet, 1000);
+      call LowPowerListening.setRemoteWakeupInterval(&packet, 1000);
       if (call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(radio_count_msg_t)) == SUCCESS) {
         dbg("RadioCountToLedsC", "RadioCountToLedsC: packet sent.\n", counter);        
         locked = TRUE;
index 0733e6059b6c10a46d2e324e77fe21865159cd81..9dbe0ba0bbaa1b19895509cf40e2575aeaeef732 100644 (file)
@@ -7,6 +7,9 @@ Install the application to two nodes with the following ID's:
   Node 0 (Receiver node): id = 0
   Node 1 (Transmitter node): id = 1
 
+Do this at compile time by adding the flag NODEID=<id>, thus:
+
+make <platform> NODEID=<id> ...
 
 This app sends a message from Transmitter node to 
 AM_BROADCAST_ADDR and waits 1000 ms between each 
index 749d165568d4b26be6057e255751d5aaf96b4f2b..fee5d28a4cd747138ece169acfa8901e0fabe832 100644 (file)
@@ -48,7 +48,7 @@ implementation {
 
 #if defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
   components CC1000ActiveMessageC as Lpl;
-#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB) || defined(PLATFORM_SHIMMER) || defined(PLATFORM_INTELMOTE2)
+#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB) || defined(PLATFORM_SHIMMER) || defined(PLATFORM_SHIMMER2) || defined(PLATFORM_INTELMOTE2) || defined(PLATFORM_EPIC)
   components CC2420ActiveMessageC as Lpl;
 #else
 #error "LPL testing not supported on this platform"
index dab737a81e54d014dd834c805109a5bef5c37ee8..9e7dfff9afb128e7336329632a18bb09bf41bb58 100644 (file)
@@ -71,7 +71,7 @@ implementation {
     transmitter = (call AMPacket.address() == 1);
     count = 0;
     
-    call LowPowerListening.setLocalSleepInterval(1000);
+    call LowPowerListening.setLocalWakeupInterval(1000);
     call SplitControl.start();
   }
   
@@ -124,7 +124,7 @@ implementation {
   task void send() {
     TestPeriodicMsg *periodicMsg = (TestPeriodicMsg *) call Packet.getPayload(&fullMsg, sizeof(TestPeriodicMsg));
     periodicMsg->count = count;
-    call LowPowerListening.setRxSleepInterval(&fullMsg, 1000);
+    call LowPowerListening.setRemoteWakeupInterval(&fullMsg, 1000);
     if(call AMSend.send(AM_BROADCAST_ADDR, &fullMsg, sizeof(TestPeriodicMsg)) != SUCCESS) {
       post send();
     } else {
index d68ac00300bb8c0e9ef2c3e541d4c3758cf45244..dd6c18f6b61aeae8d3f0f76ed2b63267fe33417a 100644 (file)
@@ -48,7 +48,7 @@ implementation {
 
 #if defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
   components CC1000ActiveMessageC as Lpl;
-#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB) || defined(PLATFORM_SHIMMER) || defined(PLATFORM_INTELMOTE2)
+#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB) || defined(PLATFORM_SHIMMER) || defined(PLATFORM_SHIMMER2) || defined(PLATFORM_INTELMOTE2) || defined(PLATFORM_EPIC)
   components CC2420ActiveMessageC as Lpl;
 #else
 #error "LPL testing not supported on this platform"
index 59d3b881235e9ef0152b8214ccaa587f1478b498..4ecce8365974713351894805c17d41cdaee3e90e 100644 (file)
@@ -69,7 +69,7 @@ implementation {
     transmitter = (call AMPacket.address() != 0);
     count = 0;
     
-    call LowPowerListening.setLocalSleepInterval(1000);
+    call LowPowerListening.setLocalWakeupInterval(1000);
     call SplitControl.start();
   }
   
@@ -110,7 +110,7 @@ implementation {
   task void send() {
     TestPeriodicMsg *periodicMsg = (TestPeriodicMsg *) call Packet.getPayload(&fullMsg, sizeof(TestPeriodicMsg));
     periodicMsg->count = count;
-    call LowPowerListening.setRxSleepInterval(&fullMsg, 1000);
+    call LowPowerListening.setRemoteWakeupInterval(&fullMsg, 1000);
     if(call AMSend.send(0, &fullMsg, sizeof(TestPeriodicMsg)) != SUCCESS) {
       post send();
     } else {
index 887e5f9c18c52008b3a031335a311914b6bbc172..8e1faddf08931bfd59ce41bd55d5e4c642496857 100644 (file)
@@ -1,6 +1,6 @@
 COMPONENT=RssiToSerialC
-
 BUILD_EXTRA_DEPS = RssiSerialMsg.java SpecAnalyzer.class
+CLEAN_EXTRA = *.class RssiSerialMsg.java
 
 RssiSerialMsg.java: RssiToSerial.h
        mig java -target=$(PLATFORM) $(CFLAGS) -java-classname=RssiSerialMsg RssiToSerial.h rssi_serial_msg -o $@
index fdf318a1d21f6d7d479f39d0513b64f327628c36..b1ca74d040029b2ecb6914c86d6e854f29e230c1 100644 (file)
@@ -1,8 +1,7 @@
 COMPONENT=TestPacketLinkC
-
 CFLAGS += -DPACKET_LINK
-
 BUILD_EXTRA_DEPS = PacketLinkMsg.java TestPacketLink.class
+CLEAN_EXTRA = *.class PacketLinkMsg.java
 
 PacketLinkMsg.java: TestPacketLink.h
        mig java -target=$(PLATFORM) $(CFLAGS) -java-classname=PacketLinkMsg TestPacketLink.h PacketLinkMsg -o $@
index 4c291ba1f0412d623460dcb16bc6493588c2afd4..2a82684a34a87b70529606a680606590a0c2e476 100644 (file)
@@ -29,7 +29,7 @@ Tools:
 
   java TestPacketLink [-comm <packetsource>]
 
-  If not specified, the <packetsource> defaults to sf@localhost:9001 or
+  If not specified, the <packetsource> defaults to sf@localhost:9002 or
   to your MOTECOM environment variable (if defined).
 
   This application will report dropped and duplicate packets as seen on
diff --git a/apps/tests/cc2420/TestSecurity/BaseStation/BaseStationC.nc b/apps/tests/cc2420/TestSecurity/BaseStation/BaseStationC.nc
new file mode 100644 (file)
index 0000000..c14e727
--- /dev/null
@@ -0,0 +1,92 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ * The TinyOS 2.x base station that forwards packets between the UART
+ * and radio.It replaces the GenericBase of TinyOS 1.0 and the
+ * TOSBase of TinyOS 1.1.
+ *
+ * <p>On the serial link, BaseStation sends and receives simple active
+ * messages (not particular radio packets): on the radio link, it
+ * sends radio active messages, whose format depends on the network
+ * stack being used. BaseStation will copy its compiled-in group ID to
+ * messages moving from the serial link to the radio, and will filter
+ * out incoming radio messages that do not contain that group ID.</p>
+ *
+ * <p>BaseStation includes queues in both directions, with a guarantee
+ * that once a message enters a queue, it will eventually leave on the
+ * other interface. The queues allow the BaseStation to handle load
+ * spikes.</p>
+ *
+ * <p>BaseStation acknowledges a message arriving over the serial link
+ * only if that message was successfully enqueued for delivery to the
+ * radio link.</p>
+ *
+ * <p>The LEDS are programmed to toggle as follows:</p>
+ * <ul>
+ * <li><b>RED Toggle:</b>: Message bridged from serial to radio</li>
+ * <li><b>GREEN Toggle:</b> Message bridged from radio to serial</li>
+ * <li><b>YELLOW/BLUE Toggle:</b> Dropped message due to queue overflow in either direction</li>
+ * </ul>
+ *
+ * @author Phil Buonadonna
+ * @author Gilman Tolle
+ * @author David Gay
+ * @author Philip Levis
+ * @date August 10 2005
+ */
+
+configuration BaseStationC {
+}
+implementation {
+  components MainC, BaseStationP, LedsC;
+  components ActiveMessageC as Radio, SerialActiveMessageC as Serial;
+  components CC2420KeysC;
+  
+  MainC.Boot <- BaseStationP;
+
+  BaseStationP.RadioControl -> Radio;
+  BaseStationP.SerialControl -> Serial;
+  
+  BaseStationP.UartSend -> Serial;
+  BaseStationP.UartReceive -> Serial.Receive;
+  BaseStationP.UartPacket -> Serial;
+  BaseStationP.UartAMPacket -> Serial;
+  
+  BaseStationP.RadioSend -> Radio;
+  BaseStationP.RadioReceive -> Radio.Receive;
+  BaseStationP.RadioSnoop -> Radio.Snoop;
+  BaseStationP.RadioPacket -> Radio;
+  BaseStationP.RadioAMPacket -> Radio;
+  
+  BaseStationP.Leds -> LedsC;
+  BaseStationP.CC2420Keys -> CC2420KeysC;
+}
diff --git a/apps/tests/cc2420/TestSecurity/BaseStation/BaseStationP.nc b/apps/tests/cc2420/TestSecurity/BaseStation/BaseStationP.nc
new file mode 100644 (file)
index 0000000..7dfd3eb
--- /dev/null
@@ -0,0 +1,307 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/*
+ * @author Phil Buonadonna
+ * @author Gilman Tolle
+ * @author David Gay
+ * Revision:   $Id$
+ */
+  
+/* 
+ * BaseStationP bridges packets between a serial channel and the radio.
+ * Messages moving from serial to radio will be tagged with the group
+ * ID compiled into the TOSBase, and messages moving from radio to
+ * serial will be filtered by that same group id.
+ */
+
+#include "AM.h"
+#include "Serial.h"
+
+module BaseStationP @safe() {
+  uses {
+    interface Boot;
+    interface SplitControl as SerialControl;
+    interface SplitControl as RadioControl;
+
+    interface AMSend as UartSend[am_id_t id];
+    interface Receive as UartReceive[am_id_t id];
+    interface Packet as UartPacket;
+    interface AMPacket as UartAMPacket;
+    
+    interface AMSend as RadioSend[am_id_t id];
+    interface Receive as RadioReceive[am_id_t id];
+    interface Receive as RadioSnoop[am_id_t id];
+    interface Packet as RadioPacket;
+    interface AMPacket as RadioAMPacket;
+
+    interface CC2420Keys;
+
+    interface Leds;
+  }
+}
+
+implementation
+{
+  enum {
+    UART_QUEUE_LEN = 12,
+    RADIO_QUEUE_LEN = 12,
+  };
+
+  message_t  uartQueueBufs[UART_QUEUE_LEN];
+  message_t  * ONE_NOK uartQueue[UART_QUEUE_LEN];
+  uint8_t    uartIn, uartOut;
+  bool       uartBusy, uartFull;
+
+  message_t  radioQueueBufs[RADIO_QUEUE_LEN];
+  message_t  * ONE_NOK radioQueue[RADIO_QUEUE_LEN];
+  uint8_t    radioIn, radioOut;
+  bool       radioBusy, radioFull;
+
+  uint8_t key[16] = {0x98,0x67,0x7F,0xAF,0xD6,0xAD,0xB7,0x0C,0x59,0xE8,0xD9,0x47,0xC9,0x71,0x15,0x0F};
+
+  task void uartSendTask();
+  task void radioSendTask();
+
+  void dropBlink() {
+    call Leds.led2Toggle();
+  }
+
+  void failBlink() {
+    call Leds.led2Toggle();
+  }
+
+  event void Boot.booted() {
+    uint8_t i;
+
+    for (i = 0; i < UART_QUEUE_LEN; i++)
+      uartQueue[i] = &uartQueueBufs[i];
+    uartIn = uartOut = 0;
+    uartBusy = FALSE;
+    uartFull = TRUE;
+
+    for (i = 0; i < RADIO_QUEUE_LEN; i++)
+      radioQueue[i] = &radioQueueBufs[i];
+    radioIn = radioOut = 0;
+    radioBusy = FALSE;
+    radioFull = TRUE;
+
+    call RadioControl.start();
+    call SerialControl.start();
+  }
+
+  event void RadioControl.startDone(error_t error) {
+    if (error == SUCCESS) {
+      radioFull = FALSE;
+      call CC2420Keys.setKey(1, key);
+    }
+  }
+
+  event void SerialControl.startDone(error_t error) {
+    if (error == SUCCESS) {
+      uartFull = FALSE;
+    }
+  }
+
+  event void SerialControl.stopDone(error_t error) {}
+  event void RadioControl.stopDone(error_t error) {}
+
+  event void CC2420Keys.setKeyDone(uint8_t keyNo, uint8_t* skey) {}
+
+  uint8_t count = 0;
+
+  message_t* ONE receive(message_t* ONE msg, void* payload, uint8_t len);
+  
+  event message_t *RadioSnoop.receive[am_id_t id](message_t *msg,
+                                                   void *payload,
+                                                   uint8_t len) {
+    return receive(msg, payload, len);
+  }
+  
+  event message_t *RadioReceive.receive[am_id_t id](message_t *msg,
+                                                   void *payload,
+                                                   uint8_t len) {
+    return receive(msg, payload, len);
+  }
+
+  message_t* receive(message_t *msg, void *payload, uint8_t len) {
+    message_t *ret = msg;
+
+    atomic {
+      if (!uartFull)
+       {
+         ret = uartQueue[uartIn];
+         uartQueue[uartIn] = msg;
+
+         uartIn = (uartIn + 1) % UART_QUEUE_LEN;
+       
+         if (uartIn == uartOut)
+           uartFull = TRUE;
+
+         if (!uartBusy)
+           {
+             post uartSendTask();
+             uartBusy = TRUE;
+           }
+       }
+      else
+       dropBlink();
+    }
+    
+    return ret;
+  }
+
+  uint8_t tmpLen;
+  
+  task void uartSendTask() {
+    uint8_t len;
+    am_id_t id;
+    am_addr_t addr, src;
+    message_t* msg;
+    atomic
+      if (uartIn == uartOut && !uartFull)
+       {
+         uartBusy = FALSE;
+         return;
+       }
+
+    msg = uartQueue[uartOut];
+    tmpLen = len = call RadioPacket.payloadLength(msg);
+    id = call RadioAMPacket.type(msg);
+    addr = call RadioAMPacket.destination(msg);
+    src = call RadioAMPacket.source(msg);
+    call UartPacket.clear(msg);
+    call UartAMPacket.setSource(msg, src);
+
+    if (call UartSend.send[id](addr, uartQueue[uartOut], len) == SUCCESS)
+      call Leds.led1Toggle();
+    else
+      {
+       failBlink();
+       post uartSendTask();
+      }
+  }
+
+  event void UartSend.sendDone[am_id_t id](message_t* msg, error_t error) {
+    if (error != SUCCESS)
+      failBlink();
+    else
+      atomic
+       if (msg == uartQueue[uartOut])
+         {
+           if (++uartOut >= UART_QUEUE_LEN)
+             uartOut = 0;
+           if (uartFull)
+             uartFull = FALSE;
+         }
+    post uartSendTask();
+  }
+
+  event message_t *UartReceive.receive[am_id_t id](message_t *msg,
+                                                  void *payload,
+                                                  uint8_t len) {
+    message_t *ret = msg;
+    bool reflectToken = FALSE;
+
+    atomic
+      if (!radioFull)
+       {
+         reflectToken = TRUE;
+         ret = radioQueue[radioIn];
+         radioQueue[radioIn] = msg;
+         if (++radioIn >= RADIO_QUEUE_LEN)
+           radioIn = 0;
+         if (radioIn == radioOut)
+           radioFull = TRUE;
+
+         if (!radioBusy)
+           {
+             post radioSendTask();
+             radioBusy = TRUE;
+           }
+       }
+      else
+       dropBlink();
+
+    if (reflectToken) {
+      //call UartTokenReceive.ReflectToken(Token);
+    }
+    
+    return ret;
+  }
+
+  task void radioSendTask() {
+    uint8_t len;
+    am_id_t id;
+    am_addr_t addr,source;
+    message_t* msg;
+    
+    atomic
+      if (radioIn == radioOut && !radioFull)
+       {
+         radioBusy = FALSE;
+         return;
+       }
+
+    msg = radioQueue[radioOut];
+    len = call UartPacket.payloadLength(msg);
+    addr = call UartAMPacket.destination(msg);
+    source = call UartAMPacket.source(msg);
+    id = call UartAMPacket.type(msg);
+
+    call RadioPacket.clear(msg);
+    call RadioAMPacket.setSource(msg, source);
+    
+    if (call RadioSend.send[id](addr, msg, len) == SUCCESS)
+      call Leds.led0Toggle();
+    else
+      {
+       failBlink();
+       post radioSendTask();
+      }
+  }
+
+  event void RadioSend.sendDone[am_id_t id](message_t* msg, error_t error) {
+    if (error != SUCCESS)
+      failBlink();
+    else
+      atomic
+       if (msg == radioQueue[radioOut])
+         {
+           if (++radioOut >= RADIO_QUEUE_LEN)
+             radioOut = 0;
+           if (radioFull)
+             radioFull = FALSE;
+         }
+    
+    post radioSendTask();
+  }
+}  
diff --git a/apps/tests/cc2420/TestSecurity/BaseStation/Makefile b/apps/tests/cc2420/TestSecurity/BaseStation/Makefile
new file mode 100644 (file)
index 0000000..0015d83
--- /dev/null
@@ -0,0 +1,8 @@
+COMPONENT=BaseStationC
+CFLAGS += -DCC2420_NO_ACKNOWLEDGEMENTS
+CFLAGS += -DCC2420_NO_ADDRESS_RECOGNITION
+CFLAGS += -DCC2420_HW_SECURITY
+CFLAGS += -DTOSH_DATA_LENGTH=115
+CFLAGS += -DTASKLET_IS_TASK
+include $(MAKERULES)
+
diff --git a/apps/tests/cc2420/TestSecurity/README.txt b/apps/tests/cc2420/TestSecurity/README.txt
new file mode 100644 (file)
index 0000000..84fbc2c
--- /dev/null
@@ -0,0 +1,49 @@
+README for TestSecurity
+
+Author/Contact:
+JeongGil Ko <jgko@cs.jhu.edu>
+Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+Jong Hyun Lim <ljh@cs.jhu.edu>
+
+Description:
+
+Test the CC2420 hardware security support
+
+
+Applications:
+
+1. RadioCountToLeds1/ 
+
+This application is a modification to the RadioCountToLeds/
+application with CC2420 security features added to outgoing
+packets. The packets are decrypted at the receiver node. 
+
+> INSTALL
+
+Compile one node with ID 1 as the transmitter and other nodes with any
+node IDs to receive the decrypted packets
+
+>EXPECTATIONS
+
+LEDs on the receiver nodes will blink their LEDs sequentially like the
+original RadioCountToLeds/ application. The LEDs on the transmitter
+will stay off.
+
+
+2. Basestation/
+
+The BaseStation application with the security extensions
+
+> INSTALL
+
+Follow instructions on apps/BaseStation/README.txt
+
+> EXPECTATIONS
+
+Identical to the expectations in  apps/BaseStation/README.txt
+
+
+
+Known bugs/limitations:
+
+None.
diff --git a/apps/tests/cc2420/TestSecurity/RadioCountToLeds1/Makefile b/apps/tests/cc2420/TestSecurity/RadioCountToLeds1/Makefile
new file mode 100644 (file)
index 0000000..710ea3d
--- /dev/null
@@ -0,0 +1,8 @@
+COMPONENT=RadioCountToLedsAppC
+CFLAGS+=-DCC2420_HW_ACKNOWLEDGEMENTS
+CFLAGS+=-DCC2420_HW_SECURITY
+#CFLAGS+=-DCC2420_DEF_CHANNEL=25
+CFLAGS+=-DPACKET_LINK
+CFLAGS+=-DTOSH_DATA_LENGTH=115
+#CFLAGS+=-I%T/lib/printf
+include $(MAKERULES)
diff --git a/apps/tests/cc2420/TestSecurity/RadioCountToLeds1/RadioCountToLeds.h b/apps/tests/cc2420/TestSecurity/RadioCountToLeds1/RadioCountToLeds.h
new file mode 100644 (file)
index 0000000..404470d
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * "Copyright (c) 2004-2005 The Regents of the University  of California.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+#ifndef RADIO_COUNT_TO_LEDS_H
+#define RADIO_COUNT_TO_LEDS_H
+
+typedef nx_struct radio_count_msg {
+  nx_uint16_t counter;
+  nx_uint16_t counter2[20];
+} radio_count_msg_t;
+
+enum {
+  AM_RADIO_COUNT_MSG = 6,
+};
+
+#endif
diff --git a/apps/tests/cc2420/TestSecurity/RadioCountToLeds1/RadioCountToLedsAppC.nc b/apps/tests/cc2420/TestSecurity/RadioCountToLeds1/RadioCountToLedsAppC.nc
new file mode 100644 (file)
index 0000000..9d7ceb8
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+#include "RadioCountToLeds.h"
+
+/**
+ * Configuration for the RadioCountToLeds application. RadioCountToLeds
+ * maintains a 4Hz counter, broadcasting its value in an AM packet
+ * every time it gets updated. A RadioCountToLeds node that hears a counter
+ * displays the bottom three bits on its LEDs. This application is a useful
+ * test to show that basic AM communication and timers work.
+ *
+ * @author Philip Levis
+ * @date   June 6 2005
+ */
+
+configuration RadioCountToLedsAppC {}
+implementation {
+  components MainC, RadioCountToLedsC as App, LedsC, NoLedsC;
+  components new SecAMSenderC(AM_RADIO_COUNT_MSG) as AMSenderC;
+  components new AMReceiverC(AM_RADIO_COUNT_MSG);
+  components new TimerMilliC();
+  components CC2420KeysC;
+  components ActiveMessageC;
+
+  App.Boot -> MainC.Boot;
+  App.Receive -> AMReceiverC;
+  App.AMSend -> AMSenderC;
+  App.AMControl -> ActiveMessageC;
+  App.Leds -> LedsC;
+  App.MilliTimer -> TimerMilliC;
+  App.Packet -> AMSenderC;
+  App.CC2420Security -> AMSenderC;
+  App.CC2420Keys -> CC2420KeysC;
+
+  components CC2420ActiveMessageC as Radio;
+  App.PacketLink -> Radio;
+}
diff --git a/apps/tests/cc2420/TestSecurity/RadioCountToLeds1/RadioCountToLedsC.nc b/apps/tests/cc2420/TestSecurity/RadioCountToLeds1/RadioCountToLedsC.nc
new file mode 100644 (file)
index 0000000..fb6f291
--- /dev/null
@@ -0,0 +1,158 @@
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+#include "Timer.h"
+#include "RadioCountToLeds.h"
+//#include "printf.h"
+/**
+ * Implementation of the RadioCountToLeds application. RadioCountToLeds
+ * maintains a 4Hz counter, broadcasting its value in an AM packet
+ * every time it gets updated. A RadioCountToLeds node that hears a counter
+ * displays the bottom three bits on its LEDs. This application is a useful
+ * test to show that basic AM communication and timers work.
+ *
+ * @author Philip Levis
+ * @date   June 6 2005
+ */
+
+module RadioCountToLedsC {
+  uses {
+    interface Leds;
+    interface Boot;
+    interface Receive;
+    interface AMSend;
+    interface Timer<TMilli> as MilliTimer;
+    interface SplitControl as AMControl;
+    interface Packet;
+    interface CC2420SecurityMode as CC2420Security;
+    interface CC2420Keys;
+
+    interface PacketLink;
+  }
+}
+implementation {
+
+  message_t packet;
+  uint8_t key[16] = {0x98,0x67,0x7F,0xAF,0xD6,0xAD,0xB7,0x0C,0x59,0xE8,0xD9,0x47,0xC9,0x71,0x15,0x0F};
+  uint8_t keyReady = 0; // should be set to 1 when key setting is done
+
+  bool locked;
+  uint16_t counter = 0;
+
+  event void Boot.booted()
+  {
+    call AMControl.start();
+  }
+
+  event void AMControl.startDone(error_t err)
+  {
+    if (err == SUCCESS) {
+      call CC2420Keys.setKey(1, key);
+      if(TOS_NODE_ID == 1)
+       call MilliTimer.startPeriodic(128);
+    } else {
+      call AMControl.start();
+    }
+  }
+
+  event void AMControl.stopDone(error_t err)
+  {
+  }
+
+  event void CC2420Keys.setKeyDone(uint8_t keyNo, uint8_t* skey)
+  {
+    keyReady = 1;
+  }
+
+  event void MilliTimer.fired()
+  {
+    counter++;
+    dbg("RadioCountToLedsC", "RadioCountToLedsC: timer fired, counter is %hu.\n", counter);
+    if (locked) {
+      return;
+    }
+    else if(keyReady == 1) {
+
+      radio_count_msg_t* rcm = (radio_count_msg_t*)call Packet.getPayload(&packet, sizeof(radio_count_msg_t));
+
+      if (rcm == NULL) {
+       return;
+      }
+
+      rcm->counter = counter;
+      //call CC2420Security.setCtr(&packet, 0, 0);
+      //call CC2420Security.setCbcMac(&packet, 0, 0, 16);
+      call CC2420Security.setCcm(&packet, 1, 0, 16);
+      call PacketLink.setRetries(&packet, 3);
+      if (call AMSend.send(AM_BROADCAST_ADDR, &packet, sizeof(radio_count_msg_t)) == SUCCESS) {
+       dbg("RadioCountToLedsC", "RadioCountToLedsC: packet sent.\n", counter);
+       locked = TRUE;
+      }
+    }
+  }
+
+  event message_t* Receive.receive(message_t* bufPtr,
+                                  void* payload, uint8_t len)
+  {
+    dbg("RadioCountToLedsC", "Received packet of length %hhu.\n", len);
+    if (len != sizeof(radio_count_msg_t)) {return bufPtr;}
+    else {
+      radio_count_msg_t* rcm = (radio_count_msg_t*)payload;
+      //printf("counter: %d len: %d\n",rcm->counter, len);
+      //printfflush();
+      if (rcm->counter & 0x1) {
+       call Leds.led0On();
+      }
+      else {
+       call Leds.led0Off();
+      }
+      if (rcm->counter & 0x2) {
+       call Leds.led1On();
+      }
+      else {
+       call Leds.led1Off();
+      }
+      if (rcm->counter & 0x4) {
+       call Leds.led2On();
+      }
+      else {
+       call Leds.led2Off();
+      }
+      return bufPtr;
+    }
+  }
+
+  event void AMSend.sendDone(message_t* msg, error_t error)
+  {
+    if (&packet == msg) {
+      locked = FALSE;
+    }
+  }
+
+}
index cf72257e232a580266591c4d2744926be773df6d..bbc8e5332443b8c0fb7a7ab678731fddedb1fff0 100644 (file)
@@ -1,7 +1,6 @@
 COMPONENT=TxThroughputC
-
-
 BUILD_EXTRA_DEPS = ThroughputMsg.py ThroughputMsg.java ThroughputMsg.class
+CLEAN_EXTRA = *.class *.pyc ThroughputMsg.py ThroughputMsg.java
 
 ThroughputMsg.py: TxThroughput.h
        mig python -target=$(PLATFORM) $(CFLAGS) -python-classname=ThroughputMsg TxThroughput.h ThroughputMsg -o $@
diff --git a/apps/tests/deluge/Basestation/BasestationAppC.nc b/apps/tests/deluge/Basestation/BasestationAppC.nc
new file mode 100644 (file)
index 0000000..4571c4a
--- /dev/null
@@ -0,0 +1,33 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ */
+
+configuration BasestationAppC {}
+
+implementation
+{
+  components DelugeC;
+}
+
diff --git a/apps/tests/deluge/Basestation/Makefile b/apps/tests/deluge/Basestation/Makefile
new file mode 100644 (file)
index 0000000..6af8922
--- /dev/null
@@ -0,0 +1,6 @@
+COMPONENT=BasestationAppC
+BOOTLOADER=tosboot
+
+CFLAGS += -DDELUGE_BASESTATION
+
+include $(MAKERULES)
diff --git a/apps/tests/deluge/Basestation/README.txt b/apps/tests/deluge/Basestation/README.txt
new file mode 100644 (file)
index 0000000..28a9f64
--- /dev/null
@@ -0,0 +1,22 @@
+README for apps/tests/deluge/Basestation
+Author/Contact:
+
+Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+
+Description:
+
+This is a sample application for Deluge T2. The application is similar
+with GoldenImage, but it includes the basestation behavior by using
+the CFLAGS=-DDELUGE_BASESTATION flag.
+
+For telosb the command to install the program is like this:
+         make telosb install bsl,/dev/ttyUSB0
+
+Prerequisites:
+
+Python 2.4 with pySerial
+
+References:
+
+The Deluge T2 wiki page from http://docs.tinyos.net/
diff --git a/apps/tests/deluge/Basestation/volumes-at45db.xml b/apps/tests/deluge/Basestation/volumes-at45db.xml
new file mode 100644 (file)
index 0000000..8b22ebe
--- /dev/null
@@ -0,0 +1,6 @@
+<volume_table>
+  <volume name="GOLDENIMAGE" size="65536" base="0" />
+  <volume name="DELUGE1" size="65536"/>
+  <volume name="DELUGE2" size="65536"/>
+  <volume name="DELUGE3" size="65536"/>
+</volume_table>
\ No newline at end of file
diff --git a/apps/tests/deluge/Basestation/volumes-stm25p.xml b/apps/tests/deluge/Basestation/volumes-stm25p.xml
new file mode 100644 (file)
index 0000000..4210f08
--- /dev/null
@@ -0,0 +1,6 @@
+<volume_table>
+  <volume name="GOLDENIMAGE" size="65536" base="983040" />
+  <volume name="DELUGE1" size="65536"/>
+  <volume name="DELUGE2" size="65536"/>
+  <volume name="DELUGE3" size="65536"/>
+</volume_table>
\ No newline at end of file
index 2189ce46059aa1a8cfd8b75eb26dbc1255c01de1..1d873c40ac48ad3861704d86aeaaf95babc9bdb4 100644 (file)
@@ -28,7 +28,7 @@
  */
 
 /**
- * Blink is a basic application that toggles the a mote LED periodically.
+ * Blink is a basic application that toggles a mote's LED periodically.
  * It does so by starting a Timer that fires every second. It uses the
  * OSKI TimerMilli service to achieve this goal.
  *
index 1e82f5d3b23859ce8d8440fff2b1bf7f5985b89d..fa4a3b1e00e2ec128d919e3d25c425ac38ee765d 100755 (executable)
@@ -1,41 +1,37 @@
 #!/bin/bash
 
-python -c '
-import sys
-try: 
-  import serial
-except ImportError, e: 
-  sys.exit(1)'
-
-if [[ $? != 0 ]]
-then
-  echo "Please install PySerial first." 
-  exit 2
-fi
-
 TOS_DELUGE=`type -p tos-deluge`
 if [[ ! -x ${TOS_DELUGE} ]] ; then 
     TOS_DELUGE=../../../../tools/tinyos/misc/tos-deluge
 fi 
 
-if [[ $# -ne 2 && $# -ne 3 ]]; then
-  echo "Usage: $0 <port> [<comm_port>] <platform>"
-  echo "  <port>       /dev/ttyUSB0"
-  echo "  <comm_port>  /dev/ttyUSB1"
-  echo "  <platform>   micaz, telosb or iris"
+$TOS_DELUGE > /dev/null
+
+if [[ $? != 0 ]]
+then
+  echo "Unable to locate tos-deluge."
   exit 2
 fi
 
-PPORT=$1
-CPORT=$1
-PLATFORM=$2
-
-if [ $# -eq 3 ]; then
- CPORT=$2
- PLATFORM=$3
+if [[ $# -ne 3 ]]; then
+  echo "Usage: $0 <prog_source> <comm_source> <platform>"
+  echo "  <prog_source> bsl,PORT | mib510,PORT | eprb,HOST"
+  echo "  <comm_source> serial@PORT:SPEED | network@HOST:PORT"
+  echo "  <platform>    micaz | telosb | iris | epic | mulle"
+  exit 2
 fi
 
-if [ ${PLATFORM} != 'micaz' -a ${PLATFORM} != 'telosb' -a ${PLATFORM} != 'iris' ]; then
+PPORT=$1
+CPORT=$2
+PLATFORM=$3
+
+if [ ${PLATFORM} != 'micaz' -a \
+     ${PLATFORM} != 'telosb' -a \
+     ${PLATFORM} != 'iris' -a \
+     ${PLATFORM} != 'mulle' -a \
+     ${PLATFORM} != 'tinynode' -a \
+     ${PLATFORM} != 'epic' ]
+then
   echo "\"${PLATFORM}\" is not a supported platform"
   exit 2
 fi
@@ -49,16 +45,7 @@ fi
 make clean
 
 echo ============================ Compile and load Blink ============================
-if [ $PLATFORM == 'micaz' ]
-then
-  CFLAGS=-DDELUGE_BASESTATION make ${PLATFORM} install mib510,${PPORT}
-elif [ $PLATFORM == 'telosb' ]
-then
-  CFLAGS=-DDELUGE_BASESTATION make ${PLATFORM} install bsl,${PPORT}
-elif [ $PLATFORM == 'iris' ]
-then
-  CFLAGS=-DDELUGE_BASESTATION make ${PLATFORM} install mib510,${PPORT}
-fi
+CFLAGS=-DDELUGE_BASESTATION make ${PLATFORM} install ${PPORT}
 
 
 echo '           +-------------------------------------------------------+'
@@ -74,7 +61,7 @@ echo  ============================= Compile a new Blink ========================
 CFLAGS=-DBLINK_REVERSE\ -DDELUGE_BASESTATION make ${PLATFORM}
 
 echo =============================== Upload the image ===============================
-${TOS_DELUGE} ${CPORT} ${PLATFORM} -i 1 build/${PLATFORM}/tos_image.xml
+${TOS_DELUGE} ${CPORT} -i 1 build/${PLATFORM}/tos_image.xml
 
 echo '       +----------------------------------------------------------------+'
 echo '       |                                                                |'
@@ -91,4 +78,4 @@ echo '       +----------------------------------------------------------------+'
 read
 
 echo =========================== Reboot the base station ============================
-${TOS_DELUGE} ${CPORT} ${PLATFORM} -r 1 
+${TOS_DELUGE} ${CPORT} -r 1 
index cc14666103f45bec4c182d6d0994cfee0e61a281..36f1f4cbe17ad6046b4cffb14ea51b329bd72e15 100755 (executable)
@@ -5,9 +5,17 @@ if [[ ! -x ${TOS_DELUGE} ]] ; then
     TOS_DELUGE=../../../../tools/tinyos/misc/tos-deluge
 fi 
 
+$TOS_DELUGE > /dev/null
+
+if [[ $? != 0 ]]
+then
+  echo "Unable to locate tos-deluge."
+  exit 2
+fi
+
 if [ $# -ne 2 ]; then
   echo "Usage: $0 <platform> <number of motes>"
-  echo "  <platform>         micaz, telosb or iris"
+  echo "  <platform>         micaz, telosb, iris or mulle"
   echo "  <number of motes>  how many motes will be used in the test"
   exit 2
 fi
@@ -15,7 +23,13 @@ fi
 PLATFORM=$1
 NO_MOTES=$2
 
-if [ ${PLATFORM} != 'micaz' -a ${PLATFORM} != 'telosb' -a ${PLATFORM} != 'iris' ]; then
+if [ ${PLATFORM} != 'micaz' -a \
+     ${PLATFORM} != 'telosb' -a \
+     ${PLATFORM} != 'iris' \
+     ${PLATFORM} != 'iris' -a \
+     ${PLATFORM} != 'mulle' -a \
+     ${PLATFORM} != 'epic' ]
+then
   echo "\"${PLAFTORM}\" is not a supported platform"
   exit 2
 fi
@@ -32,19 +46,10 @@ ID=0
 
 function burn_one() {
     ID=`expr $ID + 1`
-    echo -n ">>> Please plug mote $ID and type the programming port to continue: "
+    echo -n ">>> Please plug mote $ID and type the programming sorce (bsl,PORT | mib510,PORT | eprb,HOST): "
     read PORT
 
-    if [ ${PLATFORM} == 'micaz' ]
-    then
-       CFLAGS=$1 make ${PLATFORM} install,$ID mib510,${PORT}
-    elif [ ${PLATFORM} == 'telosb' ]
-    then
-       CFLAGS=$1 make ${PLATFORM} install,$ID bsl,${PORT}
-    elif [ ${PLATFORM} == 'iris' ]
-    then
-       CFLAGS=$1 make ${PLATFORM} install,$ID mib510,${PORT}
-    fi
+    CFLAGS=$1 make ${PLATFORM} install,$ID ${PORT}
 }
 
 while [[ ${NO_MOTES} > 1 ]]
@@ -54,9 +59,8 @@ do
 done
 echo ">>> Note: this last mote will be the basestation! <<<"
 burn_one -DDELUGE_BASESTATION
-echo -n ">>> Please plug mote $ID and type the communication port to continue: "
-read PORT
-BASESTATION_PORT=$PORT
+echo -n ">>> Please plug mote $ID and type the communication sorce (serial@PORT:SPEED | network@HOST:PORT) to continue: "
+read CPORT
 
 echo '   +------------------------------------------------------------------------+'
 echo '   |                                                                        |'
@@ -71,7 +75,7 @@ echo ============================= Compile a new Blink =========================
 CFLAGS=-DBLINK_REVERSE\ -DDELUGE_LIGHT_BASESTATION make ${PLATFORM} 
 
 echo ========= Upload the new image to the external flash of the last mote ==========
-${TOS_DELUGE} ${BASESTATION_PORT} ${PLATFORM} -i 1 build/${PLATFORM}/tos_image.xml
+${TOS_DELUGE} ${CPORT} -i 1 build/${PLATFORM}/tos_image.xml
 
 echo '            +-----------------------------------------------------+'
 echo '            |                                                     |'
@@ -85,7 +89,7 @@ echo '            +-----------------------------------------------------+'
 read
 
 echo ============================= Start dissemination ==============================
-${TOS_DELUGE} ${BASESTATION_PORT} ${PLATFORM} -dr 1
+${TOS_DELUGE} ${CPORT} -dr 1
 
 echo '         +------------------------------------------------------------+'
 echo '         |                                                            |'
@@ -96,8 +100,11 @@ echo '         | After a mote gets the whole image he will reboot and       |'
 echo '         | reprogram itself. If the new image contains Deluge he will |'
 echo '         | continue participating in dissemination.                   |'
 echo '         |                                                            |'
-echo '         | In the next step the motes will be rebooted to allow the   |'
-echo '         | reprogramming to take place.                               |'
+echo '         | In the next step all the motes except the basestation will |'
+echo '         | be rebooted to allow the reprogramming to take place.      |'
+echo '         |                                                            |'
+echo '         | After reboot the motes should start blinking the 3rd led   |'
+echo '         | (blue/yellow).                                             |'
 echo '         |                                                            |'
 echo '         +------------------------------------------------------------+'
 
index f27635f4171c890a81a6fd0f52af8ba1002ef70f..5847026eb10ebecf11a6999649329bd683bfd893 100644 (file)
@@ -29,5 +29,8 @@ configuration GoldenImageAppC {}
 implementation
 {
   components DelugeC;
+  components LedsC;
+
+  DelugeC.Leds -> LedsC;
 }
 
index caf65c10909db995cc64301f7d87ba4a7f94cc77..c560f82c459e8bd8395dd470d7f6a3fc428f3b96 100644 (file)
@@ -1,7 +1,6 @@
 COMPONENT=GoldenImageAppC
 BOOTLOADER=tosboot
 
-#CFLAGS += -DDELUGE_BASESTATION
-#CFLAGS += -DDELUGE_LIGHT_BASESTATION
+CFLAGS+=-DDELUGE_LIGHT_BASESTATION
 
 include $(MAKERULES)
index 6b2a7f64cadcaa6ad0b1a96d37b8a480f0fedc02..6160096b31bc5a8deda7cace7624815b8b9150a9 100644 (file)
@@ -7,12 +7,9 @@ Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
 Description:
 
 This is a sample application for Deluge T2. The application is similar 
-to Null, but it includes Deluge T2.
-
-To program a basestation (a mote which can accept images over the
-serial port) you have to add CFLAGS=-DDELUGE_BASESTATION to the make
-command. For telosb this might look like this:
-        CFLAGS=-DDELUGE_BASESTATION make telosb install bsl,/dev/ttyUSB0
+to Null, but it includes Deluge T2. The Makefile includes the
+DELUGE_LIGHT_BASESTATION flag to allow the nodes to be pinged using
+tos-deluge.
 
 Prerequisites:
 
index 14ef6855f21e99c91fc07f6ac4a9823eb5dcd725..e98a3bc3e4de19a26d2b0549d61fb32ed9e19d3d 100644 (file)
@@ -1,5 +1,6 @@
 COMPONENT=RadioCountToFlashAppC
 BUILD_EXTRA_DEPS = RadioCountMsg.py RadioCountMsg.class
+CLEAN_EXTRA = *.class RadioCountMsg.py RadioCountMsg.java
 
 RadioCountMsg.py: RadioCountToFlash.h
        mig python -target=$(PLATFORM) $(CFLAGS) -python-classname=RadioCountMsg RadioCountToFlash.h RadioCountMsg -o $@
index 30e176b32b2997e07f009a33d026620e84c3860e..7df22fd1f300cb071f79da85662e1dd475ae8b3f 100644 (file)
@@ -94,7 +94,7 @@ implementation
 
   // Multi, none
   components new TestAdcMultiC(CONFIG_AVCC,
-                     SUPPLY_VOLTAGE_HALF_CHANNEL, REFERENCE_AVcc_AVss) as TestMulti1,
+                     TEMPERATURE_DIODE_CHANNEL, REFERENCE_AVcc_AVss) as TestMulti1,
              new Msp430Adc12ClientC() as Wrapper4;
 
   TestMulti1 -> MainC.Boot;
@@ -104,7 +104,7 @@ implementation
 
   // Multi, RefVolt
   components new TestAdcMultiC(CONFIG_VREF,
-                      SUPPLY_VOLTAGE_HALF_CHANNEL, REFERENCE_VREFplus_AVss) as TestMulti2,
+                      TEMPERATURE_DIODE_CHANNEL, REFERENCE_VREFplus_AVss) as TestMulti2,
              new Msp430Adc12ClientAutoRVGC() as Wrapper5;
 
   TestMulti2 -> MainC.Boot;
index 2115b8bfada279d6ca1908da1710b57b9eaed50b..6a2495031e016980f8eedd8c491f5b8d854b7efb 100644 (file)
@@ -66,10 +66,12 @@ implementation
 {
   
 #define BUFFER_SIZE 100
+#define NUM_REPETITIONS 5
   const msp430adc12_channel_config_t config = {inch, sref, ref2_5v, adc12ssel, adc12div, sht, sampcon_ssel, sampcon_id};
   adc12memctl_t memCtl = {inch2, sref2};
   norace uint8_t state;
   uint16_t buffer[BUFFER_SIZE];
+  norace uint8_t count = 0;
   void task getData();
 
   void task signalFailure()
@@ -102,7 +104,7 @@ implementation
 
   event void Boot.booted()
   {
-    state = 0;
+    count = NUM_REPETITIONS;
     post getData();
   }
 
@@ -119,11 +121,15 @@ implementation
 
   async event void MultiChannel.dataReady(uint16_t *buf, uint16_t numSamples)
   {
-    if (assertData(buf, numSamples) && state++ == 0)
-      post signalSuccess();
-    else
+    if (!assertData(buf, numSamples)){
       post signalFailure();
-    call Resource.release();
+    } else if (count){
+      count--;
+      call MultiChannel.getData();
+    } else {
+      post signalSuccess();
+      call Resource.release();
+    }
   }
 
   command error_t Notify.enable(){}
index e44d9ae4cc2ea7fdd56ff43df7562d9e4e05a1a2..d6ef05e8f8092c4b0fa71e63ab3e53af2fcbcd73 100644 (file)
@@ -62,11 +62,19 @@ generic module TestAdcSingleC(
 implementation
 {
 #define BUFFER_SIZE 100
+#define NUM_REPETITIONS 5
   const msp430adc12_channel_config_t config = {inch, sref, ref2_5v, adc12ssel, adc12div, sht, sampcon_ssel, sampcon_id};
-  uint8_t state;
-  norace uint8_t numDone;
+  norace uint8_t state;
+  norace uint8_t count = 0;
   uint16_t buffer[BUFFER_SIZE];
   void task getData();
+  enum {
+    SINGLE_DATA,
+    SINGLE_DATA_REPEAT,
+    MULTIPLE_DATA,
+    MULTIPLE_DATA_REPEAT,
+  };
+
 
   void task signalFailure()
   {
@@ -83,7 +91,7 @@ implementation
 
   event void Boot.booted()
   {
-    state = 0;
+    state = SINGLE_DATA;
     post getData();
   }
 
@@ -99,36 +107,52 @@ implementation
   
   event void Resource.granted()
   {
+    count = NUM_REPETITIONS;
     switch(state)
     {
-      case 0: state++;
-              if (call SingleChannel.configureSingleRepeat(&config, 0) == SUCCESS)
+      case SINGLE_DATA: 
+              if (call SingleChannel.configureSingle(&config) == SUCCESS)
                 call SingleChannel.getData();
               break;
-      case 1: state++;
-              if (call SingleChannel.configureSingle(&config) == SUCCESS)
+      case SINGLE_DATA_REPEAT: 
+              if (call SingleChannel.configureSingleRepeat(&config, 10) == SUCCESS)
                 call SingleChannel.getData();
               break;
-      case 2: state++;
-              if (call SingleChannel.configureMultiple(&config, buffer, BUFFER_SIZE, 0) == SUCCESS)
+      case MULTIPLE_DATA: 
+              if (call SingleChannel.configureMultiple(&config, buffer, BUFFER_SIZE, 10) == SUCCESS)
                 call SingleChannel.getData();
               break;
-      case 3: state++;
-              if (call SingleChannel.configureMultipleRepeat(&config, buffer, 16, 0) == SUCCESS)
+      case MULTIPLE_DATA_REPEAT: 
+              if (call SingleChannel.configureMultipleRepeat(&config, buffer, 16, 10) == SUCCESS)
                 call SingleChannel.getData();
               break;
       default: call Resource.release();
-              if (numDone == state)
-                signal Notify.notify(TRUE);
+              signal Notify.notify(TRUE);
               break;
     }
   }
 
   async event error_t SingleChannel.singleDataReady(uint16_t data)
   { 
-    numDone++;
     assertData(&data, 1);
+    switch(state)
+    {
+      case SINGLE_DATA: 
+              if (count){
+                count--;
+                call SingleChannel.getData();
+                return SUCCESS;
+              }
+              break;
+      case SINGLE_DATA_REPEAT:
+              if (count){
+                count--;
+                return SUCCESS;
+              }
+              break;
+    }
     call Resource.release();
+    state++;
     post getData();
     return FAIL;
   }
@@ -136,9 +160,24 @@ implementation
     
   async event uint16_t* SingleChannel.multipleDataReady(uint16_t *buf, uint16_t length)
   {
-    numDone++;
     assertData(buf, length);
+    switch(state)
+    {
+      case MULTIPLE_DATA: 
+              if (count){
+                count--;
+                call SingleChannel.getData();
+                return 0;
+              }
+              break;
+      case MULTIPLE_DATA_REPEAT:
+              if (count){
+                count--;
+                return buf;
+              }
+    }   
     call Resource.release();
+    state++;
     post getData();
     return 0;
   }
diff --git a/apps/tests/rf230/Ieee154CountToLeds/Makefile b/apps/tests/rf230/Ieee154CountToLeds/Makefile
new file mode 100644 (file)
index 0000000..74cfe31
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=RadioCountToLedsAppC
+
+include $(MAKERULES)
diff --git a/apps/tests/rf230/Ieee154CountToLeds/RadioCountToLeds.h b/apps/tests/rf230/Ieee154CountToLeds/RadioCountToLeds.h
new file mode 100644 (file)
index 0000000..8d29f3f
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * "Copyright (c) 2004-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+#ifndef RADIO_COUNT_TO_LEDS_H
+#define RADIO_COUNT_TO_LEDS_H
+
+typedef nx_struct radio_count_msg {
+  nx_uint16_t counter;
+} radio_count_msg_t;
+
+enum {
+  AM_RADIO_COUNT_MSG = 6,
+};
+
+#endif
diff --git a/apps/tests/rf230/Ieee154CountToLeds/RadioCountToLedsAppC.nc b/apps/tests/rf230/Ieee154CountToLeds/RadioCountToLedsAppC.nc
new file mode 100644 (file)
index 0000000..5feaad7
--- /dev/null
@@ -0,0 +1,61 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+#include "RadioCountToLeds.h"
+
+/**
+ * Configuration for the RadioCountToLeds application. RadioCountToLeds 
+ * maintains a 4Hz counter, broadcasting its value in an AM packet 
+ * every time it gets updated. A RadioCountToLeds node that hears a counter 
+ * displays the bottom three bits on its LEDs. This application is a useful 
+ * test to show that basic AM communication and timers work.
+ *
+ * @author Philip Levis
+ * @date   June 6 2005
+ */
+
+configuration RadioCountToLedsAppC {}
+implementation {
+  components MainC, RadioCountToLedsC as App, LedsC;
+  components Ieee154MessageC;
+  components new TimerMilliC();
+  
+  App.Boot -> MainC.Boot;
+  
+  App.Receive -> Ieee154MessageC;
+  App.Send -> Ieee154MessageC;
+  App.SplitControl -> Ieee154MessageC;
+  App.Leds -> LedsC;
+  App.MilliTimer -> TimerMilliC;
+  App.Packet -> Ieee154MessageC;
+}
+
+
diff --git a/apps/tests/rf230/Ieee154CountToLeds/RadioCountToLedsC.nc b/apps/tests/rf230/Ieee154CountToLeds/RadioCountToLedsC.nc
new file mode 100644 (file)
index 0000000..2be5356
--- /dev/null
@@ -0,0 +1,139 @@
+// $Id$
+
+/*                                                                     tab:4
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+#include "Timer.h"
+#include "RadioCountToLeds.h"
+/**
+ * Implementation of the RadioCountToLeds application. RadioCountToLeds 
+ * maintains a 4Hz counter, broadcasting its value in an AM packet 
+ * every time it gets updated. A RadioCountToLeds node that hears a counter 
+ * displays the bottom three bits on its LEDs. This application is a useful 
+ * test to show that basic AM communication and timers work.
+ *
+ * @author Philip Levis
+ * @date   June 6 2005
+ */
+
+module RadioCountToLedsC @safe() {
+  uses {
+    interface Leds;
+    interface Boot;
+    interface Receive;
+    interface Ieee154Send as Send;
+    interface Timer<TMilli> as MilliTimer;
+    interface SplitControl;
+    interface Packet;
+  }
+}
+implementation {
+
+  message_t packet;
+
+  bool locked;
+  uint16_t counter = 0;
+  
+  event void Boot.booted() {
+    call SplitControl.start();
+  }
+
+  event void SplitControl.startDone(error_t err) {
+    if (err == SUCCESS) {
+      call MilliTimer.startPeriodic(250);
+    }
+    else {
+      call SplitControl.start();
+    }
+  }
+
+  event void SplitControl.stopDone(error_t err) {
+    // do nothing
+  }
+  
+  event void MilliTimer.fired() {
+    counter++;
+    dbg("RadioCountToLedsC", "RadioCountToLedsC: timer fired, counter is %hu.\n", counter);
+    if (locked) {
+      return;
+    }
+    else {
+      radio_count_msg_t* rcm = (radio_count_msg_t*)call Packet.getPayload(&packet, sizeof(radio_count_msg_t));
+      if (rcm == NULL) {
+       return;
+      }
+
+      rcm->counter = counter;
+      if (call Send.send(AM_BROADCAST_ADDR, &packet, sizeof(radio_count_msg_t)) == SUCCESS) {
+       dbg("RadioCountToLedsC", "RadioCountToLedsC: packet sent.\n", counter); 
+       locked = TRUE;
+      }
+    }
+  }
+
+  event message_t* Receive.receive(message_t* bufPtr, 
+                                  void* payload, uint8_t len) {
+    dbg("RadioCountToLedsC", "Received packet of length %hhu.\n", len);
+    if (len != sizeof(radio_count_msg_t)) {return bufPtr;}
+    else {
+      radio_count_msg_t* rcm = (radio_count_msg_t*)payload;
+      if (rcm->counter & 0x1) {
+       call Leds.led0On();
+      }
+      else {
+       call Leds.led0Off();
+      }
+      if (rcm->counter & 0x2) {
+       call Leds.led1On();
+      }
+      else {
+       call Leds.led1Off();
+      }
+      if (rcm->counter & 0x4) {
+       call Leds.led2On();
+      }
+      else {
+       call Leds.led2Off();
+      }
+      return bufPtr;
+    }
+  }
+
+  event void Send.sendDone(message_t* bufPtr, error_t error) {
+    if (&packet == bufPtr) {
+      locked = FALSE;
+    }
+  }
+
+}
+
+
+
+
index aae82975b096d800e1bde4509430f37eccae6686..ce38f16f68a49cffc05c5034206c52579c50f8d5 100644 (file)
@@ -2,5 +2,6 @@ COMPONENT=RF230SnifferC
 CFLAGS += -I$(TOSDIR)/lib/diagmsg
 CFLAGS += -DTASKLET_IS_TASK
 CFLAGS += -DDIAGMSG_RECORDED_MSGS=60
-CFLAGS += -DRF230_DEBUG -DRF230_DEBUG_MESSAGES
+CFLAGS += -DRADIO_DEBUG -DRADIO_DEBUG_MESSAGES
+CFLAGS += -DRF230_RSSI_ENERGY
 include $(MAKERULES)
index 489583937a437a3ad334c4111a4b65aaaf9015ef..340898332347116b4d71d612032b482aabd0045b 100644 (file)
@@ -27,16 +27,35 @@ configuration RF230SnifferC
 
 implementation
 {
-       components RF230SnifferP, MainC, SerialActiveMessageC, RF230LayerC, RF230ActiveMessageP, IEEE154PacketC, AssertC;
+       components RF230SnifferP, MainC, SerialActiveMessageC, AssertC;
        
        RF230SnifferP.Boot -> MainC;
        RF230SnifferP.SplitControl -> SerialActiveMessageC;
-       RF230SnifferP.RadioState -> RF230LayerC;
-
-       RF230LayerC.RF230Config -> RF230ActiveMessageP;
-
-       RF230ActiveMessageP.IEEE154Packet -> IEEE154PacketC;
+       RF230SnifferP.RadioState -> RF230DriverLayerC;
 
        // just to avoid a timer compilation bug
        components new TimerMilliC();
+
+// -------- ActiveMessage
+
+       components RF230RadioP, Ieee154PacketLayerC;
+       RF230RadioP.Ieee154PacketLayer -> Ieee154PacketLayerC;
+
+// -------- TimeStamping
+
+       components TimeStampingLayerC;
+       TimeStampingLayerC.LocalTimeRadio -> RF230DriverLayerC;
+       TimeStampingLayerC.SubPacket -> MetadataFlagsLayerC;
+
+// -------- MetadataFlags
+
+       components MetadataFlagsLayerC;
+       MetadataFlagsLayerC.SubPacket -> RF230DriverLayerC;
+
+// -------- RF230 Driver
+
+       components RF230DriverLayerC;
+       RF230DriverLayerC.Config -> RF230RadioP;
+       RF230DriverLayerC.PacketTimeStamp -> TimeStampingLayerC;
+
 }
index 98bd7f7c75d9fccead680269d382bb7fe9cd7e72..fc8562d5a921f23e3ef9fe7d0a85308fd7db7ca6 100644 (file)
@@ -21,9 +21,7 @@
  * Author: Miklos Maroti
  */
 
-#include <RF230Packet.h>
 #include <Tasklet.h>
-#include <message.h>
 
 module RF230SnifferP
 {
index 27463abf23659bfe72807e123abc09c3edeeda00..3b03b67cbe5fa5284195eaa2608479933bcf7bcf 100644 (file)
@@ -37,8 +37,8 @@ implementation
        RF230TestM.SplitControl -> SerialActiveMessageC;
        RF230TestM.Timer -> TimerMilliC;
 
-       components RF230LayerC, RF230ActiveMessageC;
+       components RF230DriverLayerC, RF230ActiveMessageC;
 
-       RF230TestM.RadioState -> RF230LayerC;
+       RF230TestM.RadioState -> RF230DriverLayerC;
        RF230TestM.AMSend -> RF230ActiveMessageC;
 }
index 4cb5b6e4f0db07b59f094c723e625c240bb83e46..931e0737b95827c335d4cb87ea54e155d50f3187 100644 (file)
@@ -27,7 +27,7 @@ configuration RadioCountToDiagC
 
 implementation
 {
-       components MainC, RadioCountToDiagP, DiagMsgC;
+       components MainC, RadioCountToDiagP, DiagMsgC, LedsC;
        components ActiveMessageC, SerialActiveMessageC;
        components new TimerMilliC() as SendTimerC;
        components new TimerMilliC() as ReportTimerC;
@@ -50,4 +50,6 @@ implementation
        RadioCountToDiagP.ActiveMessageAddress -> ActiveMessageAddressC;
 
        RadioCountToDiagP.LowPowerListening -> ActiveMessageC;
+
+       RadioCountToDiagP.Leds -> LedsC;
 }
index e464cebd4bcc9aa7be69a8c140c1e2c743ba1a2e..0cf4d49c1dc5482a9e01ab37a455567abe5a7c24 100644 (file)
@@ -42,11 +42,13 @@ module RadioCountToDiagP
 
                interface ActiveMessageAddress;
                interface LowPowerListening;
+
+               interface Leds;
        }
 }
 
 #ifndef SEND_PERIOD
-#define SEND_PERIOD 10
+#define SEND_PERIOD 20
 #endif
 
 #ifndef SLEEP_INTERVAL
@@ -68,7 +70,7 @@ implementation
                else
                {
 #ifdef LOW_POWER_LISTENING
-                       call LowPowerListening.setLocalSleepInterval(SLEEP_INTERVAL);
+                       call LowPowerListening.setLocalWakeupInterval(SLEEP_INTERVAL);
 #endif         
                        call SendTimer.startPeriodic(SEND_PERIOD);
                        call ReportTimer.startPeriodic(1000);
@@ -116,6 +118,8 @@ implementation
 
        event void ReportTimer.fired()
        {
+               call Leds.led0Toggle();
+
                if( call DiagMsg.record() )
                {
                        call DiagMsg.uint16(sendCount);
@@ -141,10 +145,12 @@ implementation
        {
                uint16_t addr;
 
+               call Leds.led1Toggle();
+               
                call Packet.clear(&txMsg);
                call PacketAcknowledgements.requestAck(&txMsg);
 #ifdef LOW_POWER_LISTENING
-               call LowPowerListening.setRxSleepInterval(&txMsg, SLEEP_INTERVAL);
+               call LowPowerListening.setRemoteWakeupInterval(&txMsg, SLEEP_INTERVAL);
 #endif
 
                addr = call ActiveMessageAddress.amAddress();
index 7cc59802a58dd56c2db58d44d98fcce66c6fa761..e221874e19a1b1b295be8246ae5591420227c34e 100644 (file)
@@ -1,4 +1,4 @@
 <volume_table>
   <volume name="LOGTEST" size="262144"/>
-  <volume name="CONFIGTEST" size="4608"/>
+  <volume name="CONFIGTEST" size="5120"/>
 </volume_table>
index 0c7ee628a86165df2ccb0c2f7a4ace69e4403d49..7a79e132a96bf34803c8129c402826a85e630814 100644 (file)
@@ -138,8 +138,16 @@ implementation {
       scheck(call LogWrite.sync());
     else
       {
+       error_t result;
        setParameters();
-       scheck(call LogWrite.append(data + offset, len));
+       result = call LogWrite.append(data + offset, len);
+       if (result == ESIZE) {
+         // We have reached the end of the log, sync it
+         scheck(call LogWrite.sync());
+       }
+       else {
+         scheck(result);
+       }
       }
   }
 
index 06212b52584c4e48e12a269e43633e66096ffc71..100847b17a8b255c3f5cd8610ca83d13743066d0 100644 (file)
@@ -1,4 +1,4 @@
-PLATFORMS = telosb
+PLATFORMS = telosb micaz
 TKN154_PLATFORM_INCLUDE?=$(TOSDIR)/platforms/$(PLATFORM)/mac/tkn154/Makefile.include
 
 CFLAGS += -I$(TOSDIR)/lib/mac/tkn154 \
@@ -12,6 +12,12 @@ ifdef IEEE154_EXTENDED_ADDRESS
 PFLAGS += -DIEEE154_EXTENDED_ADDRESS=$(IEEE154_EXTENDED_ADDRESS)
 endif
 
+ifdef TKN154_DEBUG
+PFLAGS += -DTKN154_DEBUG
+CFLAGS += -I$(TOSDIR)/lib/printf
+PFLAGS += -DPRINTF_BUFFER_SIZE=1000
+endif
+
 # parses the PLATFORM variable
 include $(MAKERULES)
 
index eb9457979499171f22af3bffd70123542ecff9db..8aa63d9e98e9f19dddf818654f452ffbcc76154e 100644 (file)
@@ -1,12 +1,14 @@
 README for tkn154 test applications
-Author/Contact: tinyos-help@millennium.berkeley.edu
+Author/Contact: Jan Hauer <hauer@tkn.tu-berlin.de>
 
 Description:
 
 This folder contains test applications for "TKN15.4", a platform-independent
-IEEE 802.15.4-2006 MAC implementation. Every test application resides in a
-separate subdirectory which includes a README.txt describing what it does and
-how it can be installed, respectively.
+IEEE 802.15.4-2006 MAC implementation. Applications that use the beacon-enabled
+mode are located in the "beacon-enabled" folder, applications that use the
+nonbeacon-enabled mode are in the "nonbeacon-enabled" folder. Every test
+application resides in a separate subdirectory which includes a README.txt
+describing what it does and how it can be installed.
 
 The TKN15.4 implementation can be found in tinyos-2.x/tos/lib/mac/tkn154.
 Note: TEP3 recommends that interface names "should be mixed case, starting
diff --git a/apps/tests/tkn154/TestAssociate/README.txt b/apps/tests/tkn154/TestAssociate/README.txt
deleted file mode 100644 (file)
index eefdf41..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-README for TestAssociate
-Author/Contact: tinyos-help@millennium.berkeley.edu
-
-Description:
-
-In this application one node takes the role of a PAN coordinator in a
-beacon-enabled 802.15.4 PAN; it transmits periodic beacons and waits for
-devices to request association to its PAN. Whenever a device tries to
-associate, the PAN coordinator allows association and assigns to the device a
-unique short address (starting from zero, incremented for every device
-requesting association). 
-
-A second node acts as a device; it first scans the pre-defined channel for
-beacons from the coordinator and once it finds a beacon it tries to associate
-to the PAN and synchronize to and track all future beacons. A short time after
-association the device then disassociates from the PAN. 
-
-The third LED (Telos: blue) is toggled whenever the coordinator has transmitted
-a beacon or whenever a device has received a beacon. On the coordinator the
-second LED (Telos: green) is switched on whenever an association request was
-successful and it is switched off, whenever a disassociation request was
-received. On a device the second LED is switched on while the device is
-associated to the PAN, i.e. it is switched off after disassociation. The first
-LED (Telos: red) is used for debugging, it denotes an error in the protocol
-stack and should never be on.
-
-Tools: NONE
-
-Usage: 
-
-1. Install the coordinator:
-
-    $ cd coordinator; make telosb install
-
-2. Install one (or more) devices:
-
-    $ cd device; make telosb install
-
-You can change some of the configuration parameters in app_profile.h
-
-Known bugs/limitations:
-
-- Currently this application only works on TelosB nodes
-- The MAC timing is not standard compliant, because TelosB lacks a
-  clock with sufficient precision/accuracy
-
-$Id$o
-
diff --git a/apps/tests/tkn154/TestAssociate/app_profile.h b/apps/tests/tkn154/TestAssociate/app_profile.h
deleted file mode 100644 (file)
index 21641f6..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#ifndef __APP_PROFILE_H
-#define __APP_PROFILE_H
-
-enum {
-  RADIO_CHANNEL = 26,
-  PAN_ID = 0x1238,
-  COORDINATOR_ADDRESS = 0x9182,
-  BEACON_ORDER = 6,
-  SUPERFRAME_ORDER = 6,
-};
-
-#endif
diff --git a/apps/tests/tkn154/TestAssociate/coordinator/Makefile b/apps/tests/tkn154/TestAssociate/coordinator/Makefile
deleted file mode 100644 (file)
index 7fe7134..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-COMPONENT=TestAssociateAppC
-CFLAGS += -I$(shell pwd)/..
-include ../../Makefile.include
diff --git a/apps/tests/tkn154/TestAssociate/coordinator/TestAssociateAppC.nc b/apps/tests/tkn154/TestAssociate/coordinator/TestAssociateAppC.nc
deleted file mode 100644 (file)
index 5945ddf..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-configuration TestAssociateAppC
-{
-} implementation {
-  components MainC, LedsC, Ieee802154MacC as Ieee802154MacC;
-  components TestCoordC as App;
-
-  MainC.Boot <- App;
-  App.Leds -> LedsC;
-  App.MLME_RESET -> Ieee802154MacC;
-  App.MLME_SET -> Ieee802154MacC;
-  App.MLME_GET -> Ieee802154MacC;
-
-  App.MLME_START -> Ieee802154MacC;
-  App.MLME_ASSOCIATE -> Ieee802154MacC;
-  App.MLME_DISASSOCIATE -> Ieee802154MacC;
-  App.MLME_COMM_STATUS -> Ieee802154MacC;
-  App.Frame -> Ieee802154MacC;
-  App.IEEE154TxBeaconPayload -> Ieee802154MacC;
-}
diff --git a/apps/tests/tkn154/TestAssociate/coordinator/TestCoordC.nc b/apps/tests/tkn154/TestAssociate/coordinator/TestCoordC.nc
deleted file mode 100644 (file)
index ceb793c..0000000
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#include "TKN154.h"
-#include "app_profile.h"
-module TestCoordC
-{
-  uses {
-    interface Boot;
-    interface MLME_RESET;
-    interface MLME_START;
-    interface MLME_ASSOCIATE;
-    interface MLME_DISASSOCIATE;
-    interface MLME_COMM_STATUS;
-    interface MLME_SET;
-    interface MLME_GET;
-    interface IEEE154Frame as Frame;
-    interface IEEE154TxBeaconPayload;
-    interface Leds;
-  }
-} implementation {
-
-  ieee154_address_t m_lastDevice;
-  uint16_t m_shortAddress;
-
-  event void Boot.booted() {
-    call MLME_RESET.request(TRUE, BEACON_ENABLED_PAN);
-  }
-
-  event void MLME_RESET.confirm(ieee154_status_t status)
-  {
-    if (status != IEEE154_SUCCESS)
-      return;
-    call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
-    call MLME_SET.macAssociationPermit(TRUE);
-    call MLME_START.request(
-                          PAN_ID,           // PANId
-                          RADIO_CHANNEL,    // LogicalChannel
-                          0,                // ChannelPage,
-                          0,                // StartTime,
-                          BEACON_ORDER,     // BeaconOrder
-                          SUPERFRAME_ORDER, // SuperframeOrder
-                          TRUE,             // PANCoordinator
-                          FALSE,            // BatteryLifeExtension
-                          FALSE,            // CoordRealignment
-                          0,                // no realignment security
-                          0                 // no beacon security
-                        );
-  }
-
-  event void MLME_START.confirm(ieee154_status_t status) { }
-
-  event void MLME_ASSOCIATE.indication (
-                          uint64_t DeviceAddress,
-                          ieee154_CapabilityInformation_t CapabilityInformation,
-                          ieee154_security_t *security
-                        )
-  {
-    call MLME_ASSOCIATE.response(DeviceAddress, m_shortAddress++, IEEE154_ASSOCIATION_SUCCESSFUL, 0);
-  }
-
-  event void MLME_DISASSOCIATE.indication (
-                          uint64_t DeviceAddress,
-                          ieee154_disassociation_reason_t DisassociateReason,
-                          ieee154_security_t *security
-                        )
-  {
-    call Leds.led1Off();
-  }
-
-
-  event void MLME_COMM_STATUS.indication (
-                          uint16_t PANId,
-                          uint8_t SrcAddrMode,
-                          ieee154_address_t SrcAddr,
-                          uint8_t DstAddrMode,
-                          ieee154_address_t DstAddr,
-                          ieee154_status_t status,
-                          ieee154_security_t *security
-                        )
-  {
-    if (status == IEEE154_SUCCESS){
-      // association was successful
-      call Leds.led1On();
-      m_lastDevice.extendedAddress = DstAddr.extendedAddress;
-    } else {
-      call Leds.led1Off();
-    }
-  }
-
-  event void MLME_DISASSOCIATE.confirm    (
-                          ieee154_status_t status,
-                          uint8_t DeviceAddrMode,
-                          uint16_t DevicePANID,
-                          ieee154_address_t DeviceAddress
-                        ){}
-
-  event void MLME_ASSOCIATE.confirm    (
-                          uint16_t AssocShortAddress,
-                          uint8_t status,
-                          ieee154_security_t *security
-                        ){}
-
-  event void IEEE154TxBeaconPayload.aboutToTransmit() { }
-
-  event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) { }
-
-  event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) { }
-
-  event void IEEE154TxBeaconPayload.beaconTransmitted() 
-  {
-    ieee154_macBSN_t beaconSequenceNumber = call MLME_GET.macBSN();
-    if (beaconSequenceNumber & 1)
-      call Leds.led2On();
-    else
-      call Leds.led2Off();
-  }  
-}
diff --git a/apps/tests/tkn154/TestAssociate/device/Makefile b/apps/tests/tkn154/TestAssociate/device/Makefile
deleted file mode 100644 (file)
index 7fe7134..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-COMPONENT=TestAssociateAppC
-CFLAGS += -I$(shell pwd)/..
-include ../../Makefile.include
diff --git a/apps/tests/tkn154/TestAssociate/device/TestAssociateAppC.nc b/apps/tests/tkn154/TestAssociate/device/TestAssociateAppC.nc
deleted file mode 100644 (file)
index c99e233..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-configuration TestAssociateAppC
-{
-} implementation {
-  components MainC, LedsC, Ieee802154MacC as Ieee802154MacC,
-             new Timer62500C() as Timer;
-  components TestDeviceC as App;
-
-  MainC.Boot <- App;
-  App.Leds -> LedsC;
-  App.MLME_RESET -> Ieee802154MacC;
-  App.MLME_SET -> Ieee802154MacC;
-  App.MLME_GET -> Ieee802154MacC;
-  App.DisassociateTimer -> Timer;  
-  App.MLME_SCAN -> Ieee802154MacC;
-  App.MLME_SYNC -> Ieee802154MacC;
-  App.MLME_BEACON_NOTIFY -> Ieee802154MacC;
-  App.MLME_SYNC_LOSS -> Ieee802154MacC;
-  App.MLME_ASSOCIATE -> Ieee802154MacC;
-  App.MLME_DISASSOCIATE -> Ieee802154MacC;
-  App.MLME_COMM_STATUS -> Ieee802154MacC;
-  App.BeaconFrame -> Ieee802154MacC;
-
-}
diff --git a/apps/tests/tkn154/TestAssociate/device/TestDeviceC.nc b/apps/tests/tkn154/TestAssociate/device/TestDeviceC.nc
deleted file mode 100644 (file)
index 1c22739..0000000
+++ /dev/null
@@ -1,242 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154.h"
-#include "app_profile.h"
-module TestDeviceC
-{
-  uses {
-    interface Boot;
-    interface MLME_RESET;
-    interface MLME_SET;
-    interface MLME_GET;
-    interface MLME_SCAN;
-    interface MLME_SYNC;
-    interface MLME_ASSOCIATE;
-    interface MLME_DISASSOCIATE;
-    interface MLME_COMM_STATUS;
-    interface MLME_BEACON_NOTIFY;
-    interface MLME_SYNC_LOSS;
-    interface Leds;
-    interface IEEE154BeaconFrame as BeaconFrame;
-    interface Timer<T62500hz> as DisassociateTimer;
-  }
-} implementation {
-
-  ieee154_CapabilityInformation_t m_capabilityInformation;
-  ieee154_PANDescriptor_t m_PANDescriptor;
-  bool m_isPANDescriptorValid;
-  void startApp();
-
-  event void Boot.booted() {
-    m_capabilityInformation.AlternatePANCoordinator = 0;
-    m_capabilityInformation.DeviceType = 0;
-    m_capabilityInformation.PowerSource = 0;
-    m_capabilityInformation.ReceiverOnWhenIdle = 0;
-    m_capabilityInformation.Reserved = 0;
-    m_capabilityInformation.SecurityCapability = 0;
-    m_capabilityInformation.AllocateAddress = 1;    
-    call MLME_RESET.request(TRUE, BEACON_ENABLED_PAN);
-  }
-
-  event void MLME_RESET.confirm(ieee154_status_t status)
-  {
-    if (status == IEEE154_SUCCESS)
-      startApp();
-  }
-
-  void startApp()
-  {
-    ieee154_phyChannelsSupported_t channel;
-    uint8_t scanDuration = BEACON_ORDER; 
-
-    m_isPANDescriptorValid = FALSE;
-
-    // scan only one channel
-    channel = ((uint32_t) 1) << RADIO_CHANNEL;
-
-    // we want all received beacons to be signalled 
-    // through the MLME_BEACON_NOTIFY interface, i.e.
-    // we set the macAutoRequest attribute to FALSE
-    call MLME_SET.macAutoRequest(FALSE);
-    m_isPANDescriptorValid = FALSE;
-    call MLME_SCAN.request  (
-                           PASSIVE_SCAN,           // ScanType
-                           channel,                // ScanChannels
-                           scanDuration,           // ScanDuration
-                           0x00,                   // ChannelPage
-                           0,                      // EnergyDetectListNumEntries
-                           NULL,                   // EnergyDetectList
-                           0,                      // PANDescriptorListNumEntries
-                           NULL,                   // PANDescriptorList
-                           NULL                    // security
-                        );
-  }
-
-  event message_t* MLME_BEACON_NOTIFY.indication (message_t* frame)
-  {
-    // received a beacon frame
-    ieee154_phyCurrentPage_t page = call MLME_GET.phyCurrentPage();
-    ieee154_macBSN_t beaconSequenceNumber = call BeaconFrame.getBSN(frame);
-
-    if (beaconSequenceNumber & 1)
-      call Leds.led2On();
-    else
-      call Leds.led2Off();   
-    if (!m_isPANDescriptorValid && call BeaconFrame.parsePANDescriptor(
-          frame, RADIO_CHANNEL, page, &m_PANDescriptor) == SUCCESS){
-      // let's see if the beacon is from the coordinator we expect...
-      if (m_PANDescriptor.CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
-          m_PANDescriptor.CoordPANId == PAN_ID &&
-          m_PANDescriptor.CoordAddress.shortAddress == COORDINATOR_ADDRESS){
-        // yes - wait until SCAN is finished, then syncronize to beacons
-        m_isPANDescriptorValid = TRUE;
-      }
-    }
-    return frame;
-  }
-
-  event void MLME_SCAN.confirm    (
-                          ieee154_status_t status,
-                          uint8_t ScanType,
-                          uint8_t ChannelPage,
-                          uint32_t UnscannedChannels,
-                          uint8_t EnergyDetectListNumEntries,
-                          int8_t* EnergyDetectList,
-                          uint8_t PANDescriptorListNumEntries,
-                          ieee154_PANDescriptor_t* PANDescriptorList
-                        )
-  {
-    if (m_isPANDescriptorValid){
-      call MLME_SET.macPANId(m_PANDescriptor.CoordPANId);
-      call MLME_SET.macCoordShortAddress(m_PANDescriptor.CoordAddress.shortAddress);
-      call MLME_SYNC.request(m_PANDescriptor.LogicalChannel, m_PANDescriptor.ChannelPage, TRUE);
-      call MLME_ASSOCIATE.request(
-          m_PANDescriptor.LogicalChannel,
-          m_PANDescriptor.ChannelPage,
-          m_PANDescriptor.CoordAddrMode,
-          m_PANDescriptor.CoordPANId,
-          m_PANDescriptor.CoordAddress,
-          m_capabilityInformation,
-          NULL  // security
-          );
-    } else
-      startApp();
-  }
-
-  event void MLME_ASSOCIATE.confirm    (
-                          uint16_t AssocShortAddress,
-                          uint8_t status,
-                          ieee154_security_t *security
-                        )
-  {
-    if ( status == IEEE154_SUCCESS ){
-      // we are now associated - set a timer for disassociation 
-      call Leds.led1On();
-      call DisassociateTimer.startOneShot(312500U);
-    } else {
-      call MLME_ASSOCIATE.request(
-          m_PANDescriptor.LogicalChannel,
-          m_PANDescriptor.ChannelPage,
-          m_PANDescriptor.CoordAddrMode,
-          m_PANDescriptor.CoordPANId,
-          m_PANDescriptor.CoordAddress,
-          m_capabilityInformation,
-          NULL  // security
-          );
-    }
-  }
-
-  event void DisassociateTimer.fired()
-  {
-    if (call MLME_DISASSOCIATE.request  (
-        m_PANDescriptor.CoordAddrMode,
-        m_PANDescriptor.CoordPANId,
-        m_PANDescriptor.CoordAddress,
-        IEEE154_DEVICE_WISHES_TO_LEAVE,
-        FALSE,
-        NULL
-        ) != IEEE154_SUCCESS)
-      call DisassociateTimer.startOneShot(312500U);
-  }
-
-  event void MLME_DISASSOCIATE.confirm    (
-                          ieee154_status_t status,
-                          uint8_t DeviceAddrMode,
-                          uint16_t DevicePANID,
-                          ieee154_address_t DeviceAddress
-                        )
-  {
-    if (status == IEEE154_SUCCESS){
-      call Leds.led1Off();
-    } else {
-      call DisassociateTimer.startOneShot(312500U);
-    }
-  }
-
-  event void MLME_ASSOCIATE.indication (
-                          uint64_t DeviceAddress,
-                          ieee154_CapabilityInformation_t CapabilityInformation,
-                          ieee154_security_t *security
-                        ){}  
-
-  event void MLME_SYNC_LOSS.indication(
-                          ieee154_status_t lossReason,
-                          uint16_t PANId,
-                          uint8_t LogicalChannel,
-                          uint8_t ChannelPage,
-                          ieee154_security_t *security)
-  {
-    startApp();
-  }
-
-  event void MLME_DISASSOCIATE.indication (
-                          uint64_t DeviceAddress,
-                          ieee154_disassociation_reason_t DisassociateReason,
-                          ieee154_security_t *security
-                        ){}
-
-
-  event void MLME_COMM_STATUS.indication (
-                          uint16_t PANId,
-                          uint8_t SrcAddrMode,
-                          ieee154_address_t SrcAddr,
-                          uint8_t DstAddrMode,
-                          ieee154_address_t DstAddr,
-                          ieee154_status_t status,
-                          ieee154_security_t *security
-                        )
-  {
-  }
-}
diff --git a/apps/tests/tkn154/TestData/README.txt b/apps/tests/tkn154/TestData/README.txt
deleted file mode 100644 (file)
index 08d0939..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-README for TestData
-Author/Contact: tinyos-help@millennium.berkeley.edu
-
-Description:
-
-In this application one node takes the role of a PAN coordinator in a
-beacon-enabled 802.15.4 PAN; it transmits periodic beacons and waits for
-incoming DATA frames. A second node acts as a device; it first scans the
-pre-defined channel for beacons from the coordinator and once it finds a beacon
-it tries to synchronize to and track all future beacons. It then starts to
-transmit DATA frames to the coordinator as fast as possible (direct
-transmission in the contention access period, CAP).
-
-The third LED (Telos: blue) is toggled whenever the coordinator has transmitted
-a beacon or whenever a device has received a beacon. On the coordinator the
-second LED (Telos: green) is toggled for every 20 received DATA frames. On a
-device the second LED is toggled for every 20 transmitted (and acknowledged)
-DATA frames. The first LED (Telos: red) is used for debugging, it denotes an
-error in the protocol stack and should never be on.
-
-Tools: NONE
-
-Usage: 
-
-1. Install the coordinator:
-
-    $ cd coordinator; make telosb install
-
-2. Install one or more devices
-
-    $ cd device; make telosb install,X
-
-    where X is a pre-assigned short address and should be different 
-    for every device.
-
-You can change some of the configuration parameters in app_profile.h
-
-Known bugs/limitations:
-
-- Currently this application only works on TelosB nodes
-- The MAC timing is not standard compliant, because TelosB lacks a
-  clock with sufficient precision/accuracy
-
-$Id$o
-
diff --git a/apps/tests/tkn154/TestData/app_profile.h b/apps/tests/tkn154/TestData/app_profile.h
deleted file mode 100644 (file)
index bf736a0..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#ifndef __APP_PROFILE_H
-#define __APP_PROFILE_H
-
-enum {
-  RADIO_CHANNEL = 26,
-  PAN_ID = 0x8172,
-  COORDINATOR_ADDRESS = 0x4331,
-  BEACON_ORDER = 5,
-  SUPERFRAME_ORDER = 5,
-};
-
-#endif
diff --git a/apps/tests/tkn154/TestData/coordinator/Makefile b/apps/tests/tkn154/TestData/coordinator/Makefile
deleted file mode 100644 (file)
index 42f1130..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-COMPONENT=TestDataAppC
-CFLAGS += -I$(shell pwd)/..
-include ../../Makefile.include
diff --git a/apps/tests/tkn154/TestData/coordinator/TestCoordReceiverC.nc b/apps/tests/tkn154/TestData/coordinator/TestCoordReceiverC.nc
deleted file mode 100644 (file)
index db59ec0..0000000
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#include "TKN154.h"
-#include "app_profile.h"
-module TestCoordReceiverC
-{
-  uses {
-    interface Boot;
-    interface MCPS_DATA;
-    interface MLME_RESET;
-    interface MLME_START;
-    interface MLME_SET;
-    interface MLME_GET;
-    interface IEEE154Frame as Frame;
-    interface IEEE154TxBeaconPayload;
-    interface Leds;
-  }
-} implementation {
-
-  bool m_ledCount;
-
-  event void Boot.booted() {
-    call MLME_RESET.request(TRUE, BEACON_ENABLED_PAN);
-  }
-
-  event void MLME_RESET.confirm(ieee154_status_t status)
-  {
-    if (status != IEEE154_SUCCESS)
-      return;
-    call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
-    call MLME_SET.macAssociationPermit(FALSE);
-    call MLME_START.request(
-                          PAN_ID,               // PANId
-                          RADIO_CHANNEL,        // LogicalChannel
-                          0,                    // ChannelPage,
-                          0,                    // StartTime,
-                          BEACON_ORDER,         // BeaconOrder
-                          SUPERFRAME_ORDER,     // SuperframeOrder
-                          TRUE,                 // PANCoordinator
-                          FALSE,                // BatteryLifeExtension
-                          FALSE,                // CoordRealignment
-                          0,                    // CoordRealignSecurity,
-                          0                     // BeaconSecurity
-                        );
-  }
-
-  event message_t* MCPS_DATA.indication ( message_t* frame )
-  {
-    if (m_ledCount++ == 20){
-      m_ledCount = 0;
-      call Leds.led1Toggle();
-    }
-    return frame;
-  }
-
-  event void MLME_START.confirm(ieee154_status_t status) {}
-
-  event void MCPS_DATA.confirm(
-                          message_t *msg,
-                          uint8_t msduHandle,
-                          ieee154_status_t status,
-                          uint32_t Timestamp
-                        ){}
-
-  event void IEEE154TxBeaconPayload.aboutToTransmit() { }
-
-  event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) { }
-
-  event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) { }
-
-  event void IEEE154TxBeaconPayload.beaconTransmitted() 
-  {
-    ieee154_macBSN_t beaconSequenceNumber = call MLME_GET.macBSN();
-    if (beaconSequenceNumber & 1)
-      call Leds.led2On();
-    else
-      call Leds.led2Off();
-  }  
-}
diff --git a/apps/tests/tkn154/TestData/coordinator/TestDataAppC.nc b/apps/tests/tkn154/TestData/coordinator/TestDataAppC.nc
deleted file mode 100644 (file)
index eeb8d0d..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-configuration TestDataAppC
-{
-} implementation {
-  components MainC, LedsC, Ieee802154MacC;
-
-  components TestCoordReceiverC as App;
-  App.MLME_START -> Ieee802154MacC;
-  App.MCPS_DATA -> Ieee802154MacC;
-  App.Frame -> Ieee802154MacC;
-
-  MainC.Boot <- App;
-  App.Leds -> LedsC;
-  App.MLME_RESET -> Ieee802154MacC;
-  App.MLME_SET -> Ieee802154MacC;
-  App.MLME_GET -> Ieee802154MacC;
-  App.IEEE154TxBeaconPayload -> Ieee802154MacC;
-}
diff --git a/apps/tests/tkn154/TestData/device/Makefile b/apps/tests/tkn154/TestData/device/Makefile
deleted file mode 100644 (file)
index 42f1130..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-COMPONENT=TestDataAppC
-CFLAGS += -I$(shell pwd)/..
-include ../../Makefile.include
diff --git a/apps/tests/tkn154/TestData/device/TestDataAppC.nc b/apps/tests/tkn154/TestData/device/TestDataAppC.nc
deleted file mode 100644 (file)
index f59355c..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-configuration TestDataAppC
-{
-} implementation {
-  components MainC, LedsC, Ieee802154MacC;
-
-  components TestDeviceSenderC as App;
-  App.MLME_SCAN -> Ieee802154MacC;
-  App.MLME_SYNC -> Ieee802154MacC;
-  App.MLME_BEACON_NOTIFY -> Ieee802154MacC;
-  App.MLME_SYNC_LOSS -> Ieee802154MacC;
-  App.MCPS_DATA -> Ieee802154MacC;
-  App.Frame -> Ieee802154MacC;
-  App.BeaconFrame -> Ieee802154MacC;
-  App.Packet -> Ieee802154MacC;
-
-  MainC.Boot <- App;
-  App.Leds -> LedsC;
-  App.MLME_RESET -> Ieee802154MacC;
-  App.MLME_SET -> Ieee802154MacC;
-  App.MLME_GET -> Ieee802154MacC;
-}
diff --git a/apps/tests/tkn154/TestData/device/TestDeviceSenderC.nc b/apps/tests/tkn154/TestData/device/TestDeviceSenderC.nc
deleted file mode 100644 (file)
index 4534df2..0000000
+++ /dev/null
@@ -1,208 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#include "TKN154.h"
-#include "app_profile.h"
-module TestDeviceSenderC
-{
-  uses {
-    interface Boot;
-    interface MCPS_DATA;
-    interface MLME_RESET;
-    interface MLME_SET;
-    interface MLME_GET;
-    interface MLME_SCAN;
-    interface MLME_SYNC;
-    interface MLME_BEACON_NOTIFY;
-    interface MLME_SYNC_LOSS;
-    interface IEEE154Frame as Frame;
-    interface IEEE154BeaconFrame as BeaconFrame;
-    interface Leds;
-    interface Packet;
-  }
-} implementation {
-
-  message_t m_frame;
-  uint8_t m_payloadLen;
-  ieee154_PANDescriptor_t m_PANDescriptor;
-  bool m_ledCount;
-  bool m_isPANDescriptorValid;
-  bool m_sending;
-
-  void startApp();
-  task void packetSendTask();
-
-
-  event void Boot.booted() {
-    char payload[] = "Hello Coordinator!";
-    uint8_t *payloadRegion;
-
-    m_payloadLen = strlen(payload);
-    payloadRegion = call Packet.getPayload(&m_frame, m_payloadLen);
-    if (m_payloadLen <= call Packet.maxPayloadLength()){
-      memcpy(payloadRegion, payload, m_payloadLen);
-      call MLME_RESET.request(TRUE, BEACON_ENABLED_PAN);
-    }
-  }
-
-  event void MLME_RESET.confirm(ieee154_status_t status)
-  {
-    if (status == IEEE154_SUCCESS)
-      startApp();
-  }
-
-  void startApp()
-  {
-    ieee154_phyChannelsSupported_t channelMask;
-    uint8_t scanDuration = BEACON_ORDER;
-
-    m_isPANDescriptorValid = FALSE;
-    call MLME_SET.macShortAddress(TOS_NODE_ID);
-
-    // scan only one channel
-    channelMask = ((uint32_t) 1) << RADIO_CHANNEL;
-
-    // we want all received beacons to be signalled 
-    // through the MLME_BEACON_NOTIFY interface, i.e.
-    // we set the macAutoRequest attribute to FALSE
-    call MLME_SET.macAutoRequest(FALSE);
-    call MLME_SCAN.request  (
-                           PASSIVE_SCAN,           // ScanType
-                           channelMask,            // ScanChannels
-                           scanDuration,           // ScanDuration
-                           0x00,                   // ChannelPage
-                           0,                      // EnergyDetectListNumEntries
-                           NULL,                   // EnergyDetectList
-                           0,                      // PANDescriptorListNumEntries
-                           NULL,                   // PANDescriptorList
-                           0                       // security
-                        );
-  }
-
-  event message_t* MLME_BEACON_NOTIFY.indication (message_t* frame)
-  {
-    // received a beacon frame
-    ieee154_phyCurrentPage_t page = call MLME_GET.phyCurrentPage();
-    ieee154_macBSN_t beaconSequenceNumber = call BeaconFrame.getBSN(frame);
-
-    if (beaconSequenceNumber & 1)
-      call Leds.led2On();
-    else
-      call Leds.led2Off();   
-    if (!m_isPANDescriptorValid && call BeaconFrame.parsePANDescriptor(
-          frame, RADIO_CHANNEL, page, &m_PANDescriptor) == SUCCESS){
-      // let's see if the beacon is from our coordinator...
-      if (m_PANDescriptor.CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
-          m_PANDescriptor.CoordPANId == PAN_ID &&
-          m_PANDescriptor.CoordAddress.shortAddress == COORDINATOR_ADDRESS){
-        // yes! wait until SCAN is finished, then syncronize to the beacons
-        m_isPANDescriptorValid = TRUE;
-      }
-    }
-    return frame;
-  }
-
-  event void MLME_SCAN.confirm    (
-                          ieee154_status_t status,
-                          uint8_t ScanType,
-                          uint8_t ChannelPage,
-                          uint32_t UnscannedChannels,
-                          uint8_t EnergyDetectListNumEntries,
-                          int8_t* EnergyDetectList,
-                          uint8_t PANDescriptorListNumEntries,
-                          ieee154_PANDescriptor_t* PANDescriptorList
-                        )
-  {
-    if (m_isPANDescriptorValid){
-      call MLME_SET.macCoordShortAddress(m_PANDescriptor.CoordAddress.shortAddress);
-      call MLME_SET.macPANId(m_PANDescriptor.CoordPANId);
-      call MLME_SYNC.request(m_PANDescriptor.LogicalChannel, m_PANDescriptor.ChannelPage, TRUE);
-      call Frame.setAddressingFields(
-          &m_frame,                
-          ADDR_MODE_SHORT_ADDRESS,        // SrcAddrMode,
-          ADDR_MODE_SHORT_ADDRESS,        // DstAddrMode,
-          m_PANDescriptor.CoordPANId,     // DstPANId,
-          &m_PANDescriptor.CoordAddress,  // DstAddr,
-          NULL                            // security
-          );
-      post packetSendTask(); 
-    } else
-      startApp();
-  }
-
-  task void packetSendTask()
-  {
-    if (!m_sending && m_isPANDescriptorValid &&
-        call MCPS_DATA.request  (
-          &m_frame,                         // frame,
-          m_payloadLen,                     // payloadLength,
-          0,                                // msduHandle,
-          TX_OPTIONS_ACK                    // TxOptions,
-          ) == IEEE154_SUCCESS)
-      m_sending = TRUE;
-  }
-
-  event void MCPS_DATA.confirm    (
-                          message_t *msg,
-                          uint8_t msduHandle,
-                          ieee154_status_t status,
-                          uint32_t timestamp
-                        )
-  {
-    m_sending = FALSE;
-    if (status == IEEE154_SUCCESS && m_ledCount++ == 20){
-      m_ledCount = 0;
-      call Leds.led1Toggle();
-    }
-    post packetSendTask(); 
-  }
-
-  event void MLME_SYNC_LOSS.indication(
-                          ieee154_status_t lossReason,
-                          uint16_t PANId,
-                          uint8_t LogicalChannel,
-                          uint8_t ChannelPage,
-                          ieee154_security_t *security)
-  {
-    startApp();
-  }
-
-  event message_t* MCPS_DATA.indication (message_t* frame)
-  {
-    // we don't expect data
-    return frame;
-  }
-
-}
diff --git a/apps/tests/tkn154/TestIndirect/README.txt b/apps/tests/tkn154/TestIndirect/README.txt
deleted file mode 100644 (file)
index c452520..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-README for TestIndirect
-Author/Contact: tinyos-help@millennium.berkeley.edu
-
-Description:
-
-In this application one node takes the role of a PAN coordinator in a
-beacon-enabled 802.15.4 PAN; it transmits periodic beacons and additionally in
-every beacon interval it tries to transmit one DATA frame to a device using
-indirect tranmission. A second node that takes the role of a device first scans
-the pre-defined channel for beacons from the coordinator and once it finds a
-beacon it tries to synchronize to and track all future beacons. Whenever the
-coordinator has data to send (indicated in the beacon), the device extracts the
-DATA frame from the coordinator.
-
-The third LED (Telos: blue) is toggled whenever the coordinator has transmitted
-a beacon, it is not used on the device. On the coordinator the second LED
-(Telos: green) is toggled for every transmitted DATA frames. On a device the
-second LED is toggled for every received DATA frame. The first LED (Telos: red)
-is used for debugging, it denotes an error in the protocol stack and should
-never be on.
-
-Tools: NONE
-
-Usage: 
-
-1. Install the coordinator:
-
-    $ cd coordinator; make telosb install
-
-2. Install one device
-
-    $ cd device; make telosb install
-
-You can change some of the configuration parameters in app_profile.h
-
-Known bugs/limitations:
-
-- Currently this application only works on TelosB nodes
-- The MAC timing is not standard compliant, because TelosB lacks a
-  clock with sufficient precision/accuracy
-
-$Id$
-
diff --git a/apps/tests/tkn154/TestIndirect/app_profile.h b/apps/tests/tkn154/TestIndirect/app_profile.h
deleted file mode 100644 (file)
index 185bbcd..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#ifndef __APP_PROFILE_H
-#define __APP_PROFILE_H
-
-enum {
-  RADIO_CHANNEL = 26,
-  PAN_ID = 0x1152,
-  DEVICE_ADDRESS = 0x4342,
-  COORDINATOR_ADDRESS = 0x5341,
-  BEACON_ORDER = 5,
-  SUPERFRAME_ORDER = 5,
-};
-
-#endif
diff --git a/apps/tests/tkn154/TestIndirect/coordinator/Makefile b/apps/tests/tkn154/TestIndirect/coordinator/Makefile
deleted file mode 100644 (file)
index acdecfd..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-COMPONENT=TestIndirectAppC
-PFLAGS += -DIEEE154_BEACON_SYNC_DISABLED -DIEEE154_SCAN_DISABLED
-CFLAGS += -I$(shell pwd)/..
-include ../../Makefile.include
diff --git a/apps/tests/tkn154/TestIndirect/coordinator/TestCoordSenderC.nc b/apps/tests/tkn154/TestIndirect/coordinator/TestCoordSenderC.nc
deleted file mode 100644 (file)
index 454cbda..0000000
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#include "TKN154.h"
-#include "app_profile.h"
-module TestCoordSenderC
-{
-  uses {
-    interface Boot;
-    interface MCPS_DATA;
-    interface MLME_RESET;
-    interface MLME_START;
-    interface MLME_SET;
-    interface MLME_GET;
-    interface Leds;
-    interface IEEE154Frame as Frame;
-    interface IEEE154TxBeaconPayload;
-    interface Packet;
-  }
-} implementation {
-
-  message_t m_frame;
-  uint8_t m_payloadLen;
-
-  event void Boot.booted() {
-    char payload[] = "Hello Device!";
-    uint8_t *payloadRegion;
-    ieee154_address_t deviceShortAddress;
-
-    // construct the frame
-    m_payloadLen = strlen(payload);
-    payloadRegion = call Packet.getPayload(&m_frame, m_payloadLen);
-    deviceShortAddress.shortAddress = DEVICE_ADDRESS; // destination
-    if (m_payloadLen <= call Packet.maxPayloadLength()){
-      memcpy(payloadRegion, payload, m_payloadLen);
-      call Frame.setAddressingFields(
-          &m_frame,                
-          ADDR_MODE_SHORT_ADDRESS, // SrcAddrMode,
-          ADDR_MODE_SHORT_ADDRESS, // DstAddrMode,
-          PAN_ID,                  // DstPANId,
-          &deviceShortAddress,     // DstAddr,
-          NULL                     // security
-          );
-      call MLME_RESET.request(TRUE, BEACON_ENABLED_PAN);
-    }
-  }
-
-  event void MLME_RESET.confirm(ieee154_status_t status)
-  {
-    if (status != IEEE154_SUCCESS)
-      return;
-    call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
-    call MLME_SET.macAssociationPermit(FALSE);
-    call MLME_START.request(
-                          PAN_ID,           // PANId
-                          RADIO_CHANNEL,    // LogicalChannel
-                          0,                // ChannelPage,
-                          0,                // StartTime,
-                          BEACON_ORDER,     // BeaconOrder
-                          SUPERFRAME_ORDER, // SuperframeOrder
-                          TRUE,             // PANCoordinator
-                          FALSE,            // BatteryLifeExtension
-                          FALSE,            // CoordRealignment
-                          0,                // CoordRealignSecurity
-                          0                 // BeaconSecurity
-                        );
-  }
-
-  void dataRequest()
-  {
-    call MCPS_DATA.request  (
-        &m_frame,                                 // msdu,
-        m_payloadLen,                             // payloadLength,
-        0,                                        // msduHandle,
-        TX_OPTIONS_ACK | TX_OPTIONS_INDIRECT      // TxOptions,
-        );
-  }
-
-  event void MLME_START.confirm(ieee154_status_t status)
-  {
-    if (status == IEEE154_SUCCESS)
-      dataRequest();
-  }
-
-  event void MCPS_DATA.confirm(
-                          message_t *msg,
-                          uint8_t msduHandle,
-                          ieee154_status_t status,
-                          uint32_t Timestamp
-                        )
-  {
-    if (status == IEEE154_SUCCESS)
-      call Leds.led1Toggle();
-    dataRequest();
-  }
-
-  event message_t* MCPS_DATA.indication ( message_t* frame)
-  {
-    return frame;
-  }
-
-  event void IEEE154TxBeaconPayload.aboutToTransmit() { }
-
-  event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) { }
-
-  event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) { }
-
-  event void IEEE154TxBeaconPayload.beaconTransmitted() 
-  {
-    ieee154_macBSN_t beaconSequenceNumber = call MLME_GET.macBSN();
-    if (beaconSequenceNumber & 1)
-      call Leds.led2On();
-    else
-      call Leds.led2Off();
-  }  
-  
-}
diff --git a/apps/tests/tkn154/TestIndirect/coordinator/TestIndirectAppC.nc b/apps/tests/tkn154/TestIndirect/coordinator/TestIndirectAppC.nc
deleted file mode 100644 (file)
index c64332b..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-configuration TestIndirectAppC
-{
-} implementation {
-  components MainC, LedsC, Ieee802154MacC;
-  components TestCoordSenderC as App;
-
-  MainC.Boot <- App;
-  App.Leds -> LedsC;
-  App.MLME_RESET -> Ieee802154MacC;
-  App.MLME_SET -> Ieee802154MacC;
-  App.MLME_GET -> Ieee802154MacC;
-  App.MLME_START -> Ieee802154MacC;
-  App.MCPS_DATA -> Ieee802154MacC;
-  App.Frame -> Ieee802154MacC;
-  App.IEEE154TxBeaconPayload -> Ieee802154MacC;
-  App.Packet -> Ieee802154MacC;
-
-}
diff --git a/apps/tests/tkn154/TestIndirect/device/Makefile b/apps/tests/tkn154/TestIndirect/device/Makefile
deleted file mode 100644 (file)
index 09b0d21..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-COMPONENT=TestIndirectAppC
-PFLAGS += -DIEEE154_BEACON_TX_DISABLED
-CFLAGS += -I$(shell pwd)/..
-include ../../Makefile.include
diff --git a/apps/tests/tkn154/TestIndirect/device/TestDeviceReceiverC.nc b/apps/tests/tkn154/TestIndirect/device/TestDeviceReceiverC.nc
deleted file mode 100644 (file)
index 45396db..0000000
+++ /dev/null
@@ -1,163 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154.h"
-#include "app_profile.h"
-module TestDeviceReceiverC
-{
-  uses {
-    interface Boot;
-    interface MCPS_DATA;
-    interface MLME_RESET;
-    interface MLME_SET;
-    interface MLME_GET;
-    interface MLME_SCAN;
-    interface MLME_SYNC;
-    interface MLME_BEACON_NOTIFY;
-    interface MLME_SYNC_LOSS;
-    interface IEEE154BeaconFrame as BeaconFrame;
-    interface Leds;
-  }
-} implementation {
-
-  ieee154_address_t m_coordAddress;
-  uint8_t m_coordAddressMode;
-  ieee154_macPANId_t m_coordPANID;
-  ieee154_PANDescriptor_t m_PANDescriptor;
-  bool m_isPANDescriptorValid;
-  void startApp();
-
-  event void Boot.booted() {
-    call MLME_RESET.request(TRUE, BEACON_ENABLED_PAN);
-  }
-  
-  event void MLME_RESET.confirm(ieee154_status_t status)
-  {
-    if (status == IEEE154_SUCCESS)
-      startApp();
-  }
-
-  void startApp()
-  {
-    ieee154_phyChannelsSupported_t channel;
-    uint8_t scanDuration = BEACON_ORDER;
-
-    // in this application the coordinator assumes that 
-    // the device has a certain short address    
-    call MLME_SET.macShortAddress(DEVICE_ADDRESS);
-    channel = ((uint32_t) 1) << RADIO_CHANNEL;
-
-    // we want all received beacons to be signalled 
-    // through the MLME_BEACON_NOTIFY interface, i.e.
-    // we set the macAutoRequest attribute to FALSE
-    call MLME_SET.macAutoRequest(FALSE);
-    call MLME_SCAN.request  (
-                           PASSIVE_SCAN,           // ScanType
-                           channel,                // ScanChannels
-                           scanDuration,           // ScanDuration
-                           0x00,                   // ChannelPage
-                           0,                      // EnergyDetectListNumEntries
-                           NULL,                   // EnergyDetectList
-                           0,                      // PANDescriptorListNumEntries
-                           NULL,                   // PANDescriptorList
-                           0                       // security
-                        );
-  }
-
-  event message_t* MLME_BEACON_NOTIFY.indication (message_t* frame)
-  {
-    // received a beacon frame during SCAN
-    ieee154_phyCurrentPage_t page = call MLME_GET.phyCurrentPage();
-
-    if (!m_isPANDescriptorValid && call BeaconFrame.parsePANDescriptor(
-          frame, RADIO_CHANNEL, page, &m_PANDescriptor) == SUCCESS){
-      // let's see if the beacon is from our coordinator...
-      if (m_PANDescriptor.CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
-          m_PANDescriptor.CoordPANId == PAN_ID &&
-          m_PANDescriptor.CoordAddress.shortAddress == COORDINATOR_ADDRESS){
-        // wait until SCAN is finished, then syncronize to beacons
-        m_isPANDescriptorValid = TRUE;
-      }
-    }
-    return frame;
-  }
-
-  event void MLME_SCAN.confirm    (
-                          ieee154_status_t status,
-                          uint8_t ScanType,
-                          uint8_t ChannelPage,
-                          uint32_t UnscannedChannels,
-                          uint8_t EnergyDetectListNumEntries,
-                          int8_t* EnergyDetectList,
-                          uint8_t PANDescriptorListNumEntries,
-                          ieee154_PANDescriptor_t* PANDescriptorList
-                        )
-  {
-    if (m_isPANDescriptorValid){
-      // set the macAutoRequest attribute to TRUE, so indirect
-      // transmissions are automatically carried through
-      call MLME_SET.macAutoRequest(TRUE);
-      call MLME_SET.macCoordShortAddress(m_PANDescriptor.CoordAddress.shortAddress);
-      call MLME_SET.macPANId(m_PANDescriptor.CoordPANId);
-      call MLME_SYNC.request(m_PANDescriptor.LogicalChannel, m_PANDescriptor.ChannelPage, TRUE);
-    } else
-      startApp();
-  }
-
-  event void MCPS_DATA.confirm(
-                          message_t *msg,
-                          uint8_t msduHandle,
-                          ieee154_status_t status,
-                          uint32_t Timestamp
-                        )
-  {
-  }
-
-  event void MLME_SYNC_LOSS.indication(
-                          ieee154_status_t lossReason,
-                          uint16_t PANId,
-                          uint8_t LogicalChannel,
-                          uint8_t ChannelPage,
-                          ieee154_security_t *security)
-  {
-    call Leds.led1Off();
-    startApp();
-  }
-
-  event message_t* MCPS_DATA.indication (message_t* frame)
-  {
-    call Leds.led1Toggle();
-    return frame;
-  }
-}
diff --git a/apps/tests/tkn154/TestIndirect/device/TestIndirectAppC.nc b/apps/tests/tkn154/TestIndirect/device/TestIndirectAppC.nc
deleted file mode 100644 (file)
index 4583acb..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-configuration TestIndirectAppC
-{
-} implementation {
-  components MainC, LedsC, Ieee802154MacC;
-  components TestDeviceReceiverC as App;
-
-  MainC.Boot <- App;
-  App.Leds -> LedsC;
-  App.MLME_RESET -> Ieee802154MacC;
-  App.MLME_SET -> Ieee802154MacC;
-  App.MLME_GET -> Ieee802154MacC;
-  App.MLME_SCAN -> Ieee802154MacC;
-  App.MLME_SYNC -> Ieee802154MacC;
-  App.MLME_BEACON_NOTIFY -> Ieee802154MacC;
-  App.MLME_SYNC_LOSS -> Ieee802154MacC;
-  App.MCPS_DATA -> Ieee802154MacC;
-  App.BeaconFrame -> Ieee802154MacC;
-}
diff --git a/apps/tests/tkn154/TestPromiscuous/Makefile b/apps/tests/tkn154/TestPromiscuous/Makefile
deleted file mode 100644 (file)
index 1aabe6f..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-COMPONENT=TestPromiscuousAppC
-PFLAGS += -DIEEE154_BEACON_TX_DISABLED -DIEEE154_BEACON_SYNC_DISABLED -DIEEE154_SCAN_DISABLED
-PFLAGS += -DPRINTF_BUFFER_SIZE=1000
-CFLAGS += -I$(TOSDIR)/lib/printf
-include ../Makefile.include
diff --git a/apps/tests/tkn154/TestPromiscuous/README.txt b/apps/tests/tkn154/TestPromiscuous/README.txt
deleted file mode 100644 (file)
index 8f1b1f5..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-README for TestPromiscuous
-Author/Contact: tinyos-help@millennium.berkeley.edu
-
-Description:
-
-In this application the node enables promiscuous mode, i.e. its radio is
-switched to receive mode and all incoming frames that pass the CRC check are
-signalled to the upper layer. The application uses the TinyOS printf library
-(tos/lib/printf) to output information on the MAC header fields and payload for
-every received frame over the serial port. The second (TelosB: green) LED is
-toggled whenever a frame is received.
-
-Tools: The printf java client in $TOSDIR/../apps/tests/TestPrintf
-
-Usage: 
-
-Install the application on a node
-
-    $ make telosb install
-
-Start the printf client on 
-
-    $ java net.tinyos.tools.PrintfClient -comm serial@/dev/ttyUSBXXX:telosb
-
-(http://docs.tinyos.net/ has a section on how to use the TinyOS printf library)
-
-Known bugs/limitations:
-
-- Currently this application only works on TelosB nodes
-- The timestamps for ACKs are incorrect
-
-$Id$
-
diff --git a/apps/tests/tkn154/TestPromiscuous/TestPromiscuousAppC.nc b/apps/tests/tkn154/TestPromiscuous/TestPromiscuousAppC.nc
deleted file mode 100644 (file)
index e48ac50..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-configuration TestPromiscuousAppC
-{
-} implementation {
- components MainC, TestPromiscuousC as App, LedsC, 
-            Ieee802154MacC as Ieee802154MacC;
-
-  MainC.Boot <- App;
-  App.Leds -> LedsC;
-
-  App.MLME_RESET -> Ieee802154MacC;
-  App.MLME_SET -> Ieee802154MacC;
-  App.MLME_GET -> Ieee802154MacC;
-  App.MCPS_DATA -> Ieee802154MacC;
-  App.Frame -> Ieee802154MacC;
-  App.BeaconFrame -> Ieee802154MacC;
-  App.PromiscuousMode -> Ieee802154MacC;
-}
diff --git a/apps/tests/tkn154/TestPromiscuous/TestPromiscuousC.nc b/apps/tests/tkn154/TestPromiscuous/TestPromiscuousC.nc
deleted file mode 100644 (file)
index bc3699f..0000000
+++ /dev/null
@@ -1,158 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154.h"
-module TestPromiscuousC
-{
-  uses {
-    interface Boot;
-    interface MLME_RESET;
-    interface MLME_SET;
-    interface MLME_GET;
-    interface MCPS_DATA;
-    interface Leds;
-    interface IEEE154Frame as Frame;
-    interface IEEE154BeaconFrame as BeaconFrame;
-    interface SplitControl as PromiscuousMode;
-  }
-} implementation {
-
-  const char *m_frametype[] = {"Beacon", "Data","Acknowledgement","MAC command", "Unknown"};
-  const char *m_cmdframetype[] = {"unknown command", "Association request","Association response",
-    "Disassociation notification","Data request","PAN ID conflict notification",
-    "Orphan notification", "Beacon request", "Coordinator realignment", "GTS request"};
-
-  enum {
-    RADIO_CHANNEL = 26,
-  };
-
-  event void Boot.booted() {
-    call MLME_RESET.request(TRUE, BEACON_ENABLED_PAN);
-  }
-
-  event void MLME_RESET.confirm(ieee154_status_t status)
-  {
-    call MLME_SET.phyCurrentChannel(RADIO_CHANNEL);
-    call PromiscuousMode.start();
-  }
-
-  event message_t* MCPS_DATA.indication (message_t* frame)
-  {
-    uint8_t i;
-    uint8_t *payload = call Frame.getPayload(frame);
-    uint8_t payloadLen = call Frame.getPayloadLength(frame);
-    uint8_t *header = call Frame.getHeader(frame);
-    uint8_t headerLen = call Frame.getHeaderLength(frame);
-    uint8_t SrcAddrMode, DstAddrMode;
-    uint8_t frameType, cmdFrameType;
-    ieee154_address_t SrcAddress, DstAddress;
-    uint16_t SrcPANId=0, DstPANId=0;
-
-    if (call Frame.hasStandardCompliantHeader(frame)){
-      frameType = call Frame.getFrameType(frame);
-      if (frameType > FRAMETYPE_CMD)
-        frameType = 4;
-      call Frame.getSrcPANId(frame, &SrcPANId);
-      call Frame.getDstPANId(frame, &DstPANId);
-      call Frame.getSrcAddr(frame, &SrcAddress);
-      call Frame.getDstAddr(frame, &DstAddress);
-      SrcAddrMode = call Frame.getSrcAddrMode(frame);
-      DstAddrMode = call Frame.getDstAddrMode(frame);
-
-      printf("\n");
-      printf("Frametype: %s", m_frametype[frameType]);
-      if (frameType == FRAMETYPE_CMD){
-        cmdFrameType = payload[0];
-        if (cmdFrameType > 9)
-          cmdFrameType = 0;
-        printf(" (%s)", m_cmdframetype[cmdFrameType]);
-      }
-      printf("\n");
-      printf("SrcAddrMode: %d\n", SrcAddrMode);
-      printf("SrcAddr: ");
-      if (SrcAddrMode == ADDR_MODE_SHORT_ADDRESS){
-        printf("0x%hx\n", SrcAddress.shortAddress);
-        printf("SrcPANId: 0x%x\n", SrcPANId);
-      } else if (SrcAddrMode == ADDR_MODE_EXTENDED_ADDRESS){
-        for (i=0; i<8; i++)
-          printf("0x%hx ", ((uint8_t*) &(SrcAddress.extendedAddress))[i]);
-        printf("\n");
-        printf("SrcPANId: 0x%x\n", SrcPANId);
-      } else printf("\n");
-      printf("DstAddrMode: %d\n", DstAddrMode);
-      printf("DstAddr: ");
-      if ( DstAddrMode == ADDR_MODE_SHORT_ADDRESS){
-        printf("0x%hx\n", DstAddress.shortAddress);
-        printf("DestPANId: 0x%x\n", DstPANId);
-      } else if  ( DstAddrMode == ADDR_MODE_EXTENDED_ADDRESS) {
-        for (i=0; i<8; i++)
-          printf("0x%hx ", ((uint8_t*) &(DstAddress.extendedAddress))[i]);
-        printf("\n");    
-        printf("DestPANId: 0x%x\n", DstPANId);
-      } else printf("\n");
-
-      printf("DSN: %d\n", call Frame.getDSN(frame));
-      printf("MHRLen: %d\n", headerLen);
-      printf("MHR: ");
-      for (i=0; i<headerLen; i++){
-        printf("0x%hx ", header[i]);
-      }
-      printf("\n");      
-      printf("PayloadLen: %d\n", payloadLen);
-      printf("Payload: ");
-      for (i=0; i<payloadLen; i++){
-        printf("0x%hx ", payload[i]);
-      }
-      printf("\n");
-      printf("MpduLinkQuality: %d\n", call Frame.getLinkQuality(frame));
-
-      printf("Timestamp: ");
-      if (call Frame.isTimestampValid(frame))
-        printf("%ld\n", call Frame.getTimestamp(frame));
-      else
-        printf("INVALID\n");
-      printfflush(); 
-    }
-    call Leds.led1Toggle();
-    return frame;
-  }
-
-  event void MCPS_DATA.confirm( message_t *msg, uint8_t msduHandle, ieee154_status_t status, uint32_t Timestamp){}
-  event void PromiscuousMode.startDone(error_t error) 
-  {
-    printf("\n*** Radio is now in promiscuous mode, listening on channel %d ***\n", RADIO_CHANNEL);
-    printfflush(); 
-  }
-  event void PromiscuousMode.stopDone(error_t error) {}
-}
diff --git a/apps/tests/tkn154/TestStartSync/README.txt b/apps/tests/tkn154/TestStartSync/README.txt
deleted file mode 100644 (file)
index e58dc33..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-README for TestStartSync
-Author/Contact: tinyos-help@millennium.berkeley.edu
-
-Description:
-
-In this application one node takes the role of a PAN coordinator in a
-beacon-enabled 802.15.4 PAN; it transmits periodic beacons with a frequency
-defined in the app_profile.h file. A second node acts as a device; it first
-scans all available channels for beacons from the coordinator and once it finds
-a beacon it tries to synchronize to and track all future beacons. 
-
-The third LED (Telos: blue) is toggled whenever the coordinator has transmitted
-a beacon or whenever a device has received a beacon. On the coordinator the
-second LED (Telos: green) is switched on after it has started transmitting
-beacons. On a device the second LED is switched on whenever the device is
-synchronized to the coordinator's beacons. The first LED (Telos: red) is used
-for debugging, it denotes an error in the protocol stack and should never be
-on.
-
-Tools: NONE
-
-Usage: 
-
-1. Install the coordinator:
-
-    $ cd coordinator; make telosb install
-
-2. Install one (or more) devices:
-
-    $ cd device; make telosb install
-
-You can change some of the configuration parameters in app_profile.h
-
-Known bugs/limitations:
-
-- Currently this application only works on TelosB nodes
-- The beacon period is not standard-compliant, because TelosB lacks a
-  clock with sufficient precision/accuracy
-
-$Id$
-
diff --git a/apps/tests/tkn154/TestStartSync/app_profile.h b/apps/tests/tkn154/TestStartSync/app_profile.h
deleted file mode 100644 (file)
index 366f111..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#ifndef __APP_PROFILE_H
-#define __APP_PROFILE_H
-
-enum {
-  RADIO_CHANNEL = 26,
-  PAN_ID = 0x7761,
-  COORDINATOR_ADDRESS = 0x1832,
-  BEACON_ORDER = 5,
-  SUPERFRAME_ORDER = 5,
-};
-
-#endif
diff --git a/apps/tests/tkn154/TestStartSync/coordinator/Makefile b/apps/tests/tkn154/TestStartSync/coordinator/Makefile
deleted file mode 100644 (file)
index 13db21c..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-COMPONENT=TestStartSyncAppC
-CFLAGS += -I$(shell pwd)/..
-include ../../Makefile.include
diff --git a/apps/tests/tkn154/TestStartSync/coordinator/TestCoordC.nc b/apps/tests/tkn154/TestStartSync/coordinator/TestCoordC.nc
deleted file mode 100644 (file)
index f752bda..0000000
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#include "TKN154.h"
-#include "app_profile.h"
-module TestCoordC
-{
-  uses {
-    interface Boot;
-    interface MLME_RESET;
-    interface MLME_START;
-    interface MLME_SET;
-    interface MLME_GET;
-    interface Leds;
-    interface IEEE154TxBeaconPayload;
-  }
-} implementation {
-
-  uint8_t m_beaconPayload[] = {0x01, 0x02, 0x03, 0x04, 0x05};
-
-  event void Boot.booted() {
-    call MLME_RESET.request(TRUE, BEACON_ENABLED_PAN);
-  }
-
-  event void MLME_RESET.confirm(ieee154_status_t status)
-  {
-    if (status == IEEE154_SUCCESS){
-      call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
-      call MLME_SET.macAssociationPermit(FALSE);
-      call MLME_START.request(
-          PAN_ID,             // PANId
-          RADIO_CHANNEL,      // LogicalChannel
-          0,                  // ChannelPage,
-          0,                  // StartTime,
-          BEACON_ORDER,       // BeaconOrder
-          SUPERFRAME_ORDER,   // SuperframeOrder
-          TRUE,               // PANCoordinator
-          FALSE,              // BatteryLifeExtension
-          FALSE,              // CoordRealignment
-          0,                  // no realignment security
-          0                   // no beacon security
-          );
-    }
-  }
-
-  event void MLME_START.confirm(ieee154_status_t status)
-  {
-    if (status == IEEE154_SUCCESS){
-      call IEEE154TxBeaconPayload.setBeaconPayload(m_beaconPayload, sizeof(m_beaconPayload));
-      call Leds.led1On();
-    }
-  }
-
-  event void IEEE154TxBeaconPayload.aboutToTransmit() { }
-
-  event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) { }
-
-  event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) { }
-
-  event void IEEE154TxBeaconPayload.beaconTransmitted() 
-  {
-    ieee154_macBSN_t beaconSequenceNumber = call MLME_GET.macBSN();
-    if (beaconSequenceNumber & 1)
-      call Leds.led2On();
-    else
-      call Leds.led2Off();
-  }
-}
diff --git a/apps/tests/tkn154/TestStartSync/coordinator/TestStartSyncAppC.nc b/apps/tests/tkn154/TestStartSync/coordinator/TestStartSyncAppC.nc
deleted file mode 100644 (file)
index d0913c7..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-configuration TestStartSyncAppC
-{
-} implementation {
-
-  components MainC, LedsC, Ieee802154MacC as Ieee802154MacC;
-  components TestCoordC as App;
-
-  MainC.Boot <- App;
-  App.MLME_START -> Ieee802154MacC;
-  App.IEEE154TxBeaconPayload -> Ieee802154MacC;
-  App.Leds -> LedsC;
-  App.MLME_RESET -> Ieee802154MacC;
-  App.MLME_SET -> Ieee802154MacC;
-  App.MLME_GET -> Ieee802154MacC;
-}
diff --git a/apps/tests/tkn154/TestStartSync/device/Makefile b/apps/tests/tkn154/TestStartSync/device/Makefile
deleted file mode 100644 (file)
index 1f9448f..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-COMPONENT=TestStartSyncAppC
-PFLAGS += -DIEEE154_BEACON_TX_DISABLED
-CFLAGS += -I$(shell pwd)/..
-include ../../Makefile.include
diff --git a/apps/tests/tkn154/TestStartSync/device/TestDeviceC.nc b/apps/tests/tkn154/TestStartSync/device/TestDeviceC.nc
deleted file mode 100644 (file)
index 93713b8..0000000
+++ /dev/null
@@ -1,159 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#include "TKN154.h"
-#include "app_profile.h"
-module TestDeviceC
-{
-  uses {
-    interface Boot;
-    interface MLME_RESET;
-    interface MLME_SET;
-    interface MLME_GET;
-    interface MLME_SCAN;
-    interface MLME_SYNC;
-    interface MLME_BEACON_NOTIFY;
-    interface MLME_SYNC_LOSS;
-    interface Leds;
-    interface IEEE154BeaconFrame as BeaconFrame;
-  }
-} implementation {
-
-  enum {
-    NUM_PAN_DESCRIPTORS = 10,
-  };
-  ieee154_PANDescriptor_t m_PANDescriptor[NUM_PAN_DESCRIPTORS];
-  void startApp();
-
-  event void Boot.booted() {
-    call MLME_RESET.request(TRUE, BEACON_ENABLED_PAN);
-  }
-  
-  event void MLME_RESET.confirm(ieee154_status_t status)
-  {
-    if (status == IEEE154_SUCCESS)
-      startApp();
-  }
-
-  void startApp()
-  {
-    ieee154_phyChannelsSupported_t supportedChannels;
-    uint8_t scanDuration = BEACON_ORDER;
-
-    // set the short address to whatever was passed 
-    // as a parameter to make system ("make install,X")
-    call MLME_SET.macShortAddress(TOS_NODE_ID); 
-    supportedChannels = call MLME_GET.phyChannelsSupported();
-
-    // setting the macAutoRequest attribute to TRUE means
-    // that during the scan beacons will not be signalled
-    // through MLME_BEACON_NOTIFY
-    call MLME_SET.macAutoRequest(TRUE);
-    call MLME_SCAN.request  (
-        PASSIVE_SCAN,           // ScanType
-        supportedChannels,      // ScanChannels
-        scanDuration,           // ScanDuration
-        0x00,                   // ChannelPage
-        0,                      // EnergyDetectListNumEntries
-        NULL,                   // EnergyDetectList
-        NUM_PAN_DESCRIPTORS,    // PANDescriptorListNumEntries
-        m_PANDescriptor,        // PANDescriptorList
-        0                       // security
-        );
-  }
-
-  event void MLME_SCAN.confirm    (
-                          ieee154_status_t status,
-                          uint8_t ScanType,
-                          uint8_t ChannelPage,
-                          uint32_t UnscannedChannels,
-                          uint8_t EnergyDetectListNumEntries,
-                          int8_t* EnergyDetectList,
-                          uint8_t PANDescriptorListNumEntries,
-                          ieee154_PANDescriptor_t* PANDescriptorList
-                        )
-  {
-    uint8_t i;
-    switch (status){
-      case IEEE154_NO_BEACON:
-        startApp();
-        break;
-      case IEEE154_SUCCESS:
-        if (PANDescriptorListNumEntries > 0){
-          for (i=0; i<PANDescriptorListNumEntries; i++)
-            if (PANDescriptorList[i].CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
-                PANDescriptorList[i].CoordPANId == PAN_ID &&
-                PANDescriptorList[i].CoordAddress.shortAddress == COORDINATOR_ADDRESS)
-              break;
-          if (i == PANDescriptorListNumEntries){
-            // found no matching entry
-            startApp();
-          } else {
-            call MLME_SET.macAutoRequest(FALSE); // from now on: give me the beacons
-            call MLME_SET.macPANId(PANDescriptorList[i].CoordPANId);
-            call MLME_SET.macCoordShortAddress(PANDescriptorList[i].CoordAddress.shortAddress);
-            call MLME_SYNC.request(PANDescriptorList[i].LogicalChannel, ChannelPage, TRUE);
-          }
-        }
-        break;
-      default:
-        break;
-    }
-  }
-
-  event message_t* MLME_BEACON_NOTIFY.indication (
-                          message_t* frame
-                        )
-  {
-    ieee154_macBSN_t beaconSequenceNumber = call BeaconFrame.getBSN(frame);
-    if (beaconSequenceNumber & 1)
-      call Leds.led2On();
-    else
-      call Leds.led2Off();    
-    call Leds.led1On();
-    return frame;
-  }
-
-  event void MLME_SYNC_LOSS.indication(
-                          ieee154_status_t lossReason,
-                          uint16_t PANId,
-                          uint8_t LogicalChannel,
-                          uint8_t ChannelPage,
-                          ieee154_security_t *security)
-  {
-    call Leds.led1Off();
-    startApp();
-  }
-}
diff --git a/apps/tests/tkn154/TestStartSync/device/TestStartSyncAppC.nc b/apps/tests/tkn154/TestStartSync/device/TestStartSyncAppC.nc
deleted file mode 100644 (file)
index 9373400..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-configuration TestStartSyncAppC
-{
-} implementation {
-
-  components MainC, LedsC, Ieee802154MacC as Ieee802154MacC;
-  components TestDeviceC as App;
-
-  App.MLME_SCAN -> Ieee802154MacC;
-  App.MLME_SYNC -> Ieee802154MacC;
-  App.MLME_BEACON_NOTIFY -> Ieee802154MacC;
-  App.MLME_SYNC_LOSS -> Ieee802154MacC;
-  App.BeaconFrame -> Ieee802154MacC;
-
-  MainC.Boot <- App;
-  App.Leds -> LedsC;
-  App.MLME_RESET -> Ieee802154MacC;
-  App.MLME_SET -> Ieee802154MacC;
-  App.MLME_GET -> Ieee802154MacC;
-
-#ifdef PRINTF_ENABLED
-  components PrintfC;
-  App.PrintfControl -> PrintfC;
-  App.PrintfFlush -> PrintfC;
-#endif
-}
diff --git a/apps/tests/tkn154/beacon-enabled/TestAssociate/README.txt b/apps/tests/tkn154/beacon-enabled/TestAssociate/README.txt
new file mode 100644 (file)
index 0000000..f8623dd
--- /dev/null
@@ -0,0 +1,44 @@
+README for TestAssociate
+Author/Contact: Jan Hauer <hauer@tkn.tu-berlin.de>
+
+Description:
+
+In this application one node takes the role of a PAN coordinator in a
+beacon-enabled 802.15.4 PAN, it transmits periodic beacons and waits for
+devices to request association to its PAN. Whenever a device tries to
+associate, the PAN coordinator accepts the association and assigns to the
+device a unique short address (starting from zero, incremented for every new
+association request). A second node acts as a device, it first scans the
+pre-defined channel for beacons from the coordinator and once it finds a beacon
+it tries to associate to the PAN. A short time after association the device
+then disassociates from the PAN. 
+
+Criteria for a successful test:
+
+Both, coordinator and device, should toggle LED1 in unison about once every 5 
+seconds. The coordinator should also toggle LED2 every second.
+
+
+Tools: NONE
+
+Usage: 
+
+1. Install the coordinator:
+
+    $ cd coordinator; make <platform> install
+
+2. Install one (or more) devices:
+
+    $ cd device; make <platform> install
+
+You can change some of the configuration parameters in app_profile.h
+
+Known bugs/limitations:
+
+- Many TinyOS 2 platforms do not have a clock that satisfies the
+  precision/accuracy requirements of the IEEE 802.15.4 standard (e.g. 
+  62.500 Hz, +-40 ppm in the 2.4 GHz band); in this case the MAC timing 
+  is not standard compliant
+
+$Id$o
+
diff --git a/apps/tests/tkn154/beacon-enabled/TestAssociate/app_profile.h b/apps/tests/tkn154/beacon-enabled/TestAssociate/app_profile.h
new file mode 100644 (file)
index 0000000..21641f6
--- /dev/null
@@ -0,0 +1,47 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#ifndef __APP_PROFILE_H
+#define __APP_PROFILE_H
+
+enum {
+  RADIO_CHANNEL = 26,
+  PAN_ID = 0x1238,
+  COORDINATOR_ADDRESS = 0x9182,
+  BEACON_ORDER = 6,
+  SUPERFRAME_ORDER = 6,
+};
+
+#endif
diff --git a/apps/tests/tkn154/beacon-enabled/TestAssociate/coordinator/Makefile b/apps/tests/tkn154/beacon-enabled/TestAssociate/coordinator/Makefile
new file mode 100644 (file)
index 0000000..c4d5d67
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=TestAssociateAppC
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/beacon-enabled/TestAssociate/coordinator/TestAssociateAppC.nc b/apps/tests/tkn154/beacon-enabled/TestAssociate/coordinator/TestAssociateAppC.nc
new file mode 100644 (file)
index 0000000..7a4ca06
--- /dev/null
@@ -0,0 +1,54 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestAssociateAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154BeaconEnabledC as MAC;
+  components TestCoordC as App;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+
+  App.MLME_START -> MAC;
+  App.MLME_ASSOCIATE -> MAC;
+  App.MLME_DISASSOCIATE -> MAC;
+  App.MLME_COMM_STATUS -> MAC;
+  App.Frame -> MAC;
+  App.IEEE154TxBeaconPayload -> MAC;
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestAssociate/coordinator/TestCoordC.nc b/apps/tests/tkn154/beacon-enabled/TestAssociate/coordinator/TestCoordC.nc
new file mode 100644 (file)
index 0000000..43c788a
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestCoordC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_START;
+    interface MLME_ASSOCIATE;
+    interface MLME_DISASSOCIATE;
+    interface MLME_COMM_STATUS;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface IEEE154Frame as Frame;
+    interface IEEE154TxBeaconPayload;
+    interface Leds;
+  }
+} implementation {
+
+  uint16_t m_assignedShortAddress;
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status != IEEE154_SUCCESS)
+      return;
+    call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
+    call MLME_SET.macAssociationPermit(TRUE);
+    call MLME_START.request(
+                          PAN_ID,           // PANId
+                          RADIO_CHANNEL,    // LogicalChannel
+                          0,                // ChannelPage,
+                          0,                // StartTime,
+                          BEACON_ORDER,     // BeaconOrder
+                          SUPERFRAME_ORDER, // SuperframeOrder
+                          TRUE,             // PANCoordinator
+                          FALSE,            // BatteryLifeExtension
+                          FALSE,            // CoordRealignment
+                          0,                // no realignment security
+                          0                 // no beacon security
+                        );
+  }
+
+  event void MLME_START.confirm(ieee154_status_t status) { }
+
+  event void MLME_ASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_CapabilityInformation_t CapabilityInformation,
+                          ieee154_security_t *security
+                        )
+  {
+    call MLME_ASSOCIATE.response(DeviceAddress, m_assignedShortAddress++, IEEE154_ASSOCIATION_SUCCESSFUL, 0);
+  }
+
+  event void MLME_DISASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_disassociation_reason_t DisassociateReason,
+                          ieee154_security_t *security
+                        )
+  {
+    call Leds.led1Off();
+  }
+
+
+  event void MLME_COMM_STATUS.indication (
+                          uint16_t PANId,
+                          uint8_t SrcAddrMode,
+                          ieee154_address_t SrcAddr,
+                          uint8_t DstAddrMode,
+                          ieee154_address_t DstAddr,
+                          ieee154_status_t status,
+                          ieee154_security_t *security
+                        )
+  {
+    if (status == IEEE154_SUCCESS){
+      // association was successful
+      call Leds.led1On();
+    } else {
+      call Leds.led1Off();
+    }
+  }
+
+  event void MLME_DISASSOCIATE.confirm    (
+                          ieee154_status_t status,
+                          uint8_t DeviceAddrMode,
+                          uint16_t DevicePANID,
+                          ieee154_address_t DeviceAddress
+                        ){}
+
+  event void MLME_ASSOCIATE.confirm    (
+                          uint16_t AssocShortAddress,
+                          uint8_t status,
+                          ieee154_security_t *security
+                        ){}
+
+  event void IEEE154TxBeaconPayload.aboutToTransmit() { }
+
+  event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) { }
+
+  event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) { }
+
+  event void IEEE154TxBeaconPayload.beaconTransmitted() 
+  {
+    ieee154_macBSN_t beaconSequenceNumber = call MLME_GET.macBSN();
+    if (beaconSequenceNumber & 1)
+      call Leds.led2On();
+    else
+      call Leds.led2Off();
+  }  
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestAssociate/device/Makefile b/apps/tests/tkn154/beacon-enabled/TestAssociate/device/Makefile
new file mode 100644 (file)
index 0000000..7c0acfe
--- /dev/null
@@ -0,0 +1,4 @@
+COMPONENT=TestAssociateAppC
+PFLAGS += -DIEEE154_BEACON_TX_DISABLED
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/beacon-enabled/TestAssociate/device/TestAssociateAppC.nc b/apps/tests/tkn154/beacon-enabled/TestAssociate/device/TestAssociateAppC.nc
new file mode 100644 (file)
index 0000000..992d3dc
--- /dev/null
@@ -0,0 +1,58 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestAssociateAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154BeaconEnabledC as MAC,
+             new Timer62500C() as Timer;
+  components TestDeviceC as App;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.DisassociateTimer -> Timer;  
+  App.MLME_SCAN -> MAC;
+  App.MLME_SYNC -> MAC;
+  App.MLME_BEACON_NOTIFY -> MAC;
+  App.MLME_SYNC_LOSS -> MAC;
+  App.MLME_ASSOCIATE -> MAC;
+  App.MLME_DISASSOCIATE -> MAC;
+  App.MLME_COMM_STATUS -> MAC;
+  App.BeaconFrame -> MAC;
+
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestAssociate/device/TestDeviceC.nc b/apps/tests/tkn154/beacon-enabled/TestAssociate/device/TestDeviceC.nc
new file mode 100644 (file)
index 0000000..acd74d6
--- /dev/null
@@ -0,0 +1,238 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154.h"
+#include "app_profile.h"
+module TestDeviceC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface MLME_SCAN;
+    interface MLME_SYNC;
+    interface MLME_ASSOCIATE;
+    interface MLME_DISASSOCIATE;
+    interface MLME_COMM_STATUS;
+    interface MLME_BEACON_NOTIFY;
+    interface MLME_SYNC_LOSS;
+    interface Leds;
+    interface IEEE154BeaconFrame as BeaconFrame;
+    interface Timer<T62500hz> as DisassociateTimer;
+  }
+} implementation {
+
+  ieee154_CapabilityInformation_t m_capabilityInformation;
+  ieee154_PANDescriptor_t m_PANDescriptor;
+  bool m_wasScanSuccessful;
+  void startApp();
+
+  event void Boot.booted() {
+    m_capabilityInformation.AlternatePANCoordinator = 0;
+    m_capabilityInformation.DeviceType = 0;
+    m_capabilityInformation.PowerSource = 0;
+    m_capabilityInformation.ReceiverOnWhenIdle = 0;
+    m_capabilityInformation.Reserved = 0;
+    m_capabilityInformation.SecurityCapability = 0;
+    m_capabilityInformation.AllocateAddress = 1;    
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status == IEEE154_SUCCESS)
+      startApp();
+  }
+
+  void startApp()
+  {
+    ieee154_phyChannelsSupported_t channel;
+    uint8_t scanDuration = BEACON_ORDER; 
+
+    // scan only one channel (to save time)
+    channel = ((uint32_t) 1) << RADIO_CHANNEL;
+
+    // we want all received beacons to be signalled 
+    // through the MLME_BEACON_NOTIFY interface, i.e.
+    // we set the macAutoRequest attribute to FALSE
+    call MLME_SET.macAutoRequest(FALSE);
+    m_wasScanSuccessful = FALSE;
+    call MLME_SCAN.request  (
+                           PASSIVE_SCAN,           // ScanType
+                           channel,                // ScanChannels
+                           scanDuration,           // ScanDuration
+                           0x00,                   // ChannelPage
+                           0,                      // EnergyDetectListNumEntries
+                           NULL,                   // EnergyDetectList
+                           0,                      // PANDescriptorListNumEntries
+                           NULL,                   // PANDescriptorList
+                           NULL                    // security
+                        );
+  }
+
+  event message_t* MLME_BEACON_NOTIFY.indication (message_t* frame)
+  {
+    // received a beacon frame
+    ieee154_phyCurrentPage_t page = call MLME_GET.phyCurrentPage();
+
+    if (!m_wasScanSuccessful) {
+      if (call BeaconFrame.parsePANDescriptor(
+            frame, RADIO_CHANNEL, page, &m_PANDescriptor) == SUCCESS){
+        // let's see if the beacon is from the coordinator we expect...
+        if (m_PANDescriptor.CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
+            m_PANDescriptor.CoordPANId == PAN_ID &&
+            m_PANDescriptor.CoordAddress.shortAddress == COORDINATOR_ADDRESS){
+          // yes - wait until SCAN is finished, then syncronize to beacons
+          m_wasScanSuccessful = TRUE;
+        }
+      }
+    }
+
+    return frame;
+  }
+
+  event void MLME_SCAN.confirm    (
+                          ieee154_status_t status,
+                          uint8_t ScanType,
+                          uint8_t ChannelPage,
+                          uint32_t UnscannedChannels,
+                          uint8_t EnergyDetectListNumEntries,
+                          int8_t* EnergyDetectList,
+                          uint8_t PANDescriptorListNumEntries,
+                          ieee154_PANDescriptor_t* PANDescriptorList
+                        )
+  {
+    if (m_wasScanSuccessful) {
+      call MLME_SET.macPANId(m_PANDescriptor.CoordPANId);
+      call MLME_SET.macCoordShortAddress(m_PANDescriptor.CoordAddress.shortAddress);
+      call MLME_SYNC.request(m_PANDescriptor.LogicalChannel, m_PANDescriptor.ChannelPage, TRUE);
+      call MLME_ASSOCIATE.request(
+          m_PANDescriptor.LogicalChannel,
+          m_PANDescriptor.ChannelPage,
+          m_PANDescriptor.CoordAddrMode,
+          m_PANDescriptor.CoordPANId,
+          m_PANDescriptor.CoordAddress,
+          m_capabilityInformation,
+          NULL  // security
+          );
+    } else
+      startApp();
+  }
+
+  event void MLME_ASSOCIATE.confirm    (
+                          uint16_t AssocShortAddress,
+                          uint8_t status,
+                          ieee154_security_t *security
+                        )
+  {
+    if ( status == IEEE154_SUCCESS ) {
+      // we are now associated - set a timer for disassociation 
+      call Leds.led1On();
+      call DisassociateTimer.startOneShot(312500U);
+    } else {
+      call MLME_ASSOCIATE.request(
+          m_PANDescriptor.LogicalChannel,
+          m_PANDescriptor.ChannelPage,
+          m_PANDescriptor.CoordAddrMode,
+          m_PANDescriptor.CoordPANId,
+          m_PANDescriptor.CoordAddress,
+          m_capabilityInformation,
+          NULL  // security
+          );
+    }
+  }
+
+  event void DisassociateTimer.fired()
+  {
+    if (call MLME_DISASSOCIATE.request  (
+        m_PANDescriptor.CoordAddrMode,
+        m_PANDescriptor.CoordPANId,
+        m_PANDescriptor.CoordAddress,
+        IEEE154_DEVICE_WISHES_TO_LEAVE,
+        FALSE,
+        NULL
+        ) != IEEE154_SUCCESS)
+      call DisassociateTimer.startOneShot(312500U);
+  }
+
+  event void MLME_DISASSOCIATE.confirm    (
+                          ieee154_status_t status,
+                          uint8_t DeviceAddrMode,
+                          uint16_t DevicePANID,
+                          ieee154_address_t DeviceAddress
+                        )
+  {
+    if (status == IEEE154_SUCCESS){
+      call Leds.led1Off();
+    } else {
+      call DisassociateTimer.startOneShot(312500U);
+    }
+  }
+
+  event void MLME_ASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_CapabilityInformation_t CapabilityInformation,
+                          ieee154_security_t *security
+                        ){}  
+
+  event void MLME_SYNC_LOSS.indication(
+                          ieee154_status_t lossReason,
+                          uint16_t PANId,
+                          uint8_t LogicalChannel,
+                          uint8_t ChannelPage,
+                          ieee154_security_t *security)
+  {
+    startApp();
+  }
+
+  event void MLME_DISASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_disassociation_reason_t DisassociateReason,
+                          ieee154_security_t *security
+                        ){}
+
+
+  event void MLME_COMM_STATUS.indication (
+                          uint16_t PANId,
+                          uint8_t SrcAddrMode,
+                          ieee154_address_t SrcAddr,
+                          uint8_t DstAddrMode,
+                          ieee154_address_t DstAddr,
+                          ieee154_status_t status,
+                          ieee154_security_t *security
+                        )
+  {
+  }
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestData/README.txt b/apps/tests/tkn154/beacon-enabled/TestData/README.txt
new file mode 100644 (file)
index 0000000..c241ac5
--- /dev/null
@@ -0,0 +1,47 @@
+README for TestData
+Author/Contact: Jan Hauer <hauer@tkn.tu-berlin.de>
+
+Description:
+
+In this application one node takes the role of a PAN coordinator in a
+beacon-enabled 802.15.4 PAN, it transmits periodic beacons and waits for
+incoming DATA frames. A second node acts as a device, it first scans the
+pre-defined channel for beacons from the coordinator and once it finds a beacon
+it tries to synchronize to and track all future beacons. It then starts to
+transmit DATA frames to the coordinator as fast as possible (direct
+transmission in the contention access period, CAP).
+
+Criteria for a successful test:
+
+Coordinator and device should both toggle LED2 about twice per second in
+unison. They should also each toggle LED1 about 5 times per second (but
+not necessarily in unison). Note: the nodes should be close to each other, 
+because the transmission power is reduced to -20 dBm.
+
+
+Tools: NONE
+
+Usage: 
+
+1. Install the coordinator:
+
+    $ cd coordinator; make <platform> install
+
+2. Install one or more devices
+
+    $ cd device; make <platform> install,X
+
+    where X is a pre-assigned short address and should be different 
+    for every device.
+
+You can change some of the configuration parameters in app_profile.h
+
+Known bugs/limitations:
+
+- Many TinyOS 2 platforms do not have a clock that satisfies the
+  precision/accuracy requirements of the IEEE 802.15.4 standard (e.g. 
+  62.500 Hz, +-40 ppm in the 2.4 GHz band); in this case the MAC timing 
+  is not standard compliant
+
+$Id$o
+
diff --git a/apps/tests/tkn154/beacon-enabled/TestData/app_profile.h b/apps/tests/tkn154/beacon-enabled/TestData/app_profile.h
new file mode 100644 (file)
index 0000000..ef3cc43
--- /dev/null
@@ -0,0 +1,48 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#ifndef __APP_PROFILE_H
+#define __APP_PROFILE_H
+
+enum {
+  RADIO_CHANNEL = 26,
+  PAN_ID = 0x8172,
+  COORDINATOR_ADDRESS = 0x4331,
+  BEACON_ORDER = 5,
+  SUPERFRAME_ORDER = 5,
+  TX_POWER = -20, // in dBm
+};
+
+#endif
diff --git a/apps/tests/tkn154/beacon-enabled/TestData/coordinator/Makefile b/apps/tests/tkn154/beacon-enabled/TestData/coordinator/Makefile
new file mode 100644 (file)
index 0000000..1a86b20
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=TestDataAppC
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/beacon-enabled/TestData/coordinator/TestCoordReceiverC.nc b/apps/tests/tkn154/beacon-enabled/TestData/coordinator/TestCoordReceiverC.nc
new file mode 100644 (file)
index 0000000..23123d5
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestCoordReceiverC
+{
+  uses {
+    interface Boot;
+    interface MCPS_DATA;
+    interface MLME_RESET;
+    interface MLME_START;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface IEEE154Frame as Frame;
+    interface IEEE154TxBeaconPayload;
+    interface Leds;
+  }
+} implementation {
+
+  bool m_ledCount;
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status != IEEE154_SUCCESS)
+      return;
+    call MLME_SET.phyTransmitPower(TX_POWER);
+    call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
+    call MLME_SET.macAssociationPermit(FALSE);
+    call MLME_START.request(
+                          PAN_ID,               // PANId
+                          RADIO_CHANNEL,        // LogicalChannel
+                          0,                    // ChannelPage,
+                          0,                    // StartTime,
+                          BEACON_ORDER,         // BeaconOrder
+                          SUPERFRAME_ORDER,     // SuperframeOrder
+                          TRUE,                 // PANCoordinator
+                          FALSE,                // BatteryLifeExtension
+                          FALSE,                // CoordRealignment
+                          0,                    // CoordRealignSecurity,
+                          0                     // BeaconSecurity
+                        );
+  }
+
+  event message_t* MCPS_DATA.indication ( message_t* frame )
+  {
+    if (m_ledCount++ == 20){
+      m_ledCount = 0;
+      call Leds.led1Toggle();
+    }
+    return frame;
+  }
+
+  event void MLME_START.confirm(ieee154_status_t status) {}
+
+  event void MCPS_DATA.confirm(
+                          message_t *msg,
+                          uint8_t msduHandle,
+                          ieee154_status_t status,
+                          uint32_t Timestamp
+                        ){}
+
+  event void IEEE154TxBeaconPayload.aboutToTransmit() { }
+
+  event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) { }
+
+  event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) { }
+
+  event void IEEE154TxBeaconPayload.beaconTransmitted() 
+  {
+    ieee154_macBSN_t beaconSequenceNumber = call MLME_GET.macBSN();
+    if (beaconSequenceNumber & 1)
+      call Leds.led2On();
+    else
+      call Leds.led2Off();
+  }  
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestData/coordinator/TestDataAppC.nc b/apps/tests/tkn154/beacon-enabled/TestData/coordinator/TestDataAppC.nc
new file mode 100644 (file)
index 0000000..4c48516
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "app_profile.h"
+configuration TestDataAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154BeaconEnabledC as MAC;
+
+  components TestCoordReceiverC as App;
+  App.MLME_START -> MAC;
+  App.MCPS_DATA -> MAC;
+  App.Frame -> MAC;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.IEEE154TxBeaconPayload -> MAC;
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestData/device/Makefile b/apps/tests/tkn154/beacon-enabled/TestData/device/Makefile
new file mode 100644 (file)
index 0000000..ba70c9b
--- /dev/null
@@ -0,0 +1,4 @@
+COMPONENT=TestDataAppC
+PFLAGS += -DIEEE154_BEACON_TX_DISABLED 
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/beacon-enabled/TestData/device/TestDataAppC.nc b/apps/tests/tkn154/beacon-enabled/TestData/device/TestDataAppC.nc
new file mode 100644 (file)
index 0000000..147f483
--- /dev/null
@@ -0,0 +1,56 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "app_profile.h"
+configuration TestDataAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154BeaconEnabledC as MAC;
+
+  components TestDeviceSenderC as App;
+  App.MLME_SCAN -> MAC;
+  App.MLME_SYNC -> MAC;
+  App.MLME_BEACON_NOTIFY -> MAC;
+  App.MLME_SYNC_LOSS -> MAC;
+  App.MCPS_DATA -> MAC;
+  App.Frame -> MAC;
+  App.BeaconFrame -> MAC;
+  App.Packet -> MAC;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestData/device/TestDeviceSenderC.nc b/apps/tests/tkn154/beacon-enabled/TestData/device/TestDeviceSenderC.nc
new file mode 100644 (file)
index 0000000..e4a1ab2
--- /dev/null
@@ -0,0 +1,217 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestDeviceSenderC
+{
+  uses {
+    interface Boot;
+    interface MCPS_DATA;
+    interface MLME_RESET;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface MLME_SCAN;
+    interface MLME_SYNC;
+    interface MLME_BEACON_NOTIFY;
+    interface MLME_SYNC_LOSS;
+    interface IEEE154Frame as Frame;
+    interface IEEE154BeaconFrame as BeaconFrame;
+    interface Leds;
+    interface Packet;
+  }
+} implementation {
+
+  message_t m_frame;
+  uint8_t m_payloadLen;
+  ieee154_PANDescriptor_t m_PANDescriptor;
+  bool m_ledCount;
+  bool m_wasScanSuccessful;
+
+  void startApp();
+  task void packetSendTask();
+
+
+  event void Boot.booted() {
+    char payload[] = "Hello Coordinator!";
+    uint8_t *payloadRegion;
+
+    m_payloadLen = strlen(payload);
+    payloadRegion = call Packet.getPayload(&m_frame, m_payloadLen);
+    if (m_payloadLen <= call Packet.maxPayloadLength()){
+      memcpy(payloadRegion, payload, m_payloadLen);
+      call MLME_RESET.request(TRUE);
+    }
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status == IEEE154_SUCCESS)
+      startApp();
+  }
+
+  void startApp()
+  {
+    ieee154_phyChannelsSupported_t channelMask;
+    uint8_t scanDuration = BEACON_ORDER;
+
+    call MLME_SET.phyTransmitPower(TX_POWER);
+    call MLME_SET.macShortAddress(TOS_NODE_ID);
+
+    // scan only the channel where we expect the coordinator
+    channelMask = ((uint32_t) 1) << RADIO_CHANNEL;
+
+    // we want all received beacons to be signalled 
+    // through the MLME_BEACON_NOTIFY interface, i.e.
+    // we set the macAutoRequest attribute to FALSE
+    call MLME_SET.macAutoRequest(FALSE);
+    m_wasScanSuccessful = FALSE;
+    call MLME_SCAN.request  (
+                           PASSIVE_SCAN,           // ScanType
+                           channelMask,            // ScanChannels
+                           scanDuration,           // ScanDuration
+                           0x00,                   // ChannelPage
+                           0,                      // EnergyDetectListNumEntries
+                           NULL,                   // EnergyDetectList
+                           0,                      // PANDescriptorListNumEntries
+                           NULL,                   // PANDescriptorList
+                           0                       // security
+                        );
+  }
+
+  event message_t* MLME_BEACON_NOTIFY.indication (message_t* frame)
+  {
+    // received a beacon frame
+    ieee154_phyCurrentPage_t page = call MLME_GET.phyCurrentPage();
+    ieee154_macBSN_t beaconSequenceNumber = call BeaconFrame.getBSN(frame);
+
+    if (!m_wasScanSuccessful) {
+      // received a beacon during channel scanning
+      if (call BeaconFrame.parsePANDescriptor(
+            frame, RADIO_CHANNEL, page, &m_PANDescriptor) == SUCCESS) {
+        // let's see if the beacon is from our coordinator...
+        if (m_PANDescriptor.CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
+            m_PANDescriptor.CoordPANId == PAN_ID &&
+            m_PANDescriptor.CoordAddress.shortAddress == COORDINATOR_ADDRESS){
+          // yes! wait until SCAN is finished, then syncronize to the beacons
+          m_wasScanSuccessful = TRUE;
+        }
+      }
+    } else { 
+      // received a beacon during synchronization, toggle LED2
+      if (beaconSequenceNumber & 1)
+        call Leds.led2On();
+      else
+        call Leds.led2Off();   
+    }
+
+    return frame;
+  }
+
+  event void MLME_SCAN.confirm    (
+                          ieee154_status_t status,
+                          uint8_t ScanType,
+                          uint8_t ChannelPage,
+                          uint32_t UnscannedChannels,
+                          uint8_t EnergyDetectListNumEntries,
+                          int8_t* EnergyDetectList,
+                          uint8_t PANDescriptorListNumEntries,
+                          ieee154_PANDescriptor_t* PANDescriptorList
+                        )
+  {
+    if (m_wasScanSuccessful) {
+      // we received a beacon from the coordinator before
+      call MLME_SET.macCoordShortAddress(m_PANDescriptor.CoordAddress.shortAddress);
+      call MLME_SET.macPANId(m_PANDescriptor.CoordPANId);
+      call MLME_SYNC.request(m_PANDescriptor.LogicalChannel, m_PANDescriptor.ChannelPage, TRUE);
+      call Frame.setAddressingFields(
+          &m_frame,                
+          ADDR_MODE_SHORT_ADDRESS,        // SrcAddrMode,
+          ADDR_MODE_SHORT_ADDRESS,        // DstAddrMode,
+          m_PANDescriptor.CoordPANId,     // DstPANId,
+          &m_PANDescriptor.CoordAddress,  // DstAddr,
+          NULL                            // security
+          );
+      post packetSendTask(); 
+    } else
+      startApp();
+  }
+
+  task void packetSendTask()
+  {
+    if (!m_wasScanSuccessful)
+      return;
+    else if (call MCPS_DATA.request  (
+          &m_frame,                         // frame,
+          m_payloadLen,                     // payloadLength,
+          0,                                // msduHandle,
+          TX_OPTIONS_ACK // TxOptions,
+          ) != IEEE154_SUCCESS)
+      call Leds.led0On();
+  }
+
+  event void MCPS_DATA.confirm    (
+                          message_t *msg,
+                          uint8_t msduHandle,
+                          ieee154_status_t status,
+                          uint32_t timestamp
+                        )
+  {
+    if (status == IEEE154_SUCCESS && m_ledCount++ >= 20) {
+      m_ledCount = 0;
+      call Leds.led1Toggle();
+    }
+    post packetSendTask(); 
+  }
+
+  event void MLME_SYNC_LOSS.indication(
+                          ieee154_status_t lossReason,
+                          uint16_t PANId,
+                          uint8_t LogicalChannel,
+                          uint8_t ChannelPage,
+                          ieee154_security_t *security)
+  {
+    m_wasScanSuccessful = FALSE;
+    call Leds.led1Off();
+    call Leds.led2Off();
+  }
+
+  event message_t* MCPS_DATA.indication (message_t* frame)
+  {
+    // we don't expect data
+    return frame;
+  }
+
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestIndirect/README.txt b/apps/tests/tkn154/beacon-enabled/TestIndirect/README.txt
new file mode 100644 (file)
index 0000000..f963b80
--- /dev/null
@@ -0,0 +1,43 @@
+README for TestIndirect
+Author/Contact: Jan Hauer <hauer@tkn.tu-berlin.de>
+
+Description:
+
+In this application one node takes the role of a PAN coordinator in a
+beacon-enabled 802.15.4 PAN, it transmits periodic beacons and additionally in
+every beacon interval it tries to transmit one DATA frame to a device using
+indirect tranmission. A second node that takes the role of a device first scans
+the pre-defined channel for beacons from the coordinator and once it finds a
+beacon it tries to synchronize to and track all future beacons. Whenever the
+coordinator has data to send (indicated in the beacon), the device extracts the
+DATA frame from the coordinator.
+
+Criteria for a successful test:
+
+Both nodes should toggle the LED1 in unison, about once every half second. 
+The coordinator should also toggle LED2 with the same frequency.
+
+
+Tools: NONE
+
+Usage: 
+
+1. Install the coordinator:
+
+    $ cd coordinator; make <platform> install
+
+2. Install one device
+
+    $ cd device; make <platform> install
+
+You can change some of the configuration parameters in app_profile.h
+
+Known bugs/limitations:
+
+- Many TinyOS 2 platforms do not have a clock that satisfies the
+  precision/accuracy requirements of the IEEE 802.15.4 standard (e.g. 
+  62.500 Hz, +-40 ppm in the 2.4 GHz band); in this case the MAC timing 
+  is not standard compliant
+
+$Id$
+
diff --git a/apps/tests/tkn154/beacon-enabled/TestIndirect/app_profile.h b/apps/tests/tkn154/beacon-enabled/TestIndirect/app_profile.h
new file mode 100644 (file)
index 0000000..185bbcd
--- /dev/null
@@ -0,0 +1,48 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#ifndef __APP_PROFILE_H
+#define __APP_PROFILE_H
+
+enum {
+  RADIO_CHANNEL = 26,
+  PAN_ID = 0x1152,
+  DEVICE_ADDRESS = 0x4342,
+  COORDINATOR_ADDRESS = 0x5341,
+  BEACON_ORDER = 5,
+  SUPERFRAME_ORDER = 5,
+};
+
+#endif
diff --git a/apps/tests/tkn154/beacon-enabled/TestIndirect/coordinator/Makefile b/apps/tests/tkn154/beacon-enabled/TestIndirect/coordinator/Makefile
new file mode 100644 (file)
index 0000000..2f06080
--- /dev/null
@@ -0,0 +1,4 @@
+COMPONENT=TestIndirectAppC
+PFLAGS += -DIEEE154_BEACON_SYNC_DISABLED -DIEEE154_SCAN_DISABLED
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/beacon-enabled/TestIndirect/coordinator/TestCoordSenderC.nc b/apps/tests/tkn154/beacon-enabled/TestIndirect/coordinator/TestCoordSenderC.nc
new file mode 100644 (file)
index 0000000..e270937
--- /dev/null
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestCoordSenderC
+{
+  uses {
+    interface Boot;
+    interface MCPS_DATA;
+    interface MLME_RESET;
+    interface MLME_START;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface Leds;
+    interface IEEE154Frame as Frame;
+    interface IEEE154TxBeaconPayload;
+    interface Packet;
+  }
+} implementation {
+
+  message_t m_frame;
+  uint8_t m_payloadLen;
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status != IEEE154_SUCCESS)
+      return;
+
+    call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
+    call MLME_SET.macAssociationPermit(FALSE);
+    call MLME_START.request(
+                          PAN_ID,           // PANId
+                          RADIO_CHANNEL,    // LogicalChannel
+                          0,                // ChannelPage,
+                          0,                // StartTime,
+                          BEACON_ORDER,     // BeaconOrder
+                          SUPERFRAME_ORDER, // SuperframeOrder
+                          TRUE,             // PANCoordinator
+                          FALSE,            // BatteryLifeExtension
+                          FALSE,            // CoordRealignment
+                          0,                // CoordRealignSecurity
+                          0                 // BeaconSecurity
+                        );
+  }
+
+  void dataRequest()
+  {
+    call MCPS_DATA.request  (
+        &m_frame,                                 // msdu,
+        m_payloadLen,                             // payloadLength,
+        0,                                        // msduHandle,
+        TX_OPTIONS_ACK | TX_OPTIONS_INDIRECT      // TxOptions,
+        );
+  }
+
+  event void MLME_START.confirm(ieee154_status_t status)
+  {
+    char payload[] = "Hello Device!";
+    uint8_t *payloadRegion;
+    ieee154_address_t deviceShortAddress;
+
+    // construct the frame
+    m_payloadLen = strlen(payload);
+    payloadRegion = call Packet.getPayload(&m_frame, m_payloadLen);
+    deviceShortAddress.shortAddress = DEVICE_ADDRESS; // destination
+    if (status == IEEE154_SUCCESS && m_payloadLen <= call Packet.maxPayloadLength()) {
+      memcpy(payloadRegion, payload, m_payloadLen);
+      call Frame.setAddressingFields(
+          &m_frame,                
+          ADDR_MODE_SHORT_ADDRESS, // SrcAddrMode,
+          ADDR_MODE_SHORT_ADDRESS, // DstAddrMode,
+          PAN_ID,                  // DstPANId,
+          &deviceShortAddress,     // DstAddr,
+          NULL                     // security
+          );
+      dataRequest();
+    }
+  }
+
+  event void MCPS_DATA.confirm(
+                          message_t *msg,
+                          uint8_t msduHandle,
+                          ieee154_status_t status,
+                          uint32_t Timestamp
+                        )
+  {
+    if (status == IEEE154_SUCCESS)
+      call Leds.led1Toggle();
+    dataRequest();
+  }
+
+  event message_t* MCPS_DATA.indication ( message_t* frame)
+  {
+    return frame;
+  }
+
+  event void IEEE154TxBeaconPayload.aboutToTransmit() { }
+
+  event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) { }
+
+  event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) { }
+
+  event void IEEE154TxBeaconPayload.beaconTransmitted() 
+  {
+    ieee154_macBSN_t beaconSequenceNumber = call MLME_GET.macBSN();
+    if (beaconSequenceNumber & 1)
+      call Leds.led2On();
+    else
+      call Leds.led2Off();
+  }  
+  
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestIndirect/coordinator/TestIndirectAppC.nc b/apps/tests/tkn154/beacon-enabled/TestIndirect/coordinator/TestIndirectAppC.nc
new file mode 100644 (file)
index 0000000..2ba70e2
--- /dev/null
@@ -0,0 +1,52 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+configuration TestIndirectAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154BeaconEnabledC as MAC;
+  components TestCoordSenderC as App;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.MLME_START -> MAC;
+  App.MCPS_DATA -> MAC;
+  App.Frame -> MAC;
+  App.IEEE154TxBeaconPayload -> MAC;
+  App.Packet -> MAC;
+
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestIndirect/device/Makefile b/apps/tests/tkn154/beacon-enabled/TestIndirect/device/Makefile
new file mode 100644 (file)
index 0000000..65d2fe2
--- /dev/null
@@ -0,0 +1,4 @@
+COMPONENT=TestIndirectAppC
+PFLAGS += -DIEEE154_BEACON_TX_DISABLED
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/beacon-enabled/TestIndirect/device/TestDeviceReceiverC.nc b/apps/tests/tkn154/beacon-enabled/TestIndirect/device/TestDeviceReceiverC.nc
new file mode 100644 (file)
index 0000000..dc2482d
--- /dev/null
@@ -0,0 +1,163 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154.h"
+#include "app_profile.h"
+module TestDeviceReceiverC
+{
+  uses {
+    interface Boot;
+    interface MCPS_DATA;
+    interface MLME_RESET;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface MLME_SCAN;
+    interface MLME_SYNC;
+    interface MLME_BEACON_NOTIFY;
+    interface MLME_SYNC_LOSS;
+    interface IEEE154BeaconFrame as BeaconFrame;
+    interface Leds;
+  }
+} implementation {
+
+  ieee154_address_t m_coordAddress;
+  uint8_t m_coordAddressMode;
+  ieee154_macPANId_t m_coordPANID;
+  ieee154_PANDescriptor_t m_PANDescriptor;
+  bool m_wasScanSuccessful;
+  void startApp();
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+  
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status == IEEE154_SUCCESS)
+      startApp();
+  }
+
+  void startApp()
+  {
+    ieee154_phyChannelsSupported_t channel;
+    uint8_t scanDuration = BEACON_ORDER;
+
+    // in this application the coordinator assumes that 
+    // the device has a certain short address    
+    call MLME_SET.macShortAddress(DEVICE_ADDRESS);
+    channel = ((uint32_t) 1) << RADIO_CHANNEL;
+
+    // we want all received beacons to be signalled 
+    // through the MLME_BEACON_NOTIFY interface, i.e.
+    // we set the macAutoRequest attribute to FALSE
+    call MLME_SET.macAutoRequest(FALSE);
+    m_wasScanSuccessful = FALSE;
+    call MLME_SCAN.request  (
+                           PASSIVE_SCAN,           // ScanType
+                           channel,                // ScanChannels
+                           scanDuration,           // ScanDuration
+                           0x00,                   // ChannelPage
+                           0,                      // EnergyDetectListNumEntries
+                           NULL,                   // EnergyDetectList
+                           0,                      // PANDescriptorListNumEntries
+                           NULL,                   // PANDescriptorList
+                           0                       // security
+                        );
+  }
+
+  event message_t* MLME_BEACON_NOTIFY.indication (message_t* frame)
+  {
+    // received a beacon frame during SCAN
+    ieee154_phyCurrentPage_t page = call MLME_GET.phyCurrentPage();
+
+    if (!m_wasScanSuccessful && call BeaconFrame.parsePANDescriptor(
+          frame, RADIO_CHANNEL, page, &m_PANDescriptor) == SUCCESS){
+      // let's see if the beacon is from our coordinator...
+      if (m_PANDescriptor.CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
+          m_PANDescriptor.CoordPANId == PAN_ID &&
+          m_PANDescriptor.CoordAddress.shortAddress == COORDINATOR_ADDRESS){
+        // wait until SCAN is finished, then syncronize to beacons
+        m_wasScanSuccessful = TRUE;
+      }
+    }
+    return frame;
+  }
+
+  event void MLME_SCAN.confirm    (
+                          ieee154_status_t status,
+                          uint8_t ScanType,
+                          uint8_t ChannelPage,
+                          uint32_t UnscannedChannels,
+                          uint8_t EnergyDetectListNumEntries,
+                          int8_t* EnergyDetectList,
+                          uint8_t PANDescriptorListNumEntries,
+                          ieee154_PANDescriptor_t* PANDescriptorList
+                        )
+  {
+    if (m_wasScanSuccessful){
+      // set the macAutoRequest attribute to TRUE, so indirect
+      // transmissions are automatically carried through
+      call MLME_SET.macAutoRequest(TRUE);
+      call MLME_SET.macCoordShortAddress(m_PANDescriptor.CoordAddress.shortAddress);
+      call MLME_SET.macPANId(m_PANDescriptor.CoordPANId);
+      call MLME_SYNC.request(m_PANDescriptor.LogicalChannel, m_PANDescriptor.ChannelPage, TRUE);
+    } else
+      startApp();
+  }
+
+  event void MCPS_DATA.confirm(
+                          message_t *msg,
+                          uint8_t msduHandle,
+                          ieee154_status_t status,
+                          uint32_t Timestamp
+                        )
+  {
+  }
+
+  event void MLME_SYNC_LOSS.indication(
+                          ieee154_status_t lossReason,
+                          uint16_t PANId,
+                          uint8_t LogicalChannel,
+                          uint8_t ChannelPage,
+                          ieee154_security_t *security)
+  {
+    call Leds.led1Off();
+  }
+
+  event message_t* MCPS_DATA.indication (message_t* frame)
+  {
+    call Leds.led1Toggle();
+    return frame;
+  }
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestIndirect/device/TestIndirectAppC.nc b/apps/tests/tkn154/beacon-enabled/TestIndirect/device/TestIndirectAppC.nc
new file mode 100644 (file)
index 0000000..f077e5d
--- /dev/null
@@ -0,0 +1,53 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestIndirectAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154BeaconEnabledC as MAC;
+  components TestDeviceReceiverC as App;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.MLME_SCAN -> MAC;
+  App.MLME_SYNC -> MAC;
+  App.MLME_BEACON_NOTIFY -> MAC;
+  App.MLME_SYNC_LOSS -> MAC;
+  App.MCPS_DATA -> MAC;
+  App.BeaconFrame -> MAC;
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestStartSync/README.txt b/apps/tests/tkn154/beacon-enabled/TestStartSync/README.txt
new file mode 100644 (file)
index 0000000..0f4b39c
--- /dev/null
@@ -0,0 +1,40 @@
+README for TestStartSync
+Author/Contact: Jan Hauer <hauer@tkn.tu-berlin.de>
+
+Description:
+
+In this application one node takes the role of a PAN coordinator in a
+beacon-enabled 802.15.4 PAN, it transmits periodic beacons with a frequency
+defined in the app_profile.h file. A second node acts as a device, it first
+scans all available channels for beacons from the coordinator and once it finds
+a beacon it tries to synchronize to and track all future beacons. 
+
+Criteria for a successful test:
+
+After a few seconds all nodes should have the LED1 turned on and LED2
+toggling in unison every second.
+
+
+Tools: NONE
+
+Usage: 
+
+1. Install the coordinator:
+
+    $ cd coordinator; make <platform> install
+
+2. Install one (or more) devices:
+
+    $ cd device; make <platform> install
+
+You can change some of the configuration parameters in app_profile.h
+
+Known bugs/limitations:
+
+- Many TinyOS 2 platforms do not have a clock that satisfies the
+  precision/accuracy requirements of the IEEE 802.15.4 standard (e.g. 
+  62.500 Hz, +-40 ppm in the 2.4 GHz band); in this case the MAC timing 
+  is not standard compliant
+
+$Id$
+
diff --git a/apps/tests/tkn154/beacon-enabled/TestStartSync/app_profile.h b/apps/tests/tkn154/beacon-enabled/TestStartSync/app_profile.h
new file mode 100644 (file)
index 0000000..366f111
--- /dev/null
@@ -0,0 +1,47 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#ifndef __APP_PROFILE_H
+#define __APP_PROFILE_H
+
+enum {
+  RADIO_CHANNEL = 26,
+  PAN_ID = 0x7761,
+  COORDINATOR_ADDRESS = 0x1832,
+  BEACON_ORDER = 5,
+  SUPERFRAME_ORDER = 5,
+};
+
+#endif
diff --git a/apps/tests/tkn154/beacon-enabled/TestStartSync/coordinator/Makefile b/apps/tests/tkn154/beacon-enabled/TestStartSync/coordinator/Makefile
new file mode 100644 (file)
index 0000000..0b0bf72
--- /dev/null
@@ -0,0 +1,4 @@
+COMPONENT=TestStartSyncAppC
+CFLAGS += -I$(shell pwd)/..
+CFLAGS += -DIEEE154_SCAN_DISABLED -DIEEE154_BEACON_SYNC_DISABLED
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/beacon-enabled/TestStartSync/coordinator/TestCoordC.nc b/apps/tests/tkn154/beacon-enabled/TestStartSync/coordinator/TestCoordC.nc
new file mode 100644 (file)
index 0000000..e401db6
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestCoordC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_START;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface Leds;
+    interface IEEE154TxBeaconPayload;
+  }
+} implementation {
+
+  uint8_t m_beaconPayload[] = {0x01, 0x02, 0x03, 0x04, 0x05};
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status == IEEE154_SUCCESS){
+      call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
+      call MLME_SET.macAssociationPermit(FALSE);
+      call MLME_START.request(
+          PAN_ID,             // PANId
+          RADIO_CHANNEL,      // LogicalChannel
+          0,                  // ChannelPage,
+          0,                  // StartTime,
+          BEACON_ORDER,       // BeaconOrder
+          SUPERFRAME_ORDER,   // SuperframeOrder
+          TRUE,               // PANCoordinator
+          FALSE,              // BatteryLifeExtension
+          FALSE,              // CoordRealignment
+          0,                  // no realignment security
+          0                   // no beacon security
+          );
+    }
+  }
+
+  event void MLME_START.confirm(ieee154_status_t status)
+  {
+    if (status == IEEE154_SUCCESS){
+      call IEEE154TxBeaconPayload.setBeaconPayload(m_beaconPayload, sizeof(m_beaconPayload));
+      call Leds.led1On();
+    }
+  }
+
+  event void IEEE154TxBeaconPayload.aboutToTransmit() { }
+
+  event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) { }
+
+  event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) { }
+
+  event void IEEE154TxBeaconPayload.beaconTransmitted() 
+  {
+    ieee154_macBSN_t beaconSequenceNumber = call MLME_GET.macBSN();
+    if (beaconSequenceNumber & 1)
+      call Leds.led2On();
+    else
+      call Leds.led2Off();
+  }
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestStartSync/coordinator/TestStartSyncAppC.nc b/apps/tests/tkn154/beacon-enabled/TestStartSync/coordinator/TestStartSyncAppC.nc
new file mode 100644 (file)
index 0000000..6020c4b
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestStartSyncAppC
+{
+} implementation {
+
+  components MainC, LedsC, Ieee802154BeaconEnabledC as MAC;
+  components TestCoordC as App;
+
+  MainC.Boot <- App;
+  App.MLME_START -> MAC;
+  App.IEEE154TxBeaconPayload -> MAC;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestStartSync/device/Makefile b/apps/tests/tkn154/beacon-enabled/TestStartSync/device/Makefile
new file mode 100644 (file)
index 0000000..3fb3698
--- /dev/null
@@ -0,0 +1,4 @@
+COMPONENT=TestStartSyncAppC
+PFLAGS += -DIEEE154_BEACON_TX_DISABLED
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/beacon-enabled/TestStartSync/device/TestDeviceC.nc b/apps/tests/tkn154/beacon-enabled/TestStartSync/device/TestDeviceC.nc
new file mode 100644 (file)
index 0000000..c11193a
--- /dev/null
@@ -0,0 +1,160 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestDeviceC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface MLME_SCAN;
+    interface MLME_SYNC;
+    interface MLME_BEACON_NOTIFY;
+    interface MLME_SYNC_LOSS;
+    interface Leds;
+    interface IEEE154BeaconFrame as BeaconFrame;
+  }
+} implementation {
+
+  enum {
+    NUM_PAN_DESCRIPTORS = 10,
+  };
+  ieee154_PANDescriptor_t m_PANDescriptor[NUM_PAN_DESCRIPTORS];
+  void startApp();
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+  
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status == IEEE154_SUCCESS)
+      startApp();
+  }
+
+  void startApp()
+  {
+    ieee154_phyChannelsSupported_t scanChannels;
+    uint8_t scanDuration = BEACON_ORDER;
+
+    // set the short address to whatever was passed 
+    // as a parameter to make system ("make install,X")
+    call MLME_SET.macShortAddress(TOS_NODE_ID); 
+    scanChannels = call MLME_GET.phyChannelsSupported();
+    //scanChannels = (uint32_t) 1 << RADIO_CHANNEL;
+
+    // setting the macAutoRequest attribute to TRUE means
+    // that during the scan beacons will not be signalled
+    // through MLME_BEACON_NOTIFY
+    call MLME_SET.macAutoRequest(TRUE);
+    call MLME_SCAN.request  (
+        PASSIVE_SCAN,           // ScanType
+        scanChannels,           // ScanChannels
+        scanDuration,           // ScanDuration
+        0x00,                   // ChannelPage
+        0,                      // EnergyDetectListNumEntries
+        NULL,                   // EnergyDetectList
+        NUM_PAN_DESCRIPTORS,    // PANDescriptorListNumEntries
+        m_PANDescriptor,        // PANDescriptorList
+        0                       // security
+        );
+  }
+
+  event void MLME_SCAN.confirm    (
+                          ieee154_status_t status,
+                          uint8_t ScanType,
+                          uint8_t ChannelPage,
+                          uint32_t UnscannedChannels,
+                          uint8_t EnergyDetectListNumEntries,
+                          int8_t* EnergyDetectList,
+                          uint8_t PANDescriptorListNumEntries,
+                          ieee154_PANDescriptor_t* PANDescriptorList
+                        )
+  {
+    uint8_t i;
+    switch (status){
+      case IEEE154_NO_BEACON:
+        startApp();
+        break;
+      case IEEE154_SUCCESS:
+        if (PANDescriptorListNumEntries > 0){
+          for (i=0; i<PANDescriptorListNumEntries; i++)
+            if (PANDescriptorList[i].CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
+                PANDescriptorList[i].CoordPANId == PAN_ID &&
+                PANDescriptorList[i].CoordAddress.shortAddress == COORDINATOR_ADDRESS)
+              break;
+          if (i == PANDescriptorListNumEntries){
+            // found no matching entry
+            startApp();
+          } else {
+            call MLME_SET.macAutoRequest(FALSE); // from now on: give me the beacons
+            call MLME_SET.macPANId(PANDescriptorList[i].CoordPANId);
+            call MLME_SET.macCoordShortAddress(PANDescriptorList[i].CoordAddress.shortAddress);
+            call MLME_SYNC.request(PANDescriptorList[i].LogicalChannel, ChannelPage, TRUE);
+          }
+        }
+        break;
+      default:
+        break;
+    }
+  }
+
+  event message_t* MLME_BEACON_NOTIFY.indication (
+                          message_t* frame
+                        )
+  {
+    ieee154_macBSN_t beaconSequenceNumber = call BeaconFrame.getBSN(frame);
+    if (beaconSequenceNumber & 1)
+      call Leds.led2On();
+    else
+      call Leds.led2Off();    
+    call Leds.led1On();
+    return frame;
+  }
+
+  event void MLME_SYNC_LOSS.indication(
+                          ieee154_status_t lossReason,
+                          uint16_t PANId,
+                          uint8_t LogicalChannel,
+                          uint8_t ChannelPage,
+                          ieee154_security_t *security)
+  {
+    call Leds.led1Off();
+    startApp();
+  }
+}
diff --git a/apps/tests/tkn154/beacon-enabled/TestStartSync/device/TestStartSyncAppC.nc b/apps/tests/tkn154/beacon-enabled/TestStartSync/device/TestStartSyncAppC.nc
new file mode 100644 (file)
index 0000000..c6f1f67
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestStartSyncAppC
+{
+} implementation {
+
+  components MainC, LedsC, Ieee802154BeaconEnabledC as MAC;
+  components TestDeviceC as App;
+
+  App.MLME_SCAN -> MAC;
+  App.MLME_SYNC -> MAC;
+  App.MLME_BEACON_NOTIFY -> MAC;
+  App.MLME_SYNC_LOSS -> MAC;
+  App.BeaconFrame -> MAC;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+
+#ifdef PRINTF_ENABLED
+  components PrintfC;
+  App.PrintfControl -> PrintfC;
+  App.PrintfFlush -> PrintfC;
+#endif
+}
diff --git a/apps/tests/tkn154/makeall.sh b/apps/tests/tkn154/makeall.sh
new file mode 100755 (executable)
index 0000000..a7e9261
--- /dev/null
@@ -0,0 +1,26 @@
+#!/bin/bash
+# compile/clean all test applications
+PLATFORM=$1
+OPTIONS=
+STARTDIR=`pwd`
+MAKEFILES=`find . -name Makefile`
+
+if [ $# == 0 ];
+then
+  echo "Usage: $0 <platform|clean>"
+  exit
+fi
+
+for m in $MAKEFILES
+do
+  cd ${m%Makefile}
+  if [ "x$1" == xclean ];
+  then
+    make clean
+  else
+    make $PLATFORM $OPTIONS;
+  fi
+  cd $STARTDIR
+done
+exit
+
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/README.txt b/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/README.txt
new file mode 100644 (file)
index 0000000..4de87f2
--- /dev/null
@@ -0,0 +1,40 @@
+README for TestActiveScan
+Author/Contact: Jan Hauer <hauer@tkn.tu-berlin.de>
+
+Description:
+
+In this application one node takes the role of a PAN coordinator in a
+nonbeacon-enabled 802.15.4 PAN, it switches its radio to receive mode.  A
+second node acts as a device, it switches to the pre-defined channel and
+periodically performs active-scans (i.e. sends out beacon request frames) on
+the predefined channel and expects beacon frames in return. 
+
+Criteria for a successful test:
+
+The coordinator should toggle LED1 once every 2 seconds. The device should
+toggle LED1 and LED2 every 2 seconds (not necessarily simultaneously).
+
+
+Tools: NONE
+
+Usage: 
+
+1. Install the coordinator:
+
+    $ cd coordinator; make <platform> install
+
+2. Install one (or more) devices:
+
+    $ cd device; make <platform> install
+
+You can change some of the configuration parameters in app_profile.h
+
+Known bugs/limitations:
+
+- Many TinyOS 2 platforms do not have a clock that satisfies the
+  precision/accuracy requirements of the IEEE 802.15.4 standard (e.g. 
+  62.500 Hz, +-40 ppm in the 2.4 GHz band); in this case the MAC timing 
+  is not standard compliant
+
+$Id$o
+
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/app_profile.h b/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/app_profile.h
new file mode 100644 (file)
index 0000000..c8e46a9
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#ifndef __APP_PROFILE_H
+#define __APP_PROFILE_H
+
+enum {
+  RADIO_CHANNEL = 26,
+  PAN_ID = 0x1234,
+  COORDINATOR_ADDRESS = 0x2345,
+  DEVICE_ADDRESS = 0x2346
+};
+
+#endif
+
+
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/coordinator/Makefile b/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/coordinator/Makefile
new file mode 100644 (file)
index 0000000..8558fc7
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=TestActiveScanCoordAppC
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/coordinator/TestActiveScanCoordAppC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/coordinator/TestActiveScanCoordAppC.nc
new file mode 100644 (file)
index 0000000..a1c07f5
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestActiveScanCoordAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154NonBeaconEnabledC as MAC;
+  components new Timer62500C() as Timer1;
+  components TestActiveScanCoordC as App;
+
+  MainC.Boot <- App;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.MLME_START -> MAC;
+  App.IEEE154TxBeaconPayload -> MAC;
+
+  App.Led1Timer -> Timer1;
+  App.Leds -> LedsC;
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/coordinator/TestActiveScanCoordC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/coordinator/TestActiveScanCoordC.nc
new file mode 100644 (file)
index 0000000..515a441
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestActiveScanCoordC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_START;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface IEEE154TxBeaconPayload;
+    interface Leds;
+    interface Timer<T62500hz> as Led1Timer;
+
+  }
+} implementation {
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status) {
+    if (status != IEEE154_SUCCESS) 
+      return;
+    call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
+    call MLME_SET.macAssociationPermit(FALSE);
+    call MLME_SET.macRxOnWhenIdle(TRUE);
+    call MLME_START.request(
+                          PAN_ID,           // PANId
+                          RADIO_CHANNEL,    // LogicalChannel
+                          0,                // ChannelPage,
+                          0,                // StartTime,
+                          15,               // BeaconOrder
+                          15,               // SuperframeOrder
+                          TRUE,             // PANCoordinator
+                          FALSE,            // BatteryLifeExtension
+                          FALSE,            // CoordRealignment
+                          NULL,             // no realignment security
+                          NULL              // no beacon security
+                        );    
+  }
+
+  event void MLME_START.confirm(ieee154_status_t status) {}
+
+  event void IEEE154TxBeaconPayload.aboutToTransmit() {
+    call Leds.led1On();
+    call Led1Timer.startOneShot(62500U);
+  }
+
+  event void Led1Timer.fired(){
+    call Leds.led1Off();
+  }
+
+  event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length){}
+  event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength){}
+  event void IEEE154TxBeaconPayload.beaconTransmitted(){}
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/device/Makefile b/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/device/Makefile
new file mode 100644 (file)
index 0000000..1f7a2be
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=TestActiveScanDeviceAppC
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/device/TestActiveScanDeviceAppC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/device/TestActiveScanDeviceAppC.nc
new file mode 100644 (file)
index 0000000..941bbc4
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestActiveScanDeviceAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154NonBeaconEnabledC as MAC,
+             new Timer62500C() as Timer1, 
+             new Timer62500C() as Timer2, 
+             new Timer62500C() as Timer3, 
+             new Timer62500C() as Timer4;
+  components TestActiveScanDeviceC as App;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.MLME_SCAN -> MAC;
+
+  App.ScanTimer -> Timer1;
+  App.Led0Timer -> Timer2;
+  App.Led1Timer -> Timer3;
+  App.Led2Timer -> Timer4;
+
+
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/device/TestActiveScanDeviceC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestActiveScan/device/TestActiveScanDeviceC.nc
new file mode 100644 (file)
index 0000000..8bd067b
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestActiveScanDeviceC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface MLME_SCAN;
+    interface Leds;
+    interface Timer<T62500hz> as ScanTimer;
+    interface Timer<T62500hz> as Led1Timer;
+    interface Timer<T62500hz> as Led0Timer;
+    interface Timer<T62500hz> as Led2Timer;
+  }
+} implementation {
+
+  ieee154_PANDescriptor_t m_PANDescriptor[5];
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status) {
+    if (status == IEEE154_SUCCESS){
+    call ScanTimer.startPeriodic(125000U); 
+    }
+  }
+
+  event void ScanTimer.fired() {
+    ieee154_phyChannelsSupported_t channelMask;
+    channelMask = ((uint32_t) 1) << RADIO_CHANNEL;
+    call Leds.led2On();
+    call Led2Timer.startOneShot(62500U);
+    call MLME_SCAN.request  (
+                           ACTIVE_SCAN,            // ScanType
+                           channelMask,            // ScanChannels
+                           5,                      // ScanDuration
+                           0x00,                   // ChannelPage
+                           0,                      // EnergyDetectListNumEntries
+                           NULL,                   // EnergyDetectList
+                           5,                      // PANDescriptorListNumEntries
+                           m_PANDescriptor,        // PANDescriptorList
+                           0                       // security
+                        );
+  }
+
+  event void MLME_SCAN.confirm    (
+                          ieee154_status_t status,
+                          uint8_t ScanType,
+                          uint8_t ChannelPage,
+                          uint32_t UnscannedChannels,
+                          uint8_t EnergyDetectListNumEntries,
+                          int8_t* EnergyDetectList,
+                          uint8_t PANDescriptorListNumEntries,
+                          ieee154_PANDescriptor_t* PANDescriptorList
+                        ){
+    uint8_t scanIndex;
+    uint8_t rightCoordFound = FALSE;
+
+    for(scanIndex = 0; scanIndex < PANDescriptorListNumEntries; scanIndex++){
+      if( (PANDescriptorList[scanIndex].CoordAddrMode == ADDR_MODE_SHORT_ADDRESS) && 
+          (PANDescriptorList[scanIndex].CoordAddress.shortAddress == COORDINATOR_ADDRESS) &&
+          (PANDescriptorList[scanIndex].CoordPANId == PAN_ID) ) {
+        call Leds.led1On();
+        call Led1Timer.startOneShot(62500U);
+        rightCoordFound = TRUE;
+        break;
+      }
+    }
+    if(rightCoordFound == FALSE) {
+      // call Leds.led0On();
+      // call Led0Timer.startOneShot(62500U); 
+    }
+  }
+
+  event void Led0Timer.fired(){
+    call Leds.led0Off();
+  }
+
+  event void Led1Timer.fired(){
+    call Leds.led1Off();
+  }
+
+  event void Led2Timer.fired(){
+    call Leds.led2Off();
+  }
+
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/README.txt b/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/README.txt
new file mode 100644 (file)
index 0000000..194911f
--- /dev/null
@@ -0,0 +1,44 @@
+README for TestAssociate
+Author/Contact: Jan Hauer <hauer@tkn.tu-berlin.de>
+
+Description:
+
+In this application one node takes the role of a PAN coordinator in a
+nonbeacon-enabled 802.15.4 PAN, it switches its radio to receive mode and waits
+for devices to request association to its PAN. Whenever a device tries to
+associate, the PAN coordinator allows association and assigns to the device a
+unique short address (starting from zero, incremented for every device
+requesting association).  A second node acts as a device, it switches to the
+pre-defined channel and tries to associate to the PAN. A short time after
+association the device then disassociates from the PAN. 
+
+Criteria for a successful test:
+
+Assuming one coordinator and one device has been installed, both should
+simultaneously switch on LED1. About 5 seconds later both should switch LED1
+off. That's all.
+
+
+Tools: NONE
+
+Usage: 
+
+1. Install the coordinator:
+
+    $ cd coordinator; make <platform> install
+
+2. Install one (or more) devices:
+
+    $ cd device; make <platform> install
+
+You can change some of the configuration parameters in app_profile.h
+
+Known bugs/limitations:
+
+- Many TinyOS 2 platforms do not have a clock that satisfies the
+  precision/accuracy requirements of the IEEE 802.15.4 standard (e.g. 
+  62.500 Hz, +-40 ppm in the 2.4 GHz band); in this case the MAC timing 
+  is not standard compliant
+
+$Id$o
+
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/app_profile.h b/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/app_profile.h
new file mode 100644 (file)
index 0000000..bf986b5
--- /dev/null
@@ -0,0 +1,45 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#ifndef __APP_PROFILE_H
+#define __APP_PROFILE_H
+
+enum {
+  RADIO_CHANNEL = 26,
+  PAN_ID = 0x9678,
+  COORDINATOR_ADDRESS = 0x7722,
+};
+
+#endif
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/coordinator/Makefile b/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/coordinator/Makefile
new file mode 100644 (file)
index 0000000..c4d5d67
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=TestAssociateAppC
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/coordinator/TestAssociateAppC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/coordinator/TestAssociateAppC.nc
new file mode 100644 (file)
index 0000000..1905234
--- /dev/null
@@ -0,0 +1,52 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestAssociateAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154NonBeaconEnabledC as MAC;
+  components TestCoordC as App;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+
+  App.MLME_START -> MAC;
+  App.MLME_ASSOCIATE -> MAC;
+  App.MLME_DISASSOCIATE -> MAC;
+  App.MLME_COMM_STATUS -> MAC;
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/coordinator/TestCoordC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/coordinator/TestCoordC.nc
new file mode 100644 (file)
index 0000000..31930dc
--- /dev/null
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestCoordC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_START;
+    interface MLME_ASSOCIATE;
+    interface MLME_DISASSOCIATE;
+    interface MLME_COMM_STATUS;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface Leds;
+  }
+} implementation {
+
+  ieee154_address_t m_lastDevice;
+  uint16_t m_shortAddress;
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status != IEEE154_SUCCESS)
+      return;
+    call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
+    call MLME_SET.macAssociationPermit(TRUE);
+    call MLME_SET.macRxOnWhenIdle(TRUE);
+    call MLME_START.request(
+                          PAN_ID,           // PANId
+                          RADIO_CHANNEL,    // LogicalChannel
+                          0,                // ChannelPage,
+                          0,                // StartTime,
+                          15,               // BeaconOrder
+                          15,               // SuperframeOrder
+                          TRUE,             // PANCoordinator
+                          FALSE,            // BatteryLifeExtension
+                          FALSE,            // CoordRealignment
+                          NULL,             // no realignment security
+                          NULL              // no beacon security
+                        );    
+  }
+
+  event void MLME_START.confirm(ieee154_status_t status) {
+    // good, let's wait for association requests ...
+  }
+
+  event void MLME_ASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_CapabilityInformation_t CapabilityInformation,
+                          ieee154_security_t *security
+                        )
+  {
+    call MLME_ASSOCIATE.response(DeviceAddress, m_shortAddress++, IEEE154_ASSOCIATION_SUCCESSFUL, 0);
+  }
+
+  event void MLME_DISASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_disassociation_reason_t DisassociateReason,
+                          ieee154_security_t *security
+                        )
+  {
+    call Leds.led1Off();
+  }
+
+
+  event void MLME_COMM_STATUS.indication (
+                          uint16_t PANId,
+                          uint8_t SrcAddrMode,
+                          ieee154_address_t SrcAddr,
+                          uint8_t DstAddrMode,
+                          ieee154_address_t DstAddr,
+                          ieee154_status_t status,
+                          ieee154_security_t *security
+                        )
+  {
+    if (status == IEEE154_SUCCESS){
+      // association was successful
+      call Leds.led1On();
+      m_lastDevice.extendedAddress = DstAddr.extendedAddress;
+    } else {
+      call Leds.led1Off();
+    }
+  }
+
+  event void MLME_DISASSOCIATE.confirm    (
+                          ieee154_status_t status,
+                          uint8_t DeviceAddrMode,
+                          uint16_t DevicePANID,
+                          ieee154_address_t DeviceAddress
+                        ){}
+
+  event void MLME_ASSOCIATE.confirm    (
+                          uint16_t AssocShortAddress,
+                          uint8_t status,
+                          ieee154_security_t *security
+                        ){}
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/device/Makefile b/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/device/Makefile
new file mode 100644 (file)
index 0000000..c4d5d67
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=TestAssociateAppC
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/device/TestAssociateAppC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/device/TestAssociateAppC.nc
new file mode 100644 (file)
index 0000000..0ead6a3
--- /dev/null
@@ -0,0 +1,53 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestAssociateAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154NonBeaconEnabledC as MAC,
+             new Timer62500C() as Timer;
+  components TestDeviceC as App;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.DisassociateTimer -> Timer;  
+  App.MLME_ASSOCIATE -> MAC;
+  App.MLME_DISASSOCIATE -> MAC;
+  App.MLME_COMM_STATUS -> MAC;
+
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/device/TestDeviceC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestAssociate/device/TestDeviceC.nc
new file mode 100644 (file)
index 0000000..955b60c
--- /dev/null
@@ -0,0 +1,158 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154.h"
+#include "app_profile.h"
+module TestDeviceC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface MLME_ASSOCIATE;
+    interface MLME_DISASSOCIATE;
+    interface MLME_COMM_STATUS;
+    interface Leds;
+    interface Timer<T62500hz> as DisassociateTimer;
+  }
+} implementation {
+
+  ieee154_CapabilityInformation_t m_capabilityInformation;
+  void startApp();
+
+  event void Boot.booted() {
+    m_capabilityInformation.AlternatePANCoordinator = 0;
+    m_capabilityInformation.DeviceType = 0;
+    m_capabilityInformation.PowerSource = 0;
+    m_capabilityInformation.ReceiverOnWhenIdle = 0;
+    m_capabilityInformation.Reserved = 0;
+    m_capabilityInformation.SecurityCapability = 0;
+    m_capabilityInformation.AllocateAddress = 1;    
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status == IEEE154_SUCCESS)
+      startApp();
+  }
+
+  void startApp()
+  {
+    ieee154_address_t coordAdr;
+
+    coordAdr.shortAddress = COORDINATOR_ADDRESS;
+    call MLME_SET.phyCurrentChannel(RADIO_CHANNEL);
+    call MLME_SET.macAutoRequest(FALSE);
+    call MLME_SET.macPANId(PAN_ID);
+    call MLME_SET.macCoordShortAddress(COORDINATOR_ADDRESS);
+    call MLME_ASSOCIATE.request(
+          RADIO_CHANNEL,
+          call MLME_GET.phyCurrentPage(),
+          ADDR_MODE_SHORT_ADDRESS,
+          PAN_ID,
+          coordAdr,
+          m_capabilityInformation,
+          NULL  // security
+          );    
+  }
+
+  event void MLME_ASSOCIATE.confirm    (
+                          uint16_t AssocShortAddress,
+                          uint8_t status,
+                          ieee154_security_t *security
+                        )
+  {
+    if ( status == IEEE154_SUCCESS ){
+      // we are now associated - set a timer for disassociation 
+      call Leds.led1On();
+      call DisassociateTimer.startOneShot(312500U);
+    } else {
+      startApp(); // retry
+    }
+  }
+
+  event void DisassociateTimer.fired()
+  {
+    ieee154_address_t coordAdr;
+    coordAdr.shortAddress = COORDINATOR_ADDRESS;
+    if (call MLME_DISASSOCIATE.request  (
+          ADDR_MODE_SHORT_ADDRESS,
+          PAN_ID,
+          coordAdr,
+          IEEE154_DEVICE_WISHES_TO_LEAVE,
+          FALSE,
+          NULL
+          ) != IEEE154_SUCCESS)
+      call DisassociateTimer.startOneShot(312500U);
+  }
+
+  event void MLME_DISASSOCIATE.confirm    (
+                          ieee154_status_t status,
+                          uint8_t DeviceAddrMode,
+                          uint16_t DevicePANID,
+                          ieee154_address_t DeviceAddress
+                        )
+  {
+    if (status == IEEE154_SUCCESS){
+      call Leds.led1Off();
+    } else {
+      call DisassociateTimer.startOneShot(312500U);
+    }
+  }
+
+  event void MLME_ASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_CapabilityInformation_t CapabilityInformation,
+                          ieee154_security_t *security
+                        ){}  
+
+  event void MLME_DISASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_disassociation_reason_t DisassociateReason,
+                          ieee154_security_t *security
+                        ){}
+
+
+  event void MLME_COMM_STATUS.indication (
+                          uint16_t PANId,
+                          uint8_t SrcAddrMode,
+                          ieee154_address_t SrcAddr,
+                          uint8_t DstAddrMode,
+                          ieee154_address_t DstAddr,
+                          ieee154_status_t status,
+                          ieee154_security_t *security
+                        ) {}
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/README.txt b/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/README.txt
new file mode 100644 (file)
index 0000000..7334f3d
--- /dev/null
@@ -0,0 +1,42 @@
+README for TestIndirectData
+Author/Contact: Jan Hauer <hauer@tkn.tu-berlin.de>
+
+Description:
+
+In this application one node takes the role of a PAN coordinator in a
+nonbeacon-enabled 802.15.4 PAN, every 3 seconds it sends a packet to a device
+using indirect transmission (i.e. the packet is buffered until it is polled by
+the device). A second node acts as the device, it switches to the pre-defined
+channel and polls the coordinator every 1 second for outstanding indirect
+transmissions.
+
+Criteria for a successful test:
+
+Assuming one coordinator and one device has been installed, the coordinator
+should briefly flash LED1 every 3 seconds. The device should briefly flash 
+LED2 every 1 second. 
+
+
+Tools: NONE
+
+Usage: 
+
+1. Install the coordinator:
+
+    $ cd coordinator; make <platform> install
+
+2. Install one (or more) devices:
+
+    $ cd device; make <platform> install
+
+You can change some of the configuration parameters in app_profile.h
+
+Known bugs/limitations:
+
+- Many TinyOS 2 platforms do not have a clock that satisfies the
+  precision/accuracy requirements of the IEEE 802.15.4 standard (e.g. 
+  62.500 Hz, +-40 ppm in the 2.4 GHz band); in this case the MAC timing 
+  is not standard compliant
+
+$Id$o
+
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/app_profile.h b/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/app_profile.h
new file mode 100644 (file)
index 0000000..a308332
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#ifndef __APP_PROFILE_H
+#define __APP_PROFILE_H
+
+enum {
+  RADIO_CHANNEL = 26,
+  PAN_ID = 0x4927,
+  COORDINATOR_ADDRESS = 0x6287,
+  DEVICE_ADDRESS = 0x6288
+};
+
+#endif
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/coordinator/Makefile b/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/coordinator/Makefile
new file mode 100644 (file)
index 0000000..ebe71b3
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=TestIndirectDataCoordAppC
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/coordinator/TestIndirectDataCoordAppC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/coordinator/TestIndirectDataCoordAppC.nc
new file mode 100644 (file)
index 0000000..d5fac24
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestIndirectDataCoordAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154NonBeaconEnabledC as MAC;
+  components TestIndirectDataCoordC as App;
+  components new Timer62500C() as Timer1;
+  components new Timer62500C() as Timer2;
+  components new Timer62500C() as Timer3;
+
+  MainC.Boot <- App;
+  App.MCPS_DATA -> MAC;
+  App.Frame -> MAC;
+  App.Packet -> MAC;
+  App.DataTimer -> Timer1;
+  App.Led1Timer -> Timer2;
+  App.Led0Timer -> Timer3;
+
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.MLME_START -> MAC;
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/coordinator/TestIndirectDataCoordC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/coordinator/TestIndirectDataCoordC.nc
new file mode 100644 (file)
index 0000000..1997631
--- /dev/null
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestIndirectDataCoordC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_START;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface MCPS_DATA;
+    interface IEEE154Frame as Frame;
+    interface Leds;
+    interface Packet;
+    interface Timer<T62500hz> as DataTimer;
+    interface Timer<T62500hz> as Led1Timer;
+    interface Timer<T62500hz> as Led0Timer;
+  }
+} implementation {
+
+  message_t frame;
+  uint8_t *payloadRegion;
+  uint8_t m_payloadLen;
+
+  char payload[] = "TestIndirect, Coordinator talking now!";
+
+  void sendIndirectData();
+
+  event void Boot.booted() {
+    m_payloadLen = strlen(payload);
+    payloadRegion = call Packet.getPayload(&frame, m_payloadLen);
+    if (m_payloadLen <= call Packet.maxPayloadLength()){
+      memcpy(payloadRegion, payload, m_payloadLen);
+      call MLME_RESET.request(TRUE);
+    }
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status != IEEE154_SUCCESS)
+      return;
+    call MLME_SET.macShortAddress(COORDINATOR_ADDRESS);
+    call MLME_SET.macAssociationPermit(FALSE);
+    call MLME_SET.macRxOnWhenIdle(TRUE);
+    call MLME_START.request(
+                          PAN_ID,           // PANId
+                          RADIO_CHANNEL,    // LogicalChannel
+                          0,                // ChannelPage,
+                          0,                // StartTime,
+                          15,               // BeaconOrder
+                          15,               // SuperframeOrder
+                          TRUE,             // PANCoordinator
+                          FALSE,            // BatteryLifeExtension
+                          FALSE,            // CoordRealignment
+                          NULL,             // no realignment security
+                          NULL              // no beacon security
+                        );    
+  }
+
+  void sendIndirectData(){
+    ieee154_address_t deviceAddress;
+    deviceAddress.shortAddress = DEVICE_ADDRESS;
+    call Frame.setAddressingFields(
+                          &frame,                
+                          ADDR_MODE_SHORT_ADDRESS,     // SrcAddrMode,
+                          ADDR_MODE_SHORT_ADDRESS,     // DstAddrMode,
+                          PAN_ID,                      // DstPANId,
+                          &deviceAddress,              // DstAddr,
+                          NULL                         // security
+                        );
+    call MCPS_DATA.request(
+                          &frame,                               // frame,
+                          strlen(payload),                      // payloadLength,
+                          0,                                    // msduHandle,
+                          TX_OPTIONS_INDIRECT | TX_OPTIONS_ACK  // TxOptions,
+                        ); 
+    call Leds.led1On();
+    call Led1Timer.startOneShot(12500U);
+  }
+
+  event void MLME_START.confirm(ieee154_status_t status) {
+    sendIndirectData();
+  }
+
+  event void DataTimer.fired(){
+    sendIndirectData();
+  }
+
+  event void Led1Timer.fired(){
+    call Leds.led1Off();
+  }
+
+  event void MCPS_DATA.confirm(
+                          message_t *msg,
+                          uint8_t msduHandle,
+                          ieee154_status_t status,
+                          uint32_t Timestamp
+                        )
+  {
+    if(status == IEEE154_TRANSACTION_EXPIRED){
+      call Leds.led0On();
+      call Led0Timer.startOneShot(125000U);
+      sendIndirectData();
+    }else if(status == SUCCESS){
+      call DataTimer.startOneShot(125000U);
+    }
+  }
+
+  event void Led0Timer.fired(){
+    call Leds.led0Off();
+  }
+
+  event message_t* MCPS_DATA.indication ( message_t* frame__ ){
+    return frame__;
+  }
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/device/Makefile b/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/device/Makefile
new file mode 100644 (file)
index 0000000..7ca4abd
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=TestIndirectDataDeviceAppC
+CFLAGS += -I$(shell pwd)/..
+include ../../../Makefile.include
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/device/TestIndirectDataDeviceAppC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/device/TestIndirectDataDeviceAppC.nc
new file mode 100644 (file)
index 0000000..ce3e780
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestIndirectDataDeviceAppC
+{
+} implementation {
+  components MainC, LedsC, Ieee802154NonBeaconEnabledC as MAC,
+             new Timer62500C() as Timer1, 
+             new Timer62500C() as Timer2;
+  components TestIndirectDataDeviceC as App;
+
+  MainC.Boot <- App;
+  App.MCPS_DATA -> MAC;
+  App.Leds -> LedsC;
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.PollTimer -> Timer1;
+  App.Led2Timer -> Timer2;
+  App.MLME_POLL -> MAC;
+
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/device/TestIndirectDataDeviceC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestIndirectData/device/TestIndirectDataDeviceC.nc
new file mode 100644 (file)
index 0000000..71108b0
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154.h"
+#include "app_profile.h"
+module TestIndirectDataDeviceC
+{
+  uses {
+    interface Boot;
+    interface MCPS_DATA;
+    interface MLME_RESET;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface MLME_POLL;
+    interface Leds;
+    interface Timer<T62500hz> as PollTimer;
+    interface Timer<T62500hz> as Led2Timer;
+  }
+} implementation {
+
+  void startApp();
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    if (status == IEEE154_SUCCESS)
+      startApp();
+  }
+
+  void startApp()
+  {
+    call MLME_SET.phyCurrentChannel(RADIO_CHANNEL);
+    call MLME_SET.macAutoRequest(FALSE);
+    call MLME_SET.macPANId(PAN_ID);
+    call MLME_SET.macCoordShortAddress(COORDINATOR_ADDRESS);  
+    call MLME_SET.macShortAddress(DEVICE_ADDRESS);
+    call PollTimer.startPeriodic(62500U); 
+  }
+
+  event void PollTimer.fired(){
+    // check the coordinator for outstanding transmissions
+    ieee154_address_t coordAdr;
+    coordAdr.shortAddress = COORDINATOR_ADDRESS;
+    call MLME_POLL.request  (
+                          ADDR_MODE_SHORT_ADDRESS,
+                          PAN_ID,
+                          coordAdr,
+                          NULL
+                        );
+  }
+
+  event void MLME_POLL.confirm    (
+                          ieee154_status_t status
+                        ){}
+
+  event void MCPS_DATA.confirm(
+                          message_t *msg,
+                          uint8_t msduHandle,
+                          ieee154_status_t status,
+                          uint32_t Timestamp
+                        ){}
+
+  event message_t* MCPS_DATA.indication ( message_t* frame__ ){
+    call Leds.led2On();
+    call Led2Timer.startOneShot(12500U);
+    return frame__;
+  }
+
+  event void Led2Timer.fired(){
+    call Leds.led2Off();
+  }
+
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/Makefile b/apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/Makefile
new file mode 100644 (file)
index 0000000..4feced1
--- /dev/null
@@ -0,0 +1,5 @@
+COMPONENT=TestPromiscuousAppC
+PFLAGS += -DPRINTF_BUFFER_SIZE=1000
+CFLAGS += -I$(TOSDIR)/lib/printf
+CFLAGS += -DIEEE154_SCAN_DISABLED -DIEEE154_BEACON_SYNC_DISABLED -DIEEE154_BEACON_TX_DISABLED -DIEEE154_RXENABLE_DISABLED -DIEEE154_ASSOCIATION_DISABLED -DIEEE154_DISASSOCIATION_DISABLED -DIEEE154_COORD_REALIGNMENT_DISABLED -DIEEE154_COORD_BROADCAST_DISABLED
+include ../../Makefile.include
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/README.txt b/apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/README.txt
new file mode 100644 (file)
index 0000000..743fa3a
--- /dev/null
@@ -0,0 +1,42 @@
+README for TestPromiscuous
+Author/Contact: Jan Hauer <hauer@tkn.tu-berlin.de>
+
+Description:
+
+In this application the node enables promiscuous mode, i.e. its radio is
+switched to receive mode and all incoming frames that pass the CRC check are
+signalled to the upper layer. The application uses the TinyOS printf library
+(tos/lib/printf) to output information on the MAC header fields and payload for
+every received frame over the serial port. The second (TelosB: green) LED is
+toggled whenever a frame is received.
+
+Criteria for a successful test:
+
+A successful test means that for every received frame LED1 is toggled
+and the java application outputs some text. To see this effect you need a
+second node sending a packet, for example, use the
+../../beacon-enabled/TestStartSync/coordinator application to send periodic
+beacon packets. In this case LED1 should toggle every half second and
+printf java client should output some text on the frame content.
+
+
+Tools: The printf java client in $TOSDIR/../apps/tests/TestPrintf
+
+Usage: 
+
+Install the application on a node
+
+    $ make <platform> install
+
+Start the printf client, e.g. 
+
+    $ java net.tinyos.tools.PrintfClient -comm serial@/dev/ttyUSBXXX:<platform>
+
+(http://docs.tinyos.net/ has a section on how to use the TinyOS printf library)
+
+Known bugs/limitations:
+
+- The timestamps for ACKs are incorrect
+
+$Id$
+
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/TestPromiscuousAppC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/TestPromiscuousAppC.nc
new file mode 100644 (file)
index 0000000..fd752f0
--- /dev/null
@@ -0,0 +1,52 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration TestPromiscuousAppC
+{
+} implementation {
+ components MainC, TestPromiscuousC as App, LedsC, 
+            Ieee802154NonBeaconEnabledC as MAC;
+
+  MainC.Boot <- App;
+  App.Leds -> LedsC;
+
+  App.MLME_RESET -> MAC;
+  App.MLME_SET -> MAC;
+  App.MLME_GET -> MAC;
+  App.MCPS_DATA -> MAC;
+  App.Frame -> MAC;
+  App.BeaconFrame -> MAC;
+  App.PromiscuousMode -> MAC;
+}
diff --git a/apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/TestPromiscuousC.nc b/apps/tests/tkn154/nonbeacon-enabled/TestPromiscuous/TestPromiscuousC.nc
new file mode 100644 (file)
index 0000000..8ffaa75
--- /dev/null
@@ -0,0 +1,158 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154.h"
+module TestPromiscuousC
+{
+  uses {
+    interface Boot;
+    interface MLME_RESET;
+    interface MLME_SET;
+    interface MLME_GET;
+    interface MCPS_DATA;
+    interface Leds;
+    interface IEEE154Frame as Frame;
+    interface IEEE154BeaconFrame as BeaconFrame;
+    interface SplitControl as PromiscuousMode;
+  }
+} implementation {
+
+  const char *m_frametype[] = {"Beacon", "Data","Acknowledgement","MAC command", "Unknown"};
+  const char *m_cmdframetype[] = {"unknown command", "Association request","Association response",
+    "Disassociation notification","Data request","PAN ID conflict notification",
+    "Orphan notification", "Beacon request", "Coordinator realignment", "GTS request"};
+
+  enum {
+    RADIO_CHANNEL = 26,
+  };
+
+  event void Boot.booted() {
+    call MLME_RESET.request(TRUE);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    call MLME_SET.phyCurrentChannel(RADIO_CHANNEL);
+    call PromiscuousMode.start();
+  }
+
+  event message_t* MCPS_DATA.indication (message_t* frame)
+  {
+    uint8_t i;
+    uint8_t *payload = call Frame.getPayload(frame);
+    uint8_t payloadLen = call Frame.getPayloadLength(frame);
+    uint8_t *header = call Frame.getHeader(frame);
+    uint8_t headerLen = call Frame.getHeaderLength(frame);
+    uint8_t SrcAddrMode, DstAddrMode;
+    uint8_t frameType, cmdFrameType;
+    ieee154_address_t SrcAddress, DstAddress;
+    uint16_t SrcPANId=0, DstPANId=0;
+
+    if (call Frame.hasStandardCompliantHeader(frame)){
+      frameType = call Frame.getFrameType(frame);
+      if (frameType > FRAMETYPE_CMD)
+        frameType = 4;
+      call Frame.getSrcPANId(frame, &SrcPANId);
+      call Frame.getDstPANId(frame, &DstPANId);
+      call Frame.getSrcAddr(frame, &SrcAddress);
+      call Frame.getDstAddr(frame, &DstAddress);
+      SrcAddrMode = call Frame.getSrcAddrMode(frame);
+      DstAddrMode = call Frame.getDstAddrMode(frame);
+
+      printf("\n");
+      printf("Frametype: %s", m_frametype[frameType]);
+      if (frameType == FRAMETYPE_CMD){
+        cmdFrameType = payload[0];
+        if (cmdFrameType > 9)
+          cmdFrameType = 0;
+        printf(" (%s)", m_cmdframetype[cmdFrameType]);
+      }
+      printf("\n");
+      printf("SrcAddrMode: %d\n", SrcAddrMode);
+      printf("SrcAddr: ");
+      if (SrcAddrMode == ADDR_MODE_SHORT_ADDRESS){
+        printf("0x%02X\n", SrcAddress.shortAddress);
+        printf("SrcPANId: 0x%02X\n", SrcPANId);
+      } else if (SrcAddrMode == ADDR_MODE_EXTENDED_ADDRESS){
+        for (i=0; i<8; i++)
+          printf("0x%02X ", ((uint8_t*) &(SrcAddress.extendedAddress))[i]);
+        printf("\n");
+        printf("SrcPANId: 0x%02X\n", SrcPANId);
+      } else printf("\n");
+      printf("DstAddrMode: %d\n", DstAddrMode);
+      printf("DstAddr: ");
+      if ( DstAddrMode == ADDR_MODE_SHORT_ADDRESS){
+        printf("0x%02X\n", DstAddress.shortAddress);
+        printf("DestPANId: 0x%02X\n", DstPANId);
+      } else if  ( DstAddrMode == ADDR_MODE_EXTENDED_ADDRESS) {
+        for (i=0; i<8; i++)
+          printf("0x%02X ", ((uint8_t*) &(DstAddress.extendedAddress))[i]);
+        printf("\n");    
+        printf("DestPANId: 0x%02X\n", DstPANId);
+      } else printf("\n");
+
+      printf("DSN: %d\n", call Frame.getDSN(frame));
+      printf("MHRLen: %d\n", headerLen);
+      printf("MHR: ");
+      for (i=0; i<headerLen; i++){
+        printf("0x%02X ", header[i]);
+      }
+      printf("\n");      
+      printf("PayloadLen: %d\n", payloadLen);
+      printf("Payload: ");
+      for (i=0; i<payloadLen; i++){
+        printf("0x%02X ", payload[i]);
+      }
+      printf("\n");
+      printf("MpduLinkQuality: %d\n", call Frame.getLinkQuality(frame));
+
+      printf("Timestamp: ");
+      if (call Frame.isTimestampValid(frame))
+        printf("%ld\n", call Frame.getTimestamp(frame));
+      else
+        printf("INVALID\n");
+      printfflush(); 
+    }
+    call Leds.led1Toggle();
+    return frame;
+  }
+
+  event void MCPS_DATA.confirm( message_t *msg, uint8_t msduHandle, ieee154_status_t status, uint32_t Timestamp){}
+  event void PromiscuousMode.startDone(error_t error) 
+  {
+    printf("\n*** Radio is now in promiscuous mode, listening on channel %d ***\n", RADIO_CHANNEL);
+    printfflush(); 
+  }
+  event void PromiscuousMode.stopDone(error_t error) {}
+}
index 063fa3a0ad521736d07f262fb7a75714cfbe62c5..5497f40bcfeb964b241fae31d212ec3ec5e123df 100644 (file)
  */
 
 /**
+ * BaseStation is a reimplementation of the standard BaseStation application using
+ * the TOSThreads thread library.  It transparently forwards any AM messages it
+ * receives from its radio interface to its serial interface and vice versa.
+ *
+ * <p>On the serial link, BaseStation sends and receives simple active
+ * messages (not particular radio packets): on the radio link, it
+ * sends radio active messages, whose format depends on the network
+ * stack being used. BaseStation will copy its compiled-in group ID to
+ * messages moving from the serial link to the radio, and will filter
+ * out incoming radio messages that do not contain that group ID.</p>
+ *
+ * <p>BaseStation includes queues in both directions, with a guarantee
+ * that once a message enters a queue, it will eventually leave on the
+ * other interface. The queues allow the BaseStation to handle load
+ * spikes.</p>
+ *
+ * <p>BaseStation acknowledges a message arriving over the serial link
+ * only if that message was successfully enqueued for delivery to the
+ * radio link.</p>
+ *
+ * <p>The LEDS are programmed to toggle as follows:</p>
+ * <ul>
+ * <li><b>LED0:</b> Message bridged from serial to radio</li>
+ * <li><b>LED1:</b> Message bridged from radio to serial</li>
+ * <li><b>LED2:</b> Dropped message due to queue overflow in either direction</li>
+ * </ul>
+ *
  * @author Kevin Klues <klueska@cs.stanford.edu>
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
index 46f26a53f8df13d2eeca75264cb2dd1acae1ac77..09ca717efcb67ab987e89e2091ecb0852d0ac2f0 100644 (file)
  */
 
 /**
+ * BaseStation is a reimplementation of the standard BaseStation application using
+ * the TOSThreads thread library.  It transparently forwards any AM messages it
+ * receives from its radio interface to its serial interface and vice versa. 
+ *
+ * <p>On the serial link, BaseStation sends and receives simple active
+ * messages (not particular radio packets): on the radio link, it
+ * sends radio active messages, whose format depends on the network
+ * stack being used. BaseStation will copy its compiled-in group ID to
+ * messages moving from the serial link to the radio, and will filter
+ * out incoming radio messages that do not contain that group ID.</p>
+ *
+ * <p>BaseStation includes queues in both directions, with a guarantee
+ * that once a message enters a queue, it will eventually leave on the
+ * other interface. The queues allow the BaseStation to handle load
+ * spikes.</p>
+ *
+ * <p>BaseStation acknowledges a message arriving over the serial link
+ * only if that message was successfully enqueued for delivery to the
+ * radio link.</p>
+ *
+ * <p>The LEDS are programmed to toggle as follows:</p>
+ * <ul>
+ * <li><b>LED0:</b> Message bridged from serial to radio</li>
+ * <li><b>LED1:</b> Message bridged from radio to serial</li>
+ * <li><b>LED2:</b> Dropped message due to queue overflow in either direction</li>
+ * </ul>
+ *
  * @author Kevin Klues <klueska@cs.stanford.edu>
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
@@ -105,12 +132,4 @@ implementation
   SerialReceiveRadioSendP.SendAMPacket -> BlockingRadioActiveMessageC;             
   SerialReceiveRadioSendP.BlockingReceiveAny -> BlockingSerialActiveMessageC.BlockingReceiveAny;
   SerialReceiveRadioSendP.BlockingAMSend -> BlockingRadioActiveMessageC;
-  
-  components ActiveMessageC, SerialActiveMessageC;
-  BlockingRadioActiveMessageC.Receive -> ActiveMessageC.Receive;
-  BlockingRadioActiveMessageC.Snoop -> ActiveMessageC.Snoop;
-  BlockingRadioActiveMessageC.AMSend -> ActiveMessageC.AMSend;
-  
-  BlockingSerialActiveMessageC.Receive -> SerialActiveMessageC.Receive;
-  BlockingSerialActiveMessageC.AMSend -> SerialActiveMessageC.AMSend;
 }
index 268978d6ea90fcacc2db81419b41186bfbddec38..987aa6bc6ffc088d875cae0adcf83fc4951d8890 100644 (file)
  */
 
 /**
+ * BaseStation is a reimplementation of the standard BaseStation application using
+ * the TOSThreads thread library.  It transparently forwards any AM messages it
+ * receives from its radio interface to its serial interface and vice versa.
+ *
+ * <p>On the serial link, BaseStation sends and receives simple active
+ * messages (not particular radio packets): on the radio link, it
+ * sends radio active messages, whose format depends on the network
+ * stack being used. BaseStation will copy its compiled-in group ID to
+ * messages moving from the serial link to the radio, and will filter
+ * out incoming radio messages that do not contain that group ID.</p>
+ *
+ * <p>BaseStation includes queues in both directions, with a guarantee
+ * that once a message enters a queue, it will eventually leave on the
+ * other interface. The queues allow the BaseStation to handle load
+ * spikes.</p>
+ *
+ * <p>BaseStation acknowledges a message arriving over the serial link
+ * only if that message was successfully enqueued for delivery to the
+ * radio link.</p>
+ *
+ * <p>The LEDS are programmed to toggle as follows:</p>
+ * <ul>
+ * <li><b>LED0:</b> Message bridged from serial to radio</li>
+ * <li><b>LED1:</b> Message bridged from radio to serial</li>
+ * <li><b>LED2:</b> Dropped message due to queue overflow in either direction</li>
+ * </ul>
+ *
  * @author Kevin Klues <klueska@cs.stanford.edu>
  */
 
index 9c3c246da07b657f05305e5323be9343113377ba..11c1a6224d799d781e89264fe1fd5bf67970db2e 100644 (file)
@@ -13,7 +13,7 @@ forwarding, LED1 is toggled.  If there are any errors, LED2 is toggled.
 To run this application install it on a mote via the command:
   make <platform> threads install.45
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 Installing with NODE_ID 45 (i.e. AM_ADDRESS 45) is just to verify that the
 application forwards packets with an arbitrarily chosen id, which it should.
index d95f71926d22d518532cb13c99769f16db086aeb..850583121233b16ef5b74cc56dd9afbe7d7b4f0b 100644 (file)
  */
  
 /**
+ * Blink is a simple application used to test the basic functionality of
+ * TOSThreads.
+ *
+ * Upon a successful burn, you should see LED0 flashing with a period of every
+ * 200ms, and LED1 and LED2 flashing in unison with a period of 1000ms.
+ *
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
index e4027006baa98a6274623ad953fe94cc349ff335..ed6fcb7d2fbefe2815e5211d45c0210ee8b63ddd 100644 (file)
  */
  
 /**
+ * Blink is a simple application used to test the basic functionality of
+ * TOSThreads.
+ *
+ * Upon a successful burn, you should see LED0 flashing with a period of every
+ * 200ms, and LED1 and LED2 flashing in unison with a period of 1000ms.
+ *
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
index b8f240d916c0834ef660c5a8de7301effd0be3a4..31ed5dcb99020af67c7671757075965e766bbe62 100644 (file)
@@ -10,7 +10,7 @@ TOSThreads.
 You can install Blink on a mote via the following command:
   make <platform> threads install
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 Upon a successful burn, you should see LED0 flashing with a period of every
 200ms, and LED1 and LED2 flashing in unison with a period of 1000ms.
diff --git a/apps/tosthreads/apps/Blink_DynamicThreads/BlinkAppC.nc b/apps/tosthreads/apps/Blink_DynamicThreads/BlinkAppC.nc
new file mode 100644 (file)
index 0000000..7b2dc31
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * Blink is a simple application used to test the basic functionality of
+ * TOSThreads using dynamic threads rather than static threads.
+ *
+ * Upon a successful burn, you should see LED0 flashing with a period of every
+ * 200ms, and LED1 and LED2 flashing in unison with a period of 1000ms.
+ *
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+configuration BlinkAppC {}
+
+implementation {
+  components MainC,
+             BlinkC,
+             LedsC,
+             DynamicThreadC;
+
+  BlinkC.Boot -> MainC;
+  
+  BlinkC.Leds -> LedsC;
+  BlinkC.DynamicThread -> DynamicThreadC;
+}
diff --git a/apps/tosthreads/apps/Blink_DynamicThreads/BlinkC.nc b/apps/tosthreads/apps/Blink_DynamicThreads/BlinkC.nc
new file mode 100644 (file)
index 0000000..49b274e
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * Blink is a simple application used to test the basic functionality of
+ * TOSThreads using dynamic threads rather than static threads.
+ *
+ * Upon a successful burn, you should see LED0 flashing with a period of every
+ * 200ms, and LED1 and LED2 flashing in unison with a period of 1000ms.
+ *
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+module BlinkC {
+  uses {
+    interface Boot;
+    interface Leds;
+    interface DynamicThread;
+  }
+}
+
+implementation {
+  tosthread_t blink1;
+  tosthread_t blink2;
+  tosthread_t blink3;
+  uint16_t a1 = 1;
+  uint16_t a2 = 2;
+  uint16_t a3 = 3;
+
+  void blink_thread(void* arg)
+  {
+    uint16_t *a = (uint16_t *)arg;
+    
+    for (;;) {
+      if (*a == 1) {
+        call Leds.led0Toggle();
+        call DynamicThread.sleep(200);
+      } else if (*a == 2) {
+        call Leds.led1Toggle();
+        call DynamicThread.sleep(1000);
+      } else if (*a == 3) {
+        call Leds.led2Toggle();
+        call DynamicThread.sleep(1000);
+      }
+    }
+  }
+    
+  event void Boot.booted()
+  {
+    call DynamicThread.create(&blink1, blink_thread, &a1, 500);
+    call DynamicThread.create(&blink2, blink_thread, &a2, 500);
+    call DynamicThread.create(&blink3, blink_thread, &a3, 500);
+  }
+}
diff --git a/apps/tosthreads/apps/Blink_DynamicThreads/Makefile b/apps/tosthreads/apps/Blink_DynamicThreads/Makefile
new file mode 100644 (file)
index 0000000..7f9fb6b
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=BlinkAppC
+
+include $(MAKERULES)
diff --git a/apps/tosthreads/apps/Blink_DynamicThreads/README b/apps/tosthreads/apps/Blink_DynamicThreads/README
new file mode 100644 (file)
index 0000000..d5cd5c9
--- /dev/null
@@ -0,0 +1,21 @@
+README for TOSThreads Blink_DynamicThreads
+Author/Contact: tinyos-help@millennium.berkeley.edu
+Author: Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+
+Description:
+
+Blink_DynamicThreads is the dynamic-thread version of Blink.
+
+You can install Blink_DynamicThread on a mote via the following command:
+  make <platform> threads install
+  
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
+
+Upon a successful burn, you should see LED0 flashing with a period of every
+200ms, and LED1 and LED2 flashing in unison with a period of 1000ms.
+
+Tools:
+  None.
+
+Known bugs/limitations:
+  None.
index 0cd7d74e79b3908fc79a54001a2444517cde6c7a..d8ff0f9fa640bc0fd54df317498434c480f1ed41 100644 (file)
@@ -15,7 +15,7 @@ You can install Bounce on a mote via the following command:
   make <platform> threads install.0
   make <platform> threads install.1
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 Three different threads run, and each contains an infinite loop that first sends
 a message and then waits to receive a message before returning to the top of the
index ddfe8e369f67bd0b2b48261494580093f9d1b708..e0eb96771bad670aaba6c53015f69d90338326cc 100644 (file)
@@ -12,7 +12,7 @@ You can install RadioStress on a mote via the following command:
   make <platform> threads install.0
   make <platform> threads install.1
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 The application burned with NODE_ID 0 will be programmed as a receiver and will
 wait for messages from the sender programmed with NODE_ID 1.  In the case of the
index 4d9ca1d0f71d51554afab084083164d2d939ae9e..ba7d7d3de19dfa035162330c16e1212e11455ba8 100644 (file)
@@ -2,7 +2,7 @@ COMPONENT=TestBasicsbSensorsAppC
 CFLAGS += -I$(TOSDIR)/sensorboards/basicsb
 CFLAGS += -I$(TOSDIR)/lib/tosthreads/sensorboards/basicsb
 
-ifneq ($(filter mica2 micaz iris clean,$(MAKECMDGOALS)),)
+ifneq ($(filter mica2 mica2dot micaz iris clean,$(MAKECMDGOALS)),)
   include $(MAKERULES)
 else
 %:
index d1e3aca7aeab246b3e9dbf1bcac1edcd845b00db..0bc9f115e7ae53710b26ed6da44f5af4962468a6 100644 (file)
  */
  
 /**
+ * This application is used to test the threaded version of the API for accessing
+ * sensors on the basicsb sensor board.
+ * 
+ * This application simply takes sensor readings in an infinite loop from the
+ * Photo and Temperature sensors on the basicsb sensor board and forwards them
+ * over the serial interface.  Upon successful transmission, LED0 is toggled.
+ * 
+ * A successful test will result in the TestBasicsbSensors mote constantly
+ * flickering LED0. Additionally, messages containing the sensor readings should
+ * be forwarded over the serial interface as verified by running the following
+ * for the platform of interest:
+ *   java net.tinyos.tools.Listen -comm serial@/dev/ttyUSBXXX:<baud_rate>
+ * 
+ * Once this java application is running, you should see output containing the
+ * sensor readings being streamed to your terminal.
+ *
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
@@ -37,7 +53,7 @@ configuration TestBasicsbSensorsAppC {
 }
 implementation {
   components MainC, TestBasicsbSensorsC;
-  components new ThreadC(100) as MainThread;
+  components new ThreadC(125) as MainThread;
   
   components new BlockingPhotoC();
   components new BlockingTempC();
index f43e886860d5f72bfaf234941c2a82270bc0e523..d9e633737b572acc1003ddbb2d60f88304def748 100644 (file)
@@ -67,6 +67,7 @@ implementation {
       while( call Temp.read(&(readings->temp)) != SUCCESS );
       while( call BlockingAMSend.send(AM_BROADCAST_ADDR, &msg, sizeof(sensor_readings_t)) != SUCCESS );
       call Leds.led0Toggle();
+      call MainThread.sleep(512);
     }
   }
 }
index b29338571c377214155bc94ee37455b7d2fa5f22..3d43d2a2194c6bc713bba420fc60614ecc88523f 100644 (file)
 */
 
 /**
+ * This application is used to test the threaded version of the API for performing
+ * block storage.
+ * 
+ * This application first checks the size of the block storage volume, and
+ * erases it. Then, it randomly writes records, followed by a verification
+ * with read.
+ * 
+ * Successful running of this application results in LED0 being ON
+ * throughout the duration of the erase, write, and read sequence. Finally,
+ * if all tests pass, LED1 is turned ON. Otherwise, all three LEDs are
+ * turned ON to indicate problems.
+ *
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
 
index 316cbece9354112837c1a8083fa938e4c2298d30..81b191b0cc4aec65e5b1532e5f03649fe3c027a5 100644 (file)
 */
 
 /**
+ * This application is used to test the threaded version of the API for performing
+ * block storage.
+ * 
+ * This application first checks the size of the block storage volume, and
+ * erases it. Then, it randomly writes records, followed by a verification
+ * with read.
+ * 
+ * Successful running of this application results in LED0 being ON
+ * throughout the duration of the erase, write, and read sequence. Finally,
+ * if all tests pass, LED1 is turned ON. Otherwise, all three LEDs are
+ * turned ON to indicate problems.
+ *
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
 
index 32c26f545250d37d036ddcf9f5ed92236ba6e522..509e4d6cfd7283586dd1223f2a6f5c395581863e 100644 (file)
@@ -14,7 +14,7 @@ application.
 You can install TestCollection on a mote via the following command:
   make <platform> threads install
 
-Valid platforms are currently: tmote, telosb, mica2, micaz and iris
+Valid platforms are currently: tmote, telosb, mica2, micaz, iris, and epic
 
 At least two motes must be used by this application, with one of them installed
 as a base station.  Base station motes can be created by installing them with
@@ -27,7 +27,7 @@ All other nodes can be installed with arbitrary NODE_IDs.
   make <platform> threads install.123
 
 Successful running of this application is verified by all NON-base station motes
-periodically flashing LED0 upon sending a message, and the base station mote,
+periodically flashing LED1 upon sending a message, and the base station mote,
 flashing LED2 upon successful reception of a message.  Additionally, correct
 operation should be verified by running the java tool described in the following
 section.
@@ -40,12 +40,12 @@ TestCollection/java subdirectory and type:
 
   make
   java net.tinyos.sf.SerialForwarder -comm serial@<serial port>:<baud_rate>
-  # e.g., java net.tinyps.sf.SerialForwarder -comm serial@/dev/ttyUSB0:mica2
-  # or java net.tinyps.sf.SerialForwarder -comm serial@COM2:telosb
+  # e.g., java net.tinyos.sf.SerialForwarder -comm serial@/dev/ttyUSB0:mica2
+  # or java net.tinyos.sf.SerialForwarder -comm serial@COM2:telosb
   ./run
 
 NOTE::  The baud rate 57600 must be used telos based motes, as its configuration
-has been changed to work with this baud rate when compiled for tosthreads. I.e.
+has been changed to work with this baud rate when compiled for TOSThreads. I.e.
 DO NOT just substitute 'telosb' or 'tmote' for <baud_rate> above.  Explicitly
 set it to 57600.
 
index 4db9f298a37df58e0f12fef129879cdc980f1b9f..f248d97084be500577a3a9f968c628aea1a870c8 100644 (file)
  * THE POSSIBILITY OF SUCH DAMAGE.
 */
 
-/*
+/**
+ * TestCollection is a reimplementation of the Multihop Oscilloscope application
+ * using TOSThreads. It periodically samples a universal software-based SineSensor
+ * and broadcasts a message every few readings. These readings can be displayed by
+ * the Java "Oscilloscope" application found in the the TestCollection/java
+ * subdirectory. The sampling rate starts at 4Hz, but can be changed from the Java
+ * application.
+ * 
+ * At least two motes must be used by this application, with one of them installed
+ * as a base station.  Base station motes can be created by installing them with
+ * NODE_ID % 500 == 0.
+ *   i.e. make <platform> threads install.0
+ *        make <platform> threads install.500
+ *        make <platform> threads install.1000
+ * 
+ * All other nodes can be installed with arbitrary NODE_IDs.
+ *   make <platform> threads install.123
+ * 
+ * Successful running of this application is verified by all NON-base station motes
+ * periodically flashing LED1 upon sending a message, and the base station mote,
+ * flashing LED2 upon successful reception of a message.  Additionally, correct
+ * operation should be verified by running the java tool described in the following
+ * section.
+ *
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
 
index 46ed34e632091de830729145984a6b64dd068e2e..51c9bdb03cb8fcb35f795824b83ed1d068177ef6 100644 (file)
  * THE POSSIBILITY OF SUCH DAMAGE.
 */
 
-/*
+/**
+ * TestCollection is a reimplementation of the Multihop Oscilloscope application
+ * using TOSThreads. It periodically samples a universal software-based SineSensor
+ * and broadcasts a message every few readings. These readings can be displayed by
+ * the Java "Oscilloscope" application found in the the TestCollection/java
+ * subdirectory. The sampling rate starts at 4Hz, but can be changed from the Java
+ * application.
+ * 
+ * At least two motes must be used by this application, with one of them installed
+ * as a base station.  Base station motes can be created by installing them with
+ * NODE_ID % 500 == 0.
+ *   i.e. make <platform> threads install.0
+ *        make <platform> threads install.500
+ *        make <platform> threads install.1000
+ * 
+ * All other nodes can be installed with arbitrary NODE_IDs.
+ *   make <platform> threads install.123
+ * 
+ * Successful running of this application is verified by all NON-base station motes
+ * periodically flashing LED1 upon sending a message, and the base station mote,
+ * flashing LED2 upon successful reception of a message.  Additionally, correct
+ * operation should be verified by running the java tool described in the following
+ * section.
+ *
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
 
diff --git a/apps/tosthreads/apps/TestJoin/Makefile b/apps/tosthreads/apps/TestJoin/Makefile
new file mode 100644 (file)
index 0000000..3cb1212
--- /dev/null
@@ -0,0 +1,3 @@
+COMPONENT=TestJoinAppC
+
+include $(MAKERULES)
diff --git a/apps/tosthreads/apps/TestJoin/README b/apps/tosthreads/apps/TestJoin/README
new file mode 100644 (file)
index 0000000..2f45af0
--- /dev/null
@@ -0,0 +1,32 @@
+README for TOSThreads TestJoin
+Author/Contact: tinyos-help@millennium.berkeley.edu
+Author: Kevin Klues <klueska@cs.stanford.edu>
+
+Description:
+
+TestJoin is a simple application used to test the basic functionality of
+the join() system call for waiting on a set of threads in a TOSThreads 
+based application.
+
+You can install TestJoin on a mote via the following command:
+  make <platform> threads install
+  
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
+
+Upon a successful burn, you should see all LEDs toggle in the following pattern,
+repeating every 8 seconds:
+
+0s: (110) LED0  ON, LED1  ON, LED2 OFF
+1s: (000) LED0 OFF, LED1 OFF, LED2 OFF
+2s: (010) LED0 OFF, LED1  ON, LED2 OFF
+3s: (000) LED0 OFF, LED1 OFF, LED2 OFF
+4s: (111) LED0  ON, LED1  ON, LED2 ON
+5s: (001) LED0 OFF, LED1 OFF, LED2 ON
+6s: (011) LED0 OFF, LED1  ON, LED2 ON
+7s: (001) LED0 OFF, LED1 OFF, LED2 ON
+
+Tools:
+  None.
+
+Known bugs/limitations:
+  None.
diff --git a/apps/tosthreads/apps/TestJoin/TestJoinAppC.nc b/apps/tosthreads/apps/TestJoin/TestJoinAppC.nc
new file mode 100644 (file)
index 0000000..9b875e6
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * TestJoin is a simple application used to test the basic functionality of
+ * the join() system call for waiting on a set of threads in a TOSThreads 
+ * based application.
+ * 
+ * Upon a successful burn, you should see all LEDs toggle in the following pattern,
+ * repeating every 8 seconds:
+ * 
+ * 0s: (110) LED0  ON, LED1  ON, LED2 OFF  <br>
+ * 1s: (000) LED0 OFF, LED1 OFF, LED2 OFF  <br>
+ * 2s: (010) LED0 OFF, LED1  ON, LED2 OFF  <br>
+ * 3s: (000) LED0 OFF, LED1 OFF, LED2 OFF  <br>
+ * 4s: (111) LED0  ON, LED1  ON, LED2  ON  <br>
+ * 5s: (001) LED0 OFF, LED1 OFF, LED2  ON  <br>
+ * 6s: (011) LED0 OFF, LED1  ON, LED2  ON  <br>
+ * 7s: (001) LED0 OFF, LED1 OFF, LED2  ON  <br>
+ *
+ * @author Kevin Klues (klueska@cs.stanford.edu)
+ */
+
+configuration TestJoinAppC {
+}
+implementation {
+  components MainC, TestJoinC,  LedsC;
+  components new ThreadC(100) as NullThread;
+  components new ThreadC(100) as TinyThread0;
+  components new ThreadC(100) as TinyThread1;
+
+  MainC.Boot <- TestJoinC;
+  TestJoinC.NullThread -> NullThread;
+  TestJoinC.TinyThread0 -> TinyThread0;
+  TestJoinC.TinyThread1 -> TinyThread1; 
+
+  TestJoinC.Leds -> LedsC;
+}
+
diff --git a/apps/tosthreads/apps/TestJoin/TestJoinC.nc b/apps/tosthreads/apps/TestJoin/TestJoinC.nc
new file mode 100644 (file)
index 0000000..ada0333
--- /dev/null
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * TestJoin is a simple application used to test the basic functionality of
+ * the join() system call for waiting on a set of threads in a TOSThreads 
+ * based application.
+ * 
+ * Upon a successful burn, you should see all LEDs toggle in the following pattern,
+ * repeating every 8 seconds:
+ * 
+ * 0s: (110) LED0  ON, LED1  ON, LED2 OFF  <br>
+ * 1s: (000) LED0 OFF, LED1 OFF, LED2 OFF  <br>
+ * 2s: (010) LED0 OFF, LED1  ON, LED2 OFF  <br>
+ * 3s: (000) LED0 OFF, LED1 OFF, LED2 OFF  <br>
+ * 4s: (111) LED0  ON, LED1  ON, LED2  ON  <br>
+ * 5s: (001) LED0 OFF, LED1 OFF, LED2  ON  <br>
+ * 6s: (011) LED0 OFF, LED1  ON, LED2  ON  <br>
+ * 7s: (001) LED0 OFF, LED1 OFF, LED2  ON  <br>
+ *
+ * @author Kevin Klues (klueska@cs.stanford.edu)
+ */
+
+module TestJoinC {
+  uses {
+    interface Boot;
+    interface Thread as NullThread;
+    interface Thread as TinyThread0;
+    interface Thread as TinyThread1;
+    interface Leds;
+  }
+}
+
+implementation {
+  event void Boot.booted() {
+    call NullThread.start(NULL);
+  }
+
+  event void NullThread.run(void* arg) {
+    for(;;){
+      call TinyThread0.start(NULL);
+      call TinyThread1.start(NULL);
+      call TinyThread0.join();
+      call TinyThread1.join();
+      call Leds.led2Toggle();
+    }
+  }  
+  event void TinyThread0.run(void* arg) {
+    int i;
+    for(i=0; i<2; i++){
+      call Leds.led0Toggle();
+      call TinyThread0.sleep(1000);
+    }
+  }
+  event void TinyThread1.run(void* arg) {
+    int i;
+    for(i=0; i<4; i++){ 
+      call Leds.led1Toggle();
+      call TinyThread1.sleep(1000);
+    }
+  }
+}
index 60370341e5891bfc28d5f1c0e8345eaf174831df..fa2ddb339dfc2bde1537bcdb761a639c536b7da2 100644 (file)
@@ -11,10 +11,11 @@ prints.
 You can install TestPrintf on a mote via the following command:
   make <platform> threads install
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 Once burned on a mote, the java based PrintfClient must be ran to verify
-proper operation of the application.
+proper operation of the application. For example, to connect PrintfClient
+to a mote over a USB serial port:
   java net.tinyos.tools.PrintfClient -comm serial@/dev/ttyUSBXXX:<baud_rate>
   
 NOTE::  The baud rate 57600 must be used telos based motes, as its configuration
index e9d8d1ac1d60ba096fd3bc2f79d3541adf9f26dc..eeb6d7d71fcf47f07a265ed7aa4aa5d7c5508017 100644 (file)
  */
  
 /**
+ * This application tests the operation of the Printf client in TOSThreads.  It
+ * continuously prints the value of a counter starting at 0, increasing as it
+ * prints.
+ * 
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
index 904a3919ad5c845ed29c00ad4915d4f14b692644..3f308a664bdd0b9d24b166342db747bdee1f6c80 100644 (file)
  */
  
 /**
+ * This application tests the operation of the Printf client in TOSThreads.  It
+ * continuously prints the value of a counter starting at 0, increasing as it
+ * prints.
+ * 
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
index d70629e12194a2627b09f43adf82739ff0941c1e..50e6386c7d8ad09a245e1e40f6164e3c3e09b0b7 100644 (file)
@@ -10,7 +10,7 @@ the software based SineSensor usable by any platform for demonstration purposes.
 You can install TestSineSensor on a mote via the following command:
   make <platform> threads install
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 This application simply takes sensor readings in an infinite loop from the
 SineSensor and forwards them over the serial interface.  Upon successful
index d601e09ea40baaf61506437613746bc4d1d44575..926a68090718db89ba4f5e7d95603d845941d5c6 100644 (file)
  */
  
 /**
+ * This application is used to test the threaded version of the API for accessing
+ * the software based SineSensor usable by any platform for demonstration purposes.
+ * 
+ * This application simply takes sensor readings in an infinite loop from the
+ * SineSensor and forwards them over the serial interface.  Upon successful
+ * transmission, LED0 is toggled.
+ *
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
index f3a277739157fb06432a87a676946159b4aa01fe..cb97ecf893d63135640886e1967d66e7a8f1eb2e 100644 (file)
  */
  
 /**
+ * This application is used to test the threaded version of the API for accessing
+ * the software based SineSensor usable by any platform for demonstration purposes.
+ * 
+ * This application simply takes sensor readings in an infinite loop from the
+ * SineSensor and forwards them over the serial interface.  Upon successful
+ * transmission, LED0 is toggled.
+ *
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
index 6aa49538bff9c5c4dc1661835f007b4f2f46d7ba..5d421a3fee429e184188ab9bfa30f0966c330a1f 100644 (file)
  */
 
 /**
- * Base station implementation using tosthreads
+ * BaseStation is a reimplementation of the standard BaseStation application using
+ * the TOSThreads thread library.  It transparently forwards any AM messages it
+ * receives from its radio interface to its serial interface and vice versa.
+ *
+ * <p>On the serial link, BaseStation sends and receives simple active
+ * messages (not particular radio packets): on the radio link, it
+ * sends radio active messages, whose format depends on the network
+ * stack being used. BaseStation will copy its compiled-in group ID to
+ * messages moving from the serial link to the radio, and will filter
+ * out incoming radio messages that do not contain that group ID.</p>
+ *
+ * <p>BaseStation includes queues in both directions, with a guarantee
+ * that once a message enters a queue, it will eventually leave on the
+ * other interface. The queues allow the BaseStation to handle load
+ * spikes.</p>
+ *
+ * <p>BaseStation acknowledges a message arriving over the serial link
+ * only if that message was successfully enqueued for delivery to the
+ * radio link.</p>
+ *
+ * <p>The LEDS are programmed to toggle as follows:</p>
+ * <ul>
+ * <li><b>LED0:</b> Message bridged from serial to radio</li>
+ * <li><b>LED1:</b> Message bridged from radio to serial</li>
+ * <li><b>LED2:</b> Dropped message due to queue overflow in either direction</li>
+ * </ul>
  *
  * @author Kevin Klues <klueska@cs.stanford.edu>
  */
index 66ef052f2246f50dee879b94fb3808a865cd6964..f0a5492e6d8076d4dccd0da9b552bc78c3d1125a 100644 (file)
@@ -36,7 +36,7 @@ leds rapidly.  Additionally, messages should be forwarded over the serial interf
 as verified by running the following for the platform of interest:
   java net.tinyos.tools.Listen -comm serial@/dev/ttyUSBXXX:<baud_rate>
   
-NOTE::  The baud rate 57600 must be used telos based motes, as its configuration
+NOTE:  The baud rate 57600 must be used telos based motes, as its configuration
 has been changed to work with this baud rate when compiled for tosthreads. I.e.
 DO NOT just substitute 'telosb' or 'tmote' for <baud_rate> above.  Explicitly
 set it to 57600.
index bcbeee06dd975d41c48ad96d4b7758015ceba701..c9e733be06d5f8ac194770a7d71099f2e7d3f78e 100644 (file)
  */
  
 /**
+ * Blink is a simple application used to test the basic functionality of
+ * TOSThreads.
+ *
+ * Upon a successful burn, you should see LED0 flashing with a period of every
+ * 200ms, and LED1 and LED2 flashing in unison with a period of 1000ms.
+ *
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
index 853f0ce136f2a6dbe74930a72d509005d58e073b..2321f41c5766b4a7eff6816c623041390d5c7376 100644 (file)
@@ -10,7 +10,7 @@ TOSThreads.
 You can install Blink on a mote via the following command:
   make <platform> cthreads install
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 Upon a successful burn, you should see LED0 flashing with a period of every
 200ms, and LED1 and LED2 flashing in unison with a period of 1000ms.
index 2d2b34eb5806655814ba386092b233e554125933..f048403580ebc26bae3d13473fb3b9424dbfe0fd 100644 (file)
 */
 
 /**
+ * This application is derived from a similar application in the TinyThread 
+ * implementation by William P. McCartney from Cleveland State University (2006)
+ * 
+ * This application stresses the operation of the thread based AM commands for
+ * packet transmission and reception.  To run this application you will need to
+ * burn it on one mote with NODE_ID 0, and a second mote with NODE_ID 1. 
+ * 
+ * Three different threads run that each contain an infinite loop that first sends
+ * a message and then waits to receive a message before returning to the top of the
+ * loop. After each message reception, one of the onboard LEDs is toggled to
+ * indicate that it was received. Thread 0 blinks LED0, thread 1 blinks LED1, and
+ * thread 2 blinks LED2. The three threads run independently, and three different
+ * messages are bounced back and forth between the two motes in an unsynchronized
+ * fashion.  In contrast to the more complicated Bounce application found in the
+ * normal nesC threads version of this application, once a thread receives a
+ * message it will immediately flip on its LED instead of waiting on a Barrier and
+ * synchronizing the LEDs to come on only once messages have been received from all
+ * threads.  In this way, messages are bounced back and forth between the two motes
+ * in an asynchronous fashion, and LEDS are toggled immediately upon message
+ * reception..  
+ * 
+ * Successful running of this application results in each LED bouncing back and
+ * forth between each mote independent of one another.  This will continue in an
+ * finite loop forever.
+ *  
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
 
index 7bedfdecef040ba1c6f7968878246e703aaeb716..2a5c010028e474e7dc9fad5f3e4388a3bab85929 100644 (file)
@@ -15,7 +15,7 @@ You can install Bounce on a mote via the following command:
   make <platform> cthreads install.0
   make <platform> cthreads install.1
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 Three different threads run that each contain an infinite loop that first sends
 a message and then waits to receive a message before returning to the top of the
index 889ffabe149ed56aed77afb9a45ac70eb6ff0fc4..87bbde51ca4b98205bdf1f45ad83ff271e0f2bcc 100644 (file)
 */
 
 /**
+ * Null is an empty skeleton application for testing the basic compilation and
+ * runtime of a c-based tosthreads application.  It is useful to test that the build
+ * environment is functional in its most minimal sense, i.e., you can correctly
+ * compile an application. It is also useful to test the minimum power consumption
+ * of a node when it has absolutely no interrupts or resources active.
+ *
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
 
index c568d2dc0f4139d38356e8cc1ebb74119c07cacf..ec0740967a1524ffe51cc7ec71f4c66e93589f6a 100644 (file)
@@ -1,15 +1,16 @@
 README for TOSTHREADS Null
 Author/Contact: tinyos-help@millennium.berkeley.edu
-Author: Kevin Klues <klueska@cs.stanford.edu>
+Author: Kevin Klues <klueska@cs.berkeley.edu>
 
 Description:
 
 Null is an empty skeleton application for testing the basic compilation and
-runtime of a c-based tosthreads application.  It is useful to test that the build
-environment is functional in its most minimal sense, i.e., you can correctly
+runtime of a c-based tosthreads application.  It is useful to test that the build environment is functional in its most minimal sense, i.e., you can correctly
 compile an application. It is also useful to test the minimum power consumption
 of a node when it has absolutely no interrupts or resources active.
 
+Successful running of this application is that it simply compiles and installs.  No LEDs should be flashed.
+
 Tools:
   None.
 
index a6263dffb67a20aa83dc0486d94d38695610a400..fae9f9f749fd11e13b97331049f986ebf6fcf083 100644 (file)
@@ -12,7 +12,7 @@ You can install RadioStress on a mote via the following command:
   make <platform> cthreads install.0
   make <platform> cthreads install.1
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 The application burned with NODE_ID 0 will be programmed as a Receiver and will
 wait for messages from the sender programmed with NODE_ID 1.  In the case of the
index 911a04200fc5bb6ba443c5ce08536a6d2af96ae3..edf90505bf3e2e09f4950e87d11c7f782834c9d5 100644 (file)
@@ -1,7 +1,7 @@
 TOSTHREAD_MAIN=SenseAndSend.c
 CFLAGS += -I$(TOSDIR)/lib/tosthreads/sensorboards/tmote_onboard
 
-ifneq ($(filter telosb tmote clean,$(MAKECMDGOALS)),) 
+ifneq ($(filter telosb tmote epic clean,$(MAKECMDGOALS)),) 
   include $(MAKERULES)
 else
 %:
index 242d6503f3ce7a0db6c89738ce401928b5ecc605..c49a761e62955ca4c0dbbd62ee6d18c2531639eb 100644 (file)
  */
 
 /**
+ * SenseAndSend is a threaded implementation of an application that takes various
+ * sensor readings in parallel (by dedicating one thread to each reading), and
+ * assembling them into a packet to be sent out over the radio.  It is written
+ * specifically for use with the tmote onboard sensor package, and will not compile
+ * for any other platforms.
+ * 
+ * Readings are taken from each of the 4 oboard sensors and sent out over the radio
+ * interface in an infinite loop.  Upon successful transmission, LED0 is toggled,
+ * and the process starts over again.
+ * 
+ * A successful test will result in LED0 toggling periodically at a rate of
+ * approximately 220ms (the time it takes to take a humidity + temperature sensor
+ * reading since they share the same hardware and cannot be taken in parallel). 
+ * 
+ * Additionally, a base station application should be run to verify the reception
+ * of packets sent from a SenseAndSend mote, with reasonable looking sensor data.
+ *
  * @author Kevin Klues <klueska@cs.stanford.edu>
  */
 
index 5b9e5bb2c3bbb1371aac57989f46283b8650d690..93a75a4043c90ed64bbbe8d51dc465705a8fb9b5 100644 (file)
  */
 
 /**
+ * SenseStoreAndForward is a threaded implementation of an application that takes
+ * various sensor readings in parallel (by dedicating one thread to each reading),
+ * logs them to flash, and then sends them out over the radio at some later time. 
+ * In the current implementation, sensor readings are taken as quickly as possible,
+ * and records containing a set of readings from each iteration are batched out
+ * over the radio every 10000ms.  This application is written specifically for use
+ * with the tmote onboard sensor package, and will not compile for any other
+ * platforms.
+ *
+ * Readings are taken from each of the 4 oboard sensors and logged to flash as one
+ * record in an infinite loop. Records are then read out of flash and and sent out
+ * over the radio interface in separate infinite loop. Before the application
+ * starts running, the entire contents of the flash drive are erased.
+ * 
+ * A successful test will result in LED0 remaining solid for approximately 6s while
+ * the flash is being erased.  After that LED0 will toggle with each successful set
+ * of sensor readings logged to flash, at a rate of approximately 220ms (the time
+ * it takes to take a humidity + temperature sensor reading since they share the
+ * same hardware and cannot be taken in parallel).  Also, LED1 will begin toggling
+ * in rapid succession once every 10000ms as records are successfully read from
+ * flash and sent out over the radio.  Once all of the records currently recorded
+ * to flash since the last batch of sends have been sent out, LED2 Toggles to
+ * indicate completion.  This process continues in an infinite loop forever.
+ * 
+ * Additionally, a base station application should be run to verify the reception
+ * of packets sent from a SenseStoreAndForward mote, with reasonable looking sensor 
+ * data.
+ *
  * @author Kevin Klues <klueska@cs.stanford.edu>
  */
 
index aeac9db9161604d63924943f52d667cdeb5a99e7..7e378bf078429c641532acaaf1e7eb17309bf94b 100644 (file)
@@ -8,11 +8,11 @@ CFLAGS += -I$(TOSDIR)/lib/net/
 CFLAGS += -I$(TOSDIR)/lib/tosthreads/lib/net/ctp
 CFLAGS += -I$(TOSDIR)/lib/net/ctp  -I$(TOSDIR)/lib/net/4bitle
 
-ifneq ($(filter telosb tmote tinynode shimmer iris clean,$(MAKECMDGOALS)),) 
+ifneq ($(filter telosb tmote tinynode shimmer iris epic clean,$(MAKECMDGOALS)),) 
   include $(MAKERULES)
 else
 %:
-       @echo "    Sorry, this application only works on platforms with >8kB of RAM (telos, iris)"
+       @echo "    Sorry, this application only works on platforms with >8kB of RAM (telos, iris, etc.)"
 cthreads:
        @:
 dynthreads:
index 63cd279db724d767187f3c5930692bf16abc33ba..1eb94411164309b44d89ed82f43aa37dfb4b1b9a 100644 (file)
@@ -14,7 +14,7 @@ application.
 You can install TestCollection on a mote via the following command:
   make <platform> cthreads install
 
-Valid platforms are currently: tmote, telosb, mica2, micaz and iris
+Valid platforms are currently: tmote, telosb, mica2, micaz, iris, and epic
 
 At least two motes must be used by this application, with one of them installed
 as a base station.  Base station motes can be created by installing them with
@@ -24,7 +24,7 @@ NODE_ID % 500 == 0.
        make <platform> cthreads install.1000
 
 All other nodes can be installed with arbitrary NODE_IDs.
-  make <platform> threads install.123
+  make <platform> cthreads install.123
 
 Successful running of this application is verified by all NON-base station motes
 periodically flashing LED0 upon sending a message, and the base station mote,
@@ -34,14 +34,13 @@ section.
 
 Tools:
 
-The Java application displays readings it receives from motes running the
-MultihopOscilloscope demo via a serial forwarder. To run it, change to the
-TestCollection/java subdirectory and type:
+The Java application displays readings it receives from motes via a
+serial forwarder. To run it, change to the java subdirectory and type:
 
   make
   java net.tinyos.sf.SerialForwarder -comm serial@<serial port>:<baud_rate>
-  # e.g., java net.tinyps.sf.SerialForwarder -comm serial@/dev/ttyUSB0:mica2
-  # or java net.tinyps.sf.SerialForwarder -comm serial@COM2:telosb
+  # e.g., java net.tinyos.sf.SerialForwarder -comm serial@/dev/ttyUSB0:mica2
+  # or java net.tinyos.sf.SerialForwarder -comm serial@COM2:57600
   ./run
 
 NOTE::  The baud rate 57600 must be used telos based motes, as its configuration
@@ -59,10 +58,10 @@ Notes:
   underlying collection protocol.  The makefile can be modified to work with
   MultihopLQI by changing the appropriate include directories.
 
+  The baud rate 57600 must be used telos based motes, as its configuration
+  has been changed to work with this baud rate when compiled for tosthreads. I.e.
+  DO NOT just substitute 'telosb' or 'tmote' for <baud_rate> above.  Explicitly
+  set it to 57600.
+
 Known bugs/limitations:
-  Warnings are issued about fan out on the 'Snoop.receive' and 'Receive.receive'
-  events.  These warnings are harmless and are the result of providing a C based
-  API in which all events for receiving and snooping must be handled even if not
-  used by a particular application.  The warnings occur because the underlying
-  CTP or MultihopLQI stacks wire up to particular AM ids, which are also wired
-  into the C API for handling message reception.
+  None
index 21aca5a0ff6426540ae2a9afaf3f04cb8da9d3fb..bc2ddceb1d6967743dfec59f0570d913d4ee204b 100644 (file)
  */
 
 /**
+ * TestCollection is a reimplementation of the Multihop Oscilloscope application
+ * using TOSThreads. It periodically samples a universal software-based SineSensor
+ * and broadcasts a message every few readings. These readings can be displayed by
+ * the Java "Oscilloscope" application found in the the TestCollection/java
+ * subdirectory. The sampling rate starts at 4Hz, but can be changed from the Java
+ * application.
+ * 
+ * At least two motes must be used by this application, with one of them installed
+ * as a base station.  Base station motes can be created by installing them with
+ * NODE_ID % 500 == 0.
+ *   i.e. make <platform> cthreads install.0
+ *        make <platform> cthreads install.500
+ *        make <platform> cthreads install.1000
+ * 
+ * All other nodes can be installed with arbitrary NODE_IDs.
+ *   make <platform> cthreads install.123
+ * 
+ * Successful running of this application is verified by all NON-base station motes
+ * periodically flashing LED1 upon sending a message, and the base station mote,
+ * flashing LED2 upon successful reception of a message.  Additionally, correct
+ * operation should be verified by running the java tool described in the following
+ * section.
+ *
  * @author Kevin Klues <klueska@cs.stanford.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
 
 #include "tosthread.h"
@@ -51,19 +75,28 @@ uint8_t reading = 0;   /* 0 to NREADINGS */
 message_t sendbuf;
 message_t recvbuf;
 
-void tosthread_main(void* arg) {
+enum {
+  MY_COLLECTION_ID = NEW_COLLECTION_CLIENT_ID(),   // Gets a collection sender instance
+};
+
+void tosthread_main(void* arg)
+{
   local.interval = DEFAULT_INTERVAL;
   local.id = TOS_NODE_ID;
   local.version = 0;
   
   while ( amRadioStart() != SUCCESS );
   while ( collectionRoutingStart() != SUCCESS );
+  
+  collectionSetCollectionId(MY_COLLECTION_ID, AM_OSCILLOSCOPE);   // Associates the collection sender
+                                                                  //  with AM_OSCILLOSCOPE collection ID
+  
   if (local.id % 500 == 0) {
-    while ( amSerialStart() != SUCCESS);
+    while ( amSerialStart() != SUCCESS );
     collectionSetRoot();
     for (;;) {
-      if ( collectionReceive(&recvbuf, 0, AM_OSCILLOSCOPE) == SUCCESS) {
+      // Waits for incoming packets with AM_OSCILLOSCOPE collection ID
+      if (collectionReceive(&recvbuf, 0, AM_OSCILLOSCOPE) == SUCCESS) {
         oscilloscope_t *recv_o = (oscilloscope_t *) collectionGetPayload(&recvbuf, sizeof(oscilloscope_t));
         oscilloscope_t *send_o = (oscilloscope_t *) serialGetPayload(&sendbuf, sizeof(oscilloscope_t));
         memcpy(send_o, recv_o, sizeof(oscilloscope_t));
@@ -73,7 +106,7 @@ void tosthread_main(void* arg) {
     }
   } else {
     uint16_t var;
-      
+
     for (;;) {
       if (reading == NREADINGS) {
         oscilloscope_t *o = (oscilloscope_t *) collectionGetPayload(&sendbuf, sizeof(oscilloscope_t));
@@ -82,7 +115,7 @@ void tosthread_main(void* arg) {
           return;
         }
         memcpy(o, &local, sizeof(local));
-        if (collectionSend(&sendbuf, sizeof(local), AM_OSCILLOSCOPE) == SUCCESS) {
+        if (collectionSend(&sendbuf, sizeof(local), MY_COLLECTION_ID) == SUCCESS) {
           local.count++;
           report_sent();
         } else {
@@ -91,18 +124,19 @@ void tosthread_main(void* arg) {
         
         reading = 0;
       }
-          
+        
       if (sinesensor_read(&var) == SUCCESS) {
         local.readings[reading++] = var;
       }
-        
+      
       tosthread_sleep(local.interval);
     }
   }
 }
   
 // Use LEDs to report various status issues.
-void fatal_problem() { 
+void fatal_problem()
+{
   led0On(); 
   led1On();
   led2On();
diff --git a/apps/tosthreads/capps/TestJoin/Makefile b/apps/tosthreads/capps/TestJoin/Makefile
new file mode 100644 (file)
index 0000000..37ac73c
--- /dev/null
@@ -0,0 +1,3 @@
+TOSTHREAD_MAIN=TestJoin.c
+
+include $(MAKERULES)
diff --git a/apps/tosthreads/capps/TestJoin/README b/apps/tosthreads/capps/TestJoin/README
new file mode 100644 (file)
index 0000000..35eba60
--- /dev/null
@@ -0,0 +1,32 @@
+README for TOSThreads TestJoin
+Author/Contact: tinyos-help@millennium.berkeley.edu
+Author: Kevin Klues <klueska@cs.stanford.edu>
+
+Description:
+
+TestJoin is a simple application used to test the basic functionality of
+the join() system call for waiting on a set of threads in a TOSThreads 
+based application.
+
+You can install TestJoin on a mote via the following command:
+  make <platform> threads install
+  
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
+
+Upon a successful burn, you should see all LEDs toggle in the following pattern,
+repeating every 8 seconds:
+
+0s: (110) LED0  ON, LED1  ON, LED2 OFF
+1s: (000) LED0 OFF, LED1 OFF, LED2 OFF
+2s: (010) LED0 OFF, LED1  ON, LED2 OFF
+3s: (000) LED0 OFF, LED1 OFF, LED2 OFF
+4s: (111) LED0  ON, LED1  ON, LED2  ON
+5s: (001) LED0 OFF, LED1 OFF, LED2  ON
+6s: (011) LED0 OFF, LED1  ON, LED2  ON
+7s: (001) LED0 OFF, LED1 OFF, LED2  ON
+
+Tools:
+  None.
+
+Known bugs/limitations:
+  None.
diff --git a/apps/tosthreads/capps/TestJoin/TestJoin.c b/apps/tosthreads/capps/TestJoin/TestJoin.c
new file mode 100644 (file)
index 0000000..3ff35b5
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * TestJoin is a simple application used to test the basic functionality of
+ * the join() system call for waiting on a set of threads in a TOSThreads 
+ * based application.
+ * 
+ * Upon a successful burn, you should see all LEDs toggle in the following pattern,
+ * repeating every 8 seconds:
+ * 
+ * 0s: (110) LED0  ON, LED1  ON, LED2 OFF  <br>
+ * 1s: (000) LED0 OFF, LED1 OFF, LED2 OFF  <br>
+ * 2s: (010) LED0 OFF, LED1  ON, LED2 OFF  <br>
+ * 3s: (000) LED0 OFF, LED1 OFF, LED2 OFF  <br>
+ * 4s: (111) LED0  ON, LED1  ON, LED2  ON  <br>
+ * 5s: (001) LED0 OFF, LED1 OFF, LED2  ON  <br>
+ * 6s: (011) LED0 OFF, LED1  ON, LED2  ON  <br>
+ * 7s: (001) LED0 OFF, LED1 OFF, LED2  ON  <br>
+ *
+ * @author Kevin Klues (klueska@cs.stanford.edu)
+ */
+
+#include "stack.h"
+#include "tosthread.h"
+#include "tosthread_leds.h"
+
+//Initialize variables associated with each thread
+tosthread_t init;
+tosthread_t blink0;
+tosthread_t blink1;
+
+void init_thread(void* arg);
+void blink0_thread(void* arg);
+void blink1_thread(void* arg);
+
+void tosthread_main(void* arg) {
+  //Use stack estimator to calculate maximum stack size
+  //  on a thread by thread basis
+  tosthread_create(&init, init_thread, NULL, INIT_STACK_SIZE);
+}
+
+void init_thread(void* arg) {
+  for(;;) {
+    tosthread_create(&blink0, blink0_thread, NULL, BLINK0_STACK_SIZE);
+    tosthread_create(&blink1, blink1_thread, NULL, BLINK1_STACK_SIZE);
+    tosthread_join(&blink0);
+    tosthread_join(&blink1);
+    led2Toggle();
+  }
+}
+
+void blink0_thread(void* arg) {
+  int i;
+  for(i=0; i<2; i++) {
+    led0Toggle();
+    tosthread_sleep(1000);
+  }
+}
+
+void blink1_thread(void* arg) {
+  int i;
+  for(i=0; i<4; i++) {
+    led1Toggle();
+    tosthread_sleep(1000);
+  }
+}
+
diff --git a/apps/tosthreads/capps/TestJoin/stack.h b/apps/tosthreads/capps/TestJoin/stack.h
new file mode 100644 (file)
index 0000000..392794a
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * @author Kevin Klues <klueska@cs.stanford.edu>
+ */
+
+enum {
+  INIT_STACK_SIZE = 50,
+  BLINK0_STACK_SIZE = 200,
+  BLINK1_STACK_SIZE = 200,
+  BLINK2_STACK_SIZE = 200,
+};
index 5a4a3997dcd6976c69b8ed44db401afd04004545..cf587f24074f815c9300d4a19a04af77ada3aa10 100644 (file)
@@ -1,11 +1,11 @@
 TOSTHREAD_MAIN=TestLogStorage.c
-THIS_SUPPORTED_PLATFORMS=tmote telos telosb eyesIFXv1 eyesIFXv2 mica2 mica2dot telosa eyesIFX micaz iris tinynode
+THIS_SUPPORTED_PLATFORMS=tmote telos telosb eyesIFXv1 eyesIFXv2 mica2 mica2dot telosa eyesIFX micaz iris tinynode epic
 
 ifneq ($(filter $(THIS_SUPPORTED_PLATFORMS) clean,$(MAKECMDGOALS)),)
         ifneq ($(filter tmote telos telosb eyesIFXv1,$(MAKECMDGOALS)),)
                 CFLAGS+=-DUSE_STM25P
         endif
-        ifneq ($(filter mica2 telosa mica2dot eyesIFX eyesIFXv2 micaz iris tinynode,$(MAKECMDGOALS)),)
+        ifneq ($(filter mica2 telosa mica2dot eyesIFX eyesIFXv2 micaz iris tinynode epic,$(MAKECMDGOALS)),)
                 CFLAGS+=-DUSE_AT45DB
         endif
 
index 7016add8ef2a386d87e8f5c7ff26b26433889dc6..3c83d84f0e832f15ec51d417ab8c9bb3a5ebda28 100644 (file)
@@ -4,21 +4,20 @@ Author: Kevin Klues <klueska@cs.stanford.edu>
 
 Description:
 
-TestLogStorage is a threaded implementation of an application that takes a dummy
-sensor readings of a counter, logs it flash, and then sends it out over the
-serial port at some later time. In the current implementation, each sensor reading is
-taken once every 3000ms, and records containing a set of readings from each
-iteration are batched out over the radio every 10000ms.  This application is
-very similar to the SenseStoreAndForward application contained in this same
-directory, except that it is written using a dummy sensor value instead of
-sensors specific to the tmote onboard suite. In this way, the LogStorage
-functionality can be tested in conjunction with the sending facility in a
-platform independent way.
+TestLogStorage is a threaded application that takes dummy sensor readings of a
+counter, logs them to flash, and then sends out over the serial port at some
+later time. In the current implementation, each sensor reading is taken once
+every 3000ms, and records containing a set of readings from each iteration are
+batched out over the radio every 10000ms.  This application is very similar to
+the SenseStoreAndForward application contained in this same directory, except
+that it uses a dummy sensor instead of sensors specific to the tmote onboard
+suite.  In this way, the LogStorage functionality can be tested in conjunction
+with the sending facility in a platform independent way.
 
 To run this application install it on a mote via the command:
   make <platform> cthreads install
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz
+Valid platforms are currently:  tmote, telosb, iris, mica2, micaz, and epic
 
 Readings are taken from the dummy sensor and logged to flash as one record in an
 infinite loop. Records are then read out of flash and and sent out over the
@@ -35,14 +34,24 @@ to indicate completion.  This process continues in an infinite loop forever.
 
 Since the TestLogStorage mote writes its records out to the serial
 port, you can test that the application is working properly by reading these
-packets (e.g., through seriallisten) and checking that they have reasonable
-values, counting up from 0. E.g.:
-
-00 ff ff 00 00 06 00 25 00 00 00 9f 00 9f 
-00 ff ff 00 00 06 00 25 00 00 00 a0 00 a0 
-00 ff ff 00 00 06 00 25 00 00 00 a1 00 a1 
-00 ff ff 00 00 06 00 25 00 00 00 a2 00 a2 
-00 ff ff 00 00 06 00 25 00 00 00 a3 00 a3 
+packets (e.g., through seriallisten):
+
+  java net.tinyos.tools.Listen -comm serial@/dev/ttyUSBXXX:<baud_rate>
+
+Once this java application is running, you should see output containing
+the sensor readings being streamed to your terminal.  Check that the
+output has reasonable values, counting up from 0. E.g.:
+
+  00 ff ff 00 00 06 00 25 00 00 00 9f 00 9f 
+  00 ff ff 00 00 06 00 25 00 00 00 a0 00 a0 
+  00 ff ff 00 00 06 00 25 00 00 00 a1 00 a1 
+  00 ff ff 00 00 06 00 25 00 00 00 a2 00 a2 
+  00 ff ff 00 00 06 00 25 00 00 00 a3 00 a3 
+
+NOTE:  The baud rate 57600 must be used telos based motes, as its configuration
+has been changed to work with this baud rate when compiled for tosthreads. I.e.
+DO NOT just substitute 'telosb' or 'tmote' for <baud_rate> above.  Explicitly
+set it to 57600.
 
 Tools:
   None.
index b157228a01ca24c024c299bb59674b36aab0dfb8..6e48a21778e0ca362c44ae08bb4cc61fca5f61be 100644 (file)
  */
 
 /**
+ * TestLogStorage is a threaded implementation of an application that takes a dummy
+ * sensor readings of a counter, logs it flash, and then sends it out over the
+ * serial port at some later time. In the current implementation, each sensor reading is
+ * taken once every 3000ms, and records containing a set of readings from each
+ * iteration are batched out over the radio every 10000ms.  This application is
+ * very similar to the SenseStoreAndForward application contained in this same
+ * directory, except that it is written using a dummy sensor value instead of
+ * sensors specific to the tmote onboard suite. In this way, the LogStorage
+ * functionality can be tested in conjunction with the sending facility in a
+ * platform independent way.
+ * 
+ * Readings are taken from the dummy sensor and logged to flash as one record in an
+ * infinite loop. Records are then read out of flash and and sent out over the
+ * serial interface in separate infinite loop.  Before the application starts
+ * running, the entire contents of the flash drive are erased.
+ * 
+ * A successful test will result in LED0 remaining solid for approximately 6s while
+ * the flash is being erased.  After that LED0 will toggle with each successful
+ * sensor readings logged to flash, at a rate of 3000ms.  Also, LED1 will begin
+ * toggling in rapid succession once every 10000ms as records are successfully read
+ * from flash and sent out over the serial port.  Once all of the records currently
+ * recorded to flash since the last batch of sends have been sent out, LED2 Toggles
+ * to indicate completion.  This process continues in an infinite loop forever.
+ *
  * @author Kevin Klues <klueska@cs.stanford.edu>
  */
 
index 46106b0849e2b20c0bbc98cd05d367efc698cec6..17294b551455c479e7bc6807cdb1a23fb7309477 100644 (file)
@@ -11,13 +11,13 @@ prints.
 You can install TestPrintf on a mote via the following command:
   make <platform> cthreads install
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 Once burned on a mote, the java based PrintfClient must be ran to verify
 proper operation of the application.
   java net.tinyos.tools.PrintfClient -comm serial@/dev/ttyUSBXXX:<baud_rate>
   
-NOTE::  The baud rate 57600 must be used telos based motes, as its configuration
+NOTE:  The baud rate 57600 must be used telos based motes, as its configuration
 has been changed to work with this baud rate when compiled for tosthreads. I.e.
 DO NOT just substitute 'telosb' or 'tmote' for <baud_rate> above.  Explicitly
 set it to 57600.
index 28badaf7c4861e17eb6f3fe13191baa9c0c74fac..e06c3308bf9e95ade7350111c488dc05ae0d9f26 100644 (file)
  */
  
 /**
+ * This application tests the operation of the Printf client in TOSThreads.  It
+ * continuously prints the value of a counter starting at 0, increasing as it
+ * prints.
+ * 
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
index b95b8fdf31e3791089bc58de98609cbfa6f344b9..852411adc24085a05975ec91ec1afa7c7362732f 100644 (file)
@@ -10,7 +10,7 @@ the software based SineSensor usable by any platform for demonstration purposes.
 You can install TestSineSensor on a mote via the following comand:
   make <platform> cthreads install
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 This application simply takes sensor readings in an infinite loop from the
 SineSensor and forwards them over the serial interface.  Upon successful
@@ -22,7 +22,7 @@ over the serial interface as verified by running the following for the platform
 of interest:
   java net.tinyos.tools.Listen -comm serial@/dev/ttyUSBXXX:<baud_rate>
   
-NOTE::  The baud rate 57600 must be used telos based motes, as its configuration
+NOTE:  The baud rate 57600 must be used telos based motes, as its configuration
 has been changed to work with this baud rate when compiled for tosthreads. I.e.
 DO NOT just substitute 'telosb' or 'tmote' for <baud_rate> above.  Explicitly
 set it to 57600.
index bf2f7d61da4644a9595588226234bd1cb98bbf07..c6483ea65ffb05d863f81699d5eb4f30f44f474b 100644 (file)
  */
 
 /**
+ * This application is used to test the threaded version of the API for accessing
+ * the software based SineSensor usable by any platform for demonstration purposes.
+ *
+ * This application simply takes sensor readings in an infinite loop from the
+ * SineSensor and forwards them over the serial interface.  Upon successful
+ * transmission, LED0 is toggled.
+ *
  * @author Kevin Klues <klueska@cs.stanford.edu>
  */
 
index ce519719be260380bb2293f629a7d18452468c0b..34c59e6f83ce2dbe3e9859481aaa850daef882c5 100644 (file)
@@ -13,7 +13,7 @@ toggled is offset so that the three LEDS do not come on in unison.
 You can install ThreadStress on a mote via the following command:
   make <platform> cthreads install
   
-Valid platforms are currently: tmote, telosb, iris, mica2, and micaz 
+Valid platforms are currently: tmote, telosb, iris, mica2, micaz, and epic
 
 Successful running of this application will result in all three leds flashing at
 a rate determined by how long it takes to spawn a thread on a given platform. 
index 8949738243d18f4974dc8e080dc5228e0398b731..8d26bbe3d51f4e6f34f40f5d26c4ff20d3101b68 100644 (file)
  */
  
 /**
+ * This application stresses the creation and destruction of dynamic threads by
+ * spawning lots and lots of threads over and over again and letting them run to
+ * completion.  Three different thread start functions are used, each toggling one
+ * of LED0, LED1, and LED2 every 256 spawnings. The time at which each LED is
+ * toggled is offset so that the three LEDS do not come on in unison.
+ * 
+ * Successful running of this application will result in all three leds flashing at
+ * a rate determined by how long it takes to spawn a thread on a given platform. 
+ * All three LEDs should flash at this rate in an infinite loop forever.  Given the
+ * dynamics on the mote the rate may vary over time, but the important thing is
+ * that all three LEDs continue to toggle at a reasonably visible rate.  
+ *
  * @author Kevin Klues (klueska@cs.stanford.edu)
  */
 
diff --git a/apps/tosthreads/tinyld/LoadFromRAM/LoadFromRAMAppC.nc b/apps/tosthreads/tinyld/LoadFromRAM/LoadFromRAMAppC.nc
new file mode 100644 (file)
index 0000000..804dd46
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * LoadFromRAM is a simple program that dynamically loads two loadable
+ * programs hardcoded in the byte arrays; One program is Blink, and the
+ * other one is Basestation.
+ *
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+configuration LoadFromRAMAppC {}
+
+implementation {
+  components MainC,
+             LoadFromRAMP,
+             DynamicLoaderC,
+             LedsC;
+             
+  LoadFromRAMP.Boot -> MainC;
+  LoadFromRAMP.DynamicLoader -> DynamicLoaderC;
+  LoadFromRAMP.Leds -> LedsC;
+}
diff --git a/apps/tosthreads/tinyld/LoadFromRAM/LoadFromRAMP.nc b/apps/tosthreads/tinyld/LoadFromRAM/LoadFromRAMP.nc
new file mode 100644 (file)
index 0000000..7b7e96e
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * LoadFromRAM is a simple program that dynamically loads two loadable
+ * programs hardcoded in the byte arrays; One program is Blink, and the
+ * other one is Basestation.
+ *
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+module LoadFromRAMP 
+{
+  uses {
+    interface Boot;
+    interface DynamicLoader;
+    interface Leds;
+  }
+}
+
+implementation
+{
+  // The following blinks led 2
+  uint8_t code1[] = {
+    0x1c, 0x00, 0x01, 0x00, 0x03, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x00,
+    0x28, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x01, 0x00, 0x2c, 0x00, 0x08, 0x00, 0x44, 0x00, 0x09, 0x00,
+    0x56, 0x00, 0x0a, 0x00, 0x32, 0x00, 0x30, 0x00, 0x24, 0x00, 0x0f, 0x42, 0x12, 0xc3, 0x0f, 0x10,
+    0x0f, 0x11, 0x0f, 0x11, 0x5f, 0xf3, 0x32, 0xc2, 0x03, 0x43, 0x7f, 0xf3, 0x30, 0x41, 0x4f, 0x93,
+    0x01, 0x24, 0x32, 0xd2, 0x30, 0x41, 0x3c, 0x40, 0xf4, 0x01, 0x0d, 0x43, 0x3e, 0x40, 0x00, 0x00,
+    0x3f, 0x40, 0x00, 0x00, 0xb0, 0x12, 0x00, 0x00, 0x30, 0x41, 0xb0, 0x12, 0x00, 0x00, 0x3e, 0x40,
+    0xe8, 0x03, 0x0f, 0x43, 0xb0, 0x12, 0x4e, 0x00, 0xf8, 0x3f, 0x30, 0x41, 0xb0, 0x12, 0x00, 0x00,
+    0x3e, 0x40, 0xe8, 0x03, 0x0f, 0x43, 0xb0, 0x12, 0x60, 0x00, 0xf8, 0x3f, 0x30, 0x41, 0xb0, 0x12,
+    0x00, 0x00, 0x3e, 0x40, 0xe8, 0x03, 0x0f, 0x43, 0xb0, 0x12, 0x00, 0x00, 0xf8, 0x3f, 0x30, 0x41
+  };
+
+  // The following is BaseStationForC
+  uint8_t code2[] = {
+    0x1c, 0x00, 0x05, 0x00, 0x58, 0x01, 0x1e, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x26, 0x03, 0xac, 0x00,
+    0x26, 0x00, 0xae, 0x00, 0x88, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x01, 0x00, 0x52, 0x00, 0x02, 0x00,
+    0x64, 0x00, 0x01, 0x00, 0x44, 0x00, 0x08, 0x00, 0xe2, 0x00, 0x09, 0x00, 0x00, 0x02, 0x0a, 0x00,
+    0xdc, 0x00, 0x0b, 0x00, 0x32, 0x00, 0x0d, 0x00, 0x10, 0x03, 0x0e, 0x00, 0x98, 0x01, 0x11, 0x00,
+    0xd6, 0x02, 0x12, 0x00, 0xce, 0x02, 0x14, 0x00, 0x9c, 0x02, 0x16, 0x00, 0xc6, 0x02, 0x1a, 0x00,
+    0x94, 0x02, 0x1b, 0x00, 0xde, 0x02, 0x22, 0x00, 0x2e, 0x00, 0x24, 0x00, 0xb6, 0x00, 0x25, 0x00,
+    0xfa, 0x02, 0x28, 0x00, 0x84, 0x02, 0x29, 0x00, 0x7c, 0x02, 0x2b, 0x00, 0xee, 0x02, 0x2d, 0x00,
+    0x74, 0x02, 0x31, 0x00, 0xe6, 0x02, 0x32, 0x00, 0x8c, 0x02, 0x3f, 0x00, 0xa2, 0x00, 0x40, 0x00,
+    0x04, 0x01, 0x42, 0x00, 0x18, 0x01, 0x44, 0x00, 0x98, 0x00, 0x45, 0x00, 0xec, 0x00, 0x46, 0x00,
+    0x0e, 0x01, 0x51, 0x00, 0x8a, 0x01, 0x6d, 0x00, 0x6c, 0x01, 0x90, 0x00, 0x22, 0x00, 0xb0, 0x00,
+    0x3c, 0x00, 0x84, 0x01, 0x4e, 0x00, 0x92, 0x01, 0x60, 0x00, 0x0a, 0x03, 0x72, 0x00, 0x18, 0x03,
+    0x84, 0x00, 0xbe, 0x00, 0xba, 0x00, 0x28, 0x01, 0xf4, 0x00, 0x00, 0x00, 0x46, 0x01, 0xa0, 0x01,
+    0x9c, 0x01, 0x18, 0x02, 0xbc, 0x01, 0xb8, 0x02, 0xfc, 0x01, 0x66, 0x02, 0x08, 0x02, 0x0f, 0x42,
+    0x12, 0xc3, 0x0f, 0x10, 0x0f, 0x11, 0x0f, 0x11, 0x5f, 0xf3, 0x32, 0xc2, 0x03, 0x43, 0x7f, 0xf3,
+    0x30, 0x41, 0x4f, 0x93, 0x01, 0x24, 0x32, 0xd2, 0x30, 0x41, 0x3f, 0x40, 0x40, 0x00, 0xb0, 0x12,
+    0x2a, 0x00, 0x3f, 0x40, 0x76, 0x00, 0xb0, 0x12, 0x00, 0x00, 0xb0, 0x12, 0x00, 0x00, 0xb0, 0x12,
+    0x00, 0x00, 0x3c, 0x40, 0xc8, 0x00, 0x0d, 0x43, 0x3e, 0x40, 0x00, 0x00, 0x3f, 0x40, 0xb2, 0x00,
+    0xb0, 0x12, 0x56, 0x00, 0x3c, 0x40, 0xc8, 0x00, 0x0d, 0x43, 0x3e, 0x40, 0x00, 0x00, 0x3f, 0x40,
+    0x00, 0x00, 0xb0, 0x12, 0x68, 0x00, 0x3c, 0x40, 0xc8, 0x00, 0x0d, 0x43, 0x3e, 0x40, 0x00, 0x00,
+    0x3f, 0x40, 0x00, 0x00, 0xb0, 0x12, 0x7a, 0x00, 0x3c, 0x40, 0xc8, 0x00, 0x0d, 0x43, 0x3e, 0x40,
+    0x00, 0x00, 0x3f, 0x40, 0x0c, 0x03, 0xb0, 0x12, 0x8c, 0x00, 0x3c, 0x40, 0xc8, 0x00, 0x0d, 0x43,
+    0x3e, 0x40, 0x00, 0x00, 0x3f, 0x40, 0x00, 0x00, 0xb0, 0x12, 0x00, 0x00, 0x30, 0x41, 0x0b, 0x12,
+    0x0b, 0x4f, 0x2f, 0x52, 0xb0, 0x12, 0x00, 0x00, 0x0f, 0x4b, 0x3f, 0x50, 0x0a, 0x00, 0xb0, 0x12,
+    0x00, 0x00, 0xcb, 0x43, 0xaa, 0x00, 0xcb, 0x43, 0xab, 0x00, 0x3b, 0x41, 0x30, 0x41, 0x3e, 0x40,
+    0x86, 0x01, 0x3f, 0x40, 0x00, 0x00, 0xb0, 0x12, 0x8e, 0x01, 0x30, 0x41, 0x0b, 0x12, 0x0a, 0x12,
+    0x09, 0x12, 0x31, 0x80, 0x34, 0x00, 0x09, 0x4f, 0x0b, 0x4e, 0x7c, 0x43, 0x0d, 0x43, 0x0e, 0x43,
+    0x0f, 0x41, 0x89, 0x12, 0x4f, 0x93, 0x03, 0x24, 0xb0, 0x12, 0x00, 0x00, 0xf6, 0x3f, 0xb0, 0x12,
+    0x00, 0x00, 0x0a, 0x4b, 0x2a, 0x52, 0x0f, 0x4a, 0xb0, 0x12, 0xb6, 0x01, 0x0e, 0x41, 0x0f, 0x4b,
+    0xb0, 0x12, 0x00, 0x00, 0x5f, 0x93, 0x07, 0x20, 0x0e, 0x4a, 0x0f, 0x4b, 0x3f, 0x50, 0x0a, 0x00,
+    0xb0, 0x12, 0xcc, 0x01, 0xf3, 0x3f, 0x0f, 0x4b, 0x2f, 0x52, 0xb0, 0x12, 0xe6, 0x01, 0x0f, 0x4b,
+    0x3f, 0x50, 0x0a, 0x00, 0xb0, 0x12, 0xf0, 0x01, 0xd8, 0x3f, 0x31, 0x50, 0x34, 0x00, 0x39, 0x41,
+    0x3a, 0x41, 0x3b, 0x41, 0x30, 0x41, 0x0b, 0x12, 0x0a, 0x12, 0x09, 0x12, 0x09, 0x4f, 0x0d, 0x4e,
+    0xff, 0x90, 0x03, 0x00, 0xaa, 0x00, 0x20, 0x2c, 0x5f, 0x4f, 0xab, 0x00, 0x0a, 0x4f, 0x3c, 0x40,
+    0x34, 0x00, 0xb0, 0x12, 0x48, 0x02, 0x0e, 0x59, 0x3e, 0x50, 0x0e, 0x00, 0x0f, 0x4d, 0x3d, 0x40,
+    0x34, 0x00, 0xfe, 0x4f, 0x00, 0x00, 0x1e, 0x53, 0x1d, 0x83, 0xfb, 0x23, 0x5f, 0x49, 0xab, 0x00,
+    0x1f, 0x53, 0x0c, 0x4f, 0x3a, 0x40, 0x03, 0x00, 0xb0, 0x12, 0x3e, 0x02, 0xc9, 0x4e, 0xab, 0x00,
+    0xd9, 0x53, 0xaa, 0x00, 0x0f, 0x43, 0x01, 0x3c, 0x1f, 0x43, 0x39, 0x41, 0x3a, 0x41, 0x3b, 0x41,
+    0x30, 0x41, 0x3e, 0x40, 0x94, 0x01, 0x3f, 0x40, 0x00, 0x00, 0xb0, 0x12, 0x14, 0x03, 0x30, 0x41,
+    0x3e, 0x40, 0x00, 0x00, 0x3f, 0x40, 0xf4, 0x01, 0xb0, 0x12, 0x22, 0x03, 0x30, 0x41, 0x0b, 0x12,
+    0x0a, 0x12, 0x09, 0x12, 0x31, 0x80, 0x34, 0x00, 0x09, 0x4f, 0x0b, 0x4e, 0x0a, 0x4b, 0x2a, 0x52,
+    0x0f, 0x4a, 0xb0, 0x12, 0x00, 0x00, 0x0f, 0x4b, 0xb0, 0x12, 0x00, 0x00, 0x0f, 0x93, 0x07, 0x20,
+    0x0e, 0x4a, 0x0f, 0x4b, 0x3f, 0x50, 0x0a, 0x00, 0xb0, 0x12, 0x00, 0x00, 0xf4, 0x3f, 0x0d, 0x41,
+    0x3e, 0x40, 0x34, 0x00, 0xfd, 0x4f, 0x00, 0x00, 0x1d, 0x53, 0x1e, 0x83, 0xfb, 0x23, 0x0f, 0x4b,
+    0x2f, 0x52, 0xb0, 0x12, 0x00, 0x00, 0x0f, 0x4b, 0x3f, 0x50, 0x0a, 0x00, 0xb0, 0x12, 0x00, 0x00,
+    0x39, 0x90, 0xa8, 0x02, 0x06, 0x24, 0x0f, 0x41, 0xb0, 0x12, 0x00, 0x00, 0xb0, 0x12, 0x00, 0x00,
+    0xd5, 0x3f, 0x0f, 0x41, 0xb0, 0x12, 0x00, 0x00, 0xf9, 0x3f, 0x31, 0x50, 0x34, 0x00, 0x39, 0x41,
+    0x3a, 0x41, 0x3b, 0x41, 0x30, 0x41, 0x0b, 0x12, 0x0a, 0x12, 0x09, 0x12, 0x08, 0x12, 0x09, 0x4f,
+    0x58, 0x4f, 0xaa, 0x00, 0x48, 0x93, 0x18, 0x24, 0x5f, 0x4f, 0xab, 0x00, 0x4e, 0x48, 0x0f, 0x8e,
+    0x3f, 0x50, 0x03, 0x00, 0x0c, 0x4f, 0x3a, 0x40, 0x03, 0x00, 0xb0, 0x12, 0x00, 0x00, 0x0a, 0x4e,
+    0x3c, 0x40, 0x34, 0x00, 0xb0, 0x12, 0x00, 0x00, 0x0f, 0x4e, 0x0f, 0x59, 0x78, 0x53, 0xc9, 0x48,
+    0xaa, 0x00, 0x3f, 0x50, 0x0e, 0x00, 0x01, 0x3c, 0x0f, 0x43, 0x38, 0x41, 0x39, 0x41, 0x3a, 0x41,
+    0x3b, 0x41, 0x30, 0x41, 0x0b, 0x12, 0x0a, 0x12, 0x09, 0x12, 0x08, 0x12, 0x07, 0x12, 0x0b, 0x4f,
+    0xb0, 0x12, 0x00, 0x00, 0x47, 0x4f, 0x0f, 0x4b, 0xb0, 0x12, 0x00, 0x00, 0x09, 0x4f, 0x0f, 0x4b,
+    0xb0, 0x12, 0x00, 0x00, 0x08, 0x4f, 0x0f, 0x4b, 0xb0, 0x12, 0x00, 0x00, 0x4a, 0x4f, 0x0f, 0x4b,
+    0xb0, 0x12, 0x00, 0x00, 0x0e, 0x49, 0x0f, 0x4b, 0xb0, 0x12, 0x00, 0x00, 0x4c, 0x47, 0x4d, 0x4a,
+    0x0e, 0x4b, 0x0f, 0x48, 0xb0, 0x12, 0x00, 0x00, 0x7f, 0xf3, 0x37, 0x41, 0x38, 0x41, 0x39, 0x41,
+    0x3a, 0x41, 0x3b, 0x41, 0x30, 0x41, 0x0b, 0x12, 0x0a, 0x12, 0x09, 0x12, 0x08, 0x12, 0x07, 0x12,
+    0x0b, 0x4f, 0xb0, 0x12, 0x00, 0x00, 0x47, 0x4f, 0x0f, 0x4b, 0xb0, 0x12, 0x00, 0x00, 0x09, 0x4f,
+    0x0f, 0x4b, 0xb0, 0x12, 0x00, 0x00, 0x08, 0x4f, 0x0f, 0x4b, 0xb0, 0x12, 0x00, 0x00, 0x4a, 0x4f,
+    0x0f, 0x4b, 0xb0, 0x12, 0x00, 0x00, 0x0e, 0x49, 0x0f, 0x4b, 0xb0, 0x12, 0x00, 0x00, 0x4c, 0x47,
+    0x4d, 0x4a, 0x0e, 0x4b, 0x0f, 0x48, 0xb0, 0x12, 0x1e, 0x03, 0x7f, 0xf3, 0x37, 0x41, 0x38, 0x41,
+    0x39, 0x41, 0x3a, 0x41, 0x3b, 0x41, 0x30, 0x41, 0x3e, 0x40, 0x1a, 0x03, 0x3f, 0x40, 0x00, 0x00,
+    0xb0, 0x12, 0x00, 0x00, 0x30, 0x41, 0x3e, 0x40, 0x00, 0x00, 0x3f, 0x40, 0x00, 0x00, 0xb0, 0x12,
+    0x00, 0x00, 0x30, 0x41
+  };
+
+  task void loadCode1() {
+    call DynamicLoader.loadFromMemory(code1);
+  }
+
+  task void loadCode2() {
+    call DynamicLoader.loadFromMemory(code2);
+  }
+
+  event void DynamicLoader.loadFromMemoryDone(void *addr, tosthread_t id, error_t error)
+  {
+    if (addr == code1) {
+      post loadCode2();
+    }
+  }
+
+  event void Boot.booted() {
+    post loadCode1();
+  }
+  
+  event void DynamicLoader.loadFromFlashDone(uint8_t volumeId, tosthread_t id, error_t error) {}
+}
diff --git a/apps/tosthreads/tinyld/LoadFromRAM/Makefile b/apps/tosthreads/tinyld/LoadFromRAM/Makefile
new file mode 100644 (file)
index 0000000..97b77fa
--- /dev/null
@@ -0,0 +1,17 @@
+COMPONENT=LoadFromRAMAppC
+
+GOALS += threads
+
+THREADS_DIR ?= $(TOSDIR)/lib/tosthreads
+CFLAGS += -I$(THREADS_DIR)/lib/tinyld
+CFLAGS += -I$(THREADS_DIR)/csystem
+CFLAGS += -I$(THREADS_DIR)/sensorboards/tmote_onboard
+CFLAGS += -I$(THREADS_DIR)/sensorboards/universal
+CFLAGS += -I$(THREADS_DIR)/lib/net/ctp
+CFLAGS += -I$(THREADS_DIR)/lib/net
+CFLAGS += -I$(TOSDIR)/lib/net
+CFLAGS += -I$(TOSDIR)/lib/net/ctp
+CFLAGS += -I$(TOSDIR)/lib/net/4bitle
+CFLAGS += -I$(THREADS_DIR)/lib/printf
+
+include $(MAKERULES)
diff --git a/apps/tosthreads/tinyld/LoadFromRAM/README b/apps/tosthreads/tinyld/LoadFromRAM/README
new file mode 100644 (file)
index 0000000..95a32cc
--- /dev/null
@@ -0,0 +1,22 @@
+README for LoadFromRAM
+Author/Contact: Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+
+Description:
+
+LoadFromRAM is a simple program that dynamically loads two loadable
+programs hardcoded in the byte arrays; One program is Blink, and the
+other one is Basestation.
+
+You can install LoadFromRAM on a mote via the following command:
+  make <platform> install
+
+If you would like to generate your own loadable program run, for example:
+  cd ../../capps/Blink
+  make telosb dynthreads
+  (the output file needed is ../../capps/Blink/build/telosb/dynthreads/main.tos)       
+  
+Tools:
+  None.
+
+Known bugs/limitations:
+  None.
diff --git a/apps/tosthreads/tinyld/LoadFromRAM/volumes-at45db.xml b/apps/tosthreads/tinyld/LoadFromRAM/volumes-at45db.xml
new file mode 100644 (file)
index 0000000..26c8665
--- /dev/null
@@ -0,0 +1,3 @@
+<volume_table>
+  <volume name="MICROEXEIMAGE" size="262144" type="block"/>
+</volume_table>          
diff --git a/apps/tosthreads/tinyld/LoadFromRAM/volumes-stm25p.xml b/apps/tosthreads/tinyld/LoadFromRAM/volumes-stm25p.xml
new file mode 100755 (executable)
index 0000000..dfc0bd4
--- /dev/null
@@ -0,0 +1,3 @@
+<volume_table>
+  <volume name="MICROEXEIMAGE" size="65536" type="block"/>
+</volume_table>
diff --git a/apps/tosthreads/tinyld/Makefile b/apps/tosthreads/tinyld/Makefile
new file mode 100644 (file)
index 0000000..90989c7
--- /dev/null
@@ -0,0 +1,57 @@
+#-*-makefile-*-
+######################################################################
+# 
+# Makes the entire suite of TinyOS applications for a given platform.
+#
+# Author:      Martin Turon
+# Date:                August 18, 2005
+#
+######################################################################
+# $Id$
+
+# MAKECMDGOALS is the way to get the arguments passed into a Makefile ...
+TARGET=$(MAKECMDGOALS)
+NESDOC_TARGET=$(filter-out nesdoc,$(TARGET))
+
+# Here is a way to get the list of subdirectories in a Makefile ...
+ROOT=.
+SUBDIRS := $(shell find * -type d)
+
+# Okay, match any target, and recurse the subdirectories
+%: 
+       @for i in $(SUBDIRS); do \
+         HERE=$$PWD; \
+         if [ -f $$i/Makefile ]; then \
+             echo Building ... $(PWD)/$$i; \
+             echo make $(TARGET); \
+             cd $$i; \
+             $(MAKE) $(TARGET); \
+             cd $$HERE; \
+         fi; \
+       done
+
+threads:
+       @:
+cthreads:
+       @:
+dynthreads:
+       @:
+
+BASEDIR = $(shell pwd | sed 's@\(.*\)/apps.*$$@\1@' )
+# The output directory for generated documentation
+DOCDIR = $(BASEDIR)/doc/nesdoc
+
+nesdoc:
+       @echo This target rebuilds documentation for all known platforms.
+       @echo It DOES NOT overwrite any existing documentation, thus, it 
+       @echo is best run after deleting all old documentation.
+       @echo
+       @echo To delete all old documentation, delete the contents of the
+       @echo $(DOCDIR) directory.
+       @echo
+       @echo Press Enter to continue, or ^C to abort.
+       @read
+       for platform in `ncc -print-platforms`; do \
+         $(MAKE) $$platform docs.nohtml.preserve; \
+         nesdoc -o $(DOCDIR) -html -target=$$platform; \
+       done
diff --git a/apps/tosthreads/tinyld/SerialLoader/Makefile b/apps/tosthreads/tinyld/SerialLoader/Makefile
new file mode 100755 (executable)
index 0000000..92bfa55
--- /dev/null
@@ -0,0 +1,25 @@
+COMPONENT=SerialLoaderAppC
+
+GOALS += threads
+
+THREADS_DIR ?= $(TOSDIR)/lib/tosthreads
+CFLAGS += -I$(THREADS_DIR)/lib/tinyld
+CFLAGS += -I$(THREADS_DIR)/csystem
+CFLAGS += -I$(THREADS_DIR)/sensorboards/tmote_onboard
+CFLAGS += -I$(THREADS_DIR)/sensorboards/universal
+CFLAGS += -I$(THREADS_DIR)/lib/net/ctp
+CFLAGS += -I$(THREADS_DIR)/lib/net
+CFLAGS += -I$(TOSDIR)/lib/net
+CFLAGS += -I$(TOSDIR)/lib/net/ctp
+CFLAGS += -I$(TOSDIR)/lib/net/4bitle
+CFLAGS += -I$(THREADS_DIR)/lib/printf
+
+ifdef TENET
+    CFLAGS += -DTOSTHREAD_TENET=1
+endif
+CFLAGS += -DDISABLE_LOADER_FLASH=1
+CFLAGS += -DDISABLE_LOADER_USERBUTTON=1
+
+CLEAN_EXTRA += *.pyc
+
+include $(MAKERULES)
diff --git a/apps/tosthreads/tinyld/SerialLoader/README b/apps/tosthreads/tinyld/SerialLoader/README
new file mode 100644 (file)
index 0000000..7cd3c04
--- /dev/null
@@ -0,0 +1,33 @@
+README for SerialLoader
+Author/Contact: Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+
+Description:
+
+SerialLoader receives loadable programs from the serial port and stores
+it in a byte array. Then, when it receives the command to load the code,
+it makes the call to the dynamic loader.
+
+Here are the steps:
+1.) Load SerialLoader:
+    make telosb install bsl,<device_port>
+    
+2.) Create the loadable code, main.tos:
+       cd ../../capps/Blink
+       make telosb dynthreads
+       (the output file needed is ../../capps/Blink/build/telosb/dynthreads/main.tos)  
+
+3.) Clear the byte array in the mote RAM buffer:
+    ./serialloader.py <device_port> 0
+
+4.) Upload the binary:
+    ./serialloader.py <device_port> 1 main.tos
+    
+5.) Run the binary:
+    ./serialloader.py <device_port> 7
+
+Tools:
+  None.
+
+Known bugs/limitations:
+  None.
+
diff --git a/apps/tosthreads/tinyld/SerialLoader/SerialLoader.h b/apps/tosthreads/tinyld/SerialLoader/SerialLoader.h
new file mode 100755 (executable)
index 0000000..d3ff65a
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#ifndef SERIALLOADER_H
+#define SERIALLOADER_H
+
+#define MAX_BIN_SIZE 2000
+
+#define SERIALMSG_ERASE 0
+#define SERIALMSG_WRITE 1
+#define SERIALMSG_READ  2
+#define SERIALMSG_CRC   3
+#define SERIALMSG_LEDS  5
+#define SERIALMSG_RUN   7
+
+typedef nx_struct SerialReqPacket {
+  nx_uint8_t msg_type;
+  nx_uint8_t pad;
+  nx_uint16_t offset;
+  nx_uint16_t len;
+  nx_uint8_t data[0];
+} SerialReqPacket;
+
+#define SERIALMSG_SUCCESS 0
+#define SERIALMSG_FAIL    1
+
+typedef nx_struct SerialReplyPacket {
+  nx_uint8_t error;
+  nx_uint8_t pad;
+  nx_uint8_t data[0];
+} SerialReplyPacket;
+
+#endif
diff --git a/apps/tosthreads/tinyld/SerialLoader/SerialLoaderAppC.nc b/apps/tosthreads/tinyld/SerialLoader/SerialLoaderAppC.nc
new file mode 100755 (executable)
index 0000000..d9e4946
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * SerialLoader receives loadable programs from the serial port and stores
+ * it in a byte array. Then, when it receives the command to load the code,
+ * it makes the call to the dynamic loader.
+ * 
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Jeongyeup Paek <jpaek@enl.usc.edu>
+ */
+
+#include "AM.h"
+#include "SerialLoader.h"
+
+configuration SerialLoaderAppC {}
+implementation
+{
+  components MainC,
+             SerialActiveMessageC,
+             new SerialAMSenderC(0xAB),
+             new SerialAMReceiverC(0xAB),
+             SerialLoaderP,
+             BigCrcC,
+             LedsC;
+  
+  SerialLoaderP.Boot -> MainC;
+  SerialLoaderP.SerialSplitControl -> SerialActiveMessageC;
+  SerialLoaderP.SerialAMSender -> SerialAMSenderC;
+  SerialLoaderP.SerialAMReceiver -> SerialAMReceiverC;
+  SerialLoaderP.Leds -> LedsC;
+  SerialLoaderP.BigCrc -> BigCrcC;
+
+  components DynamicLoaderC;
+  SerialLoaderP.DynamicLoader -> DynamicLoaderC;
+}
+
diff --git a/apps/tosthreads/tinyld/SerialLoader/SerialLoaderP.nc b/apps/tosthreads/tinyld/SerialLoader/SerialLoaderP.nc
new file mode 100755 (executable)
index 0000000..b66e2ef
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * SerialLoader receives loadable programs from the serial port and stores
+ * it in a byte array. Then, when it receives the command to load the code,
+ * it makes the call to the dynamic loader.
+ * 
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Jeongyeup Paek <jpaek@enl.usc.edu>
+ **/
+
+#include "SerialLoader.h"
+
+module SerialLoaderP
+{
+  uses {
+    interface Boot;
+    interface SplitControl as SerialSplitControl;
+    interface AMSend as SerialAMSender;
+    interface Receive as SerialAMReceiver;
+    interface Leds;
+    interface DynamicLoader;
+    interface BigCrc;
+  }
+}
+implementation
+{
+  message_t serialMsg;
+  uint32_t dumpAddr = 0;
+  
+  uint8_t image[MAX_BIN_SIZE];
+
+  event void Boot.booted()
+  {
+    call SerialSplitControl.start();
+  }
+  
+  event void SerialSplitControl.startDone(error_t error)
+  {
+    if (error != SUCCESS) {
+      call SerialSplitControl.start();
+    }
+  }
+  
+  event void SerialSplitControl.stopDone(error_t error) {}
+  
+  void sendReply(error_t error, uint8_t len)
+  {
+    SerialReplyPacket *srpkt = (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg, sizeof(SerialReplyPacket));
+    if (error == SUCCESS) {
+      srpkt->error = SERIALMSG_SUCCESS;
+    } else {
+      srpkt->error = SERIALMSG_FAIL;
+    }
+    call SerialAMSender.send(AM_BROADCAST_ADDR, &serialMsg, len);
+  }
+  
+  
+  event void SerialAMSender.sendDone(message_t* msg, error_t error) {}
+  
+  error_t write_image(uint16_t offset, void *data, uint16_t len) {
+    if ((offset + len > MAX_BIN_SIZE) || (data == NULL))
+      return FAIL;
+    memcpy(&image[offset], data, len);
+    return SUCCESS;
+  }
+
+  error_t read_image(uint16_t offset, void *readbuf, uint16_t len) {
+    if ((offset + len > MAX_BIN_SIZE) || (readbuf == NULL))
+      return FAIL;
+    memcpy(readbuf, &image[offset], len);
+    return SUCCESS;
+  }
+
+  event void DynamicLoader.loadFromFlashDone(uint8_t volumeId, tosthread_t id, error_t error) {}
+  event void DynamicLoader.loadFromMemoryDone(void *addr, tosthread_t id, error_t error) {
+    sendReply(error, sizeof(SerialReplyPacket));
+  }
+
+  event void BigCrc.computeCrcDone(void* buf, uint16_t len, uint16_t crc, error_t error)
+  {
+    SerialReplyPacket *srpkt = (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg, sizeof(SerialReplyPacket));
+        
+    srpkt->data[1] = crc & 0xFF;
+    srpkt->data[0] = (crc >> 8) & 0xFF;
+    sendReply(SUCCESS, 2 + sizeof(SerialReplyPacket));
+  }
+
+  void sendCrcReply(uint16_t offset, uint16_t len)
+  {
+    call BigCrc.computeCrc(&(image[offset]), len);
+  }
+
+
+  event message_t* SerialAMReceiver.receive(message_t* msg, void* payload, uint8_t len)
+  {
+    uint16_t i;
+    error_t error = FAIL;
+    SerialReqPacket *srpkt = (SerialReqPacket *)payload;
+    SerialReplyPacket *serialMsg_payload = (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg, sizeof(SerialReplyPacket));
+    
+    switch (srpkt->msg_type) {
+      case SERIALMSG_ERASE :
+        for (i = 0; i < MAX_BIN_SIZE; i++) { image[i] = 0; }
+        call Leds.set(7);
+        for (i = 0; i < 2000; i++) {}
+        call Leds.set(0);
+        sendReply(SUCCESS, sizeof(SerialReplyPacket));
+        break;
+      case SERIALMSG_RUN :
+        error = call DynamicLoader.loadFromMemory(image);
+        if (error != SUCCESS)
+          sendReply(error, sizeof(SerialReplyPacket));
+        break;
+      case SERIALMSG_WRITE :
+        error = write_image(srpkt->offset, srpkt->data, srpkt->len);
+        if (error != SUCCESS)
+          call Leds.led0On();
+        sendReply(error, sizeof(SerialReplyPacket));
+        break;
+      case SERIALMSG_READ :
+        error = read_image(srpkt->offset, serialMsg_payload->data, srpkt->len);
+        if (error != SUCCESS)
+          sendReply(error, sizeof(SerialReplyPacket));
+        else
+          sendReply(error, len + sizeof(SerialReplyPacket));
+        break;
+      case SERIALMSG_LEDS:
+        call Leds.set(7);
+        for (i = 0; i < 2000; i++) {}
+        call Leds.set(0);
+        break;
+      case SERIALMSG_CRC :
+        sendCrcReply(srpkt->offset, srpkt->len);
+        break;
+    }
+    
+    return msg;
+  }
+}
+
diff --git a/apps/tosthreads/tinyld/SerialLoader/serialloader.py b/apps/tosthreads/tinyld/SerialLoader/serialloader.py
new file mode 100755 (executable)
index 0000000..f7964dd
--- /dev/null
@@ -0,0 +1,232 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2008 Johns Hopkins University.
+# All rights reserved.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose, without fee, and without written
+# agreement is hereby granted, provided that the above copyright
+# notice, the (updated) modification history and the author appear in
+# all copies of this source code.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+# OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+# @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+
+import sys, os, stat, struct
+import tinyos
+
+SERIAL_BAUDRATE = 57600
+SERIALMSG_AMGROUP = 0
+SERIALMSG_AMID    = 0xAB
+
+SERIALMSG_ERASE = 0
+SERIALMSG_WRITE = 1
+SERIALMSG_READ  = 2
+SERIALMSG_CRC   = 3
+SERIALMSG_LEDS  = 5
+SERIALMSG_RUN   = 7
+
+SERIALMSG_SUCCESS = 0
+SERIALMSG_FAIL    = 1
+
+SERIALMSG_DATA_PAYLOAD_SIZE = 20
+MAX_BIN_SIZE = 2000
+
+HEX_OUTPUT_LINE_SIZE = 16
+
+class SerialReqPacket(tinyos.GenericPacket):
+  def __init__(self, packet = None):
+      tinyos.GenericPacket.__init__(self,
+                             [('msg_type', 'int', 1),
+                              ('pad', 'int', 1),
+                              ('offset', 'int', 2),
+                              ('len', 'int', 2),
+                              ('data', 'blob', None)],
+                             packet)
+
+class SerialReplyPacket(tinyos.GenericPacket):
+  def __init__(self, packet = None):
+      tinyos.GenericPacket.__init__(self,
+                             [('error', 'int', 1),
+                              ('pad', 'int', 1),
+                             ('data', 'blob', None)],
+                             packet)
+
+# Display an integer representation of byte stream to hex representation
+def print_hex(start_addr, byte_stream):
+  byte_stream = ["%02x" % one_byte for one_byte in byte_stream]   # Converts to each byte to hex
+  
+  num_iterations = int( (len(byte_stream) - 1) / HEX_OUTPUT_LINE_SIZE )
+  num_iterations += 1
+  
+  for i in range(num_iterations):
+    line = "%07x" % start_addr + " "   # Prints memory address
+    for j in range(HEX_OUTPUT_LINE_SIZE):
+      if (i * HEX_OUTPUT_LINE_SIZE + j) < len(byte_stream):
+        line += byte_stream[i * HEX_OUTPUT_LINE_SIZE + j] + " "
+    print line
+    
+    start_addr += HEX_OUTPUT_LINE_SIZE
+
+def op_run(s, sreqpkt):
+  success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+  if success == True:
+    packet = s.read_packet()
+    sreplypkt = SerialReplyPacket(packet[1])
+    return (sreplypkt.error == SERIALMSG_SUCCESS)
+
+def op_erase(s, sreqpkt):
+  success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+  if success == True:
+    packet = s.read_packet()
+    sreplypkt = SerialReplyPacket(packet[1])
+    return (sreplypkt.error == SERIALMSG_SUCCESS)
+
+def op_print(s, sreqpkt, offset, length):
+  if (offset + length) <= DELUGE_VOLUME_SIZE:
+    while length > 0:
+      sreqpkt.offset = offset
+      # Calculates the payload size for the reply packet
+      if length >= HEX_OUTPUT_LINE_SIZE:
+        sreqpkt.len = HEX_OUTPUT_LINE_SIZE
+      else:
+        sreqpkt.len = length
+      
+      success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+      if success == True:
+        packet = s.read_packet()
+        sreplypkt = SerialReplyPacket(packet[1])
+        if sreplypkt.error != SERIALMSG_SUCCESS:
+          return False
+  
+      print_hex(offset, sreplypkt.data)
+      length -= sreqpkt.len
+      offset += sreqpkt.len
+  else:
+    print "ERROR: Specified offset and length are too large for the flash volume"
+    return False
+  
+  return True
+
+def op_write(s, sreqpkt, input_file, length):
+  local_crc = 0
+  input_file_size = length
+  
+  sreqpkt.offset = 0
+  while length > 0:
+    # Calculates the payload size for the current packet
+    if length >= SERIALMSG_DATA_PAYLOAD_SIZE:
+      sreqpkt.len = SERIALMSG_DATA_PAYLOAD_SIZE
+    else:
+      sreqpkt.len = length
+    sreqpkt.data = []
+    
+    # Reads in the file we want to transmit
+    for i in range(sreqpkt.len):
+      sreqpkt.data.append(struct.unpack("B", input_file.read(1))[0])
+    
+    # Sends over serial to the mote
+    if s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload()) == True:
+      # Waiting for confirmation
+      packet = s.read_packet()
+      sreplypkt = SerialReplyPacket(packet[1])
+      if sreplypkt.error != SERIALMSG_SUCCESS:
+        print "ERROR: !SUCCESS"
+        return False
+      local_crc = s.crc16(local_crc, sreqpkt.data)   # Computes running CRC
+    else:
+      print "ERROR: Unable to write to flash"
+      return False
+    
+    length -= sreqpkt.len
+    sreqpkt.offset += sreqpkt.len
+  
+  # Check local and remote CRC
+  sreqpkt.msg_type = SERIALMSG_CRC
+  remote_crc = op_crc(s, sreqpkt, 0, input_file_size)
+  if remote_crc != None:
+    local_crc = [(local_crc >> 8) & 0xFF, local_crc & 0xFF]
+    print "Local CRC:  " + ("%02x" % local_crc[0]) + " " + ("%02x" % local_crc[1])
+    print "Remote CRC: " + ("%02x" % remote_crc[0]) + " " + ("%02x" % remote_crc[1])
+    if remote_crc != local_crc:
+      print "ERROR: Remote CRC doesn't match local CRC"
+      return False
+  else:
+    print "ERROR: Unable to verify CRC"
+    return False
+
+  return True
+
+def op_crc(s, sreqpkt, offset, length):
+  sreqpkt.offset = offset
+  sreqpkt.len = length
+  success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+  if success == True:
+    packet = s.read_packet()
+    sreplypkt = SerialReplyPacket(packet[1])
+    if sreplypkt.error == SERIALMSG_SUCCESS:
+      return sreplypkt.data
+    else:
+      return None
+
+def op_leds(s, sreqpkt):
+  success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+
+# ======== MAIN ======== #
+if len(sys.argv) >= 3:
+  sys.argv[2] = int(sys.argv[2])
+  
+  s = tinyos.Serial(sys.argv[1], SERIAL_BAUDRATE)
+  s.set_debug(False)   # Disables debug msg
+  sreqpkt = SerialReqPacket((sys.argv[2], 0, 0, 0, []))   # msg_type, pad, offset, length, data
+  
+  if sys.argv[2] == SERIALMSG_RUN:
+    if op_run(s, sreqpkt) == True:
+      print "Loaded image should be running now!"
+    else:
+      print "ERROR: Unable to run loaded image"
+    
+  elif sys.argv[2] == SERIALMSG_ERASE:
+    if op_erase(s, sreqpkt) == True:
+      print "Flash volume has been erased"
+    else:
+      print "ERROR: Unable to erase flash volume"
+    
+  elif sys.argv[2] == SERIALMSG_WRITE:
+    input_file = file(sys.argv[3], 'rb')
+    fileStats = os.stat(sys.argv[3])
+    
+    if fileStats[stat.ST_SIZE] <= MAX_BIN_SIZE:
+      #sreqpkt = SerialReqPacket((SERIALMSG_LEDS, 0, 0, 0, []))
+      #op_leds(s, sreqpkt)
+      sreqpkt = SerialReqPacket((sys.argv[2], 0, 0, 0, []))
+      if op_write(s, sreqpkt, input_file, fileStats[stat.ST_SIZE]) == True:
+        print "File has been successfully transmitted (" + str(fileStats[stat.ST_SIZE]) + " bytes)"
+      else:
+        print "ERROR: Unable to transmit file"
+      sreqpkt = SerialReqPacket((SERIALMSG_LEDS, 0, 0, 0, []))
+      op_leds(s, sreqpkt)
+    else:
+      print "ERROR: File is larger than max buffer size (" + str(MAX_BIN_SIZE) + ")"
+  
+  elif sys.argv[2] == SERIALMSG_READ:
+    data = op_print(s, sreqpkt, int(sys.argv[3]), int(sys.argv[4]))
+    if data != True:
+      print "ERROR: Unable to read the specified range"
+    
+  elif sys.argv[2] == SERIALMSG_CRC:
+    remote_crc = op_crc(s, sreqpkt, int(sys.argv[3]), int(sys.argv[4]))
+    if remote_crc != None:
+      print_hex(0, remote_crc)
+    else:
+      print "ERROR: Unable to compute remote CRC"
diff --git a/apps/tosthreads/tinyld/SerialLoader/tinyos.py b/apps/tosthreads/tinyld/SerialLoader/tinyos.py
new file mode 100755 (executable)
index 0000000..e922f58
--- /dev/null
@@ -0,0 +1,223 @@
+import struct, time, serial
+
+class Serial:
+  HDLC_FLAG_BYTE = 0x7e
+  HDLC_CTLESC_BYTE = 0x7d
+  
+  TOS_SERIAL_ACTIVE_MESSAGE_ID = 0
+  TOS_SERIAL_CC1000_ID = 1
+  TOS_SERIAL_802_15_4_ID = 2
+  TOS_SERIAL_UNKNOWN_ID = 255
+  
+  SERIAL_PROTO_ACK = 67
+  SERIAL_PROTO_PACKET_ACK = 68
+  SERIAL_PROTO_PACKET_NOACK = 69
+  SERIAL_PROTO_PACKET_UNKNOWN = 255
+  
+  __s = None;       # An instance of serial.Serial object
+  __debug = True   # Debug mode
+  
+  def __init__(self, port, baudrate):
+     self.__s = serial.Serial(port, baudrate, rtscts=0)
+  
+  def __format_packet(self, packet):
+      return " ".join(["%02x" % p for p in packet]) + " | " + \
+             " ".join(["%d" % p for p in packet])
+  
+  def crc16(self, base_crc, frame_data):
+      crc = base_crc
+      for b in frame_data:
+          crc = crc ^ (b << 8)
+          for i in range(0, 8):
+              if crc & 0x8000 == 0x8000:
+                  crc = (crc << 1) ^ 0x1021
+              else:
+                  crc = crc << 1
+              crc = crc & 0xffff
+      return crc
+  
+  def __encode(self, val, dim):
+      output = []
+      for i in range(dim):
+          output.append(val & 0xFF)
+          val = val >> 8
+      return output
+  
+  def __decode(self, v):
+      r = long(0)
+      for i in v[::-1]:
+          r = (r << 8) + i
+      return r
+  
+  def __get_byte(self):
+      r = struct.unpack("B", self.__s.read())[0]
+      return r
+  
+  def __put_bytes(self, data):
+      for b in data:
+          self.__s.write(struct.pack('B', b))
+  
+  def __unescape(self, packet):
+      r = []
+      esc = False
+      for b in packet:
+          if esc:
+              r.append(b ^ 0x20)
+              esc = False
+          elif b == self.HDLC_CTLESC_BYTE:
+              esc = True
+          else:
+              r.append(b)
+      return r
+  
+  def __escape(self, packet):
+      r = []
+      for b in packet:
+          if b == self.HDLC_FLAG_BYTE or b == self.HDLC_CTLESC_BYTE:
+              r.append(self.HDLC_CTLESC_BYTE)
+              r.append(b ^ 0x20)
+          else:
+              r.append(b)
+      return r
+  
+  def read_packet(self):
+      d = self.__get_byte()
+      ts = time.time()
+      while d != self.HDLC_FLAG_BYTE:
+          d = self.__get_byte()
+          ts = time.time()
+      packet = [d]
+      d = self.__get_byte()
+      if d == self.HDLC_FLAG_BYTE:
+          d = self.__get_byte()
+          ts = time.time()
+      else:
+          packet.append(d)
+      while d != self.HDLC_FLAG_BYTE:
+          d = self.__get_byte()
+          packet.append(d)
+      un_packet = self.__unescape(packet)
+      crc = self.crc16(0, un_packet[1:-3])
+      packet_crc = self.__decode(un_packet[-3:-1])
+      if crc != packet_crc:
+          print "Warning: wrong CRC!"
+      if self.__debug == True:
+          print "Recv:", self.__format_packet(un_packet)
+      return (ts, un_packet)
+      
+  def write_packet(self, am_group, am_id, data):
+      # The first byte after SERIAL_PROTO_PACKET_ACK is a sequence
+      # number that will be send back by the mote to ack the receive of
+      # the data.
+      packet = [self.SERIAL_PROTO_PACKET_ACK, 0, self.TOS_SERIAL_ACTIVE_MESSAGE_ID,
+                0xff, 0xff,
+                0, 0,
+                len(data), am_group, am_id] + data;
+      crc = self.crc16(0, packet)
+      packet.append(crc & 0xff)
+      packet.append((crc >> 8) & 0xff)
+      packet = [self.HDLC_FLAG_BYTE] + self.__escape(packet) + [self.HDLC_FLAG_BYTE]
+      if self.__debug == True:
+          print "Send:", self.__format_packet(packet)
+      self.__put_bytes(packet)
+      
+      # Waiting for ACK
+      packet = self.read_packet()
+      if len(packet) > 1 and len(packet[1]) > 1:
+        return ((packet[1])[1] == self.SERIAL_PROTO_ACK)
+      return False
+  
+  def set_debug(self, debug):
+      self.__debug = debug
+
+class GenericPacket:
+    """ GenericPacket """
+
+    def __decode(self, v):
+        r = long(0)
+        for i in v:
+            r = (r << 8) + i
+        return r
+    
+    def __encode(self, val, dim):
+        output = []
+        for i in range(dim):
+            output.append(int(val & 0xFF))
+            val = val >> 8
+        output.reverse()
+        return output
+
+    def __init__(self, desc, packet = None):
+        self.__dict__['_schema'] = [(t, s) for (n, t, s) in desc]
+        self.__dict__['_names'] = [n for (n, t, s) in desc]
+        self.__dict__['_values'] = []
+        offset = 10
+        if type(packet) == type([]):
+            for (t, s) in self._schema:
+                if t == 'int':
+                    self._values.append(self.__decode(packet[offset:offset + s]))
+                    offset += s
+                elif t == 'blob':
+                    if s:
+                        self._values.append(packet[offset:offset + s])
+                        offset += s
+                    else:
+                        self._values.append(packet[offset:-3])
+        elif type(packet) == type(()):
+            for i in packet:
+                self._values.append(i)
+        else:
+            for v in self._schema:
+                self._values.append(None)
+
+    def __repr__(self):
+        return self._values.__repr__()
+
+    def __str__(self):
+        return self._values.__str__()
+
+    # Implement the map behavior
+    def __getitem__(self, key):
+        return self.__getattr__(key)
+
+    def __setitem__(self, key, value):
+        self.__setattr__(key, value)
+
+    def __len__(self):
+        return len(self._values)
+
+    def keys(self):
+        return self._names
+
+    def values(self):
+        return self._names
+
+    # Implement the struct behavior
+    def __getattr__(self, name):
+        if type(name) == type(0):
+            return self._names[name]
+        else:
+            return self._values[self._names.index(name)]
+
+    def __setattr__(self, name, value):
+        if type(name) == type(0):
+            self._values[name] = value
+        else:
+            self._values[self._names.index(name)] = value
+
+    # Custom
+    def names(self):
+        return self._names
+
+    def sizes(self):
+        return self._schema
+
+    def payload(self):
+        r = []
+        for i in range(len(self._schema)):
+            (t, s) = self._schema[i]
+            if t == 'int':
+                r += self.__encode(self._values[i], s)
+            else:
+                r += self._values[i]
+        return r
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/FlashVolumeManager.h b/apps/tosthreads/tinyld/SerialLoaderFlash/FlashVolumeManager.h
new file mode 100755 (executable)
index 0000000..8b2b5e3
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#ifndef FLASHVOLUMEMANAGER_H
+#define FLASHVOLUMEMANAGER_H
+
+#define SERIALMSG_ERASE 0
+#define SERIALMSG_WRITE 1
+#define SERIALMSG_READ  2
+#define SERIALMSG_CRC   3
+//#define SERIALMSG_ADDR  4
+#define SERIALMSG_LEDS 5
+#define SERIALMSG_RUN  7
+
+typedef nx_struct SerialReqPacket {
+  nx_uint8_t msg_type;
+  nx_uint8_t pad;
+  nx_uint16_t offset;
+  nx_uint16_t len;
+  nx_uint8_t data[0];
+} SerialReqPacket;
+
+#define SERIALMSG_SUCCESS 0
+#define SERIALMSG_FAIL    1
+
+typedef nx_struct SerialReplyPacket {
+  nx_uint8_t error;
+  nx_uint8_t pad;
+  nx_uint8_t data[0];
+} SerialReplyPacket;
+
+#endif
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/FlashVolumeManagerC.nc b/apps/tosthreads/tinyld/SerialLoaderFlash/FlashVolumeManagerC.nc
new file mode 100755 (executable)
index 0000000..bb9440f
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * SerialLoaderFlash is similar to SerialLoader in that it receives
+ * loadable programs from the serial port. However, SerialLoaderFlash
+ * stores them on the external flash. Then, when it receives the command to
+ * load the code, it makes the call to the dynamic loader.
+ * 
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "AM.h"
+
+generic configuration FlashVolumeManagerC(am_id_t AMId)
+{
+  uses {
+    interface BlockRead;
+    interface BlockWrite;
+    interface DynamicLoader;
+  }
+}
+
+implementation
+{
+  components MainC,
+             SerialActiveMessageC,
+             new SerialAMSenderC(AMId),
+             new SerialAMReceiverC(AMId),
+             new FlashVolumeManagerP(),
+             NoLedsC, LedsC;
+  
+  DynamicLoader = FlashVolumeManagerP;
+  BlockRead = FlashVolumeManagerP;
+  BlockWrite = FlashVolumeManagerP;
+  
+  FlashVolumeManagerP.Boot -> MainC;
+  FlashVolumeManagerP.SerialSplitControl -> SerialActiveMessageC;
+
+  FlashVolumeManagerP.SerialAMSender -> SerialAMSenderC;
+  FlashVolumeManagerP.SerialAMReceiver -> SerialAMReceiverC;
+  FlashVolumeManagerP.Leds -> LedsC;
+}
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/FlashVolumeManagerP.nc b/apps/tosthreads/tinyld/SerialLoaderFlash/FlashVolumeManagerP.nc
new file mode 100755 (executable)
index 0000000..b28855d
--- /dev/null
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * SerialLoaderFlash is similar to SerialLoader in that it receives
+ * loadable programs from the serial port. However, SerialLoaderFlash
+ * stores them on the external flash. Then, when it receives the command to
+ * load the code, it makes the call to the dynamic loader.
+ * 
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "FlashVolumeManager.h"
+#include "StorageVolumes.h"
+
+generic module FlashVolumeManagerP()
+{
+  uses {
+    interface Boot;
+    interface SplitControl as SerialSplitControl;
+    interface BlockRead;
+    interface BlockWrite;
+    interface AMSend as SerialAMSender;
+    interface Receive as SerialAMReceiver;
+    interface Leds;
+    interface DynamicLoader;
+  }
+}
+
+implementation
+{
+  message_t serialMsg;
+  storage_addr_t dumpAddr = 0;
+  
+  event void Boot.booted() {
+    while (call SerialSplitControl.start() != SUCCESS);
+  }
+  
+  event void SerialSplitControl.startDone(error_t error)
+  {
+    if (error != SUCCESS) {
+      while (call SerialSplitControl.start() != SUCCESS);
+    }
+  }
+    
+  void sendReply(error_t error, storage_len_t len)
+  {
+    SerialReplyPacket *srpkt = (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg, sizeof(SerialReplyPacket));
+    if (error == SUCCESS) {
+      srpkt->error = SERIALMSG_SUCCESS;
+    } else {
+      srpkt->error = SERIALMSG_FAIL;
+    }
+    call SerialAMSender.send(AM_BROADCAST_ADDR, &serialMsg, len);
+  }
+  
+  event void BlockRead.readDone(storage_addr_t addr, void* buf, storage_len_t len, error_t error) {
+    sendReply(error, len + sizeof(SerialReplyPacket));
+  }
+  
+  event void BlockRead.computeCrcDone(storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error)
+  {
+    if (error == SUCCESS) {
+      SerialReplyPacket *srpkt = (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg, sizeof(SerialReplyPacket));
+      srpkt->data[1] = crc & 0xFF;
+      srpkt->data[0] = (crc >> 8) & 0xFF;
+    }
+    sendReply(error, 2 + sizeof(SerialReplyPacket));
+  }
+  
+  event void BlockWrite.writeDone(storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    if (error != SUCCESS) {
+      call Leds.led1On();
+    }
+    sendReply(error, sizeof(SerialReplyPacket));
+  }
+  
+  event void BlockWrite.eraseDone(error_t error) {
+    sendReply(error, sizeof(SerialReplyPacket));
+  }
+    
+  event message_t* SerialAMReceiver.receive(message_t* msg, void* payload, uint8_t len)
+  {
+    uint16_t i;
+    error_t error = SUCCESS;
+    SerialReqPacket *srpkt = (SerialReqPacket *)payload;
+    SerialReplyPacket *serialMsg_payload = (SerialReplyPacket *)call SerialAMSender.getPayload(&serialMsg, sizeof(SerialReplyPacket));
+    
+    switch (srpkt->msg_type) {
+      case SERIALMSG_ERASE :
+        error = call BlockWrite.erase();
+        if (error != SUCCESS) {
+          sendReply(error, sizeof(SerialReplyPacket));
+        }
+        break;
+      case SERIALMSG_WRITE :
+        call Leds.led2On();
+        error = call BlockWrite.write(srpkt->offset, srpkt->data, srpkt->len);
+        if (error != SUCCESS) {
+          sendReply(error, sizeof(SerialReplyPacket));
+          call Leds.led0On();
+        }
+        break;
+      case SERIALMSG_READ :
+        error = call BlockRead.read(srpkt->offset, serialMsg_payload->data, srpkt->len);
+        if (error != SUCCESS) {
+          sendReply(error, sizeof(SerialReplyPacket));
+        }
+        break;
+      case SERIALMSG_CRC :
+        error = call BlockRead.computeCrc(srpkt->offset, srpkt->len, 0);
+        if (error != SUCCESS) {
+          sendReply(error, sizeof(SerialReplyPacket));
+        }
+        break;
+      case SERIALMSG_LEDS:
+        call Leds.set(7);
+        for (i = 0; i < 2000; i++) {}
+        call Leds.set(0);
+        break;
+      case SERIALMSG_RUN :
+        error = call DynamicLoader.loadFromFlash(VOLUME_MICROEXEIMAGE);
+        if (error != SUCCESS)
+          sendReply(error, sizeof(SerialReplyPacket));
+        break;
+    }
+    
+    return msg;
+  }
+  
+  event void DynamicLoader.loadFromFlashDone(uint8_t volumeId, tosthread_t id, error_t error) {
+    sendReply(error, sizeof(SerialReplyPacket));
+  }
+  
+  event void DynamicLoader.loadFromMemoryDone(void *addr, tosthread_t id, error_t error) {}
+  event void BlockWrite.syncDone(error_t error) {}
+  event void SerialAMSender.sendDone(message_t* msg, error_t error) {}
+  event void SerialSplitControl.stopDone(error_t error) {} 
+}
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/Makefile b/apps/tosthreads/tinyld/SerialLoaderFlash/Makefile
new file mode 100755 (executable)
index 0000000..83d3dbe
--- /dev/null
@@ -0,0 +1,22 @@
+COMPONENT=SerialLoaderFlashAppC
+
+GOALS += threads
+
+THREADS_DIR ?= $(TOSDIR)/lib/tosthreads
+CFLAGS += -I$(THREADS_DIR)/lib/tinyld
+CFLAGS += -I$(THREADS_DIR)/csystem
+CFLAGS += -I$(THREADS_DIR)/sensorboards/tmote_onboard
+CFLAGS += -I$(THREADS_DIR)/sensorboards/universal
+CFLAGS += -I$(THREADS_DIR)/lib/net/ctp
+CFLAGS += -I$(THREADS_DIR)/lib/net
+CFLAGS += -I$(TOSDIR)/lib/net
+CFLAGS += -I$(TOSDIR)/lib/net/ctp
+CFLAGS += -I$(TOSDIR)/lib/net/4bitle
+CFLAGS += -I$(THREADS_DIR)/lib/printf
+
+# Creates VolumeMapC.nc
+VOLUME_ALLOCATOR_FLAGS += -t
+
+CLEAN_EXTRA += *.pyc
+
+include $(MAKERULES)
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/README b/apps/tosthreads/tinyld/SerialLoaderFlash/README
new file mode 100755 (executable)
index 0000000..cbeaf47
--- /dev/null
@@ -0,0 +1,34 @@
+README for SerialLoaderFlash
+Author/Contact: Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+
+Description:
+
+SerialLoaderFlash is similar to SerialLoader in that it receives
+loadable programs from the serial port. However, SerialLoaderFlash
+stores them on the external flash. Then, when it receives the command to
+load the code, it makes the call to the dynamic loader.
+
+Here are the steps:
+1.) Load SerialLoader:
+    make telosb install bsl,<device_port>
+    
+2.) Create the loadable code, main.tos:
+       cd ../../capps/Blink
+       make telosb dynthreads
+       (the output file needed is ../../capps/Blink/build/telosb/dynthreads/main.tos)  
+
+3.) Erase the external flash:
+    ./serialloader.py <device_port> 0
+
+4.) Upload the binary:
+    ./serialloader.py <device_port> 1 main.tos
+    
+5.) Run the binary:
+    ./serialloader.py <device_port> 7
+
+Tools:
+  None.
+
+Known bugs/limitations:
+  None.
+
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/SerialLoaderFlashAppC.nc b/apps/tosthreads/tinyld/SerialLoaderFlash/SerialLoaderFlashAppC.nc
new file mode 100755 (executable)
index 0000000..e650d1f
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * SerialLoaderFlash is similar to SerialLoader in that it receives
+ * loadable programs from the serial port. However, SerialLoaderFlash
+ * stores them on the external flash. Then, when it receives the command to
+ * load the code, it makes the call to the dynamic loader.
+ * 
+ * @author Kevin Klues (klueska@cs.stanford.edu)
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "StorageVolumes.h"
+
+configuration SerialLoaderFlashAppC {}
+
+implementation {  
+  components DynamicLoaderC,
+             new FlashVolumeManagerC(0xAB),
+             new BlockStorageC(VOLUME_MICROEXEIMAGE) as ImageVolume;
+  
+  FlashVolumeManagerC.BlockRead -> ImageVolume;
+  FlashVolumeManagerC.BlockWrite -> ImageVolume;
+  FlashVolumeManagerC.DynamicLoader -> DynamicLoaderC;
+}
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/serialloader.py b/apps/tosthreads/tinyld/SerialLoaderFlash/serialloader.py
new file mode 100755 (executable)
index 0000000..686bf95
--- /dev/null
@@ -0,0 +1,229 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2008 Johns Hopkins University.
+# All rights reserved.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose, without fee, and without written
+# agreement is hereby granted, provided that the above copyright
+# notice, the (updated) modification history and the author appear in
+# all copies of this source code.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+# OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+# @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+
+import sys, os, stat, struct
+import tinyos
+
+SERIALMSG_AMGROUP = 0
+SERIALMSG_AMID    = 0xAB
+
+SERIALMSG_ERASE = 0
+SERIALMSG_WRITE = 1
+SERIALMSG_READ  = 2
+SERIALMSG_CRC   = 3
+SERIALMSG_LEDS   = 5
+SERIALMSG_RUN   = 7
+
+SERIALMSG_SUCCESS = 0
+SERIALMSG_FAIL    = 1
+
+SERIALMSG_DATA_PAYLOAD_SIZE = 20
+DELUGE_VOLUME_SIZE = 262144
+
+HEX_OUTPUT_LINE_SIZE = 16
+
+class SerialReqPacket(tinyos.GenericPacket):
+  def __init__(self, packet = None):
+      tinyos.GenericPacket.__init__(self,
+                             [('msg_type', 'int', 1),
+                              ('pad', 'int', 1),
+                              ('offset', 'int', 2),
+                              ('len', 'int', 2),
+                              ('data', 'blob', None)],
+                             packet)
+
+class SerialReplyPacket(tinyos.GenericPacket):
+  def __init__(self, packet = None):
+      tinyos.GenericPacket.__init__(self,
+                             [('error', 'int', 1),
+                              ('pad', 'int', 1),
+                             ('data', 'blob', None)],
+                             packet)
+
+# Display an integer representation of byte stream to hex representation
+def print_hex(start_addr, byte_stream):
+  byte_stream = ["%02x" % one_byte for one_byte in byte_stream]   # Converts to each byte to hex
+  
+  num_iterations = int( (len(byte_stream) - 1) / HEX_OUTPUT_LINE_SIZE )
+  num_iterations += 1
+  
+  for i in range(num_iterations):
+    line = "%07x" % start_addr + " "   # Prints memory address
+    for j in range(HEX_OUTPUT_LINE_SIZE):
+      if (i * HEX_OUTPUT_LINE_SIZE + j) < len(byte_stream):
+        line += byte_stream[i * HEX_OUTPUT_LINE_SIZE + j] + " "
+    print line
+    
+    start_addr += HEX_OUTPUT_LINE_SIZE
+
+def op_run(s, sreqpkt):
+  success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+  if success == True:
+    packet = s.read_packet()
+    sreplypkt = SerialReplyPacket(packet[1])
+    return (sreplypkt.error == SERIALMSG_SUCCESS)
+
+def op_erase(s, sreqpkt):
+  success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+  if success == True:
+    packet = s.read_packet()
+    sreplypkt = SerialReplyPacket(packet[1])
+    return (sreplypkt.error == SERIALMSG_SUCCESS)
+
+def op_print(s, sreqpkt, offset, length):
+  if (offset + length) <= DELUGE_VOLUME_SIZE:
+    while length > 0:
+      sreqpkt.offset = offset
+      # Calculates the payload size for the reply packet
+      if length >= HEX_OUTPUT_LINE_SIZE:
+        sreqpkt.len = HEX_OUTPUT_LINE_SIZE
+      else:
+        sreqpkt.len = length
+      
+      success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+      if success == True:
+        packet = s.read_packet()
+        sreplypkt = SerialReplyPacket(packet[1])
+        if sreplypkt.error != SERIALMSG_SUCCESS:
+          return False
+  
+      print_hex(offset, sreplypkt.data)
+      length -= sreqpkt.len
+      offset += sreqpkt.len
+  else:
+    print "ERROR: Specified offset and length are too large for the flash volume"
+    return False
+  
+  return True
+
+def op_write(s, sreqpkt, input_file, length):
+  local_crc = 0
+  input_file_size = length
+  
+  sreqpkt.offset = 0
+  while length > 0:
+    # Calculates the payload size for the current packet
+    if length >= SERIALMSG_DATA_PAYLOAD_SIZE:
+      sreqpkt.len = SERIALMSG_DATA_PAYLOAD_SIZE
+    else:
+      sreqpkt.len = length
+    sreqpkt.data = []
+    
+    # Reads in the file we want to transmit
+    for i in range(sreqpkt.len):
+      sreqpkt.data.append(struct.unpack("B", input_file.read(1))[0])
+    
+    # Sends over serial to the mote
+    if s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload()) == True:
+      # Waiting for confirmation
+      packet = s.read_packet()
+      sreplypkt = SerialReplyPacket(packet[1])
+      if sreplypkt.error != SERIALMSG_SUCCESS:
+        return False
+      local_crc = s.crc16(local_crc, sreqpkt.data)   # Computes running CRC
+    else:
+      print "ERROR: Unable to write to flash"
+      return False
+    
+    length -= sreqpkt.len
+    sreqpkt.offset += sreqpkt.len
+  
+  # Check local and remote CRC
+  sreqpkt.msg_type = SERIALMSG_CRC
+  remote_crc = op_crc(s, sreqpkt, 0, input_file_size)
+  if remote_crc != None:
+    local_crc = [(local_crc >> 8) & 0xFF, local_crc & 0xFF]
+    print "Local CRC:  " + ("%02x" % local_crc[0]) + " " + ("%02x" % local_crc[1])
+    print "Remote CRC: " + ("%02x" % remote_crc[0]) + " " + ("%02x" % remote_crc[1])
+    if remote_crc != local_crc:
+      print "ERROR: Remote CRC doesn't match local CRC"
+      return False
+  else:
+    print "ERROR: Unable to verify CRC"
+    return False
+    
+  return True
+
+def op_crc(s, sreqpkt, offset, length):
+  sreqpkt.offset = offset
+  sreqpkt.len = length
+  success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+  if success == True:
+    packet = s.read_packet()
+    sreplypkt = SerialReplyPacket(packet[1])
+    if sreplypkt.error == SERIALMSG_SUCCESS:
+      return sreplypkt.data
+    else:
+      return None
+
+def op_leds(s, sreqpkt):
+  success = s.write_packet(SERIALMSG_AMGROUP, SERIALMSG_AMID, sreqpkt.payload())
+
+# ======== MAIN ======== #
+if len(sys.argv) >= 3:
+  sys.argv[2] = int(sys.argv[2])
+  
+  s = tinyos.Serial(sys.argv[1], 57600)
+  s.set_debug(False)   # Disables debug msg
+  sreqpkt = SerialReqPacket((sys.argv[2], 0, 0, 0, []))   # msg_type, pad, offset, length, data
+  
+  if sys.argv[2] == SERIALMSG_RUN:
+    if op_run(s, sreqpkt) == True:
+      print "Loaded image should be running now!"
+    else:
+      print "ERROR: Unable to run loaded image"
+  elif sys.argv[2] == SERIALMSG_ERASE:
+    if op_erase(s, sreqpkt) == True:
+      print "Flash volume has been erased"
+    else:
+      print "ERROR: Unable to erase flash volume"
+    
+  elif sys.argv[2] == SERIALMSG_WRITE:
+    input_file = file(sys.argv[3], 'rb')
+    fileStats = os.stat(sys.argv[3])
+    
+    if fileStats[stat.ST_SIZE] <= DELUGE_VOLUME_SIZE:
+      #sreqpkt = SerialReqPacket((SERIALMSG_LEDS, 0, 0, 0, []))
+      #op_leds(s, sreqpkt)
+      sreqpkt = SerialReqPacket((sys.argv[2], 0, 0, 0, []))
+      if op_write(s, sreqpkt, input_file, fileStats[stat.ST_SIZE]) == True:
+        print "File has been successfully transmitted (" + str(fileStats[stat.ST_SIZE]) + " bytes)"
+      else:
+        print "ERROR: Unable to transmit file"
+      sreqpkt = SerialReqPacket((SERIALMSG_LEDS, 0, 0, 0, []))
+      op_leds(s, sreqpkt)
+    else:
+      print "ERROR: File is larger than flash volume (" + DELUGE_VOLUME_SIZE + ")"
+  
+  elif sys.argv[2] == SERIALMSG_READ:
+    data = op_print(s, sreqpkt, int(sys.argv[3]), int(sys.argv[4]))
+    if data != True:
+      print "ERROR: Unable to read the specified range"
+    
+  elif sys.argv[2] == SERIALMSG_CRC:
+    remote_crc = op_crc(s, sreqpkt, int(sys.argv[3]), int(sys.argv[4]))
+    if remote_crc != None:
+      print_hex(0, remote_crc)
+    else:
+      print "ERROR: Unable to compute remote CRC"
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/tinyos.py b/apps/tosthreads/tinyld/SerialLoaderFlash/tinyos.py
new file mode 100755 (executable)
index 0000000..e922f58
--- /dev/null
@@ -0,0 +1,223 @@
+import struct, time, serial
+
+class Serial:
+  HDLC_FLAG_BYTE = 0x7e
+  HDLC_CTLESC_BYTE = 0x7d
+  
+  TOS_SERIAL_ACTIVE_MESSAGE_ID = 0
+  TOS_SERIAL_CC1000_ID = 1
+  TOS_SERIAL_802_15_4_ID = 2
+  TOS_SERIAL_UNKNOWN_ID = 255
+  
+  SERIAL_PROTO_ACK = 67
+  SERIAL_PROTO_PACKET_ACK = 68
+  SERIAL_PROTO_PACKET_NOACK = 69
+  SERIAL_PROTO_PACKET_UNKNOWN = 255
+  
+  __s = None;       # An instance of serial.Serial object
+  __debug = True   # Debug mode
+  
+  def __init__(self, port, baudrate):
+     self.__s = serial.Serial(port, baudrate, rtscts=0)
+  
+  def __format_packet(self, packet):
+      return " ".join(["%02x" % p for p in packet]) + " | " + \
+             " ".join(["%d" % p for p in packet])
+  
+  def crc16(self, base_crc, frame_data):
+      crc = base_crc
+      for b in frame_data:
+          crc = crc ^ (b << 8)
+          for i in range(0, 8):
+              if crc & 0x8000 == 0x8000:
+                  crc = (crc << 1) ^ 0x1021
+              else:
+                  crc = crc << 1
+              crc = crc & 0xffff
+      return crc
+  
+  def __encode(self, val, dim):
+      output = []
+      for i in range(dim):
+          output.append(val & 0xFF)
+          val = val >> 8
+      return output
+  
+  def __decode(self, v):
+      r = long(0)
+      for i in v[::-1]:
+          r = (r << 8) + i
+      return r
+  
+  def __get_byte(self):
+      r = struct.unpack("B", self.__s.read())[0]
+      return r
+  
+  def __put_bytes(self, data):
+      for b in data:
+          self.__s.write(struct.pack('B', b))
+  
+  def __unescape(self, packet):
+      r = []
+      esc = False
+      for b in packet:
+          if esc:
+              r.append(b ^ 0x20)
+              esc = False
+          elif b == self.HDLC_CTLESC_BYTE:
+              esc = True
+          else:
+              r.append(b)
+      return r
+  
+  def __escape(self, packet):
+      r = []
+      for b in packet:
+          if b == self.HDLC_FLAG_BYTE or b == self.HDLC_CTLESC_BYTE:
+              r.append(self.HDLC_CTLESC_BYTE)
+              r.append(b ^ 0x20)
+          else:
+              r.append(b)
+      return r
+  
+  def read_packet(self):
+      d = self.__get_byte()
+      ts = time.time()
+      while d != self.HDLC_FLAG_BYTE:
+          d = self.__get_byte()
+          ts = time.time()
+      packet = [d]
+      d = self.__get_byte()
+      if d == self.HDLC_FLAG_BYTE:
+          d = self.__get_byte()
+          ts = time.time()
+      else:
+          packet.append(d)
+      while d != self.HDLC_FLAG_BYTE:
+          d = self.__get_byte()
+          packet.append(d)
+      un_packet = self.__unescape(packet)
+      crc = self.crc16(0, un_packet[1:-3])
+      packet_crc = self.__decode(un_packet[-3:-1])
+      if crc != packet_crc:
+          print "Warning: wrong CRC!"
+      if self.__debug == True:
+          print "Recv:", self.__format_packet(un_packet)
+      return (ts, un_packet)
+      
+  def write_packet(self, am_group, am_id, data):
+      # The first byte after SERIAL_PROTO_PACKET_ACK is a sequence
+      # number that will be send back by the mote to ack the receive of
+      # the data.
+      packet = [self.SERIAL_PROTO_PACKET_ACK, 0, self.TOS_SERIAL_ACTIVE_MESSAGE_ID,
+                0xff, 0xff,
+                0, 0,
+                len(data), am_group, am_id] + data;
+      crc = self.crc16(0, packet)
+      packet.append(crc & 0xff)
+      packet.append((crc >> 8) & 0xff)
+      packet = [self.HDLC_FLAG_BYTE] + self.__escape(packet) + [self.HDLC_FLAG_BYTE]
+      if self.__debug == True:
+          print "Send:", self.__format_packet(packet)
+      self.__put_bytes(packet)
+      
+      # Waiting for ACK
+      packet = self.read_packet()
+      if len(packet) > 1 and len(packet[1]) > 1:
+        return ((packet[1])[1] == self.SERIAL_PROTO_ACK)
+      return False
+  
+  def set_debug(self, debug):
+      self.__debug = debug
+
+class GenericPacket:
+    """ GenericPacket """
+
+    def __decode(self, v):
+        r = long(0)
+        for i in v:
+            r = (r << 8) + i
+        return r
+    
+    def __encode(self, val, dim):
+        output = []
+        for i in range(dim):
+            output.append(int(val & 0xFF))
+            val = val >> 8
+        output.reverse()
+        return output
+
+    def __init__(self, desc, packet = None):
+        self.__dict__['_schema'] = [(t, s) for (n, t, s) in desc]
+        self.__dict__['_names'] = [n for (n, t, s) in desc]
+        self.__dict__['_values'] = []
+        offset = 10
+        if type(packet) == type([]):
+            for (t, s) in self._schema:
+                if t == 'int':
+                    self._values.append(self.__decode(packet[offset:offset + s]))
+                    offset += s
+                elif t == 'blob':
+                    if s:
+                        self._values.append(packet[offset:offset + s])
+                        offset += s
+                    else:
+                        self._values.append(packet[offset:-3])
+        elif type(packet) == type(()):
+            for i in packet:
+                self._values.append(i)
+        else:
+            for v in self._schema:
+                self._values.append(None)
+
+    def __repr__(self):
+        return self._values.__repr__()
+
+    def __str__(self):
+        return self._values.__str__()
+
+    # Implement the map behavior
+    def __getitem__(self, key):
+        return self.__getattr__(key)
+
+    def __setitem__(self, key, value):
+        self.__setattr__(key, value)
+
+    def __len__(self):
+        return len(self._values)
+
+    def keys(self):
+        return self._names
+
+    def values(self):
+        return self._names
+
+    # Implement the struct behavior
+    def __getattr__(self, name):
+        if type(name) == type(0):
+            return self._names[name]
+        else:
+            return self._values[self._names.index(name)]
+
+    def __setattr__(self, name, value):
+        if type(name) == type(0):
+            self._values[name] = value
+        else:
+            self._values[self._names.index(name)] = value
+
+    # Custom
+    def names(self):
+        return self._names
+
+    def sizes(self):
+        return self._schema
+
+    def payload(self):
+        r = []
+        for i in range(len(self._schema)):
+            (t, s) = self._schema[i]
+            if t == 'int':
+                r += self.__encode(self._values[i], s)
+            else:
+                r += self._values[i]
+        return r
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/volumes-at45db.xml b/apps/tosthreads/tinyld/SerialLoaderFlash/volumes-at45db.xml
new file mode 100644 (file)
index 0000000..26c8665
--- /dev/null
@@ -0,0 +1,3 @@
+<volume_table>
+  <volume name="MICROEXEIMAGE" size="262144" type="block"/>
+</volume_table>          
diff --git a/apps/tosthreads/tinyld/SerialLoaderFlash/volumes-stm25p.xml b/apps/tosthreads/tinyld/SerialLoaderFlash/volumes-stm25p.xml
new file mode 100755 (executable)
index 0000000..801def9
--- /dev/null
@@ -0,0 +1,3 @@
+<volume_table>
+  <volume name="MICROEXEIMAGE" size="262144" type="block"/>
+</volume_table>
index 7b8aa0669ef448948d2c8ef71f71aaa0e0f982e8..3a0b7c166d4ea7e357fc1189c413012bcfdc6fd2 100644 (file)
@@ -76,7 +76,7 @@ implementation {
 #endif
 
 #if defined(PLATFORM_IRIS)
-  components RF230ActiveMessageC as LPLProvider;
+  components ActiveMessageC as LPLProvider;
   App.LPL -> LPLProvider;
 #endif
 }
index 48e2dc0245418a2d37a42f8af48bb75dad522304..7e7454c2a51f72ee927435878eaafeb07d528f38 100644 (file)
@@ -85,7 +85,7 @@ implementation {
   event message_t* SerialRequestSampleMsgsReceive.receive(message_t* msg, void* payload, uint8_t len) {
     serial_request_samples_msg_t* request_msg = payload;
     call Leds.led0On();
-    call LPL.setRxSleepInterval(&request_samples_msg, LPL_INTERVAL+100);
+    call LPL.setRemoteWakeupInterval(&request_samples_msg, LPL_INTERVAL+100);
     call RadioRequestSampleMsgsSend.send(request_msg->addr, &request_samples_msg, sizeof(request_samples_msg_t));
     return msg;
   }
index 9a07855af2a08fe366ce59e7b2853c155a560b25..e282723997e67839facf6014fa663ad9a10f0ec6 100644 (file)
@@ -71,7 +71,7 @@ implementation {
 #endif
 
 #if defined(PLATFORM_IRIS)
-  components RF230ActiveMessageC as LPLProvider;
+  components ActiveMessageC as LPLProvider;
   App.LPL -> LPLProvider;
 #endif
 
index 2fd455b3b7144a7fd28bc0910035f3b6bf16a460..2ebdd544632fabedebf796ebad97fc8e68c589ad 100644 (file)
@@ -68,7 +68,7 @@ implementation {
   }
   
   void sendSampleMsg() {
-    call LPL.setRxSleepInterval(&sample_msg, 0);
+    call LPL.setRemoteWakeupInterval(&sample_msg, 0);
     if(call SampleSend.send(BASE_STATION_ADDR, &sample_msg, sizeof(nx_sensor_sample_t)) != SUCCESS)
       post sendSampleMsgTask();
     else call Leds.led2On();
@@ -78,7 +78,7 @@ implementation {
   task void sendSampleMsgTask() { sendSampleMsg(); }
        
   event void Boot.booted() {
-    call LPL.setLocalSleepInterval(LPL_INTERVAL);
+    call LPL.setLocalWakeupInterval(LPL_INTERVAL);
     call AMControl.start();
   }
   
index 5fba6f1a30798b97587e86bf1fc991005abc7552..d9b8bd32fa1c28a01d4f5ed40c55ba3f29a21713 100644 (file)
@@ -45,8 +45,8 @@ configuration RssiBaseAppC {
   components CC2420ActiveMessageC;
   App -> CC2420ActiveMessageC.CC2420Packet;
 #elif  defined(PLATFORM_IRIS)
-  components  RF230ActiveMessageC;
-  App -> RF230ActiveMessageC.PacketRSSI;
+  components  RF2xxActiveMessageC;
+  App -> RF2xxActiveMessageC.PacketRSSI;
 #elif defined(TDA5250_MESSAGE_H)
   components Tda5250ActiveMessageC;
   App -> Tda5250ActiveMessageC.Tda5250Packet;
diff --git a/doc/html/deluge-t2-manual.html b/doc/html/deluge-t2-manual.html
deleted file mode 100644 (file)
index 8078304..0000000
+++ /dev/null
@@ -1,312 +0,0 @@
-<?xml version="1.0" encoding="utf-8" ?>
-<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
-<html>
-<head>
-<title>
-Deluge T2 - Programming Manual
-</title>
-<link rel="stylesheet" type="text/css" href="deluge-t2-manual.css" title=default>
-<meta name=robots content="index,follow">
-</head>
-<body>
-<div id=title>
-<p></p>
-<p>
-
-</p>
-<p>
-</p>
-<p>
-
-
-
-</p>
-<h1 class=title>Deluge T2 - Programming Manual</h1>
-<p></p>
-<div align=center>
-Chieh-Jan Mike Liang<br>
-Razvan Musaloiu-E.<p>January 14, 2008</p>
-</div>
-<p></p>
-<p>
-</p>
-<a name="node_sec_1"></a>
-<h1>1&nbsp;&nbsp;Introduction</h1>
-<p></p>
-<p>
-Deluge is a reliable data dissemination protocol for large objects, such 
-as program binaries. Together with a bootloader, Deluge provides a way 
-to reprogram sensor motes in a network. Deluge is maintained by Jonathan 
-Hui, and Deluge 2.0 is the most recent version. Documentations on Deluge 
-2.0 are available at 
-<a href="http://www.cs.berkeley.edu/~jwhui/research/deluge/">http://www.cs.berkeley.edu/~jwhui/research/deluge/</a>.</p>
-<p>
-Deluge T2 is an effort to port Deluge 2.0 from TinyOS 1 to TinyOS 2. 
-Although the code from Deluge 2.0 is reused as much as possible, the 
-behavior and the usage of Deluge T2 are not entirely identical to Deluge 
-2.0. Having said that, it would still be helpful to read the Deluge 2.0 
-manual and related documentations.</p>
-<p>
-Deluge T2 is still in experimental phase. One current limitation is 
-platform support. Deluge T2 has been developed on Tmote Sky (<i>telosb</i>) 
-and MicaZ only. In addition, Deluge T2 comes with 2 flash volumes by 
-default. However, more volumes can be added, if necessary. There are 
-also some minor details that will be improved in future releases.</p>
-<p>
-</p>
-<a name="node_sec_2"></a>
-<h1>2&nbsp;&nbsp;Tools Installation</h1>
-<p>Deluge T2 requires a few Python scripts that not yet included in the
-official <code class=verbatim>tinyos-tools</code> RPM package. On the CVS, the scripts are
-located in <code class=verbatim>tinyos-2.x/tools/tinyos/misc</code>. The steps to install
-them are the following:</p>
-<p>
-</p>
-<pre class=verbatim>  % cd $TOSROOT/tools
-  % ./Bootstrap
-      ...
-  % ./configure
-      ...
-  % cd tinyos/misc
-  % make ; make install
-      ...
-</pre><p></p>
-<p>
-By default, the files will be installed in <code class=verbatim>/usr/local/bin</code>. If
-desired, the <code class=verbatim>--prefix</code> parameter from <code class=verbatim>configure</code> can be
-used to indicate a different path. </p>
-<p>
-</p>
-<a name="node_sec_3"></a>
-<h1>3&nbsp;&nbsp;Quick Start</h1>
-<p></p>
-<p>
-This section introduces the basics of reprogramming with an example. In 
-addition, it provides a quick test for software prerequisite. The latest 
-TinyOS 2 CVS tree and Python 2.4 with pySerial support are recommended 
-for running Deluge T2.</p>
-<p>
-To start the example, we first compile tosboot provided in <code class=verbatim>tinyos-2.x/tos/lib/tosboot</code>.
-For example,
-</p>
-<pre class=verbatim>   % make telosb
-</pre><p>
-Then, we run the <code class=verbatim>burn</code> script provided in <code class=verbatim>tinyos-2.x/apps/tests/deluge/Blink</code>.
-For example,
-</p>
-<pre class=verbatim>   % ./burn /dev/ttyUSB0 telosb
-</pre><p>
-This <code class=verbatim>burn</code> script programs the directly-connected mote with one 
-version of Blink. Then, it injects and reprograms the mote with another 
-version of Blink. At this point, you can try to retrieve program image 
-versioning information. The script to interface with the mote is 
-provided in <code class=verbatim>tinyos-2.x/tools/tinyos/misc</code>. For example,
-</p>
-<pre class=verbatim>   % tos-deluge /dev/ttyUSB0 telosb -p 0
-</pre><p>
-You should see something similar to the output below.
-</p>
-<pre class=verbatim>   Pinging node ...
-   --------------------------------------------------
-   Currently Executing:
-     Prog Name:   BlinkAppC
-     UID:         0xA274CBBE
-     Compiled On: Mon Jan 14 13:09:38 2008
-     Node ID:     1
-   
-   Stored image 0
-     Prog Name:   BlinkAppC
-     UID:         0xD7EEFACE
-     Compiled On: Mon Jan 14 12:40:06 2008
-     Platform:    telosb
-     User ID:     tinyos2
-     Host Name:   bluephase
-     User Hash:   0x587C9C16
-     Size:        33504
-     Num Pages:   30
-   --------------------------------------------------
-</pre><p></p>
-<p>
-The usage of <code class=verbatim>tos-deluge</code> is available by running the script without 
-any arguments, and it will be discussed in section <a href="#node_sec_5">5</a>.</p>
-<p>
-</p>
-<a name="node_sec_4"></a>
-<h1>4&nbsp;&nbsp;Reprogramming a Network</h1>
-<p></p>
-<p>
-This section illustrates the procedure to reprogram a network. 
-Specifically, we will see how program images are injected and how 
-versioning information is retrieved.</p>
-<p>
-</p>
-<a name="node_sec_4.1"></a>
-<h2>4.1&nbsp;&nbsp;Setting Up the Motes</h2>
-<p>We first install both tosboot and a program that runs Deluge T2. For 
-simplicity, we use the golden image as the program. The golden image is 
-provided in <code class=verbatim>tinyos-2.x/apps/tests/deluge/GoldenImage</code>, and it does 
-nothing except initializing Deluge T2. This step can be done by 
-compiling and programming the mote normally. For example,
-</p>
-<pre class=verbatim>   % CFLAGS=-DDELUGE_BASESTATION make telosb install,0 bsl,/dev/ttyUSB0
-</pre><p>
-<code class=verbatim>CFLAGS=-DDELUGE_BASESTATION</code> indicates that the current mote will 
-act as a base station, which requires an additional component to accept 
-user commands from the serial port. Normally, only one mote in the 
-network needs to be the base station, and other motes are reprogrammed 
-over-the-air. If error occurs when running the command above, you might 
-need to compile tosboot as shown in section <a href="#node_sec_3">3</a>. 
-Deluge T2 makes sure the mote ID remain persistent over image 
-reprogramming. You can test the installation by interacting with the 
-mote through <code class=verbatim>tos-deluge</code>.</p>
-<p>
-</p>
-<a name="node_sec_4.2"></a>
-<h2>4.2&nbsp;&nbsp;Preparing Your Application</h2>
-<p>In most cases, the only two files you need to modify are the top-level
-wiring file and the Makefile. You need to make sure <code class=verbatim>DelugeC</code>
-component is included. In addition, the Makefile should have the
-following line:
-</p>
-<pre class=verbatim>   TINYOS_NP=BNP
-</pre><p>
-Finally, compile your application without installing it on the mote. For 
-example,
-</p>
-<pre class=verbatim>   % make telosb
-</pre><p></p>
-<p>
-</p>
-<a name="node_sec_4.3"></a>
-<h2>4.3&nbsp;&nbsp;Injecting Your Application</h2>
-<p>Before a program image is disseminated in the network, we need to first 
-inject it to the base station. For example,
-</p>
-<pre class=verbatim>   % tos-deluge /dev/ttyUSB0 telosb -i 1 apps/Blink/build/telosb/tos_image.xml
-</pre><p>
-You should see something similar to the output below.</p>
-<p>
-</p>
-<pre class=verbatim>   Pinging node ...
-   Connected to Deluge nodes.
-   No valid image was detected.
-   --------------------------------------------------
-   Create image: /home/tinyos2/local/bin/tos-build-deluge-image -i 1 build/telosb/tos_image.xml
-   Ihex read complete:
-     35916 bytes starting at 0x4A00
-        32 bytes starting at 0xFFE0
-     35948 bytes in 2 sections
-   CRCs:
-     0xCC0E 0xE57B 0xC224 0xE4FA 0x63EB 0xEBA5 0xE50B 
-     0x8073 0x345E 0x3BBF 0xF415 0xA7DB 0xA67C 0x6953 
-     0x6638 0x3D76 0x7218 0x0E8F 0x9C93 0xD679 0x7A50 
-     0xBFCD 0x8B57 0x7A47 0x323E 0x29FF 0x5EFF 0xB0AE 
-     0x1392 0x4A82 0xACFB 0x69D7 0x8C07 
-   --------------------------------------------------
-   36816 bytes in 28.23 seconds (1303.9932 bytes/s)     
-   --------------------------------------------------
-   Replace image with:
-     Prog Name:   BlinkAppC
-     UID:         0x76D2FB1B
-     Compiled On: Sun Jan 13 21:47:54 2008
-     Platform:    telosb
-     User ID:     tinyos2
-     Host Name:   bluephase
-     User Hash:   0x587C9C16
-     Size:        36816
-     Num Pages:   33
-   --------------------------------------------------
-</pre><p></p>
-<p>
-</p>
-<a name="node_sec_4.4"></a>
-<h2>4.4&nbsp;&nbsp;Reprogramming with New Image</h2>
-<p>After you decide which program image you want to reprogram, you can 
-first test on the base station by issuing the reboot command. For 
-example,
-</p>
-<pre class=verbatim>   % tos-deluge /dev/ttyUSB0 telosb -r 1
-</pre><p>
-After a few moments, the mote will begin quickly flashing the LEDs to 
-signify the reprogramming process.</p>
-<p>
-Now, you can have the base station disseminate a program image to the rest of 
-the network. For example,
-</p>
-<pre class=verbatim>   % tos-deluge /dev/ttyUSB0 telosb -d 1
-</pre><p>
-This command instructs the base station to notify the whole network of 
-the availability of a new program image. This notification is currently 
-done via TinyOS dissemination service, and it triggers all motes in the 
-network to get the new program image. After all motes receive the image 
-over-the-air, you can instruct the base station to disseminate the 
-command to reprogram in the network. For example,
-</p>
-<pre class=verbatim>   % tos-deluge /dev/ttyUSB0 telosb -dr 1
-</pre><p></p>
-<p>
-</p>
-<a name="node_sec_5"></a>
-<h1>5&nbsp;&nbsp;Deluge T2 Python Toolchain</h1>
-<p></p>
-<p>
-Different from Deluge 2.0, Deluge T2 toolchain is written in Python. 
-However, as demonstrated in the previous section, the usage is similar.</p>
-<p>
-</p>
-<a name="node_sec_5.1"></a>
-<h2>5.1&nbsp;&nbsp;-p -ping</h2>
-<p>This command is useful for checking the status of program images on a 
-mote. It provides information such as program name, compile time, size 
-of the image, and so on.</p>
-<p>
-</p>
-<a name="node_sec_5.2"></a>
-<h2>5.2&nbsp;&nbsp;-i -inject</h2>
-<p>This command creates a program image from the supplied
-<code class=verbatim>tos_image.xml</code> file, and it injects the image into specified
-volume on the mote. </p>
-<p>
-</p>
-<a name="node_sec_5.3"></a>
-<h2>5.3&nbsp;&nbsp;-r -reprogram</h2>
-<p>This command sets up the directly-connected mote to reprogram itself
-after reboot, and then it reboots the mote.</p>
-<p>
-</p>
-<a name="node_sec_5.4"></a>
-<h2>5.4&nbsp;&nbsp;-d -disseminate</h2>
-<p>This command instructs the base station mote to disseminate an image to 
-the network. This image is specified by the volume ID.</p>
-<p>
-</p>
-<a name="node_sec_5.5"></a>
-<h2>5.5&nbsp;&nbsp;-dr -disseminate-and-reprogram</h2>
-<p>This command asks the motes in the network not only to disseminate an
-image but also to start running it. This is accomplish using a reboot.</p>
-<p>
-</p>
-<a name="node_sec_5.6"></a>
-<h2>5.6&nbsp;&nbsp;-e -erase</h2>
-<p>This command erases a flash volume on the base station mote.</p>
-<p>
-</p>
-<a name="node_sec_5.7"></a>
-<h2>5.7&nbsp;&nbsp;-s -stop</h2>
-<p>The effect of <code class=verbatim>-d</code> and <code class=verbatim>-dr</code> is continuous which means a new
-mote will become ``infected'' if he is nearby. This command stops the
-``infection''.</p>
-<p>
-</p>
-<a name="node_sec_5.8"></a>
-<h2>5.8&nbsp;&nbsp;-ls -local-stop</h2>
-<p>When <code class=verbatim>-d</code> or <code class=verbatim>-dr</code> are in effect, the volume used by them is
-locked. This command can be used to unlock the volume in order to
-erase or inject a new image.</p>
-<p>
-</p>
-<p></p>
-<div align=right class=colophon>Last modified: Monday, January 14th, 2008 2:11:03pm<br><div align=right class=advertisement>HTML conversion by <a href="http://www.ccs.neu.edu/~dorai/tex2page/tex2page-doc.html">TeX2page 20050501</a></div></div>
-</div>
-</body>
-</html>
index 0125cf17b6a9a154fa97633ff94d5a8602229755..3e7e8dc2773dda5cf73bf2f514d259b906d7a76c 100644 (file)
@@ -3,7 +3,7 @@
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.3.6: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
 <title>Timers</title>
 <meta name="author" content="Cory Sharp, Martin Turon, David Gay" />
 <style type="text/css">
@@ -278,6 +278,7 @@ ul.auto-toc {
 </style>
 </head>
 <body>
+<div class="document" id="timers">
 <h1 class="title">Timers</h1>
 <table class="docinfo" frame="void" rules="none">
 <col class="docinfo-name" />
@@ -297,7 +298,6 @@ ul.auto-toc {
 <td>Cory Sharp, Martin Turon, David Gay</td></tr>
 </tbody>
 </table>
-<div class="document" id="timers">
 <div class="note">
 <p class="first admonition-title">Note</p>
 <p class="last">This memo documents a part of TinyOS for the TinyOS Community, and
@@ -305,15 +305,15 @@ requests discussion and suggestions for improvements.  Distribution
 of this memo is unlimited.  This memo is in full compliance with
 TEP 1.</p>
 </div>
-<div class="section" id="abstract">
-<h1><a name="abstract">Abstract</a></h1>
+<div class="section">
+<h1><a id="abstract" name="abstract">Abstract</a></h1>
 <p>This TEP proposes a Timer design that supports common timing
 requirements both in precision and width across common hardware
 configurations.  This TEP focuses on aligning the Timer abstraction
 with the three-layer Hardware Abstraction Architecture (HAA).</p>
 </div>
-<div class="section" id="introduction">
-<h1><a name="introduction">1. Introduction</a></h1>
+<div class="section">
+<h1><a id="introduction" name="introduction">1. Introduction</a></h1>
 <p>Most microcontrollers offer a rich timer system, with features like:</p>
 <ul class="simple">
 <li>several counters, possibly of different widths, with multiple clocking options</li>
@@ -327,7 +327,7 @@ the timer hardware on some current TinyOS platforms.</p>
 platform-independent fashion. Instead, following the principles of the
 HAA[_tep2], each microcontroller should expose all this functionality
 via components and interfaces at the HPL and, where appropriate, HAL levels.
-However, two aspects of timers are sufficiently common and important 
+However, two aspects of timers are sufficiently common and important
 that they should be made available in a well-defined way: measuring time,
 and triggering (possibly repeating) events at specific times. The rest
 of this TEP specifies:</p>
@@ -336,7 +336,7 @@ of this TEP specifies:</p>
 events (<a class="reference" href="#interfaces">2. Interfaces</a>)</li>
 <li>guidelines on how each microcontroller's HAL SHOULD expose its timer hardware
 in terms of the above interfaces (<a class="reference" href="#hal-guidelines">3. HAL guidelines</a>)</li>
-<li>what components a microcontroller's timer HIL MUST implement 
+<li>what components a microcontroller's timer HIL MUST implement
 (<a class="reference" href="#hil-requirements">4. HIL requirements</a>)</li>
 <li>a set of utility components whose use simplifies building the components
 specified by the HAL guidelines and HIL requirements (<a class="reference" href="#utility-components">5. Utility components</a>)</li>
@@ -344,13 +344,13 @@ specified by the HAL guidelines and HIL requirements (<a class="reference" href=
 <p>This TEP ends with appendices documenting, as an example, the mica2
 timer subsystem implementation.</p>
 </div>
-<div class="section" id="interfaces">
-<h1><a name="interfaces">2. Interfaces</a></h1>
+<div class="section">
+<h1><a id="interfaces" name="interfaces">2. Interfaces</a></h1>
 <p>Before presenting the interfaces (2.2), we start with a general
 discussion of the issues of precision, width and accuracy in
 timer interfaces (2.1).</p>
-<div class="section" id="precision-width-and-accuracy">
-<h2><a name="precision-width-and-accuracy">2.1 Precision, Width and Accuracy</a></h2>
+<div class="section">
+<h2><a id="precision-width-and-accuracy" name="precision-width-and-accuracy">2.1 Precision, Width and Accuracy</a></h2>
 <p>Three fundamental properties of timers are <em>precision</em>, <em>width</em> and
 <em>accuracy</em>.</p>
 <p>Examples of precision are millisecond, a cycle of a 32kHz clock, and
@@ -359,7 +359,7 @@ units with respect to one second.  That is, one second contains 1024
 binary milliseconds, 32768 32kHz ticks, or 1048576 microseconds.
 This TEP emphasizes millisecond and 32kHz tick precisions while
 reasonably accommodating other precisions. The use of &quot;binary&quot; units
-is motivated by the common availability of hardware clocks driven 
+is motivated by the common availability of hardware clocks driven
 by a 32768Hz crystal.</p>
 <p>Examples of widths are 8-bit, 16-bit, 32-bit, and 64-bit.  The width
 for timer interfaces and components SHOULD be 32-bits.  This TEP
@@ -392,8 +392,8 @@ typedef struct { int notUsed; } TMicro; // 1048576 ticks per second
 <p>Note that the precision names are expressed as either frequency or
 period, whichever is convenient.</p>
 </div>
-<div class="section" id="timer-interfaces">
-<h2><a name="timer-interfaces">2.2 Timer interfaces</a></h2>
+<div class="section">
+<h2><a id="timer-interfaces" name="timer-interfaces">2.2 Timer interfaces</a></h2>
 <p>This TEP proposes these timer interfaces:</p>
 <pre class="literal-block">
 interface Counter&lt; precision_tag, size_type &gt;
@@ -407,8 +407,8 @@ applications and use a fixed width of 32-bits.  The Alarm, BusyWait,
 and Counter interfaces are used by the TinyOS timer system and
 advanced user components.</p>
 </div>
-<div class="section" id="counter">
-<h2><a name="counter">Counter</a></h2>
+<div class="section">
+<h2><a id="counter" name="counter">Counter</a></h2>
 <p>The Counter interface returns the current time and provides commands
 and an event for managing overflow conditions.  These overflow
 commands and events are necessary for properly deriving larger width
@@ -423,22 +423,22 @@ interface Counter&lt;precision_tag,size_type&gt;
 }
 </pre>
 <dl class="docutils">
-<dt>get() </dt>
+<dt>get()</dt>
 <dd>return the current time.</dd>
-<dt>isOverflowPending() </dt>
+<dt>isOverflowPending()</dt>
 <dd>return TRUE if the overflow flag is set for this counter, i.e., if and
 only if an overflow event will occur after the outermost atomic
 block exits.  Return FALSE otherwise.  This command only returns the
 state of the overflow flag and causes no side effect.</dd>
-<dt>clearOverflow() </dt>
+<dt>clearOverflow()</dt>
 <dd>cancel the pending overflow event clearing the overflow flag.</dd>
-<dt>overflow() </dt>
+<dt>overflow()</dt>
 <dd>signals that an overflow in the current time.  That is, the current
 time has wrapped around from its maximum value to zero.</dd>
 </dl>
 </div>
-<div class="section" id="alarm">
-<h2><a name="alarm">Alarm</a></h2>
+<div class="section">
+<h2><a id="alarm" name="alarm">Alarm</a></h2>
 <p>Alarm components are extensions of Counters that signal an event
 when their compare register detects the alarm time has been hit.
 All commands and events of the Alarm interface are asynchronous (or
@@ -461,15 +461,15 @@ interface Alarm&lt;precision_tag,size_type&gt;
 }
 </pre>
 <dl class="docutils">
-<dt>start(dt) </dt>
+<dt>start(dt)</dt>
 <dd>cancel any previously running alarm and set to fire in dt time units
 from the time of invocation.  The alarm will only fire once then
 stop.</dd>
-<dt>stop() </dt>
+<dt>stop()</dt>
 <dd>cancel any previously running alarm.</dd>
-<dt>fired() </dt>
+<dt>fired()</dt>
 <dd>signals that the alarm has expired.</dd>
-<dt>isRunning() </dt>
+<dt>isRunning()</dt>
 <dd>return TRUE if the alarm has been started and has not been cancelled
 or has not yet fired.  FALSE is returned otherwise.</dd>
 </dl>
@@ -485,9 +485,9 @@ numerically greater than the current time (returned by <tt class="docutils liter
 represents a time from before the last wraparound.</p>
 </blockquote>
 <dl class="docutils">
-<dt>getNow() </dt>
+<dt>getNow()</dt>
 <dd>return the current time in the precision and width of the alarm.</dd>
-<dt>getAlarm() </dt>
+<dt>getAlarm()</dt>
 <dd>return the time the currently running alarm will fire or the time
 that the previously running alarm was set to fire.  getAlarm can
 be used with startAt to set an alarm from the previous alarm time,
@@ -495,8 +495,8 @@ as in startAt(getAlarm(),dt).  This pattern is used within the
 fired() event to construct periodic alarms.</dd>
 </dl>
 </div>
-<div class="section" id="busywait">
-<h2><a name="busywait">BusyWait</a></h2>
+<div class="section">
+<h2><a id="busywait" name="busywait">BusyWait</a></h2>
 <p>The BusyWait interface allows for very short synchronous delays.
 BusyWait should be used sparingly and when an Alarm would not be
 reasonably efficient or accurate.  The BusyWait interface replaces
@@ -516,8 +516,8 @@ interface BusyWait&lt;precision_tag,size_type&gt;
 <dd>block until at least dt time units have elapsed</dd>
 </dl>
 </div>
-<div class="section" id="localtime">
-<h2><a name="localtime">LocalTime</a></h2>
+<div class="section">
+<h2><a id="localtime" name="localtime">LocalTime</a></h2>
 <p>The LocalTime interface exposes a 32-bit counter without overflow
 utilities.  This is primarily for application code that does not
 care about overflow conditions.</p>
@@ -528,12 +528,12 @@ interface LocalTime&lt;precision_tag&gt;
 }
 </pre>
 <dl class="docutils">
-<dt>get() </dt>
+<dt>get()</dt>
 <dd>return the current time.</dd>
 </dl>
 </div>
-<div class="section" id="timer">
-<h2><a name="timer">Timer</a></h2>
+<div class="section">
+<h2><a id="timer" name="timer">Timer</a></h2>
 <p>All commands and events of the Timer interface are synchronous (or
 in &quot;task context&quot;).  The Timer interface provides a set of &quot;basic&quot;
 commands for common usage and provides a set of &quot;extended&quot; commands
@@ -558,26 +558,26 @@ interface Timer&lt;precision_tag&gt;
 }
 </pre>
 <dl class="docutils">
-<dt>startPeriodic(dt) </dt>
+<dt>startPeriodic(dt)</dt>
 <dd>cancel any previously running timer and set to fire in dt time units
 from the time of invocation.  The timer will fire periodically every
 dt time units until stopped.</dd>
-<dt>startOneShot(dt) </dt>
+<dt>startOneShot(dt)</dt>
 <dd>cancel any previously running timer and set to fire in dt time units
 from the time of invocation.  The timer will only fire once then
 stop.</dd>
-<dt>stop() </dt>
+<dt>stop()</dt>
 <dd>cancel any previously running timer.</dd>
 <dt>fired()</dt>
 <dd>signals that the timer has expired (one-shot) or repeated (periodic).</dd>
-<dt>isRunning() </dt>
+<dt>isRunning()</dt>
 <dd>return TRUE if the timer has been started and has not been cancelled
 and has not fired for the case of one-shot timers.  Once a periodic
 timer is started, isRunning will return TRUE until it is cancelled.</dd>
-<dt>isOneShot() </dt>
+<dt>isOneShot()</dt>
 <dd>return TRUE if the timer is a one-shot timer.  Return FALSE
 otherwise if the timer is a periodic timer.</dd>
-<dt>startPeriodicAt(t0,dt) </dt>
+<dt>startPeriodicAt(t0,dt)</dt>
 <dd><p class="first">cancel any previously running timer and set to fire at time t1 =
 t0+dt.  The timer will fire periodically every dt time units until
 stopped.</p>
@@ -585,23 +585,23 @@ stopped.</p>
 value of <tt class="docutils literal"><span class="pre">t0</span></tt> numerically greater than the current time (returned by
 <tt class="docutils literal"><span class="pre">getNow()</span></tt>) represents a time from before the last wraparound.</p>
 </dd>
-<dt>startOneShotAt(t0,dt) </dt>
+<dt>startOneShotAt(t0,dt)</dt>
 <dd><p class="first">cancel any previously running timer and set to fire at time t1 =
 t0+dt.  The timer will fire once then stop.</p>
 <p class="last"><tt class="docutils literal"><span class="pre">t0</span></tt> is as in <tt class="docutils literal"><span class="pre">startPeriodicAt</span></tt>.</p>
 </dd>
-<dt>getNow() </dt>
+<dt>getNow()</dt>
 <dd>return the current time in the precision and width of the timer.</dd>
-<dt>gett0() </dt>
+<dt>gett0()</dt>
 <dd>return the time anchor for the previously started timer or the time
 of the previous event for periodic timers.</dd>
-<dt>getdt() </dt>
+<dt>getdt()</dt>
 <dd>return the delay or period for the previously started timer.</dd>
 </dl>
 </div>
 </div>
-<div class="section" id="hal-guidelines">
-<h1><a name="hal-guidelines">3. HAL guidelines</a></h1>
+<div class="section">
+<h1><a id="hal-guidelines" name="hal-guidelines">3. HAL guidelines</a></h1>
 <p>Platforms SHOULD expose their relevant timing capabilities using
 standard Alarm and Counter interfaces.  The design pattern presented
 here defines a component naming convention to allow platform
@@ -646,8 +646,8 @@ are mutually incompatible in a single application.  Incompatible
 components SHOULD produce compile-time errors when compiled
 together.</p>
 </div>
-<div class="section" id="hil-requirements">
-<h1><a name="hil-requirements">4. HIL requirements</a></h1>
+<div class="section">
+<h1><a id="hil-requirements" name="hil-requirements">4. HIL requirements</a></h1>
 <p>The following component MUST be provided on all platforms</p>
 <pre class="literal-block">
 HilTimerMilliC
@@ -657,8 +657,8 @@ BusyWaitMicroC
 HilTimerMilliC and 1/1048576s for BusyWaitMicroC. Components using
 other precisions (e.g., regular, non-binary milliseconds) MAY also be
 provided.</p>
-<div class="section" id="hiltimermillic">
-<h2><a name="hiltimermillic">HilTimerMilliC</a></h2>
+<div class="section">
+<h2><a id="hiltimermillic" name="hiltimermillic">HilTimerMilliC</a></h2>
 <pre class="literal-block">
 configuration HilTimerMilliC
 {
@@ -673,8 +673,8 @@ TimerMilli parameterised interface.  UQ_TIMER_MILLI is defined in
 Timer.h.  HilTimerMilliC is used by the LocalTimeMilliC component and the
 TimerMilliC generic component, both found in <tt class="docutils literal"><span class="pre">tos/system/</span></tt></p>
 </div>
-<div class="section" id="busywaitmicroc">
-<h2><a name="busywaitmicroc">BusyWaitMicroC</a></h2>
+<div class="section">
+<h2><a id="busywaitmicroc" name="busywaitmicroc">BusyWaitMicroC</a></h2>
 <pre class="literal-block">
 configuration BusyWaitMicroC
 {
@@ -687,8 +687,8 @@ delay is small and setting a timer or alarm would be impractical,
 inefficient or insufficiently precise.</p>
 </div>
 </div>
-<div class="section" id="utility-components">
-<h1><a name="utility-components">5. Utility components</a></h1>
+<div class="section">
+<h1><a id="utility-components" name="utility-components">5. Utility components</a></h1>
 <p>A number of platform independent generic components are provided to
 help implementers and advanced users of the TinyOS timer system:</p>
 <ul class="simple">
@@ -701,8 +701,8 @@ help implementers and advanced users of the TinyOS timer system:</p>
 </ul>
 <p>Appendices B and C show how these can be used to help implement
 the timer HAL and HIL.</p>
-<div class="section" id="alarmtotimerc">
-<h2><a name="alarmtotimerc">AlarmToTimerC</a></h2>
+<div class="section">
+<h2><a id="alarmtotimerc" name="alarmtotimerc">AlarmToTimerC</a></h2>
 <p>AlarmToTimerC converts a 32-bit Alarm to a Timer.</p>
 <pre class="literal-block">
 generic component AlarmToTimerC( typedef precision_tag )
@@ -712,8 +712,8 @@ generic component AlarmToTimerC( typedef precision_tag )
 }
 </pre>
 </div>
-<div class="section" id="busywaitcounterc">
-<h2><a name="busywaitcounterc">BusyWaitCounterC</a></h2>
+<div class="section">
+<h2><a id="busywaitcounterc" name="busywaitcounterc">BusyWaitCounterC</a></h2>
 <p>BusyWaitCounterC uses a Counter to block until a specified amount of
 time elapses.</p>
 <pre class="literal-block">
@@ -725,8 +725,8 @@ generic component BusyWaitC( typedef precision_tag,
 }
 </pre>
 </div>
-<div class="section" id="countertolocaltimec">
-<h2><a name="countertolocaltimec">CounterToLocalTimeC</a></h2>
+<div class="section">
+<h2><a id="countertolocaltimec" name="countertolocaltimec">CounterToLocalTimeC</a></h2>
 <p>CounterToLocalTimeC converts from a 32-bit Counter to LocalTime.</p>
 <pre class="literal-block">
 generic component CounterToLocalTimeC( precision_tag )
@@ -736,12 +736,12 @@ generic component CounterToLocalTimeC( precision_tag )
 }
 </pre>
 </div>
-<div class="section" id="transformalarmc">
-<h2><a name="transformalarmc">TransformAlarmC</a></h2>
+<div class="section">
+<h2><a id="transformalarmc" name="transformalarmc">TransformAlarmC</a></h2>
 <p>TransformAlarmC decreases precision and/or widens an Alarm.  An
 already widened Counter component is used to help.</p>
 <pre class="literal-block">
-generic component TransformAlarmC( 
+generic component TransformAlarmC(
   typedef to_precision_tag,
   typedef to_size_type &#64;integer(),
   typedef from_precision_tag,
@@ -769,8 +769,8 @@ TransformAlarmC to ensure that all five of its arguments are self
 consistent.  No compile errors are generated if the parameters
 passed to TransformAlarmC are inconsistent.</p>
 </div>
-<div class="section" id="transformcounterc">
-<h2><a name="transformcounterc">TransformCounterC</a></h2>
+<div class="section">
+<h2><a id="transformcounterc" name="transformcounterc">TransformCounterC</a></h2>
 <p>TransformCounterC decreases precision and/or widens a Counter.</p>
 <pre class="literal-block">
 generic component TransformCounterC(
@@ -801,8 +801,8 @@ created:</p>
 new TransformCounterC( TMilli, uint32_t, T32khz, uint16_t, 5, uint32_t )
 </pre>
 </div>
-<div class="section" id="virtualizetimerc">
-<h2><a name="virtualizetimerc">VirtualizeTimerC</a></h2>
+<div class="section">
+<h2><a id="virtualizetimerc" name="virtualizetimerc">VirtualizeTimerC</a></h2>
 <p>VirtualizeTimerC uses a single Timer to create up to 255 virtual
 timers.</p>
 <pre class="literal-block">
@@ -815,8 +815,8 @@ generic component VirtualizeTimerC( typedef precision_tag, int max_timers )
 </pre>
 </div>
 </div>
-<div class="section" id="implementation">
-<h1><a name="implementation">6. Implementation</a></h1>
+<div class="section">
+<h1><a id="implementation" name="implementation">6. Implementation</a></h1>
 <p>The definition of the HIL interfaces are found in <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/lib/timer</span></tt>:</p>
 <blockquote>
 <ul class="simple">
@@ -856,7 +856,7 @@ generic component VirtualizeTimerC( typedef precision_tag, int max_timers )
 <li><tt class="docutils literal"><span class="pre">CounterMilli16C.nc</span></tt> provides <tt class="docutils literal"><span class="pre">Counter&lt;TMilli,uint16_t&gt;</span></tt></li>
 <li><tt class="docutils literal"><span class="pre">CounterMilli32C.nc</span></tt> provides <tt class="docutils literal"><span class="pre">Counter&lt;TMilli,uint32_t&gt;</span></tt></li>
 <li><tt class="docutils literal"><span class="pre">GpioCaptureC.nc</span></tt></li>
-<li><tt class="docutils literal"><span class="pre">HilTimerMilliC.nc</span></tt> provides <tt class="docutils literal"><span class="pre">LocalTime&lt;TMilli&gt;</span></tt> and 
+<li><tt class="docutils literal"><span class="pre">HilTimerMilliC.nc</span></tt> provides <tt class="docutils literal"><span class="pre">LocalTime&lt;TMilli&gt;</span></tt> and
 <tt class="docutils literal"><span class="pre">Timer&lt;TMilli&gt;</span> <span class="pre">as</span> <span class="pre">TimerMilli[uint8_t</span> <span class="pre">num]</span></tt></li>
 <li><tt class="docutils literal"><span class="pre">Msp430AlarmC.nc</span></tt> is generic and converts an MSP430 timer to a 16-bit Alarm</li>
 <li><tt class="docutils literal"><span class="pre">Msp430Capture.nc</span></tt> HPL interface definition for MSP430 timer captures</li>
@@ -889,8 +889,8 @@ special function registers</li>
 <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/chips/atm128/timer</span></tt> and
 <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/chips/pxa27x/timer</span></tt> respectively.</p>
 </div>
-<div class="section" id="author-s-address">
-<h1><a name="author-s-address">7. Author's Address</a></h1>
+<div class="section">
+<h1><a id="author-s-address" name="author-s-address">7. Author's Address</a></h1>
 <div class="line-block">
 <div class="line">Cory Sharp</div>
 <div class="line">Moteiv Corporation</div>
@@ -918,8 +918,8 @@ special function registers</li>
 <div class="line">email - <a class="reference" href="mailto:david.e.gay&#64;intel.com">david.e.gay&#64;intel.com</a></div>
 </div>
 </div>
-<div class="section" id="appendix-a-timer-hardware-on-various-microcontrollers">
-<h1><a name="appendix-a-timer-hardware-on-various-microcontrollers">Appendix A: Timer hardware on various microcontrollers</a></h1>
+<div class="section">
+<h1><a id="appendix-a-timer-hardware-on-various-microcontrollers" name="appendix-a-timer-hardware-on-various-microcontrollers">Appendix A: Timer hardware on various microcontrollers</a></h1>
 <blockquote>
 <ol class="loweralpha simple">
 <li>Atmega128</li>
@@ -995,8 +995,8 @@ output pin, clear counter, generate interrupt, etc)</li>
 </blockquote>
 </blockquote>
 </div>
-<div class="section" id="appendix-b-a-microcontroller-atmega-128-timer-subsystem">
-<h1><a name="appendix-b-a-microcontroller-atmega-128-timer-subsystem">Appendix B: a microcontroller: Atmega 128 timer subsystem</a></h1>
+<div class="section">
+<h1><a id="appendix-b-a-microcontroller-atmega-128-timer-subsystem" name="appendix-b-a-microcontroller-atmega-128-timer-subsystem">Appendix B: a microcontroller: Atmega 128 timer subsystem</a></h1>
 <p>The Atmega128 exposes its four timers through a common set of interfaces:</p>
 <blockquote>
 <ul class="simple">
@@ -1026,7 +1026,7 @@ interface HplAtm128Timer&lt;timer_size&gt;
   async command bool isOn();  //&lt;! Is overflow interrupt on?
 
   /// Clock initialization interface
-  async command void    off();                     //&lt;! Turn off the clock 
+  async command void    off();                     //&lt;! Turn off the clock
   async command void    setScale( uint8_t scale);  //&lt;! Turn on the clock
   async command uint8_t getScale();                //&lt;! Get prescaler setting
 }
@@ -1057,7 +1057,7 @@ interface HplAtm128Capture&lt;size_type&gt;
   /// Interrupt signals
   async event void captured(size_type t);  //&lt;! Signalled on capture int
 
-  /// Interrupt flag utilites: Bit level set/clr  
+  /// Interrupt flag utilites: Bit level set/clr
   async command void reset();          //&lt;! Clear the capture interrupt flag
   async command void start();          //&lt;! Enable the capture interrupt
   async command void stop();           //&lt;! Turn off capture interrupts
@@ -1089,7 +1089,7 @@ interface is only connected for <tt class="docutils literal"><span class="pre">i
 another value cause a compile-time error. This is achieved as follows (code
 from the implementation of <tt class="docutils literal"><span class="pre">HplAtm128Timer1C</span></tt>)</p>
 <pre class="literal-block">
-Compare[0] = HplAtm128Timer1P.CompareA; 
+Compare[0] = HplAtm128Timer1P.CompareA;
 Compare[1] = HplAtm128Timer1P.CompareB;
 Compare[2] = HplAtm128Timer1P.CompareC;
 </pre>
@@ -1133,8 +1133,8 @@ generic configuration Atm128AlarmAsyncC(typedef precision, int divider) {
 <p>which builds a 32-bit alarm and timer over timer 0. divider is used
 to initialise the timer0 scaling factor.</p>
 </div>
-<div class="section" id="appendix-c-a-mote-mica-family-timer-subsystem">
-<h1><a name="appendix-c-a-mote-mica-family-timer-subsystem">Appendix C: a mote: Mica family timer subsystem</a></h1>
+<div class="section">
+<h1><a id="appendix-c-a-mote-mica-family-timer-subsystem" name="appendix-c-a-mote-mica-family-timer-subsystem">Appendix C: a mote: Mica family timer subsystem</a></h1>
 <p>Members of the mica family (mica2, mica2dot, micaz) use the Atmega128
 microprocessor and have external crystals at 4 or 7.37MHz. Additionally,
 they can be run from an internal oscillator at 1, 2, 4, or 8 MHz. The
@@ -1157,13 +1157,13 @@ VirtualizeTimerC and CounterToLocalTimeC utility components.</p>
 <li><p class="first">Timer 1: the 16-bit hardware timer 1 is set to run at 1MHz if possible.
 However, the set of dividers for timer 1 is limited to 1, 8,
 64, 256 and 1024. So, when clocked at 2 or 4MHz, a divider of 1 is
-selected and timer 1 runs at 2 or 4MHz. To reflect this fact, the 
+selected and timer 1 runs at 2 or 4MHz. To reflect this fact, the
 HAL components exposing timer 1 are named <tt class="docutils literal"><span class="pre">CounterOne16C</span></tt> and
 <tt class="docutils literal"><span class="pre">AlarmOne16C</span></tt> (rather than the <tt class="docutils literal"><span class="pre">CounterMicro16C</span></tt> <tt class="docutils literal"><span class="pre">AlarmMicro16C</span></tt>
 as suggested in Section 3).</p>
 <p>32-bit microsecond Counters and Alarms, named <tt class="docutils literal"><span class="pre">CounterMicro32C</span></tt> and
 <tt class="docutils literal"><span class="pre">AlarmMicro32C</span></tt>, are created from <tt class="docutils literal"><span class="pre">CounterOne16C</span></tt> and
-<tt class="docutils literal"><span class="pre">AlarmOne16C</span></tt> using the TransformAlarmC and TransformCounterC 
+<tt class="docutils literal"><span class="pre">AlarmOne16C</span></tt> using the TransformAlarmC and TransformCounterC
 utility components.</p>
 <p>Three compare registers are available on timer1, so up to three instances
 of <tt class="docutils literal"><span class="pre">AlarmOne16C</span></tt> and/or <tt class="docutils literal"><span class="pre">AlarmMicro32C</span></tt> can be created. The timing
@@ -1179,7 +1179,7 @@ accuracy depends on how the mote is clocked:</p>
 <li><p class="first">Timer 3: the 16-bit hardware timer 3 is set to run at a rate close to
 32768Hz, if possible. As with timer 1, the limited set of dividers makes
 this impossible at some clock frequencies, so the 16-bit timer 3 HAL
-components are named <tt class="docutils literal"><span class="pre">CounterThree16C</span></tt> and <tt class="docutils literal"><span class="pre">AlarmThree16C</span></tt>. As 
+components are named <tt class="docutils literal"><span class="pre">CounterThree16C</span></tt> and <tt class="docutils literal"><span class="pre">AlarmThree16C</span></tt>. As
 with timer 1, the rate of timer 3 is adjusted in software to
 build 32-bit counter and 32-bit alarms, giving components
 <tt class="docutils literal"><span class="pre">Counter32khz32C</span></tt> and <tt class="docutils literal"><span class="pre">Alarm32khz32C</span></tt>. As with timer 1, three compare
index 0088c4a3a5fdc816e73de8763ef86b14765d9a28..56b758c178bcb27b6bde2b724929fac11e1419ef 100644 (file)
@@ -291,15 +291,11 @@ ul.auto-toc {
 <tr class="field"><th class="docinfo-name">Type:</th><td class="field-body">Documentary</td>
 </tr>
 <tr><th class="docinfo-name">Status:</th>
-<td>Draft</td></tr>
+<td>Final</td></tr>
 <tr class="field"><th class="docinfo-name">TinyOS-Version:</th><td class="field-body">2.x</td>
 </tr>
 <tr><th class="docinfo-name">Author:</th>
 <td>David Gay, Philip Levis, Wei Hong, Joe Polastre, and Gilman Tolle</td></tr>
-<tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">10-Jun-2006</td>
-</tr>
-<tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
-</tr>
 </tbody>
 </table>
 <div class="note">
index f8ffa3ce07ced52a9cfedcbfdc13253363e6e01e..7376cad4b9be5b56a32f68ba93ac54e3e34115ba 100644 (file)
@@ -3,7 +3,7 @@
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" />
 <title>Microcontroller Power Management</title>
 <meta name="author" content="Robert Szewczyk, Philip Levis, Martin Turon, Lama Nachman, Philip Buonadonna, Vlado Handziski" />
 <style type="text/css">
@@ -298,9 +298,9 @@ ul.auto-toc {
 <td>Robert Szewczyk, Philip Levis, Martin Turon, Lama Nachman, Philip Buonadonna, Vlado Handziski</td></tr>
 <tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">19-Sep-2005</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.7</td>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.8</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2007-01-10</td>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2009-07-07</td>
 </tr>
 <tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
 </tr>
@@ -567,6 +567,13 @@ TinyOS to behave badly. The presence of a combine function for
 mcu_power_t means that this command can have fan-out calls.</p>
 <p>Section 5 describes one example use of McuPowerOverride, in the
 timer stack for the Atmega128 microcontroller family.</p>
+<p>As part of power state override, a platform MUST define the enum
+TOS_SLEEP_NONE in its hardware.h file. This enum defines the highest
+power state of the platform's microcontroller in a chip-independent
+way. If a component wires to McuPowerOverride and returns TOS_SLEEP_NONE,
+this will cause TinyOS to never put the microcontroller into a power
+saving state. This enum allows a component to prevent sleep in a
+platform-independent way.</p>
 </div>
 <div class="section">
 <h1><a id="peripherals-and-subsystems" name="peripherals-and-subsystems">4. Peripherals and Subsystems</a></h1>
@@ -590,13 +597,23 @@ include power management into shared non-virtualized devices.</p>
 <h1><a id="implementation" name="implementation">5. Implementation</a></h1>
 <p>An implementation of McuSleepC can be found in <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/chips/atm128</span></tt>,
 <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/chips/msp430</span></tt>, and <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/chips/px27ax</span></tt>.</p>
-<p>An example of a use of McuPowerOverride can be found in the atmega128 timer
+<p>An example use of McuPowerOverride can be found in the atmega128 timer
 system. Because some low-power states have much longer wakeup latencies than
 others, the timer system does not allow long latencies if it has a timer
 that is going to fire soon.  The implementation can be found in
 <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/chips/atm128/timer/HplAtm128Timer0AsyncP.nc</span></tt>, and
 <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/chips/atm128/timer/HplAtm128Timer0AsyncC.nc</span></tt> automatically
 wires it to McuSleepC if it is included.</p>
+<p>For the atmega128 microcontroller, TOS_SLEEP_NONE is the &quot;idle&quot; power
+state.</p>
+<p>A second example use of McuPowerOverride is in the msp430 timer system.
+By default, the msp430 lowest power state is LPM4, which does not keep
+clocks enabled. If <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/chips/msp430/timer/Msp430ClockC.nc''</span>
+<span class="pre">is</span> <span class="pre">included</span> <span class="pre">in</span> <span class="pre">the</span> <span class="pre">component</span> <span class="pre">graph,</span> <span class="pre">however,</span> <span class="pre">this</span> <span class="pre">configuration</span> <span class="pre">wires</span>
+<span class="pre">the</span> <span class="pre">McuPowerOverride</span> <span class="pre">of</span> <span class="pre">``tinyos-2.x/tos/chips/msp430/timer/Msp430ClockP.nc</span></tt>
+to McuSleepC. This implemementation of McuPowerOverride raises the lowest
+power state to LPM3, which keeps clocks enabled.</p>
+<p>For msp430 microcontrollers, TOS_SLEEP_NONE is the &quot;active&quot; power state.</p>
 </div>
 <div class="section">
 <h1><a id="author-s-address" name="author-s-address">6. Author's Address</a></h1>
index d425c9ed52c87e0d7e5d39357e0e2ddb8dbdddf3..de3c6547504eb09a5f942038ce09fed57294c9e5 100644 (file)
@@ -3,7 +3,7 @@
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
 <title>Power Management of Non-Virtualised Devices</title>
 <meta name="author" content="Kevin Klues, Vlado Handziski, Jan-Hinrich Hauer, Phil Levis" />
 <style type="text/css">
index b89fc6508a162ece3ba2777aeed2f319bd22e232..07c122e9f2b53220256e54a18656cff5839643ca 100644 (file)
@@ -3,7 +3,7 @@
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
 <title>Packet Protocols</title>
 <meta name="author" content="Philip Levis" />
 <style type="text/css">
index 5e50911c09f9d1045e710ce82892ff083ff5c60f..101c5a5d4a9f92f271ef688b1ec89d526e0f75c9 100644 (file)
@@ -3,7 +3,7 @@
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
 <title>Dissemination of Small Values</title>
 <meta name="author" content="Philip Levis and Gilman Tolle" />
 <style type="text/css">
index d7000d99a4a207c07432cd8d288ce352d8fc7b02..5f9a15ef1cb302390b2d6ee0f8098defd6c0fc9a 100644 (file)
@@ -291,8 +291,8 @@ ul.auto-toc {
 <tr class="field"><th class="docinfo-name">Type:</th><td class="field-body">Documentary</td>
 </tr>
 <tr><th class="docinfo-name">Status:</th>
-<td>Draft</td></tr>
-<tr class="field"><th class="docinfo-name">TinyOS-Version:</th><td class="field-body">2.x</td>
+<td>Final</td></tr>
+<tr class="field"><th class="docinfo-name">TinyOS-Version:</th><td class="field-body">&gt; 2.1</td>
 </tr>
 <tr><th class="docinfo-name">Author:</th>
 <td>Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, and Philip Levis</td></tr>
@@ -312,46 +312,48 @@ TEP 1.</p>
 <div class="section">
 <h1><a id="abstract" name="abstract">Abstract</a></h1>
 <p>The memo documents the interfaces, components, and semantics used by
-collection protocol in TinyOS 2.x. Collection provides a best-effort,
-multihop delivery of packets to the root of a tree. There may be
-multiple tree roots in a network, and in this case the semantics
-are <em>anycast</em> delivery to at least one of the roots. A node sending
-a packet does not specify which root the packet is destined to.</p>
+the collection protocols in TinyOS 2.x. Collection provides
+best-effort, multihop delivery of packets to one of a set of
+collection points.  There may be multiple collection points in a
+network, and in this case the semantics are <em>anycast</em> delivery to at
+least one of the collection points. A node sending a packet does not
+specify which of the collection points the packet is destined to.  The
+union of the paths from each node to one or more of the collection
+points forms a set of trees, and in this document we assume that
+collection points are the roots of these trees.</p>
 </div>
 <div class="section">
 <h1><a id="introduction" name="introduction">1. Introduction</a></h1>
 <p>Collecting data at a base station is a common requirement of sensor
-network applications. The general approach used is to build one
-or more collection <em>trees</em>, each of which is rooted at a base
-station. When a node has data which needs to be collected, it
-sends the data up the tree, and it forwards collection data that
-other nodes send to it. Sometimes, depending on the form of data
-collection, systems need to be able to inspect packets as they go
-by, either to gather statistics, compute aggregates, or suppress
-redundant transmissions.</p>
-<p>When a network has multiple base stations that act as <em>root</em> nodes,
-rather than one tree, it has a <em>forest</em> of trees. By picking a
-parent node, a collection protocol implicitly joins one of these
-trees. Collection provides a best-effort,
-multihop delivery of packets to one of a network's tree roots:
-it is an <em>anycast</em> protocol. The semantics is that the protocol
-will make a reasonable effort to deliver the message to at least
-one of the roots in the network. There are however no guarantees of
-delivery, and there can be duplicates delivered to one or more
-roots. There is also no ordering guarantees.</p>
-<p>Given the limited state that nodes can store and a general need
-for distributed tree building algorithms, simple collection protocols
-encounter several challenges. These challenges are not unique to
-collection protocols. Instead, they represent a subset of common
-networking algorithmic edge cases that occur in this protocol
-family:</p>
+network applications. The general approach used is to build one or
+more collection trees, each of which is rooted at a base station. When
+a node has data which needs to be collected, it sends the data up the
+tree, and it forwards collection data that other nodes send to
+it. Sometimes, depending on the form of data collection, systems need
+to be able to inspect packets as they go by, either to gather
+statistics, compute aggregates, or suppress redundant transmissions.</p>
+<p>Collection provides best-effort, multihop delivery of packets to one
+of a network's tree roots: it is an <em>anycast</em> protocol. The
+semantics are that the protocol will make a reasonable effort to
+deliver the message to at least one of the roots in the network. By
+picking a parent node, a node implementing the collection protocol
+inductively joins the tree its parent has joined.  Delivery is best
+effort, and there can be duplicates delivered to one or more roots.
+Collection provides no ordering or real-time guarantees, although
+specific implementations may extend the basic functionality to do
+so.</p>
+<p>Given the limited state that nodes can store and a general need for
+distributed tree building algorithms, collection protocols encounter
+several challenges. These challenges are not unique to collection
+protocols. Instead, they represent a subset of common networking
+algorithmic edge cases that generally occur in wireless routing:</p>
 <blockquote>
 <ul class="simple">
-<li>Loop detection, detecting when a node selects one of its
-descendants as a new parent.</li>
-<li>Duplicate suppression, detecting and dealing with when lost
-acknowledgments are causing packets to replicate in the
-network, wasting bandwidth.</li>
+<li>Loop detection, for when a node selects one of its descendants as
+a next hop.</li>
+<li>Duplicate suppression, detecting and dealing with lost
+acknowledgments that can cause packets to replicate in the
+network, wasting capacity.</li>
 <li>Link estimation, evaluating the link quality to single-hop
 neighbors.</li>
 <li>Self-interference, preventing forwarding packets along the route
@@ -365,26 +367,28 @@ describes a set of components and interfaces for collection services.</p>
 </div>
 <div class="section">
 <h1><a id="collection-interfaces" name="collection-interfaces">2. Collection interfaces</a></h1>
-<p>A node can perform four different roles in collection: producer,
-snooper, in-network processor, and consumer. Depending on their role,
-the nodes use different interfaces to interact with the collection
-component.</p>
+<p>A node can perform four different roles in collection: sender (or
+source), snooper, in-network processor, and receiver (or
+root). Depending on their role, the nodes use different interfaces to
+interact with the collection component.</p>
 <p>The collection infrastructure can be multiplexed among independent
-applications, by means of a <em>collection identifier</em>. It is important
-to note that the <em>data</em> traffic in the protocol is multiplexed,
-while the <em>control</em> traffic is not.</p>
-<p>The nodes that generate data to be sent to the root are <em>producers</em>.
-The producers use the Send interface [<a class="reference" href="#id2">1</a>] to send data to the root
-of the collection tree.  The collection identifier is specified as a
+applications, by means of a collection identifier. The collection
+identifier is used to identify different data traffic at the sender,
+intermediate-nodes, or the receiver, much like port number in TCP. All
+data traffic, regardless of the collection identifier, use the same
+routing topology.</p>
+<p>The nodes that generate data to be sent to the root are <em>senders</em>.
+Senders use the Send interface [<a class="reference" href="#id1">1</a>] to send data to the root of
+the collection tree.  The collection identifier is specified as a
 parameter to Send during instantiation.</p>
 <p>The nodes that overhear messages in transit are <em>snoopers</em>. The
-snoopers use the Receive interface [<a class="reference" href="#id2">1</a>] to receive a snooped
+snoopers use the Receive interface [<a class="reference" href="#id1">1</a>] to receive a snooped
 message. The collection identifier is specified as a parameter
 to Receive during instantiation.</p>
-<p>The nodes can process a packet that are in transit. These in-network
-<em>processors</em> use the Intercept interface to receive
-and update a packet. The collection identifier is specified as a parameter
-to Intercept during instantiation. The Intercept interface has this
+<p>The nodes can process a packet that is in transit. These in-network
+<em>processors</em> use the Intercept interface to receive and update a
+packet. The collection identifier is specified as a parameter to
+Intercept during instantiation. The Intercept interface has this
 signature:</p>
 <pre class="literal-block">
 interface Intercept {
@@ -394,19 +398,22 @@ interface Intercept {
 <p>Intercept has a single event, Intercept.forward(). A collection
 service SHOULD signal this event when it receives a packet to forward.
 If the return value of the event is FALSE, then the collection layer
-MUST NOT forward the packet. This interface allows a higher layer
-to inspect the internals of a packet and possibly suppress it if
-it is unnecessary or if its contents can be aggregated into an
-existing packet.</p>
-<p>Root nodes that receive data from the network are <em>consumers</em>. The
-consumers use the Receive interface [<a class="reference" href="#id2">1</a>] to receive a message
-delivered by collection. The collection identifier is specified
-as a parameter to Receive during instantiation.</p>
-<p>The set of all roots and the paths that
-lead to them form the collection routing infrastructure in the network.
-For any connected set of nodes implementing the collection protocol
-there is only one collection infrastructure, <em>i.e.</em>, all roots in this
-set active at the same time are part of the same infrastructure.</p>
+MUST NOT forward the packet. The Intercept interface allows a higher
+layer to inspect the internals of a packet and suppress it if needed.
+Intercept can be used for duplicate suppression, aggregation, and
+other higher-level services. As the handler of Intercept.forward()
+does not receive ownership of the packet, it MUST NOT modify the
+packet and MUST copy data out of the packet which it wishes to use
+after the event returns.</p>
+<p>Root nodes that receive data from the network are <em>receivers</em>. Roots
+use the Receive interface [<a class="reference" href="#id1">1</a>] to receive a message delivered by
+collection. The collection identifier is specified as a parameter to
+Receive during instantiation.</p>
+<p>The set of all roots and the paths that lead to them form the
+collection routing infrastructure in the network.  For any connected
+set of nodes implementing the collection protocol there is only one
+collection infrastructure, <em>i.e.</em>, all roots in this set active at the
+same time are part of the same infrastructure.</p>
 <p>The RootControl interface configures whether a node is a
 root:</p>
 <pre class="literal-block">
@@ -416,12 +423,12 @@ interface RootControl {
   command bool isRoot();
 }
 </pre>
-<p>Both commands MUST return SUCCESS if the node is now in the specified
-state, and FAIL otherwise. For example, if a node is already a root
-and an application calls RootControl.setRoot(), the call will
+<p>The first two commands MUST return SUCCESS if the node is now in the
+specified state, and FAIL otherwise. For example, if a node is already
+a root and an application calls RootControl.setRoot(), the call will
 return SUCCESS. If setRoot() returns SUCCESS, then a subsequent call
-to isRoot() MUST return TRUE. If unsetRoot() returns SUCCESS, then
-subsequent call to isRoot() MUST return FALSE.</p>
+to isRoot() MUST return TRUE. If unsetRoot() returns SUCCESS, then a
+subsequent call to isRoot() MUST return FALSE.</p>
 </div>
 <div class="section">
 <h1><a id="collection-services" name="collection-services">3 Collection Services</a></h1>
@@ -444,10 +451,10 @@ configuration CollectionC {
   }
 }
 </pre>
-<p>CollectionC MAY have additional interfaces. These additional
-interfaces MUST have default functions on all outgoing invocations
-(commands for uses, events for provides) of those interfaces so that
-it can operate properly if they are not wired.</p>
+<p>CollectionC MAY have additional interfaces. All outgoing invocations
+(commands for uses, events for provides) of those interfaces MUST have
+default functions. Those default functions enable CollectionC to
+operate properly even when the additional interfaces are not wired.</p>
 <p>Components SHOULD NOT wire to CollectionC.Send. The generic
 component CollectionSenderC (described in section 3.1) provides
 a virtualized sending interface.</p>
@@ -456,23 +463,27 @@ collection_id_t. Each collection_id_t corresponds to a different
 protocol operating on top of collection, in the same way that
 different am_id_t values represent different protocols operating on
 top of active messages. All packets sent with a particular
-collection_id_t generally have the same payload format, so that
-snoopers, intercepters, and receivers can parse it properly.</p>
+collection_id_t generally SHOULD have the same payload format, so that
+snoopers, intercepters, and receivers can parse them properly.</p>
 <p>ColletionC MUST NOT signal Receive.receive on non-root
-nodes. CollectionC MAY signal Receive.receive on a root node when
-a data packet successfully arrives at that node. If a root node calls
-Send, CollectionC MUST treat it as it if were a received packet.
-Note that the buffer swapping semantics of Receive.receive, when
-combined with the pass semantics of Send, require that CollectionC
-make a copy of the buffer if it signals Receive.receive.</p>
-<p>If CollectionC receives a data packet to forward and it is not a
-root node, it MAY signal Intercept.forward.</p>
-<p>If CollectionC receives a data packet that a different node
-is supposed to forward, it MAY signal Snoop.receive.</p>
+nodes. CollectionC MUST signal Receive.receive on a root node when a
+unique (non-duplicate) data packet successfully arrives at that
+node. It MAY signal Receive.receive when a duplicate data packet
+successfully arrives. If a root node calls Send, CollectionC MUST
+treat it as it if were a received packet.  Note that the buffer
+swapping semantics of Receive.receive, when combined with the pass
+semantics of Send, require that CollectionC make a copy of the buffer
+if it signals Receive.receive.</p>
+<p>If CollectionC receives a data packet to forward and it is not a root
+node, it MAY signal Intercept.forward. CollectionC MAY signal
+Snoop.receive when it hears a packet which a different node is
+supposed to forward. For any given packet it receives, CollectionC
+MUST NOT signal more than one of the Snoop.receive, Receive.receive,
+and Intercept.forward events.</p>
 <p>RootControl allows a node to be made a collection tree root.
 CollectionC SHOULD NOT configure a node as a root by default.</p>
 <p>Packet and CollectionPacket allow components to access collection
-data packet fields [<a class="reference" href="#id2">1</a>].</p>
+data packet fields [<a class="reference" href="#id1">1</a>].</p>
 <div class="section">
 <h2><a id="collectionsenderc" name="collectionsenderc">3.1 CollectionSenderC</a></h2>
 <p>Collection has a virtualized sending abstraction, the generic
@@ -486,221 +497,19 @@ generic configuration CollectionSenderC(collection_id_t collectid) {
 }
 </pre>
 <p>This abstraction follows a similar virtualization approach to
-AMSenderC [<a class="reference" href="#id2">1</a>], except that it is parameterized by a collection_id_t
+AMSenderC [<a class="reference" href="#id1">1</a>], except that it is parameterized by a collection_id_t
 rather than an am_id_t. As with am_id_t, every collection_id_t SHOULD
 have a single packet format, so that receivers can parse a packet
 based on its collection ID and contents.</p>
 </div>
 </div>
 <div class="section">
-<h1><a id="implementation" name="implementation">4 Implementation</a></h1>
-<p>An implementation of this TEP can be found in
-<tt class="docutils literal"><span class="pre">tinyos-2.x/tos/lib/net/ctp</span></tt> and <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/lib/net/4bitle</span></tt>, in
-the CTP protocol. It is beyond the scope of this document to fully
-describe CTP, but we outline its main components. CTP will be
-described in an upcoming TEP [<a class="reference" href="#id3">2</a>].  This implementation is a
-reference implementation, and is not the only possibility.  It
-consists of three major components, which are wired together to form
-a CollectionC: LinkEstimatorP, CtpRoutingEngineP, and
-CtpForwardingEngineP.</p>
-<p>This decomposition tries to encourage evolution of components and
-ease of use through modularization. Neighbor management and link
-estimation are decoupled from the routing protocol. Furthermore, the
-routing protocol and route selection are decoupled from the
-forwarding policies, such as queueing and timing.</p>
-<div class="section">
-<h2><a id="linkestimatorp" name="linkestimatorp">4.1 LinkEstimatorP</a></h2>
-<p>LinkEstimatorP estimates the quality of link to or from each
-neighbor. In this TEP, we briefly describe the reference
-implementation in ''tinyos-2.x/tos/lib/4bitle'' and refer the readers
-to <a class="footnote-reference" href="#id4" id="id1" name="id1">[3]</a> for detailed description of the estimator.</p>
-<p>Link estimation is decoupled from the establishment of routes. There
-is a narrow interface -- LinkEstimator and CompareBit -- between the
-link estimator and the routing engine. The one requirement is that the
-quality returned is standardized. A smaller return value from
-LinkEstimator.getLinkQuality() MUST imply that the link to the
-neighbor is estimated to be of a higher quality than the one that
-results in a larger return value. The range of value SHOULD be
-[0,65535] and the variation in link quality in that range SHOULD be
-linear. Radio provided values such as LQI or RSI, beacon based link
-estimation to compute ETX, or their combination are some possible
-approaches to estimating link qualities. The routing engine instructs
-LinkEstimatorP to insert the neighbor, through which a high quality
-path to the root can be constructed, into the neighbor table by
-returning TRUE when LinkEstimatorP signals Comparebit.shouldInsert()
-for the newly discovered neighbor.</p>
-<p>LinkEstimatorP MAY have its own control messages to compute
-bi-directional link qualities. LinkEstimatorP provides calls (txAck(),
-txNoAck(), and clearDLQ()) to update the link estimates based on
-successful or unsuccessful data transmission to the
-neighbors. LinkEstimatorP uses the LinkPacketMetadata interface to
-determine if the channel was of high quality when a packet is received
-from a neighbor to consider the link to that neighbor for insertion
-into the neighbor table.</p>
-<p>The user of LinkEstimatorP can call insertNeighbor() to manually
-insert a node in the neighbor table, pinNeighbor() to prevent a
-neighbor from being evicted, and unpinNeighbor() to restore eviction
-policy:</p>
-<pre class="literal-block">
-typedef uint16_t neighbor_table_entry_t
-
-LinkEstimatorP {
-  provides {
-    interface StdControl;
-    interface AMSend as Send;
-    interface Receive;
-    interface LinkEstimator;
-    interface Init;
-    interface Packet;
-    interface CompareBit;
-  }
-  uses {
-    interface AMSend;
-    interface AMPacket as SubAMPacket;
-    interface Packet as SubPacket;
-    interface Receive as SubReceive;
-    interface LinkPacketMetadata;
-    interface Random;
-  }
-}
-
-interface CompareBit {
-  event bool shouldInsert(message_t *msg, void* payload, uint8_t len, bool white_bit);
-}
-
-interface LinkEstimator {
-  command uint16_t getLinkQuality(uint16_t neighbor);
-  command error_t insertNeighbor(am_addr_t neighbor);
-  command error_t pinNeighbor(am_addr_t neighbor);
-  command error_t unpinNeighbor(am_addr_t neighbor);
-  command error_t txAck(am_addr_t neighbor);
-  command error_t txNoAck(am_addr_t neighbor);
-  command error_t clearDLQ(am_addr_t neighbor);
-  event void evicted(am_addr_t neighbor);
-}
-</pre>
-</div>
-<div class="section">
-<h2><a id="ctproutingenginep" name="ctproutingenginep">4.2 CtpRoutingEngineP</a></h2>
-<p>CtpRoutingEngineP is responsible for computing routes to the roots of a
-tree. In traditional networking terminology, this is part of the
-control plane of the network, and is does not directly forward any
-data packets, which is the responsibility of CtpForwardingEngine.
-The main interface between the two is UnicastNameFreeRouting.</p>
-<p>CtpRoutingEngineP uses the LinkEstimator interface to learn
-about the nodes in the neighbor table maintained by LinkEstimatorP and
-the quality of links to and from the neighbors. The routing protocol
-on which collection is implemented MUST be a tree-based routing
-protocol with a single or multiple roots. CtpRoutingEngineP
-allows a node to be configured as a root or a non-root node
-dynamically. CtpRoutingEngineP maintains multiple candidate next hops:</p>
-<pre class="literal-block">
-generic module CtpRoutingEngineP(uint8_t routingTableSize,
-                                 uint16_t minInterval,
-                                 uint16_t maxInterval) {
-    provides {
-        interface UnicastNameFreeRouting as Routing;
-        interface RootControl;
-        interface CtpInfo;
-        interface StdControl;
-        interface CtpRoutingPacket;
-        interface Init;
-    }
-    uses {
-        interface AMSend as BeaconSend;
-        interface Receive as BeaconReceive;
-        interface LinkEstimator;
-        interface AMPacket;
-        interface SplitControl as RadioControl;
-        interface Timer&lt;TMilli&gt; as BeaconTimer;
-        interface Timer&lt;TMilli&gt; as RouteTimer;
-        interface Random;
-        interface CollectionDebug;
-        interface CtpCongestion;
-        interface Comparebit;
-    }
-}
-</pre>
-<pre class="literal-block">
-interface UnicastNameFreeRouting {
-  command am_addr_t nextHop();
-
-  command bool hasRoute();
-  event void routeFound();
-  event void noRoute();
-}
-</pre>
-</div>
-<div class="section">
-<h2><a id="ctpforwardingenginep" name="ctpforwardingenginep">4.3 CtpForwardingEngineP</a></h2>
-<p>The CtpForwardingEngineP component provides all the top level interfaces
-(except RootControl) which CollectionC provides and an application
-uses. It deals with retransmissions, duplicate suppression, packet
-timing, loop detection, and also informs the LinkEstimator of the
-outcome of attempted transmissions.:</p>
-<pre class="literal-block">
-generic module CtpForwardingEngineP() {
-  provides {
-    interface Init;
-    interface StdControl;
-    interface Send[uint8_t client];
-    interface Receive[collection_id_t id];
-    interface Receive as Snoop[collection_id_t id];
-    interface Intercept[collection_id_t id];
-    interface Packet;
-    interface CollectionPacket;
-    interface CtpPacket;
-    interface CtpCongestion;
-  }
-  uses {
-    interface SplitControl as RadioControl;
-    interface AMSend as SubSend;
-    interface Receive as SubReceive;
-    interface Receive as SubSnoop;
-    interface Packet as SubPacket;
-    interface UnicastNameFreeRouting;
-    interface Queue&lt;fe_queue_entry_t*&gt; as SendQueue;
-    interface Pool&lt;fe_queue_entry_t&gt; as QEntryPool;
-    interface Pool&lt;message_t&gt; as MessagePool;
-    interface Timer&lt;TMilli&gt; as RetxmitTimer;
-    interface LinkEstimator;
-    interface Timer&lt;TMilli&gt; as CongestionTimer;
-    interface Cache&lt;message_t*&gt; as SentCache;
-    interface CtpInfo;
-    interface PacketAcknowledgements;
-    interface Random;
-    interface RootControl;
-    interface CollectionId[uint8_t client];
-    interface AMPacket;
-    interface CollectionDebug;
-  }
-}
-</pre>
-<p>CtpForwardingEngineP uses a large number of interfaces, which can be
-broken up into a few groups of functionality:</p>
-<blockquote>
-<ul class="simple">
-<li>Single hop communication: SubSend, SubReceive, SubSnoop,
-SubPacket, PacketAcknowledgments, AMPacket</li>
-<li>Routing: UnicastNameFreeRouting, RootControl, CtpInfo,
-CollectionId, SentCache</li>
-<li>Queue and buffer management: SendQueue, MessagePool,
-QEntryPool</li>
-<li>Packet timing: Random, RetxmitTimer</li>
-</ul>
-</blockquote>
-</div>
-</div>
-<div class="section">
-<h1><a id="multihoplqi" name="multihoplqi">4.4 MultihopLqi</a></h1>
-<p>There is another implementation of collection in <tt class="docutils literal"><span class="pre">tos/lib/net/lqi</span></tt>.
-Its software structure is similar, with the exception that it does
-not have a separate link estimator. MultihopLqi only works on
-platforms that have a CC2420 radio, as it uses a special piece
-of physical layer data the radio provides (the LQI value).
-The three major components of the MultihopLqi implementation
-are the modules LqiForwardingEngineP and  LqiRoutingEngineP, as
-well as the configuration MultihopLqiP.</p>
+<h1><a id="implementation" name="implementation">4. Implementation</a></h1>
+<p>Implementations of collection can be found in
+<tt class="docutils literal"><span class="pre">tinyos-2.x/tos/lib/net/ctp</span></tt> and <tt class="docutils literal"><span class="pre">tinyos-2.x/tos/lib/net/lqi</span></tt>.
+The former is the Collection Tree Protocol (CTP), described in TEP 123
+[<a class="reference" href="#id2">2</a>]. The latter is a TinyOS 2.x port of MultihopLqi, a
+CC2420-specific collection protocol in TinyOS 1.x.</p>
 </div>
 <div class="section">
 <h1><a id="author-addresses" name="author-addresses">5. Author Addresses</a></h1>
@@ -742,22 +551,16 @@ well as the configuration MultihopLqiP.</p>
 </div>
 <div class="section">
 <h1><a id="citations" name="citations">6. Citations</a></h1>
-<table class="docutils footnote" frame="void" id="id2" rules="none">
-<colgroup><col class="label" /><col /></colgroup>
-<tbody valign="top">
-<tr><td class="label"><a name="id2">[1]</a></td><td>TEP 116: Packet Protocols</td></tr>
-</tbody>
-</table>
-<table class="docutils footnote" frame="void" id="id3" rules="none">
+<table class="docutils footnote" frame="void" id="id1" rules="none">
 <colgroup><col class="label" /><col /></colgroup>
 <tbody valign="top">
-<tr><td class="label"><a name="id3">[2]</a></td><td>TEP 123: The Collection Tree Protocol (CTP)</td></tr>
+<tr><td class="label"><a name="id1">[1]</a></td><td>TEP 116: Packet Protocols.</td></tr>
 </tbody>
 </table>
-<table class="docutils footnote" frame="void" id="id4" rules="none">
+<table class="docutils footnote" frame="void" id="id2" rules="none">
 <colgroup><col class="label" /><col /></colgroup>
 <tbody valign="top">
-<tr><td class="label"><a class="fn-backref" href="#id1" name="id4">[3]</a></td><td>Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, and Philip Levis. &quot;Four Bit Wireless Link Estimation.&quot; In Proceedings of the Sixth Workshop on Hot Topics in Networks (HotNets VI), November 2007</td></tr>
+<tr><td class="label"><a name="id2">[2]</a></td><td>TEP 123: The Collection Tree Protocol (CTP).</td></tr>
 </tbody>
 </table>
 </div>
index 9c27e37048643058a639358fa45a121600e11075..2b1ae7fb46ce4bb35c2c1b51f636bcf155b427b3 100644 (file)
@@ -818,13 +818,13 @@ interface being so different from TinyOS 1.x.</p>
 <div class="line">Anders Egeskov Petersen</div>
 <div class="line">University of Copenhagen, Dept. of Computer Science</div>
 <div class="line">Universitetsparken 1</div>
-<div class="line">DK-2100 København Ã˜</div>
+<div class="line">DK-2100 K¯benhavn Ã¿</div>
 <div class="line">Denmark</div>
 <div class="line"><br /></div>
 <div class="line">Sidsel Jensen</div>
 <div class="line">University of Copenhagen, Dept. of Computer Science</div>
 <div class="line">Universitetsparken 1</div>
-<div class="line">DK-2100 København Ã˜</div>
+<div class="line">DK-2100 K¯benhavn Ã¿</div>
 <div class="line">Denmark</div>
 <div class="line"><br /></div>
 <div class="line">email - <a class="reference" href="mailto:purps&#64;diku.dk">purps&#64;diku.dk</a></div>
@@ -832,7 +832,7 @@ interface being so different from TinyOS 1.x.</p>
 <div class="line">Martin Leoold</div>
 <div class="line">University of Copenhagen, Dept. of Computer Science</div>
 <div class="line">Universitetsparken 1</div>
-<div class="line">DK-2100 København Ã˜</div>
+<div class="line">DK-2100 K¯benhavn Ã¿</div>
 <div class="line">Denmark</div>
 <div class="line"><br /></div>
 <div class="line">Phone +45 3532 1464</div>
index d2406572123ad2137e191985854ecfd020049c31..f3ea4462388e6e3ad7d712841f39feac9837380f 100644 (file)
@@ -291,16 +291,16 @@ ul.auto-toc {
 <tr class="field"><th class="docinfo-name">Type:</th><td class="field-body">Documentary</td>
 </tr>
 <tr><th class="docinfo-name">Status:</th>
-<td>Draft</td></tr>
-<tr class="field"><th class="docinfo-name">TinyOS-Version:</th><td class="field-body">2.x</td>
+<td>Final</td></tr>
+<tr class="field"><th class="docinfo-name">TinyOS-Version:</th><td class="field-body">&gt; 2.1</td>
 </tr>
 <tr><th class="docinfo-name">Author:</th>
 <td>Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, Sukun Kim, Philip Levis, and Alec Woo</td></tr>
 <tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">3-Aug-2006</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.8</td>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.15</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2007-02-28</td>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2009-01-16</td>
 </tr>
 <tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
 </tr>
@@ -321,6 +321,18 @@ collection roots in a network.</p>
 </div>
 <div class="section">
 <h1><a id="introduction" name="introduction">1. Introduction</a></h1>
+<p>A collection protocol delivers data to one of possibly several data
+sinks, providing a many-to-one network layer. Collection is a
+fundamental component of most sensor network applications. The
+Collection Tree Protocol (CTP) is a reference Collection protocol in
+TinyOS 2.x. The users use Collection interfaces described in TEP 119
+<a class="footnote-reference" href="#id8" id="id1" name="id1">[3]</a> to use CTP in their applications.</p>
+<p>In this TEP, after a brief discussion of Collection and CTP, we
+specify the CTP routing and data frames. CTP uses routing frames to
+update and build collection tree in the network. CTP uses data frames
+to deliver application payload to the sink and to probe topology
+inconsistencies.</p>
+<p>All fields in this specification are in network byte order.</p>
 </div>
 <div class="section">
 <h1><a id="assumptions-and-limitations" name="assumptions-and-limitations">2. Assumptions and Limitations</a></h1>
@@ -337,19 +349,23 @@ a routing gradient.</p>
 <li>Provides synchronous acknowledgments for unicast packets.</li>
 <li>Provides a protocol dispatch field to support multiple higher-level
 protocols.</li>
-<li>Has single-hop source and destination fields.</li>
+<li>Has single-hop 16-bit source and destination fields.</li>
 </ol>
 </blockquote>
 <p>CTP assumes that it has link quality estimates of some number of nearby
 neighbors. These provide an estimate of the number of transmissions it
 takes for the node to send a unicast packet whose acknowledgment is
 successfully received.</p>
-<p>CTP has several mechanisms in order to improve delivery reliability,
-but it does not promise 100% reliable delivery. It is best effort, but
-a best effort that <em>tries very hard.</em></p>
-<p>CTP is designed for relatively low traffic rates. Bandwidth-limited systems
-might benefit from a different protocol, which can, for example, pack
-multiple small frames into a single data-link packet.</p>
+<p>CTP has several mechanisms in order to achieve high delivery
+reliability, but it does not promise 100% reliable delivery. It is a
+best effort protocol.</p>
+<p>CTP is designed for relatively low traffic rates such that there is
+enough space in the channel to transmit and receive routing frames
+even when the network is forwarding collection data
+frames. Bandwidth-limited systems or high data rate applications might
+benefit from a different protocol, which can, for example, pack
+multiple small frames into a single data-link packet or employ rate
+control mechanisms.</p>
 </div>
 <div class="section">
 <h1><a id="collection-and-ctp" name="collection-and-ctp">3. Collection and CTP</a></h1>
@@ -358,9 +374,9 @@ has an ETX of 0.  The ETX of a node is the ETX of its parent plus the
 ETX of its link to its parent. This additive measure assumes that
 nodes use link-level retransmissions.  Given a choice of valid routes,
 CTP SHOULD choose the one with the lowest ETX value. CTP represents
-ETX values as 16-bit fixed-point real numbers with a precision of
-hundredths. An ETX value of 451, for example, represents an ETX of
-4.51, while an ETX value of 109 represents an ETX of 1.09.</p>
+ETX values as 16-bit decimal fixed-point real numbers with a precision
+of tenths. An ETX value of 45, for example, represents an ETX of 4.5,
+while an ETX value of 10 represents an ETX of 1.</p>
 <p>Routing loops are a problem that can emerge in a CTP network. Routing
 loops generally occur when a node choose a new route that has a
 significantly higher ETX than its old one, perhaps in response to
@@ -377,13 +393,17 @@ will form a loop whose ETX increases forever. CTP's second mechanism
 is to not consider routes with an ETX higher than a reasonable constant.
 The value of this constant is implementation dependent.</p>
 <p>Packet duplication is an additional problem that can occur in CTP.
-Packet duplication occurs when a node receives a data frame successfully
-and transmits an ACK, but the ACK is not received. The sender retransmits
-the packet, and the receiver receives it a second time. This can have
-disasterous effects over multiple hops, as the duplication is exponential.
-For example, if each hop on average produces one duplicate, then on the
-first hop there will be two packets, on the second there will be four,
-on the third there will be eight, etc.</p>
+Packet duplication occurs when a node receives a data frame
+successfully and transmits an ACK, but the ACK is not received. The
+sender retransmits the packet, and the receiver receives it a second
+time. This can have disasterous effects over multiple hops, as the
+duplication is exponential.  For example, if each hop on average
+produces one duplicate, then on the first hop there will be two
+packets, on the second there will be four, on the third there will be
+eight, etc. CTP keeps a small cache of packet signature for the
+packets it has seen to detect packet duplicates. When a new packet
+arrives, if its signature results in cache hit, CTP drops the packet
+because it is a duplicate.</p>
 <p>Routing loops complicate duplicate suppression, as a routing loop may
 cause a node to legitimately receive a packet more than once. Therefore,
 if a node suppresses duplicates based solely on originating address and
@@ -398,30 +418,30 @@ to do so.</p>
 <p>The CTP data frame format is as follows:</p>
 <pre class="literal-block">
                      1
- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-|P|C| reserved  |      THL        |
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-|              ETX                |
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-|             origin              |
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-|     seqno     |   collect_id    |
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|P|C| reserved  |      THL      |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|              ETX              |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|             origin            |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|     seqno     |   collect_id  |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |    data ...
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 </pre>
 <p>Field definitions are as follows:</p>
 <blockquote>
 <ul class="simple">
-<li>P: Routing pull. The P bit allows nodes to request routing information from other nodes. If a node with a valid route hears a packet with the P bit set, it SHOULD transmit a routing frame in the near future.</li>
+<li>P: Routing pull. The P bit allows nodes to request routing information from other nodes. If the unicast destination of the data frame with a valid route hears a packet with the P bit set, it SHOULD transmit a routing frame in the near future. Nodes other than the link-layer destination of the data frame MAY respond to the P bit in the data frame.</li>
 <li>C: Congestion notification. If a node drops a CTP data frame, it MUST set the C field on the next data frame it transmits.</li>
 <li>THL: Time Has Lived. When a node generates a CTP data frame, it MUST set THL to 0. When a node receives a CTP data frame, it MUST increment the THL. If a node receives a THL of 255, it increments it to 0.</li>
 <li>ETX: The ETX routing metric of the single-hop sender. When a node transmits a CTP data frame, it MUST put the ETX value of its route through the single-hop destination in the ETX field.  If a node receives a packet with a lower gradient than its own, then it MUST schedule a routing frame in the near future.</li>
 <li>origin: The originating address of the packet. A node forwarding a data frame MUST NOT modify the origin field.</li>
 <li>seqno: Origin sequence number. The originating node sets this field, and a node forwarding a data frame MUST NOT modify it.</li>
 <li>collect_id: Higher-level protocol identifier. The origin sets this field, and a node forwarding a data frame MUST NOT modify it.</li>
-<li>data: the data payload, of zero or more bytes. A node forwarding a data frame MUST NOT modify the data payload.</li>
+<li>data: the data payload, of zero or more bytes. A node forwarding a data frame MUST NOT modify the data payload. The length of the data field is computed by subtracting the size of the CTP header from the size of the link layer payload provided by the link layer.</li>
 </ul>
 </blockquote>
 <p>Together, the origin, seqno and collect_id fields denote a unique
@@ -431,7 +451,7 @@ distinction is important for duplicate suppression in the presence
 of routing loops. If a node suppresses origin packets, then if
 asked to forward the same packet twice due to a routing loop, it will
 drop the packet. However, if it suppresses packet instances, then it
-will route succesfully in the presence of transient loops unless the
+will route successfully in the presence of transient loops unless the
 THL happens to wrap around to a forwarded packet instance.</p>
 <p>A node MUST send CTP data frames as unicast messages with link-layer
 acknowledgments enabled.</p>
@@ -441,19 +461,19 @@ acknowledgments enabled.</p>
 <p>The CTP routing frame format is as follows:</p>
 <pre class="literal-block">
                      1
- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-|P|C| reserved  |      parent     |
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-|     parent    |       ETX       |
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|P|C| reserved  |     parent    |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|     parent    |      ETX      |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 |      ETX      |
 +-+-+-+-+-+-+-+-+
 </pre>
 <p>The fields are as follows:</p>
 <blockquote>
 <ul class="simple">
-<li>P: Same as data frame.</li>
+<li>P: Same as data frame with one difference: Routing frames are broadcast so multiple nodes respond to the P bit in the routing frame.</li>
 <li>C: Congestion notification. If a node drops a CTP data frame, it MUST set the C field on the next routing frame it transmits.</li>
 <li>parent: The node's current parent.</li>
 <li>metric: The node's current routing metric value.</li>
@@ -468,6 +488,7 @@ a data packet: a parent can detect when a child's ETX is significantly
 below its own. When a parent hears a child advertise an ETX below its
 own, it MUST schedule a routing frame for transmission in the near
 future.</p>
+<p>A node MUST send CTP routing frames as broadcast messages.</p>
 </div>
 <div class="section">
 <h1><a id="implementation" name="implementation">6. Implementation</a></h1>
@@ -487,23 +508,23 @@ as well as traffic generated on the node.</p>
 <div class="section">
 <h2><a id="link-estimation" name="link-estimation">6.1 Link Estimation</a></h2>
 <p>The implementation uses two mechanisms to estimate the quality of a link:
-periodic LEEP <a class="footnote-reference" href="#id4" id="id1" name="id1">[1]</a> packets and data packets. The implementation sends
+periodic LEEP <a class="footnote-reference" href="#id6" id="id2" name="id2">[1]</a> packets and data packets. The implementation sends
 routing beacons as LEEP packets. These packets seed the neighbor table
 with bidirectional ETX values. The implementation adapts its beaconing
 rate based on network dynamics using an algorithm similar to the
-trickle dissemination protocol <a class="footnote-reference" href="#id5" id="id2" name="id2">[2]</a>. Beacons are sent on an exponentially
+trickle dissemination protocol <a class="footnote-reference" href="#id7" id="id3" name="id3">[2]</a>. Beacons are sent on an exponentially
 increasing randomized timer. The implementation resets the timer to a
 small value when one or more of the following conditions are met:</p>
 <blockquote>
 <ol class="arabic simple">
 <li>The routing table is empty (this also sets the P bit)</li>
-<li>The node's routing ETX increases by &gt;= 1 trasmission</li>
+<li>The node's routing ETX increases by &gt;= 1 transmission</li>
 <li>The node hears a packet with the P bit set</li>
 </ol>
 </blockquote>
 <p>The implementation augments the LEEP link estimates with data
 transmissions. This is a direct measure of ETX. Whenever the data path
-transmits a packet, it tells the link estimator the destimation and
+transmits a packet, it tells the link estimator the destination and
 whether it was successfully acknowledged. The estimator produces an
 ETX estimate every 5 such transmissions, where 0 successes has an ETX
 of 6.</p>
@@ -515,8 +536,9 @@ data estimates will outweigh beacon estimates. Additionally, as
 the rate at which CTP collects data estimates is proportional to
 the transmission rate, then it can quickly detect a broken link and
 switch to another candidate neighbor.</p>
-<p>The component <tt class="docutils literal"><span class="pre">tos/lib/net/le/LinkEstimatorP</span></tt> implements the
-link estimator. It couples LEEP-based and data-based estimates.</p>
+<p>The component <tt class="docutils literal"><span class="pre">tos/lib/net/4bitle/LinkEstimatorP</span></tt> implements the
+link estimator. It couples LEEP-based and data-based estimates as
+described in <a class="footnote-reference" href="#id9" id="id4" name="id4">[4]</a>.</p>
 </div>
 <div class="section">
 <h2><a id="routing-engine" name="routing-engine">6.2 Routing Engine</a></h2>
@@ -531,7 +553,7 @@ implements the routing engine.</p>
 <div class="section">
 <h2><a id="forwarding-engine" name="forwarding-engine">6.3 Forwarding Engine</a></h2>
 <p>The component <tt class="docutils literal"><span class="pre">tos/lib/net/ctp/CtpForwardingEngineP</span></tt> implements the
-forwarding engine. It has five repsonsibilities:</p>
+forwarding engine. It has five responsibilities:</p>
 <blockquote>
 <ol class="arabic simple">
 <li>Transmitting packets to the next hop, retransmitting when necessary, and
@@ -606,25 +628,57 @@ along the path.</p>
 <div class="line"><br /></div>
 <div class="line">phone - +1 650 725 9046</div>
 <div class="line">email - <a class="reference" href="mailto:pal&#64;cs.stanford.edu">pal&#64;cs.stanford.edu</a></div>
+<div class="line"><br /></div>
+<div class="line"><br /></div>
+<div class="line">Alec Woo</div>
+<div class="line">Arch Rock Corporation</div>
+<div class="line">501 2nd St. Ste 410</div>
+<div class="line">San Francisco, CA 94107-4132</div>
+<div class="line"><br /></div>
+<div class="line">email - <a class="reference" href="mailto:awoo&#64;archrock.com">awoo&#64;archrock.com</a></div>
+<div class="line"><br /></div>
+<div class="line"><br /></div>
+<div class="line">Sukun Kim</div>
+<div class="line">Samsung Electronics</div>
+<div class="line">416 Maetan-3-dong, Yeongtong-Gu</div>
+<div class="line">Suwon, Gyeonggi 443-742</div>
+<div class="line">Korea, Republic of</div>
+<div class="line"><br /></div>
+<div class="line">phone - +82 10 3065 6836</div>
+<div class="line">email - <a class="reference" href="mailto:sukun.kim&#64;samsung.com">sukun.kim&#64;samsung.com</a></div>
 </div>
 </div>
 <div class="section">
-<h1><a id="id3" name="id3">8. Citations</a></h1>
-<table class="docutils footnote" frame="void" id="id4" rules="none">
+<h1><a id="id5" name="id5">8. Citations</a></h1>
+<table class="docutils footnote" frame="void" id="id6" rules="none">
 <colgroup><col class="label" /><col /></colgroup>
 <tbody valign="top">
-<tr><td class="label"><a class="fn-backref" href="#id1" name="id4">[1]</a></td><td>TEP 124: Link Estimation Extension Protocol</td></tr>
+<tr><td class="label"><a class="fn-backref" href="#id2" name="id6">[1]</a></td><td>TEP 124: Link Estimation Extension Protocol</td></tr>
 </tbody>
 </table>
-<table class="docutils footnote" frame="void" id="id5" rules="none">
+<table class="docutils footnote" frame="void" id="id7" rules="none">
 <colgroup><col class="label" /><col /></colgroup>
 <tbody valign="top">
-<tr><td class="label"><a class="fn-backref" href="#id2" name="id5">[2]</a></td><td>Philip Levis, Neil Patel, David Culler and Scott Shenker. &quot;A
+<tr><td class="label"><a class="fn-backref" href="#id3" name="id7">[2]</a></td><td>Philip Levis, Neil Patel, David Culler and Scott Shenker. &quot;A
 Self-Regulating Algorithm for Code Maintenance and Propagation
 in Wireless Sensor Networks.&quot; In Proceedings of the First USENIX
 Conference on Networked Systems Design and Implementation (NSDI), 2004.</td></tr>
 </tbody>
 </table>
+<table class="docutils footnote" frame="void" id="id8" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a class="fn-backref" href="#id1" name="id8">[3]</a></td><td>TEP 119: Collection.</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="id9" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a class="fn-backref" href="#id4" name="id9">[4]</a></td><td>Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, and Philip Levis.
+&quot;Four Bit Wireless Link Estimation.&quot; In Proceedings of the Sixth Workshop
+on Hot Topics in Networks (HotNets VI), November 2007.</td></tr>
+</tbody>
+</table>
 </div>
 </div>
 </body>
index d318d9760cac65e3c0f8156f73ee97fc4e626f5d..37bc9316288f70e7d38241af6815ab8bf8374f2a 100644 (file)
@@ -298,9 +298,9 @@ ul.auto-toc {
 <td>Omprakash Gnawali</td></tr>
 <tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">05-Feb-2006</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.4</td>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.9</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2007-02-28</td>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2009-01-31</td>
 </tr>
 <tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
 </tr>
@@ -327,31 +327,28 @@ link from a neighbor by estimating the ratio of successfully received
 messages and the total transmitted messages. LEEP appends in-bound
 packet reception rate (PRR) estimates to packets. Other nodes hearing
 these packets can combine the in-bound PRR values with their own
-in-bound values to compute bi-directional link quality.</p>
+in-bound values to compute bi-directional link quality. Thus, LEEP is
+a discovery and link table bootstrapping mechanism. The link quality
+is often fine-tuned using different mechanisms.</p>
+<p>Link quality estimates obtained using LEEP are often used as a
+bootstrapping values in the link quality table; data transmission
+statistics can later be used to make these estimates more accurate.</p>
 </div>
 <div class="section">
 <h1><a id="definitions" name="definitions">2. Definitions</a></h1>
 <div class="section">
-<h2><a id="link-quality" name="link-quality">2.1 Link Quality</a></h2>
-<p>The link quality between a directed node pair (A,B) is the probability
-that a packet transmitted by A will be successfully received by B. The
-bidirectional link quality of an undirected node pair (A,B) is the
-product of the link quality of (A,B) and (B,A). This definition
-assumes independent link losses. It also includes the case when
-the link quality of (A,B) and (B,A) are different; this can occur
-due to local interference or noise.</p>
-</div>
-<div class="section">
-<h2><a id="in-bound-link-quality" name="in-bound-link-quality">2.2 In-bound Link Quality</a></h2>
+<h2><a id="in-bound-link-quality" name="in-bound-link-quality">2.1 In-bound Link Quality</a></h2>
 <p>In a node pair (A,B), with B as the node of reference, in-bound link
 quality is a value in the range of 0 to 255 that describes the quality
 of the link from A to B estimated by B by counting the successfully
-received packets from A among all the transmitted packets or using
-link quality indicators such as LQI and RSSI provided by the radio on
-the node B, or some other methods.</p>
+received packets from A among all the packets transmitted by A. Thus,
+in-bound link quality is the empirical probability that a packet will
+be successfully received on a given link. A value of 255 represents a
+probability of 1 and a value of 0 represents a probability of 0 of
+successfully receiving a packet on a given link.</p>
 </div>
 <div class="section">
-<h2><a id="out-bound-link-quality" name="out-bound-link-quality">2.3 Out-bound Link Quality</a></h2>
+<h2><a id="out-bound-link-quality" name="out-bound-link-quality">2.2 Out-bound Link Quality</a></h2>
 <p>In a node pair (A,B), with B as the node of reference, out-bound link
 quality is defined as the quality of the link from B to A. B can
 determine the out-bound link quality if A advertises its in-bound link
@@ -359,6 +356,18 @@ qualities. LEEP is the protocol that is used to exchange the in-bound
 link qualities.</p>
 </div>
 <div class="section">
+<h2><a id="bi-directional-link-quality" name="bi-directional-link-quality">2.3 Bi-directional Link Quality</a></h2>
+<p>LEEP does not define or compute bi-directional link quality. LEEP
+provides a way to exchange sufficient information to compute in-bound
+and out-bound link qualities. These two link qualities can be used to
+compute the bi-directional link quality. One popular way to define the
+bi-directional link quality between a node pair (A,B) as the
+probability that a packet transmitted by A will be successfully
+received and acknowledged by B. This approach computes the
+bi-directional link quality of a node pair (A,B) as the product of the
+link quality of (A,B) and (B,A).</p>
+</div>
+<div class="section">
 <h2><a id="link-information-entry" name="link-information-entry">2.4 Link Information Entry</a></h2>
 <p>Link Information Entry created by node k is a tuple (n,q) where q is
 the in-bound link quality from node n to k.</p>
@@ -385,7 +394,14 @@ link quality from the transmitter. LEEP MUST transmit Link Information
 entries describing the in-bound link qualities for a subset of its
 neighbors. The Link Information entry on the LEEP frame allows the
 receiver node to find the out-bound link quality to the transmitter
-node identified by the data link source address.</p>
+node identified by the data link source address. Thus, LEEP is also a
+way for nodes to discover new nodes and links in the network.</p>
+<p>Link quality estimation is inherently imperfect - data transmission
+and link quality estimation might be done at different timescales. The
+PRR for LEEP frames (broadcast) and data frames (unicast) might be
+different. So LEEP is better used as a link quality bootstrapping
+mechanism. The link quality estimate can be made more accurate later
+using data transmission statistics.</p>
 </div>
 <div class="section">
 <h2><a id="leep-frame" name="leep-frame">3.3 LEEP Frame</a></h2>
@@ -408,10 +424,10 @@ Information entry.</p>
 <p>The following diagram shows the LEEP header format:</p>
 <pre class="literal-block">
                      1
- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-|nentry | rsrvd |      seqno      |
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|nentry | rsrvd |     seqno     |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 </pre>
 <p>Field definitions:</p>
 <blockquote>
@@ -427,10 +443,10 @@ Information entry.</p>
 <p>The following diagram shows the Link Information Entry format:</p>
 <pre class="literal-block">
                      1
- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-|             node id             |
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+|            node id            |
++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 | link quality  |
 +-+-+-+-+-+-+-+-+
 </pre>
@@ -460,8 +476,11 @@ all the neighbors in its neighbor table by sending the largest
 possible data link frame. If there is still not enough room to fit all
 the Link Information entries, it uses a round-robin policy to select
 the entries to be exchanged that could not fit in the previous LEEP
-frame. The LEEP frames are transmitted whenever the CTP <a class="footnote-reference" href="#id4" id="id3" name="id3">[1]</a> beacons,
+frame. The LEEP frames are transmitted whenever the CTP <a class="footnote-reference" href="#id5" id="id3" name="id3">[1]</a> beacons,
 sent as a LEEP payload, are sent.</p>
+<p>Another reference implementation resides in
+<tt class="docutils literal"><span class="pre">tinyos-2.x/tos/lib/net/4bitle</span></tt>. This implementation is described in
+detail in <a class="footnote-reference" href="#id6" id="id4" name="id4">[2]</a>.</p>
 </div>
 <div class="section">
 <h1><a id="author-s-address" name="author-s-address">5. Author's Address</a></h1>
@@ -478,10 +497,18 @@ sent as a LEEP payload, are sent.</p>
 </div>
 <div class="section">
 <h1><a id="citations" name="citations">6. Citations</a></h1>
-<table class="docutils footnote" frame="void" id="id4" rules="none">
+<table class="docutils footnote" frame="void" id="id5" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a class="fn-backref" href="#id3" name="id5">[1]</a></td><td>TEP 123: The Collection Tree Protocol.</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="id6" rules="none">
 <colgroup><col class="label" /><col /></colgroup>
 <tbody valign="top">
-<tr><td class="label"><a class="fn-backref" href="#id3" name="id4">[1]</a></td><td>TEP 123: The Collection Tree Protocol.</td></tr>
+<tr><td class="label"><a class="fn-backref" href="#id4" name="id6">[2]</a></td><td>Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, and Philip Levis.
+&quot;Four Bit Wireless Link Estimation.&quot; In Proceedings of the Sixth Workshop
+on Hot Topics in Networks (HotNets VI), November 2007.</td></tr>
 </tbody>
 </table>
 </div>
index 172a5d6645176c8ff22ed1fedc25d460ca5c4010..ced538ed149aba6484f2251c0f0fe64cce1ea082 100644 (file)
@@ -3,7 +3,7 @@
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
 <title>TinyOS 802.15.4 Frames</title>
 <meta name="author" content="Jonathan Hui, Philip Levis, and David Moss" />
 <style type="text/css">
@@ -298,9 +298,9 @@ ul.auto-toc {
 <td>Jonathan Hui, Philip Levis, and David Moss</td></tr>
 <tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">2-Feb-2007</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.5</td>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.6</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-06-16</td>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-06-20</td>
 </tr>
 <tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
 </tr>
@@ -361,9 +361,9 @@ for &quot;Interoperable Frame.&quot;</p>
 | 802.15.4 Header   | 6lowpan | AM type |        data        | 802.15.4 CRC |
 +-------------------+---------+------------------------------+--------------+
 </pre>
-<p>AM type is the same as in a T-frame. 6lowpan is the NALP code to identify
-this as a TinyOS packet. NALP codes must be in the range of 0-63.
-TinyOS uses code 63.</p>
+<p>AM type is the same as in a T-frame. 6lowpan is the NALP code to
+identify this as a TinyOS packet. NALP codes must be in the range of
+0-63.  TinyOS uses code 63 (0x3F).</p>
 <p>The AM type 63 is reserved for both T-Frames and I-Frames. A TinyOS
 program MUST NOT use it.</p>
 </div>
index 934f88dad5e6e22c9f84b1981f4040e6319915ec..1d78d3212dc13716bb8399a2df84511500eea2ac 100644 (file)
@@ -3,7 +3,7 @@
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
 <title>Creating a New Platform for TinyOS 2.x</title>
 <meta name="author" content="Martin Leopold" />
 <style type="text/css">
 /*
 :Author: David Goodger
 :Contact: goodger@users.sourceforge.net
-:Date: $Date$
-:Revision: $Revision$
-:Copyright: This stylesheet has been placed in the public domain.
+:date: $Date$
+:version: $Revision$
+:copyright: This stylesheet has been placed in the public domain.
 
 Default cascading style sheet for the HTML output of Docutils.
-
-See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
-customize this style sheet.
 */
-
-/* used to remove borders from tables and images */
-.borderless, table.borderless td, table.borderless th {
-  border: 0 }
-
-table.borderless td, table.borderless th {
-  /* Override padding for "table.docutils td" with "! important".
-     The right padding separates the table cells. */
-  padding: 0 0.5em 0 0 ! important }
+body {
+  font-family: Times;
+  font-size: 16px;
+}
 
 .first {
-  /* Override more specific margin styles with "! important". */
   margin-top: 0 ! important }
 
-.last, .with-subtitle {
+.last {
   margin-bottom: 0 ! important }
 
 .hidden {
@@ -47,14 +38,9 @@ a.toc-backref {
 blockquote.epigraph {
   margin: 2em 5em ; }
 
-dl.docutils dd {
+dd {
   margin-bottom: 0.5em }
 
-/* Uncomment (and remove this text!) to get bold-faced definition list terms
-dl.docutils dt {
-  font-weight: bold }
-*/
-
 div.abstract {
   margin: 2em 5em }
 
@@ -62,18 +48,12 @@ div.abstract p.topic-title {
   font-weight: bold ;
   text-align: center }
 
-div.admonition, div.attention, div.caution, div.danger, div.error,
-div.hint, div.important, div.note, div.tip, div.warning {
+div.attention, div.caution, div.danger, div.error, div.hint,
+div.important, div.note, div.tip, div.warning, div.admonition {
   margin: 2em ;
   border: medium outset ;
   padding: 1em }
 
-div.admonition p.admonition-title, div.hint p.admonition-title,
-div.important p.admonition-title, div.note p.admonition-title,
-div.tip p.admonition-title {
-  font-weight: bold ;
-  font-family: sans-serif }
-
 div.attention p.admonition-title, div.caution p.admonition-title,
 div.danger p.admonition-title, div.error p.admonition-title,
 div.warning p.admonition-title {
@@ -81,14 +61,11 @@ div.warning p.admonition-title {
   font-weight: bold ;
   font-family: sans-serif }
 
-/* Uncomment (and remove this text!) to get reduced vertical space in
-   compound paragraphs.
-div.compound .compound-first, div.compound .compound-middle {
-  margin-bottom: 0.5em }
-
-div.compound .compound-last, div.compound .compound-middle {
-  margin-top: 0.5em }
-*/
+div.hint p.admonition-title, div.important p.admonition-title,
+div.note p.admonition-title, div.tip p.admonition-title,
+div.admonition p.admonition-title {
+  font-weight: bold ;
+  font-family: sans-serif }
 
 div.dedication {
   margin: 2em 5em ;
@@ -100,11 +77,9 @@ div.dedication p.topic-title {
   font-style: normal }
 
 div.figure {
-  margin-left: 2em ;
-  margin-right: 2em }
+  margin-left: 2em }
 
 div.footer, div.header {
-  clear: both;
   font-size: smaller }
 
 div.line-block {
@@ -120,7 +95,7 @@ div.line-block div.line-block {
 div.sidebar {
   margin-left: 1em ;
   border: medium outset ;
-  padding: 1em ;
+  padding: 0em 1em ;
   background-color: #ffffee ;
   width: 40% ;
   float: right ;
@@ -147,24 +122,31 @@ div.system-message p.system-message-title {
 div.topic {
   margin: 2em }
 
-h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
-h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
-  margin-top: 0.4em }
+h1 {
+  font-family: Arial, sans-serif;
+  font-size: 20px;
+}
 
 h1.title {
-  text-align: center }
+ text-align: center;
+ font-size: 32px;
+}
+
+h2 {
+ font-size: 16px;
+ font-family: Arial, sans-serif;
+}
 
 h2.subtitle {
   text-align: center }
 
-hr.docutils {
-  width: 75% }
-
-img.align-left {
-  clear: left }
+h3 {
+ font-size: 12px;
+ font-family: Arial, sans-serif;
+}
 
-img.align-right {
-  clear: right }
+hr {
+  width: 75% }
 
 ol.simple, ul.simple {
   margin-bottom: 1em }
@@ -222,10 +204,18 @@ pre.address {
   font-family: serif ;
   font-size: 100% }
 
+pre.line-block {
+  font-family: serif ;
+  font-size: 100% }
+
 pre.literal-block, pre.doctest-block {
   margin-left: 2em ;
   margin-right: 2em ;
-  background-color: #eeeeee }
+  background-color: #eeeeee;
+  border-color: #000000;
+  border-width: thin; 
+  font-size: 14px
+}
 
 span.classifier {
   font-family: sans-serif ;
@@ -241,49 +231,46 @@ span.interpreted {
 span.option {
   white-space: nowrap }
 
+span.option-argument {
+  font-style: italic }
+
 span.pre {
   white-space: pre }
 
 span.problematic {
   color: red }
 
-span.section-subtitle {
-  /* font-size relative to parent (h1..h6 element) */
-  font-size: 80% }
+table {
+  margin-top: 0.5em ;
+  margin-bottom: 0.5em }
 
 table.citation {
-  border-left: solid 1px gray;
-  margin-left: 1px }
+  border-left: solid thin gray ;
+  padding-left: 0.5ex }
 
 table.docinfo {
-  margin: 2em 4em }
-
-table.docutils {
-  margin-top: 0.5em ;
-  margin-bottom: 0.5em }
+  margin: 2em 4em;
+}
 
 table.footnote {
-  border-left: solid 1px black;
-  margin-left: 1px }
+  border-left: solid thin black ;
+  padding-left: 0.5ex }
 
-table.docutils td, table.docutils th,
-table.docinfo td, table.docinfo th {
+td, th {
   padding-left: 0.5em ;
   padding-right: 0.5em ;
   vertical-align: top }
 
-table.docutils th.field-name, table.docinfo th.docinfo-name {
+th.docinfo-name, th.field-name {
   font-weight: bold ;
   text-align: left ;
-  white-space: nowrap ;
-  padding-left: 0 }
+  white-space: nowrap;
+  }
 
-h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
-h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
+h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
   font-size: 100% }
 
-tt.docutils {
-  background-color: #eeeeee }
+tt {}
 
 ul.auto-toc {
   list-style-type: none }
@@ -1641,7 +1628,7 @@ interface Msp430TimerControl
 
   async command void setControl(msp430_compare_control_t control );
   async command void setControlAsCompare();
-  async command void setControlAsCapture(bool low_to_high);
+  async command void setControlAsCapture(uint8_t cm);
 
   async command void enableEvents();
   async command void disableEvents();
@@ -1840,7 +1827,7 @@ Msp430Uart0C
 -&gt; Sender videre til HplMsp430Usart1C-&gt;HplMsp430Usart1P</dd>
 <dt>..PXA27</dt>
 <dd>Parametriseret m. HplPXA27xUARTP (Init &amp;&amp; HplPXA27xUART)
--&gt; init sætter en masse registre og enabler interrupt
+-&gt; init sÃ\8atter en masse registre og enabler interrupt
 HalPXA27xSerialP: HplPXA27xUART, Init, noget DMA noget</dd>
 </dl>
 </div>
@@ -1852,7 +1839,7 @@ HalPXA27xSerialP: HplPXA27xUART, Init, noget DMA noget</dd>
 <div class="line">Martin Leoold</div>
 <div class="line">University of Copenhagen, Dept. of Computer Science</div>
 <div class="line">Universitetsparken 1</div>
-<div class="line">DK-2100 København Ã˜</div>
+<div class="line">DK-2100 K¯benhavn Ã¿</div>
 <div class="line">Denmark</div>
 <div class="line"><br /></div>
 <div class="line">Phone +45 3532 1464</div>
index 9db05b9d5d240e1b0c6fd079db369e9e93ef99b0..1f487fb1c661a732e8574c6d39b3b8f51172171f 100644 (file)
@@ -298,9 +298,9 @@ ul.auto-toc {
 <td>Miklos Maroti, Janos Sallai</td></tr>
 <tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">15-May-2008</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.0</td>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.1</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-05-15</td>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-06-17</td>
 </tr>
 <tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
 </tr>
index a94fdef102c69324eedea7f407433ef8c688f5d0..41c1f0758aa80df9cc13c7442ba205cdc80b7d5e 100644 (file)
@@ -298,9 +298,9 @@ ul.auto-toc {
 <td>Miklos Maroti, Janos Sallai</td></tr>
 <tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">15-May-2008</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.0</td>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.1</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-05-15</td>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-06-17</td>
 </tr>
 <tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
 </tr>
index 1abad852c6b28f9ab685a2d3f84aa72806822c43..558309072183e192d9fc02ae677a64458c1c55ff 100644 (file)
 /*
 :Author: David Goodger
 :Contact: goodger@users.sourceforge.net
-:Date: $Date$
-:Revision: $Revision$
-:Copyright: This stylesheet has been placed in the public domain.
+:date: $Date$
+:version: $Revision$
+:copyright: This stylesheet has been placed in the public domain.
 
 Default cascading style sheet for the HTML output of Docutils.
-
-See http://docutils.sf.net/docs/howto/html-stylesheets.html for how to
-customize this style sheet.
 */
-
-/* used to remove borders from tables and images */
-.borderless, table.borderless td, table.borderless th {
-  border: 0 }
-
-table.borderless td, table.borderless th {
-  /* Override padding for "table.docutils td" with "! important".
-     The right padding separates the table cells. */
-  padding: 0 0.5em 0 0 ! important }
+body {
+  font-family: Times;
+  font-size: 16px;
+}
 
 .first {
-  /* Override more specific margin styles with "! important". */
   margin-top: 0 ! important }
 
-.last, .with-subtitle {
+.last {
   margin-bottom: 0 ! important }
 
 .hidden {
@@ -47,14 +38,9 @@ a.toc-backref {
 blockquote.epigraph {
   margin: 2em 5em ; }
 
-dl.docutils dd {
+dd {
   margin-bottom: 0.5em }
 
-/* Uncomment (and remove this text!) to get bold-faced definition list terms
-dl.docutils dt {
-  font-weight: bold }
-*/
-
 div.abstract {
   margin: 2em 5em }
 
@@ -62,18 +48,12 @@ div.abstract p.topic-title {
   font-weight: bold ;
   text-align: center }
 
-div.admonition, div.attention, div.caution, div.danger, div.error,
-div.hint, div.important, div.note, div.tip, div.warning {
+div.attention, div.caution, div.danger, div.error, div.hint,
+div.important, div.note, div.tip, div.warning, div.admonition {
   margin: 2em ;
   border: medium outset ;
   padding: 1em }
 
-div.admonition p.admonition-title, div.hint p.admonition-title,
-div.important p.admonition-title, div.note p.admonition-title,
-div.tip p.admonition-title {
-  font-weight: bold ;
-  font-family: sans-serif }
-
 div.attention p.admonition-title, div.caution p.admonition-title,
 div.danger p.admonition-title, div.error p.admonition-title,
 div.warning p.admonition-title {
@@ -81,14 +61,11 @@ div.warning p.admonition-title {
   font-weight: bold ;
   font-family: sans-serif }
 
-/* Uncomment (and remove this text!) to get reduced vertical space in
-   compound paragraphs.
-div.compound .compound-first, div.compound .compound-middle {
-  margin-bottom: 0.5em }
-
-div.compound .compound-last, div.compound .compound-middle {
-  margin-top: 0.5em }
-*/
+div.hint p.admonition-title, div.important p.admonition-title,
+div.note p.admonition-title, div.tip p.admonition-title,
+div.admonition p.admonition-title {
+  font-weight: bold ;
+  font-family: sans-serif }
 
 div.dedication {
   margin: 2em 5em ;
@@ -100,11 +77,9 @@ div.dedication p.topic-title {
   font-style: normal }
 
 div.figure {
-  margin-left: 2em ;
-  margin-right: 2em }
+  margin-left: 2em }
 
 div.footer, div.header {
-  clear: both;
   font-size: smaller }
 
 div.line-block {
@@ -120,7 +95,7 @@ div.line-block div.line-block {
 div.sidebar {
   margin-left: 1em ;
   border: medium outset ;
-  padding: 1em ;
+  padding: 0em 1em ;
   background-color: #ffffee ;
   width: 40% ;
   float: right ;
@@ -147,24 +122,31 @@ div.system-message p.system-message-title {
 div.topic {
   margin: 2em }
 
-h1.section-subtitle, h2.section-subtitle, h3.section-subtitle,
-h4.section-subtitle, h5.section-subtitle, h6.section-subtitle {
-  margin-top: 0.4em }
+h1 {
+  font-family: Arial, sans-serif;
+  font-size: 20px;
+}
 
 h1.title {
-  text-align: center }
+ text-align: center;
+ font-size: 32px;
+}
+
+h2 {
+ font-size: 16px;
+ font-family: Arial, sans-serif;
+}
 
 h2.subtitle {
   text-align: center }
 
-hr.docutils {
-  width: 75% }
-
-img.align-left {
-  clear: left }
+h3 {
+ font-size: 12px;
+ font-family: Arial, sans-serif;
+}
 
-img.align-right {
-  clear: right }
+hr {
+  width: 75% }
 
 ol.simple, ul.simple {
   margin-bottom: 1em }
@@ -222,10 +204,18 @@ pre.address {
   font-family: serif ;
   font-size: 100% }
 
+pre.line-block {
+  font-family: serif ;
+  font-size: 100% }
+
 pre.literal-block, pre.doctest-block {
   margin-left: 2em ;
   margin-right: 2em ;
-  background-color: #eeeeee }
+  background-color: #eeeeee;
+  border-color: #000000;
+  border-width: thin; 
+  font-size: 14px
+}
 
 span.classifier {
   font-family: sans-serif ;
@@ -241,49 +231,46 @@ span.interpreted {
 span.option {
   white-space: nowrap }
 
+span.option-argument {
+  font-style: italic }
+
 span.pre {
   white-space: pre }
 
 span.problematic {
   color: red }
 
-span.section-subtitle {
-  /* font-size relative to parent (h1..h6 element) */
-  font-size: 80% }
+table {
+  margin-top: 0.5em ;
+  margin-bottom: 0.5em }
 
 table.citation {
-  border-left: solid 1px gray;
-  margin-left: 1px }
+  border-left: solid thin gray ;
+  padding-left: 0.5ex }
 
 table.docinfo {
-  margin: 2em 4em }
-
-table.docutils {
-  margin-top: 0.5em ;
-  margin-bottom: 0.5em }
+  margin: 2em 4em;
+}
 
 table.footnote {
-  border-left: solid 1px black;
-  margin-left: 1px }
+  border-left: solid thin black ;
+  padding-left: 0.5ex }
 
-table.docutils td, table.docutils th,
-table.docinfo td, table.docinfo th {
+td, th {
   padding-left: 0.5em ;
   padding-right: 0.5em ;
   vertical-align: top }
 
-table.docutils th.field-name, table.docinfo th.docinfo-name {
+th.docinfo-name, th.field-name {
   font-weight: bold ;
   text-align: left ;
-  white-space: nowrap ;
-  padding-left: 0 }
+  white-space: nowrap;
+  }
 
-h1 tt.docutils, h2 tt.docutils, h3 tt.docutils,
-h4 tt.docutils, h5 tt.docutils, h6 tt.docutils {
+h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
   font-size: 100% }
 
-tt.docutils {
-  background-color: #eeeeee }
+tt {}
 
 ul.auto-toc {
   list-style-type: none }
@@ -311,9 +298,9 @@ ul.auto-toc {
 <td>Kevin Klues, Chieh-Jan Liang, Jeongyeup Paek, Razvan Musaloiu-E, Ramesh Govindan, Andreas Terzis, Philip Levis</td></tr>
 <tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">13-May-2008</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.3</td>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.1</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-05-26</td>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-06-12</td>
 </tr>
 <tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
 </tr>
index 41f1192a5a3ecc357321a3b14e1e71bcaeacb129..a545dd48062896d3b2ca50533ac6bc8fa8eb8e6e 100644 (file)
@@ -288,7 +288,7 @@ ul.auto-toc {
 </tr>
 <tr class="field"><th class="docinfo-name">Group:</th><td class="field-body">Network Protocol Working Group</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Type:</th><td class="field-body">Documentary</td>
+<tr class="field"><th class="docinfo-name">Type:</th><td class="field-body">Informational</td>
 </tr>
 <tr><th class="docinfo-name">Status:</th>
 <td>Draft</td></tr>
@@ -298,9 +298,9 @@ ul.auto-toc {
 <td>Omprakash Gnawali</td></tr>
 <tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">19-June-2008</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.1</td>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.3</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-06-20</td>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-06-24</td>
 </tr>
 <tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
 </tr>
@@ -315,10 +315,13 @@ of this memo is unlimited. This memo is in full compliance with
 </div>
 <div class="section">
 <h1><a id="introduction" name="introduction">1. Introduction</a></h1>
-<p>In this TEP, we document the Active Message Type <a class="footnote-reference" href="#id4" id="id3" name="id3">[1]</a> allocations
-in TinyOS 2.1.</p>
+<p>TinyOS network protocols use allocated Active Message Type <a class="citation-reference" href="#tep-116" id="id3" name="id3">[TEP_116]</a>
+to prevent AM ID conflict between different protocols. <a class="citation-reference" href="#tep-4" id="id4" name="id4">[TEP_4]</a>
+describes how AM IDs are allocated for a TinyOS network protocol. In
+this TEP, we document the AM ID allocations in TinyOS 2.1.</p>
+</div>
 <div class="section">
-<h2><a id="unreserved-pool-0x80-0xff" name="unreserved-pool-0x80-0xff">2. Unreserved pool (0x80 - 0xFF)</a></h2>
+<h1><a id="unreserved-pool-128-255-0x80-0xff" name="unreserved-pool-128-255-0x80-0xff">2. Unreserved pool 128-255 (0x80 - 0xFF)</a></h1>
 <p>The unreserved pool is in the range 128-255 (0x80-0xFF). Applications
 distributed with TinyOS use AM IDs in this range. Protocols and
 applications in contrib as well as those developed by the community
@@ -326,41 +329,50 @@ but not included in the distribution or contrib SHOULD use AM IDs in
 this range.</p>
 </div>
 <div class="section">
-<h2><a id="reserved-pool-0x00-0x7f" name="reserved-pool-0x00-0x7f">3. Reserved pool (0x00 - 0x7F)</a></h2>
+<h1><a id="reserved-pool-0-127-0x00-0x7f" name="reserved-pool-0-127-0x00-0x7f">3. Reserved pool 0-127 (0x00 - 0x7F)</a></h1>
 <p>The reserved pool is in the range 0-127 (0x00-0x7F). The AM IDs in
 this range are used by protocols distributed with TinyOS.</p>
 <p>Here is a list of allocations for TinyOS 2.1:</p>
 <pre class="literal-block">
-* 0x70 - 0x7F are reserved for collection protocols maintained by
-  the Network Protocol Working Group.
+* 0x70 - 0x75 are reserved for collection protocols [TEP_119]_
+  maintained by the Network Protocol Working Group.
 
-  0x70 - CTP routing beacon and LEEP (''tos/lib/net/ctp'', TEP 119, 123, and 124)
-  0x71 - CTP data packets (''tos/lib/net/ctp'', TEP 119, 123)
-  0x72 - CTP debug messages (''tos/lib/net/ctp'')
-  0x73 - MultiHopLQI routing beacon (''tos/lib/net/lqi'')
-  0x74 - MultiHopLQI data packets (''tos/lib/net/lqi'')
-  0x75 - MultiHopLQI debug messages (''tos/lib/net/lqi'')
+  For CTP (''tos/lib/net/ctp'') [TEP_123]_ and LEEP  [TEP_124]_
+  0x70 - AM_CTP_ROUTING CTP (Routing beacon)
+  0x71 - AM_CTP_DATA CTP (Data packets)
+  0x72 - AM_CTP_DEBUG CTP (Debug messages)
 
-* 0x60 - 0x6F are reserved for dissemination protocols maintained by
-  the Network Protocol Working Group.
+  For MultiHopLQI (''tos/lib/net/lqi'')
+  0x73 - AM_LQI_BEACON_MSG (Routing beacon)
+  0x74 - AM_LQI_DATA_MSG MultiHopLQI (Data packets)
+  0x75 - AM_LQI_DEBUG MultiHopLQI (Debug messages)
+
+* 0x60 - 0x62 are reserved for dissemination protocols [TEP_118]_
+  maintained by the Network Protocol Working Group.
 
-  0x60 - Drip (''tos/lib/net/drip'', TEP 118)
-  0x61 - DIP (''tos/lib/net/dip'', TEP 118)
+  For Drip (''tos/lib/net/drip'')
+  0x60 - AM_DISSEMINATION_MESSAGE
+  0x61 - AM_DISSEMINATION_PROBE_MESSAGE
 
-* 0x50 - 0x5F are reserved for Deluge (''tos/lib/net/Deluge'')
+  For DIP (''tos/lib/net/dip'')
+  0x62 - AM_DIP
+
+* 0x50 - 0x54 are reserved for Deluge (''tos/lib/net/Deluge'')
   maintained by the Network Protocol Working Group.
 
-  0x50 - AM_DELUGEADVMSG (advertisements)
-  0x51 - AM_DELUGEREQMSG (requests)
-  0x52 - AM_DELUGEDATAMSG (data)
-  0x53 - DELUGE_AM_FLASH_VOL_MANAGER (flash volume manager)
-  0x54 - DELUGE_AM_DELUGE_MANAGER (deluge manger)
+  0x50 - AM_DELUGEADVMSG (Advertisements)
+  0x51 - AM_DELUGEREQMSG (Requests)
+  0x52 - AM_DELUGEDATAMSG (Data)
+  0x53 - DELUGE_AM_FLASH_VOL_MANAGER (Flash volume manager)
+  0x54 - DELUGE_AM_DELUGE_MANAGER (Deluge manger)
+
+* 0x3E - AM_TIMESYNCMSG for FTSP (''tos/lib/ftsp'') reserved by the
+  Core Working Group.
 
-* 0x3F - TinyOS NALP code (TEP 125) reserved by the Core Working
+* 0x3F - TinyOS NALP code [TEP_125]_ reserved by the Core Working
   Group.
 </pre>
 </div>
-</div>
 <div class="section">
 <h1><a id="author-s-address" name="author-s-address">4. Author's Address</a></h1>
 <div class="line-block">
@@ -384,13 +396,43 @@ this range are used by protocols distributed with TinyOS.</p>
 <table class="docutils citation" frame="void" id="tep-4" rules="none">
 <colgroup><col class="label" /><col /></colgroup>
 <tbody valign="top">
-<tr><td class="label"><a class="fn-backref" href="#id2" name="tep-4">[TEP_4]</a></td><td>TEP 4: Active Message ID Allocation for Network Protocols and Applications</td></tr>
+<tr><td class="label"><a name="tep-4">[TEP_4]</a></td><td><em>(<a class="fn-backref" href="#id2">1</a>, <a class="fn-backref" href="#id4">2</a>)</em> TEP 4: Active Message ID Allocation for Network Protocols and Applications</td></tr>
+</tbody>
+</table>
+<table class="docutils citation" frame="void" id="tep-116" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a class="fn-backref" href="#id3" name="tep-116">[TEP_116]</a></td><td>TEP 116: Packet Protocols</td></tr>
+</tbody>
+</table>
+<table class="docutils citation" frame="void" id="tep-118" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a name="tep-118">[TEP_118]</a></td><td>TEP 118: Dissemination of Small Values</td></tr>
+</tbody>
+</table>
+<table class="docutils citation" frame="void" id="tep-119" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a name="tep-119">[TEP_119]</a></td><td>TEP 119: Collection</td></tr>
+</tbody>
+</table>
+<table class="docutils citation" frame="void" id="tep-123" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a name="tep-123">[TEP_123]</a></td><td>TEP 123: The Collection Tree Protocol (CTP)</td></tr>
+</tbody>
+</table>
+<table class="docutils citation" frame="void" id="tep-124" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a name="tep-124">[TEP_124]</a></td><td>TEP 124: The Link Estimation Exchange Protocol (LEEP)</td></tr>
 </tbody>
 </table>
-<table class="docutils footnote" frame="void" id="id4" rules="none">
+<table class="docutils citation" frame="void" id="tep-125" rules="none">
 <colgroup><col class="label" /><col /></colgroup>
 <tbody valign="top">
-<tr><td class="label"><a class="fn-backref" href="#id3" name="id4">[1]</a></td><td>TEP 116: Packet Protocols</td></tr>
+<tr><td class="label"><a name="tep-125">[TEP_125]</a></td><td>TEP 125: TinyOS 802.15.4 Frames</td></tr>
 </tbody>
 </table>
 </div>
diff --git a/doc/html/tep136.html b/doc/html/tep136.html
new file mode 100644 (file)
index 0000000..022ffdc
--- /dev/null
@@ -0,0 +1,558 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta name="generator" content="Docutils 0.6: http://docutils.sourceforge.net/" />
+<title>Roadmap to an IP Stack in TinyOS</title>
+<meta name="author" content="Stephen Dawson-Haggerty, Matus Harvan, and Omprakash Gnawali" />
+<style type="text/css">
+
+/*
+:Author: David Goodger
+:Contact: goodger@users.sourceforge.net
+:date: $Date$
+:version: $Revision$
+:copyright: This stylesheet has been placed in the public domain.
+
+Default cascading style sheet for the HTML output of Docutils.
+*/
+body {
+  font-family: Times;
+  font-size: 16px;
+}
+
+.first {
+  margin-top: 0 ! important }
+
+.last {
+  margin-bottom: 0 ! important }
+
+.hidden {
+  display: none }
+
+a.toc-backref {
+  text-decoration: none ;
+  color: black }
+
+blockquote.epigraph {
+  margin: 2em 5em ; }
+
+dd {
+  margin-bottom: 0.5em }
+
+div.abstract {
+  margin: 2em 5em }
+
+div.abstract p.topic-title {
+  font-weight: bold ;
+  text-align: center }
+
+div.attention, div.caution, div.danger, div.error, div.hint,
+div.important, div.note, div.tip, div.warning, div.admonition {
+  margin: 2em ;
+  border: medium outset ;
+  padding: 1em }
+
+div.attention p.admonition-title, div.caution p.admonition-title,
+div.danger p.admonition-title, div.error p.admonition-title,
+div.warning p.admonition-title {
+  color: red ;
+  font-weight: bold ;
+  font-family: sans-serif }
+
+div.hint p.admonition-title, div.important p.admonition-title,
+div.note p.admonition-title, div.tip p.admonition-title,
+div.admonition p.admonition-title {
+  font-weight: bold ;
+  font-family: sans-serif }
+
+div.dedication {
+  margin: 2em 5em ;
+  text-align: center ;
+  font-style: italic }
+
+div.dedication p.topic-title {
+  font-weight: bold ;
+  font-style: normal }
+
+div.figure {
+  margin-left: 2em }
+
+div.footer, div.header {
+  font-size: smaller }
+
+div.line-block {
+  display: block ;
+  margin-top: 1em ;
+  margin-bottom: 1em }
+
+div.line-block div.line-block {
+  margin-top: 0 ;
+  margin-bottom: 0 ;
+  margin-left: 1.5em }
+
+div.sidebar {
+  margin-left: 1em ;
+  border: medium outset ;
+  padding: 0em 1em ;
+  background-color: #ffffee ;
+  width: 40% ;
+  float: right ;
+  clear: right }
+
+div.sidebar p.rubric {
+  font-family: sans-serif ;
+  font-size: medium }
+
+div.system-messages {
+  margin: 5em }
+
+div.system-messages h1 {
+  color: red }
+
+div.system-message {
+  border: medium outset ;
+  padding: 1em }
+
+div.system-message p.system-message-title {
+  color: red ;
+  font-weight: bold }
+
+div.topic {
+  margin: 2em }
+
+h1 {
+  font-family: Arial, sans-serif;
+  font-size: 20px;
+}
+
+h1.title {
+ text-align: center;
+ font-size: 32px;
+}
+
+h2 {
+ font-size: 16px;
+ font-family: Arial, sans-serif;
+}
+
+h2.subtitle {
+  text-align: center }
+
+h3 {
+ font-size: 12px;
+ font-family: Arial, sans-serif;
+}
+
+hr {
+  width: 75% }
+
+ol.simple, ul.simple {
+  margin-bottom: 1em }
+
+ol.arabic {
+  list-style: decimal }
+
+ol.loweralpha {
+  list-style: lower-alpha }
+
+ol.upperalpha {
+  list-style: upper-alpha }
+
+ol.lowerroman {
+  list-style: lower-roman }
+
+ol.upperroman {
+  list-style: upper-roman }
+
+p.attribution {
+  text-align: right ;
+  margin-left: 50% }
+
+p.caption {
+  font-style: italic }
+
+p.credits {
+  font-style: italic ;
+  font-size: smaller }
+
+p.label {
+  white-space: nowrap }
+
+p.rubric {
+  font-weight: bold ;
+  font-size: larger ;
+  color: maroon ;
+  text-align: center }
+
+p.sidebar-title {
+  font-family: sans-serif ;
+  font-weight: bold ;
+  font-size: larger }
+
+p.sidebar-subtitle {
+  font-family: sans-serif ;
+  font-weight: bold }
+
+p.topic-title {
+  font-weight: bold }
+
+pre.address {
+  margin-bottom: 0 ;
+  margin-top: 0 ;
+  font-family: serif ;
+  font-size: 100% }
+
+pre.line-block {
+  font-family: serif ;
+  font-size: 100% }
+
+pre.literal-block, pre.doctest-block {
+  margin-left: 2em ;
+  margin-right: 2em ;
+  background-color: #eeeeee;
+  border-color: #000000;
+  border-width: thin; 
+  font-size: 14px
+}
+
+span.classifier {
+  font-family: sans-serif ;
+  font-style: oblique }
+
+span.classifier-delimiter {
+  font-family: sans-serif ;
+  font-weight: bold }
+
+span.interpreted {
+  font-family: sans-serif }
+
+span.option {
+  white-space: nowrap }
+
+span.option-argument {
+  font-style: italic }
+
+span.pre {
+  white-space: pre }
+
+span.problematic {
+  color: red }
+
+table {
+  margin-top: 0.5em ;
+  margin-bottom: 0.5em }
+
+table.citation {
+  border-left: solid thin gray ;
+  padding-left: 0.5ex }
+
+table.docinfo {
+  margin: 2em 4em;
+}
+
+table.footnote {
+  border-left: solid thin black ;
+  padding-left: 0.5ex }
+
+td, th {
+  padding-left: 0.5em ;
+  padding-right: 0.5em ;
+  vertical-align: top }
+
+th.docinfo-name, th.field-name {
+  font-weight: bold ;
+  text-align: left ;
+  white-space: nowrap;
+  }
+
+h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
+  font-size: 100% }
+
+tt {}
+
+ul.auto-toc {
+  list-style-type: none }
+
+</style>
+</head>
+<body>
+<div class="document" id="roadmap-to-an-ip-stack-in-tinyos">
+<h1 class="title">Roadmap to an IP Stack in TinyOS</h1>
+<table class="docinfo" frame="void" rules="none">
+<col class="docinfo-name" />
+<col class="docinfo-content" />
+<tbody valign="top">
+<tr class="field"><th class="docinfo-name">TEP:</th><td class="field-body">136</td>
+</tr>
+<tr class="field"><th class="docinfo-name">Group:</th><td class="field-body">Network Protocol Working Group</td>
+</tr>
+<tr class="field"><th class="docinfo-name">Type:</th><td class="field-body">Informational</td>
+</tr>
+<tr><th class="docinfo-name">Status:</th>
+<td>Draft</td></tr>
+<tr class="field"><th class="docinfo-name">TinyOS-Version:</th><td class="field-body">&gt; 2.1</td>
+</tr>
+<tr><th class="docinfo-name">Author:</th>
+<td>Stephen Dawson-Haggerty, Matus Harvan, and Omprakash Gnawali</td></tr>
+</tbody>
+</table>
+<div class="section" id="abstract">
+<h1>Abstract</h1>
+<p>Recently, there has been renewed interest in the applicability of Internet
+Protocol-based networking for low power, embedded devices.  This interest is
+being driven by several sources.  One, emerging standards from the IETF are
+beginning to make it possible to design efficient, compatible
+implementations of IP for this class of resource-constrained device.  Two,
+there has been an emergence of a significant number of both open and closed IP
+embedded IP stacks which demonstrate the applicability of this model of
+networking.  Third, a set of recent academic papers have made the case that
+this network architecture is a significant research enabler and shown in more
+detail the structure of a full stack.</p>
+<p>In this TEP, we briefly explain how IP mechanisms map onto the well-studied
+problems of the sensor network community like collection routing and local
+aggregation.  Next, we discuss the current &quot;state of the standards.&quot;  Finally,
+we propose a path for the adoption of IP within TinyOS.</p>
+</div>
+<div class="section" id="ip-requirements-and-mechanisms">
+<h1>1. IP Requirements and Mechanisms</h1>
+<p>There are two versions of IP: IPv4 (RFCXXX) and IPv6 (RFCXXX).  Previous
+studies have indicated that IPv6 is more applicable to the low-power, embedded
+space then IPv4 for various reasons; most standardization efforts have focused
+on adapting IPv6 to these devices.  Therefore, we consider only IPv6.</p>
+<div class="section" id="ipv6-routing">
+<h2>1.1 IPv6 Routing</h2>
+<p>A central question for implementing IPv6 in sensor networks is what has become
+know as &quot;route over&quot; vs. &quot;mesh under&quot; in the IETF.  In mesh under networking,
+routing is done on layer two addresses, and every host is one hop from every
+other.  Although this is the most compatible with existing assumptions about
+subnet design, it leads to significant redundancies and inefficiencies in this
+space.  The alternative, so called route-over exposes the radio topology at
+the IP layer.  While not strictly compatible with some IPv6 mechanisms, this
+is becomming the favored approach since a single set of tools can be used to
+debug.  For the rest of this TEP we assume that route over is the model.</p>
+<p>There are a number of existing routing protocols for IPv6, some targeted at
+wireless links.  However, IPv6 itself does not require any particular routing
+protocol to be used with a domain; common choices in wired networks are OSPF
+and IS-IS.  Recent study in the IETF has indicated that existing protocols are
+probably not appropriate for this space [draft-ietf-roll-protocols-02], and so
+further work is needed on this point.  Existing protocols with TinyOS
+implementations such as DYMO or S4 may be appropriate for this task;
+collection and dissemination protocols like CTP or Drip are probably not
+directly applicable since they are address-free, although the insight gained
+from their implementations may be transferable.</p>
+</div>
+<div class="section" id="addressing">
+<h2>1.2 Addressing</h2>
+<p>The most well-known property of IPv6 is probably it's address length.  An IPv6
+address is 128 bits long.  Within this space, IPv6 defines unicast, anycast,
+and multicast address ranges; each of these ranges further have properties of
+their own.  For a full explaination of IPv6 addressing we refer the reader to,
+for example, [OReilly, RFC], we cover briefly some of the important details.</p>
+<div class="section" id="unicast-addressing">
+<h3>1.2.1 Unicast Addressing</h3>
+<p>Unicast addresses in IPv6 consist of two parts: the network identifier (the
+first 64 bits), and the interface identifier (the second).  The interface
+identifier is a flat space, and may be derived from the interface's MAC
+address, a random number, or other mechanism.  IPv6 contains mechanisms to
+ensure that the interface ID is unique within the subnet.  The network
+may be assigned using many different mechanisms, but some network identifiers
+are special.</p>
+<p>Unlike IPv4, each interface in IPv6 is multihomed: it is expected to have
+multiple IPv6 addresses.  When an interface is brought up, IPv6 contains
+mechanisms to configure the interface with a locally unique, non-routable
+address known as the link-local address.  This address has the network
+identifier fe80::, and can be used for communication between hosts in the same
+subnet.</p>
+<p>In a TinyOS IPv6 stack, this address range might be used to allow TinyOS nodes
+to communicate locally without routing, for instance to enable local
+aggregation.  If the TinyOS hosts can assign themselves link-local addresses
+derived from their IEEE802.15.4 16-bit short id, or full 64-bit EUID.  For
+instance, a node with short ID 16 might assign the address fe80::10 to its
+802.15.4 interface.  These addresses would not be routed; an IP stack would
+send directly to the short id 0x10 contained in the address.</p>
+<p>IPv6 also contains several mechanisms to allow a host to obtain a
+publicly-routable network identifier.  TinyOS hosts communicating with these
+addresses could contact nodes in other sensor networks or on the internet; the
+fact that they are multihomed allows them to use both public and link-local
+addresses simultaneously.</p>
+</div>
+<div class="section" id="multicast-addressing">
+<h3>1.2.2 Multicast Addressing</h3>
+<p>IPv6 contains a multicast address range; addresses beginning with the byte
+containing all ones (0xff) are multicast addresses.  Following this byte are
+four bits of flags and four bits of &quot;scope&quot;.  For instance, scope 1 is
+node-local, and scope 2 is link local.  IPv6 defines many well-known multicast
+groups [<a class="reference external" href="http://www.iana.org/assignments/ipv6-multicast-addresses">http://www.iana.org/assignments/ipv6-multicast-addresses</a>]; of most interest here are the &quot;link-local all nodes&quot; and &quot;link
+local all-routers&quot; addresses: ff02::1 and ff02::2, respectively.  Depending on
+weather TinyOS IP hosts are also IP routers, these addresses are effecitvely
+link-local broadcast addresses which might be mapped into the layer 2
+broadcast address (0xffff).  Thus IPv6 contains mechanisms for local
+broadcast.</p>
+<p>There is also a site-local scope defined in IPv6 (5) with a similar ff05::2
+address.  &quot;Site local&quot; is an administratively defined scope in IPv6, and might
+naturally consist of an entire sensor network.  Thus, sending to this address
+would correspond to disseminating a value to each node in the network and
+could be implemented with a trickle-based algorithm.</p>
+<p>Futhermore, the TinyOS community could develop additional conventions to
+provide and address for scoped flooding or delivery to nodes with particular
+capabilities.  A full IP multicast implementation within the sensor network
+could be used for many things including control applications or
+publish-subscribe network layers which have previously been special purpose.</p>
+</div>
+<div class="section" id="anycast-addressing">
+<h3>1.2.3 Anycast Addressing</h3>
+<p>Anycast addresses indicate that the packet should be delivered to at least one
+host with the anycast address.  This seems initially similar to the model for
+collection routing such as MultiHopLQI or CTP, in that a collection report is
+delivered to a single root.  However, it is more likeley that those
+&quot;collection roots&quot; in an IP-based infrastructure are not actually the final
+destination for the data; they are likely to only be intermediate routers who
+send the data on to a final destination.  Therefore, while there may be
+applications for anycast addressing, we do not believe this addressing mode to
+be appropriate in the common case.</p>
+</div>
+</div>
+<div class="section" id="ipv6-configuration-mechanisms">
+<h2>1.3 IPv6 Configuration Mechanisms</h2>
+<p>As alluded to earlier, IPv6 contains two mechanisms to allow internet hosts to
+become associated with a public network identifier.  These methods are
+stateless autoconfiguration and DHCPv6.  Stateless autoconfiguration defines
+Router Solicitations and Router Advertisements.  A host joining a network
+sends router solicitations to the link-local all-routers address (ff02::2)
+using his link-local address as the source address.  Routers respond with a
+Router Advertisement containing, among other things, a public network
+identifier which the host may use.</p>
+<p>In a TinyOS IP implementation, router solicitations and advertisements might
+be used for default route selection on the hosts, as well as neighbor
+discovery.</p>
+</div>
+<div class="section" id="extension-mechanisms">
+<h2>1.4 Extension Mechanisms</h2>
+<p>A common idiom in TinyOS is to provide &quot;stacked&quot; headers by implementing a
+series of components, all of which implement the Packet interface.  IPv6
+supports this a more flexible way with options headers.  These headers fall
+into one of two categories: hop-by-hop options headers and destination option
+headers.  These headers are chained together with small, two-octet common
+header fields which identifiy the header type of the next header, and the
+length of that options header.  This allows hosts to process a header chain
+even if they do not know how to interpret all of the options headers.</p>
+<p>These headers are commonly used for protocol options, or to piggyback data on
+outgoing packets.  For instance, a link estimator component could add an extra
+&quot;link options&quot; header to occasional outgoing packets as an options header,
+while avoiding the overhead when it is not necessary to do so.  This header
+architecture is significantly more flexible then the existing TinyOS packet
+architecture, although it does come at the slight cost of complexity.</p>
+</div>
+</div>
+<div class="section" id="the-state-of-the-standards">
+<h1>2. The State of the Standards</h1>
+<p>All of the previously defined mechanisms are well defined for IPv6 in various
+RFCs.  However, most nodes running TinyOS are significantly more
+resource-constrained then typical IPv6 hosts.  Thus, there is ongoing work on
+adapting these mechanisms to the characteristics of embedded devices.</p>
+<div class="section" id="header-compression">
+<h2>2.1 Header Compression</h2>
+<p>The first issue which must be addressed is the sheer size of the IPv6 header:
+40 octets.  Of this, 32 octets are the source and destination addresses of the
+packet.  The IETF has published RFC4944 which describes a header compression
+technique known as HC1.  However, this scheme has significant problems, most
+importantly the inability to take advantage of 16-bit short identifiers when
+available.  There have been a sequence of internet drafts proposing improved
+techinques such as HC1g, and HC.  The most recent version of these drafts is
+draft-hui-6lowpan-hc-02, and there are strong indications that the working
+group will depreciate HC1 from RFC4944 in the future.</p>
+</div>
+<div class="section" id="mtu">
+<h2>2.2 MTU</h2>
+<p>IPv6 requires a minimum link MTU of 1280 octets in RFCXXX.  Clearly, this is
+much larger then the IEEE802.15.4 link MTU of 127 octets.  RFC4944 defines
+&quot;layer 2.5&quot; fragmentation which allow packets up to this MTU to be transfered
+over small MTU links.  While there are some issues have been raised with this
+scheme, it seems likely to remain relatively unaltered.</p>
+</div>
+<div class="section" id="autoconfiguration">
+<h2>2.3 Autoconfiguration</h2>
+<p>IPv6 stateless autoconfiguration as originally defined has some problems,
+expecially once a &quot;route over&quot; network topology is established; for instance,
+Duplicate Address Detection is likely to require some changes.  A subcomittee
+of the 6lowpan working group is currently investigating these issues is is
+likely to propose adaptation mechanisms but they are currently in flux.</p>
+</div>
+<div class="section" id="routing">
+<h2>2.4 Routing</h2>
+<p>It is currently not possible to develop a standards-compliant routing layer,
+as the relevant standards do not exist.  Work in this direction is occuring in
+the Roll working group, but a full specification is likely some way off.</p>
+</div>
+</div>
+<div class="section" id="the-tinyos-way">
+<h1>3. The TinyOS Way</h1>
+<p>As the previous sections have shown, many sensor network abstractions map well
+into IPv6 mechanisms, with a significant gain in clarity of abstraction.
+However, standards are currently unavailable to specifiy exactly how this
+should be accomplished.  Therefor, our position is that TinyOS should move
+quickly to incorporate existing techinques and standards into an IPv6 stack
+where possible, while taking liberties with the standards when doing so
+improves performance or simplifies implementation.  Given that the standards
+themselves are in a state of flux, having an open implementation which
+demonstrates challenges and feasible mechaninisms is likely to be of
+significant value.</p>
+<p>The most important places where it may be necessary to move ahead of the
+standards are the routing; an IPv6 stack with no routing will not be as useful
+as one with it.  One open question is weather we choose a routing algorithm
+which functions in a completly decentralized fashion like AODV, OLSR, DYMO,
+S4, or many existing protocols or choose one which imposes more hierarchy on
+deployments.  We do note that existing standards like Zigbee and WirelessHART
+both contain multi-tier architectures with devices of differing capabilities.
+This has also been a common deployment model in many applications, but it
+limits the utility to places where this is possible.  The correct long-term
+answer is probably to support both types of routing.</p>
+</div>
+<div class="section" id="conclusion">
+<h1>4. Conclusion</h1>
+<p>This document is meant to introduce readers to the ways in which IPv6
+mechanisms can be used in a TinyOS-based sensor network deployment, and how
+they relate to previous work.  It does not address any implementation issues,
+which will be presented in a later TEP.</p>
+</div>
+<div class="section" id="authors">
+<h1>5. Authors</h1>
+<div class="line-block">
+<div class="line">Stephen Dawson-Haggerty</div>
+<div class="line">Computer Science Division</div>
+<div class="line">University of California, Berkeley</div>
+<div class="line">410 Soda Hall</div>
+<div class="line">Berkeley, CA 94701</div>
+<div class="line"><br /></div>
+<div class="line"><a class="reference external" href="mailto:stevedh&#64;eecs.berkeley.edu">stevedh&#64;eecs.berkeley.edu</a></div>
+<div class="line"><br /></div>
+<div class="line"><br /></div>
+<div class="line">Matus Harvan</div>
+<div class="line">Information Security</div>
+<div class="line">IFW C 48.1</div>
+<div class="line">ETH Zentrum</div>
+<div class="line">Haldeneggsteig 4</div>
+<div class="line">8092 Zurich</div>
+<div class="line">Switzerland</div>
+<div class="line"><br /></div>
+<div class="line">phone - +41 44 63 26876</div>
+<div class="line">email - <a class="reference external" href="mailto:mharvan&#64;inf.ethz.ch">mharvan&#64;inf.ethz.ch</a></div>
+<div class="line"><br /></div>
+<div class="line"><br /></div>
+<div class="line">Omprakash Gnawali</div>
+<div class="line">Ronald Tutor Hall (RTH) 418</div>
+<div class="line">3710 S. McClintock Avenue</div>
+<div class="line">Los Angeles, CA 90089</div>
+<div class="line"><br /></div>
+<div class="line">phone - +1 213 821-5627</div>
+<div class="line">email - <a class="reference external" href="mailto:gnawali&#64;usc.edu">gnawali&#64;usc.edu</a></div>
+</div>
+</div>
+<div class="section" id="references">
+<h1>6. References</h1>
+</div>
+</div>
+</body>
+</html>
diff --git a/doc/html/tep137.html b/doc/html/tep137.html
new file mode 100644 (file)
index 0000000..fd53e01
--- /dev/null
@@ -0,0 +1,563 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<meta name="generator" content="Docutils 0.6: http://docutils.sourceforge.net/" />
+<title>Traffic Control</title>
+<meta name="author" content="David Moss, Mark Hays, and Mark Siner" />
+<style type="text/css">
+
+/*
+:Author: David Goodger
+:Contact: goodger@users.sourceforge.net
+:date: $Date$
+:version: $Revision$
+:copyright: This stylesheet has been placed in the public domain.
+
+Default cascading style sheet for the HTML output of Docutils.
+*/
+body {
+  font-family: Times;
+  font-size: 16px;
+}
+
+.first {
+  margin-top: 0 ! important }
+
+.last {
+  margin-bottom: 0 ! important }
+
+.hidden {
+  display: none }
+
+a.toc-backref {
+  text-decoration: none ;
+  color: black }
+
+blockquote.epigraph {
+  margin: 2em 5em ; }
+
+dd {
+  margin-bottom: 0.5em }
+
+div.abstract {
+  margin: 2em 5em }
+
+div.abstract p.topic-title {
+  font-weight: bold ;
+  text-align: center }
+
+div.attention, div.caution, div.danger, div.error, div.hint,
+div.important, div.note, div.tip, div.warning, div.admonition {
+  margin: 2em ;
+  border: medium outset ;
+  padding: 1em }
+
+div.attention p.admonition-title, div.caution p.admonition-title,
+div.danger p.admonition-title, div.error p.admonition-title,
+div.warning p.admonition-title {
+  color: red ;
+  font-weight: bold ;
+  font-family: sans-serif }
+
+div.hint p.admonition-title, div.important p.admonition-title,
+div.note p.admonition-title, div.tip p.admonition-title,
+div.admonition p.admonition-title {
+  font-weight: bold ;
+  font-family: sans-serif }
+
+div.dedication {
+  margin: 2em 5em ;
+  text-align: center ;
+  font-style: italic }
+
+div.dedication p.topic-title {
+  font-weight: bold ;
+  font-style: normal }
+
+div.figure {
+  margin-left: 2em }
+
+div.footer, div.header {
+  font-size: smaller }
+
+div.line-block {
+  display: block ;
+  margin-top: 1em ;
+  margin-bottom: 1em }
+
+div.line-block div.line-block {
+  margin-top: 0 ;
+  margin-bottom: 0 ;
+  margin-left: 1.5em }
+
+div.sidebar {
+  margin-left: 1em ;
+  border: medium outset ;
+  padding: 0em 1em ;
+  background-color: #ffffee ;
+  width: 40% ;
+  float: right ;
+  clear: right }
+
+div.sidebar p.rubric {
+  font-family: sans-serif ;
+  font-size: medium }
+
+div.system-messages {
+  margin: 5em }
+
+div.system-messages h1 {
+  color: red }
+
+div.system-message {
+  border: medium outset ;
+  padding: 1em }
+
+div.system-message p.system-message-title {
+  color: red ;
+  font-weight: bold }
+
+div.topic {
+  margin: 2em }
+
+h1 {
+  font-family: Arial, sans-serif;
+  font-size: 20px;
+}
+
+h1.title {
+ text-align: center;
+ font-size: 32px;
+}
+
+h2 {
+ font-size: 16px;
+ font-family: Arial, sans-serif;
+}
+
+h2.subtitle {
+  text-align: center }
+
+h3 {
+ font-size: 12px;
+ font-family: Arial, sans-serif;
+}
+
+hr {
+  width: 75% }
+
+ol.simple, ul.simple {
+  margin-bottom: 1em }
+
+ol.arabic {
+  list-style: decimal }
+
+ol.loweralpha {
+  list-style: lower-alpha }
+
+ol.upperalpha {
+  list-style: upper-alpha }
+
+ol.lowerroman {
+  list-style: lower-roman }
+
+ol.upperroman {
+  list-style: upper-roman }
+
+p.attribution {
+  text-align: right ;
+  margin-left: 50% }
+
+p.caption {
+  font-style: italic }
+
+p.credits {
+  font-style: italic ;
+  font-size: smaller }
+
+p.label {
+  white-space: nowrap }
+
+p.rubric {
+  font-weight: bold ;
+  font-size: larger ;
+  color: maroon ;
+  text-align: center }
+
+p.sidebar-title {
+  font-family: sans-serif ;
+  font-weight: bold ;
+  font-size: larger }
+
+p.sidebar-subtitle {
+  font-family: sans-serif ;
+  font-weight: bold }
+
+p.topic-title {
+  font-weight: bold }
+
+pre.address {
+  margin-bottom: 0 ;
+  margin-top: 0 ;
+  font-family: serif ;
+  font-size: 100% }
+
+pre.line-block {
+  font-family: serif ;
+  font-size: 100% }
+
+pre.literal-block, pre.doctest-block {
+  margin-left: 2em ;
+  margin-right: 2em ;
+  background-color: #eeeeee;
+  border-color: #000000;
+  border-width: thin; 
+  font-size: 14px
+}
+
+span.classifier {
+  font-family: sans-serif ;
+  font-style: oblique }
+
+span.classifier-delimiter {
+  font-family: sans-serif ;
+  font-weight: bold }
+
+span.interpreted {
+  font-family: sans-serif }
+
+span.option {
+  white-space: nowrap }
+
+span.option-argument {
+  font-style: italic }
+
+span.pre {
+  white-space: pre }
+
+span.problematic {
+  color: red }
+
+table {
+  margin-top: 0.5em ;
+  margin-bottom: 0.5em }
+
+table.citation {
+  border-left: solid thin gray ;
+  padding-left: 0.5ex }
+
+table.docinfo {
+  margin: 2em 4em;
+}
+
+table.footnote {
+  border-left: solid thin black ;
+  padding-left: 0.5ex }
+
+td, th {
+  padding-left: 0.5em ;
+  padding-right: 0.5em ;
+  vertical-align: top }
+
+th.docinfo-name, th.field-name {
+  font-weight: bold ;
+  text-align: left ;
+  white-space: nowrap;
+  }
+
+h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
+  font-size: 100% }
+
+tt {}
+
+ul.auto-toc {
+  list-style-type: none }
+
+</style>
+</head>
+<body>
+<div class="document" id="traffic-control">
+<h1 class="title">Traffic Control</h1>
+<table class="docinfo" frame="void" rules="none">
+<col class="docinfo-name" />
+<col class="docinfo-content" />
+<tbody valign="top">
+<tr class="field"><th class="docinfo-name">TEP:</th><td class="field-body">137</td>
+</tr>
+<tr class="field"><th class="docinfo-name">Group:</th><td class="field-body">Core Working Group</td>
+</tr>
+<tr class="field"><th class="docinfo-name">Type:</th><td class="field-body">Documentary</td>
+</tr>
+<tr><th class="docinfo-name">Status:</th>
+<td>Draft</td></tr>
+<tr class="field"><th class="docinfo-name">TinyOS-Version:</th><td class="field-body">2.x</td>
+</tr>
+<tr><th class="docinfo-name">Author:</th>
+<td>David Moss, Mark Hays, and Mark Siner</td></tr>
+<tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">3-Sept-2009</td>
+</tr>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.0</td>
+</tr>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2009-09-30</td>
+</tr>
+<tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
+</tr>
+</tbody>
+</table>
+<div class="note">
+<p class="first admonition-title">Note</p>
+<p class="last">This memo documents a part of TinyOS for the TinyOS Community, and
+requests discussion and suggestions for improvements.  Distribution
+of this memo is unlimited. This memo is in full compliance with
+TEP 1.</p>
+</div>
+<div class="section" id="abstract">
+<h1>Abstract</h1>
+<p>This memo proposes traffic control interfaces to be provided by an optional
+traffic control layer integrated at the highest levels of communication
+stacks. These traffic control mechanisms are targeted to help improve acknowledgment
+success rate, energy efficiency, fairness, and routing reliability on
+any wireless platform. The available reference implementation is a platform
+independent radio stack layer designed to consume a very small memory footprint.</p>
+</div>
+<div class="section" id="introduction">
+<h1>1. Introduction</h1>
+<p>As the traffic rate of a wireless sensor network increases, the probability
+of collision, dropped packets, and missed acknowledgments also increases,
+even with sophisticated CSMA/CA implementations.</p>
+<p>It is important, especially in the case mesh networks, for packets to be
+delivered reliably and acknowledgments to be returned successfully on a hop-by-
+hop basis. One method to improve reliability is to reduce the rate of
+transmissions from each node within the network.</p>
+<p>Traffic Control has been in use for years in many different wired and wireless
+applications[1]_,[2]_,[3]_.  TinyOS already has traffic control
+mechanisms integrated directly into some networking libraries, such as CTP[4]_
+and Dissemination[5]_.  The use of Trickle[6]_ algorithms, also used
+within CTP and Dissemination, further reduces the rate of traffic throughout a
+network to improve delivery performance and prevent livelock. There has
+yet to be a centralized method of traffic control that throttles traffic
+generated from any component of a user's application.</p>
+<p>The traffic control interfaces proposed in this TEP are very basic, and are
+intended to support many different traffic control implementations.
+Two interfaces assist the application layer in controlling behavior:
+TrafficControl and TrafficPriority.</p>
+<p>The reference implementation presented here is integrated as a optional and
+generic radio stack layer (providing a Send and using a SubSend interface) and
+uses acknowledgments to dynamically adjust the transmit throttle. Other traffic
+control implementations could employ more sophisticated techniques to control
+throughput, but likely at the cost of a larger memory footprint.</p>
+<p>The ultimate goal is to allow developers to use mesh networking protocols and/or
+their own protocols without having to worry about implementing any kind of
+traffic control timer mechanism for each separate component.</p>
+</div>
+<div class="section" id="desired-behavior">
+<h1>2. Desired Behavior</h1>
+<p>Ideally, a traffic control layer SHOULD attempt to balance the rate of
+transmissions from a single node with the channel throughput capacity.
+This implies an adaptive control mechanism. If the channel is
+busy, nodes should add delay between packets to let other nodes transmit.
+Similarly, if the channel is not busy, a node should be allowed access to
+the channel more often to prevent inefficient channel downtime.  Traffic
+control SHOULD NOT listen to the channel for long periods of time to determine
+the appropriate access rates, because that defeats the purpose of low power
+communications layers used elsewhere.</p>
+<p>The traffic control implementation SHOULD have the option to be activated or
+deactivated on a system-wide level as well as a packet level. This allows for
+individual high or low priority packets. Traffic control SHOULD be deactivated
+by default, until the application or networking layers explicitly enable it.</p>
+<p>Finally, the traffic control mechanism SHOULD be small in code size to fit
+on the limited program memory available on most wireless platforms. There
+SHOULD NOT be additions or modifications to a packet's metadata structure
+that enables or disables traffic control on a per-packet basis;
+instead, per-packet priorities SHOULD be performed with a request/call back
+procedure. This keeps RAM requirements low and can be optimized out at compile
+time if those functions are not used.</p>
+<p>We also recommend any traffic control layer be implemented as an optional
+compile time add-on to a core radio stack or within the ActiveMessageC platform
+communication stack definition. This allows applications that do not require
+traffic control to remove its memory footprint from the system.</p>
+</div>
+<div class="section" id="trafficcontrolc-component-signature">
+<h1>3. TrafficControlC Component Signature</h1>
+<p>The signature of TrafficControlC is RECOMMENDED as follows:</p>
+<pre class="literal-block">
+configuration TrafficControlC {
+  provides {
+    interface Send;
+    interface TrafficControl;
+    interface TrafficPriority[am_id_t amId];
+  }
+
+  uses {
+    interface Send as SubSend;
+  }
+}
+</pre>
+<p>The Send interface provided on top and SubSend interface used underneath
+allow the TrafficControlC component to be integrated as a generic layer
+within any radio stack.</p>
+</div>
+<div class="section" id="trafficcontrol-interface">
+<h1>4. TrafficControl Interface</h1>
+<p>The TrafficControl interface allows the application layer to enable or
+disable traffic control from a system-wide level.  It also
+allows an application to set and get the current delay between packets.
+For most systems, we expect that the setDelay() and getDelay() commands may not be
+used often and will most likely get optimized out at compile time; however, some
+systems may care to explicitly increase or decrease the delay between packets or
+collect statistics on how the traffic control layer is performing.</p>
+<p>The TEP proposes the following TrafficControl interface:</p>
+<pre class="literal-block">
+interface TrafficControl {
+
+  command void enable(bool active);
+
+  command void setDelay(uint16_t delay);
+
+  command uint16_t getDelay();
+
+}
+</pre>
+</div>
+<div class="section" id="trafficpriority-interface">
+<h1>5. TrafficPriority Interface</h1>
+<p>The TrafficPriority interface is parameterized by active message ID.  It is a
+simple request / call back interface that allows components in the application layer to
+configure individual packets for priorities on a scale from 0 (lowest priority, default) to
+5 (highest priority, get the packet out immediately). There are several advantages
+to this call back method. Metadata does not need to be added
+to the end of every message_t. Additionally, a component that captures a requestPriority(...)
+event is not required to adjust the priority as it would if the event returned
+a value.</p>
+<p>When a packet enters the traffic control layer, and traffic control is
+enabled, the TrafficPriority interface MUST signal out the event
+requestPriority(...).  This event, with all the extra information it provides,
+allows the application layer to decide whether the packet is a high priority
+packet or not.  Calling the setPriority(uint8_t priority) command within the
+requestPriority(...) event MAY adjust the traffic control mechanisms applied
+to the current packet.  To aid in the definition of priority, two definitions
+are available in TrafficControl.h:</p>
+<pre class="literal-block">
+enum {
+  TRAFFICPRIORITY_LOWEST = 0,
+  TRAFFICPRIORITY_HIGHEST = 5,
+};
+</pre>
+<p>It is up to the traffic control implementation to define the meaning of each priority
+level. In the reference implementation, a priority of 0
+is the default low priority level that employs the full traffic control delays.
+Anything above 0 in the reference implementation is considered to be at the
+highest priority.</p>
+<p>If no areas of the application layer care to change the
+packet's priority, a default event handler will capture the requestPriority(...)
+event and do nothing. This would result in all packets being sent at a low
+priority with full traffic control mechanisms enforced.</p>
+<p>The TEP proposes the following TrafficPriority interface, to be provided as an
+interface parameterized by AM type:</p>
+<pre class="literal-block">
+interface TrafficPriority {
+
+  event void requestPriority(am_addr_t destination, message_t \*msg);
+
+  command void setPriority(uint8_t priority);
+
+}
+</pre>
+</div>
+<div class="section" id="reference-implementation">
+<h1>6. Reference Implementation</h1>
+<p>An implementation of the proposed traffic control layer can be found in the
+CCxx00 radio stack in
+tinyos-2.x-contrib/blaze/tos/chips/ccxx00_addons/trafficcontrol, with
+interfaces located in
+tinyos-2.x-contrib/blaze/tos/chips/ccxx00_single/interfaces and a dummy
+implementation located in
+tinyos-2.x-contrib/blaze/tos/chips/ccxx00_single/traffic.</p>
+<p>In this implementation, the default core radio stack (ccxx00_single) includes
+an empty stub for traffic control. Users that wish to include the
+traffic control implementation in their systems simply override the default
+stub component with the ccxx00_addons/trafficcontrol directory.</p>
+<p>The reference implementation works as follows. All nodes start with a default
+of 4 seconds between each packet. Changes are made to the time between outbound
+packets only when a unicast packet is sent with the request for acknowledgment
+flag set.  The reception of an acknowledgment is used as a basic indicator of
+channel activity.  For each acknowledgment received, the amount of time between
+packets is decreased so the next packet will get sent faster.  For each dropped
+acknowledgment, the amount of time between packets increases, causing the
+next packet to be sent later.</p>
+<p>When the transmission rate reaches a boundary (1 second per packet per node
+fastest, 10 seconds per packet per node slowest), it is reset to the default
+rate of 4 seconds per packet per node. This prevents nodes from unfairly
+capturing the channel.</p>
+<p>Testing this traffic control layer in a congested test bed setting of 16 nodes
+with multiple hidden terminals resulted in the acknowledgment success rate
+moving from 27-50% without traffic control to 90-100% with traffic control.
+The memory footprint increased by 260 bytes ROM / 16 bytes RAM with the
+inclusion of the traffic control layer.</p>
+</div>
+<div class="section" id="author-addresses">
+<h1>5. Author Addresses</h1>
+<div class="line-block">
+<div class="line">David Moss</div>
+<div class="line">Rincon Research Corporation</div>
+<div class="line">101 N. Wilmot Suite 101</div>
+<div class="line">Tucson AZ  85750</div>
+<div class="line">email: mossmoss at gmail dot com</div>
+<div class="line"><br /></div>
+<div class="line">Mark Hays</div>
+<div class="line">Rincon Research Corporation</div>
+<div class="line">101 N. Wilmot Suite 101</div>
+<div class="line">Tucson AZ  85750</div>
+<div class="line">email: mhh at rincon dot com</div>
+<div class="line"><br /></div>
+<div class="line">Mark Siner</div>
+<div class="line">Rincon Research Corporation</div>
+<div class="line">101 N. Wilmot, Suite 101</div>
+<div class="line">Tucson, AZ  85750</div>
+<div class="line">email: mks at rincon dot com</div>
+</div>
+</div>
+<div class="section" id="citations">
+<h1>6. Citations</h1>
+<table class="docutils footnote" frame="void" id="id1" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[1]</td><td>Bret Hull, Kyle Jamieson, Hari Balakrishnan. &quot;Mitigating Congestion in Wireless Sensor Networks.&quot; In the Proceedings of the ACM Sensys Conference 2004</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="id2" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[2]</td><td>Wan, C.-Y., Eisenman, S., and Campbell, A. &quot;CODA: Congestion Detection and Avoidance in Sensor Networks.&quot; In the Proceedings of the ACM Sensys Conference 2003</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="id3" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[3]</td><td>Woo, A., and Culler, D. &quot;A Transmission Control Scheme for Media Access in Sensor Networks.&quot; In ACM MOBICOM 2001</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="id4" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[4]</td><td>Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, Sukun Kim, Philip Levis, and Alec Woo.. &quot;TEP123: Collection Tree Protocol&quot;</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="id5" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[5]</td><td>Philip Levis and Gilman Tolle. &quot;TEP118: Dissemination of Small Values.&quot;</td></tr>
+</tbody>
+</table>
+<table class="docutils footnote" frame="void" id="id6" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label">[6]</td><td>Philip Levis, Neil Patel, David Culler, and Scott Shenker. &quot;Trickle: A Self-Regulating Algorithm for Code Maintenance and Propagation in Wireless Sensor Networks.&quot; In Proceedings of the First USENIX/ACM Symposium on Networked Systems Design and Implementation (NSDI 2004).</td></tr>
+</tbody>
+</table>
+</div>
+</div>
+</body>
+</html>
index 4c876ac7aac0487e6f7b3def2565691220cb39cf..dcfa7ff370d5ed62daedbef63ad90f56f88499d5 100644 (file)
@@ -3,7 +3,7 @@
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-<meta name="generator" content="Docutils 0.4.1: http://docutils.sourceforge.net/" />
+<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
 <title>Hardware Abstraction Architecture</title>
 <meta name="author" content="Vlado Handziski, Joseph Polastre, Jan-Hinrich Hauer, Cory Sharp, Adam Wolisz, David Culler, David Gay" />
 <style type="text/css">
index dcb02c7f2f888b7c9cc5aa05061da559498aad64..b5b84519d138a7d976c6651e4090e3442fdff05c 100644 (file)
@@ -291,16 +291,16 @@ ul.auto-toc {
 <tr class="field"><th class="docinfo-name">Type:</th><td class="field-body">Best Current Practice</td>
 </tr>
 <tr><th class="docinfo-name">Status:</th>
-<td>Draft</td></tr>
-<tr class="field"><th class="docinfo-name">TinyOS-Version:</th><td class="field-body">2.x</td>
+<td>Final</td></tr>
+<tr class="field"><th class="docinfo-name">TinyOS-Version:</th><td class="field-body">&gt; 2.1</td>
 </tr>
 <tr><th class="docinfo-name">Author:</th>
 <td>Omprakash Gnawali</td></tr>
 <tr class="field"><th class="docinfo-name">Draft-Created:</th><td class="field-body">07-May-2008</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.6</td>
+<tr class="field"><th class="docinfo-name">Draft-Version:</th><td class="field-body">1.8</td>
 </tr>
-<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-06-20</td>
+<tr class="field"><th class="docinfo-name">Draft-Modified:</th><td class="field-body">2008-11-04</td>
 </tr>
 <tr class="field"><th class="docinfo-name">Draft-Discuss:</th><td class="field-body">TinyOS Developer List &lt;tinyos-devel at mail.millennium.berkeley.edu&gt;</td>
 </tr>
@@ -315,7 +315,7 @@ is in full compliance with <a class="citation-reference" href="#tep-1" id="id1"
 </div>
 <div class="section">
 <h1><a id="introduction" name="introduction">1. Introduction</a></h1>
-<p>In order to document the Active Message Type <a class="footnote-reference" href="#id3" id="id2" name="id2">[1]</a>, also known as
+<p>In order to document the Active Message Type <a class="citation-reference" href="#tep-116" id="id2" name="id2">[TEP_116]</a>, also known as
 Active Message Identifier (AM ID), used by the protocols and to
 prevent AM ID conflicts between applications and protocols distributed
 with TinyOS 2.x, the application and protocol developers MUST use AM
@@ -357,9 +357,13 @@ protocols maintained by any working group.</p>
 Network Protocol Working Group with the following information:
 * Working Group responsible for the protocol
 * Name of the protocol and relevant TEPs
-* Location of the protocol in TinyOS source tree</p>
-<p>Upon receiving this information, the chair of the Network Protocol
-Working Group will allocate an AM ID and document the allocation.</p>
+* Location of the protocol in TinyOS source tree
+* Number of AM IDs requested and description of each ID
+* Specific AM ID request (only if necessary)</p>
+<p>Upon receiving this request, the chair of the Network Protocol Working
+Group will allocate the AM ID(s) and document the allocation. If the
+request is made for a specific AM ID, the chair of the Network
+Protocol Work Group will try to accommodate that request.</p>
 </div>
 <div class="section">
 <h1><a id="reclaiming-the-am-id-allocation" name="reclaiming-the-am-id-allocation">4. Reclaiming the AM ID Allocation</a></h1>
@@ -373,7 +377,9 @@ Group will document the deallocation.</p>
 <h1><a id="documenting-allocations-and-deallocations" name="documenting-allocations-and-deallocations">5. Documenting allocations and deallocations</a></h1>
 <p>For each TinyOS 2.x release that introduces a new protocol or use of a
 new AM ID, the chair of the Network Protocol Working Group creates a
-new TEP that lists all the AM ID allocations for that release.</p>
+new Informational TEP that lists all the AM ID allocations for that
+release. The TEP is finalized at the time of the release. <a class="citation-reference" href="#tep-135" id="id3" name="id3">[TEP_135]</a>
+documents the AM IDs allocated for TinyOS 2.1.</p>
 </div>
 <div class="section">
 <h1><a id="acknowledgments" name="acknowledgments">6. Acknowledgments</a></h1>
@@ -400,10 +406,16 @@ ID allocation policy.</p>
 <tr><td class="label"><a class="fn-backref" href="#id1" name="tep-1">[TEP_1]</a></td><td>TEP 1: TEP Structure and Keywords</td></tr>
 </tbody>
 </table>
-<table class="docutils footnote" frame="void" id="id3" rules="none">
+<table class="docutils citation" frame="void" id="tep-116" rules="none">
 <colgroup><col class="label" /><col /></colgroup>
 <tbody valign="top">
-<tr><td class="label"><a class="fn-backref" href="#id2" name="id3">[1]</a></td><td>TEP 116: Packet Protocols</td></tr>
+<tr><td class="label"><a class="fn-backref" href="#id2" name="tep-116">[TEP_116]</a></td><td>TEP 116: Packet Protocols</td></tr>
+</tbody>
+</table>
+<table class="docutils citation" frame="void" id="tep-135" rules="none">
+<colgroup><col class="label" /><col /></colgroup>
+<tbody valign="top">
+<tr><td class="label"><a class="fn-backref" href="#id3" name="tep-135">[TEP_135]</a></td><td>TEP 135: Active Message ID Allocation in TinyOS 2.1</td></tr>
 </tbody>
 </table>
 </div>
diff --git a/doc/pdf/deluge-t2-manual.pdf b/doc/pdf/deluge-t2-manual.pdf
deleted file mode 100644 (file)
index 35bb496..0000000
Binary files a/doc/pdf/deluge-t2-manual.pdf and /dev/null differ
diff --git a/doc/stylesheets/deluge-t2-manual.css b/doc/stylesheets/deluge-t2-manual.css
deleted file mode 100644 (file)
index a443e35..0000000
+++ /dev/null
@@ -1,195 +0,0 @@
-
-               body {
-               color: black;
-               /*   background-color: #e5e5e5;*/
-               background-color: #ffffff;
-               /*background-color: beige;*/
-               margin-top: 2em;
-               margin-left: 8%;
-               margin-right: 8%;
-               }
-
-               h1,h2,h3,h4,h5,h6 {
-               margin-top: .5em;
-               }
-
-               .title {
-               font-size: 200%;
-               font-weight: normal;
-               margin-top: 2.8em;
-               text-align: center;
-               }
-
-               .partheading {
-               font-size: 100%;
-               }
-
-               .chapterheading {
-               font-size: 100%;
-               }
-
-               .beginsection {
-               font-size: 110%;
-               }
-
-               .tiny {
-               font-size: 40%;
-               }
-
-               .scriptsize {
-               font-size: 60%;
-               }
-
-               .footnotesize {
-               font-size: 75%;
-               }
-
-               .small {
-               font-size: 90%;
-               }
-
-               .normalsize {
-               font-size: 100%;
-               }
-
-               .large {
-               font-size: 120%;
-               }
-
-               .largecap {
-               font-size: 150%;
-               }
-
-               .largeup {
-               font-size: 200%;
-               }
-
-               .huge {
-               font-size: 300%;
-               }
-
-               .hugecap {
-               font-size: 350%;
-               }
-
-               pre {
-               margin-left: 2em;
-               }
-
-               blockquote {
-               margin-left: 2em;
-               }
-
-               ol {
-               list-style-type: decimal;
-               }
-
-               ol ol {
-               list-style-type: lower-alpha;
-               }
-
-               ol ol ol {
-               list-style-type: lower-roman;
-               }
-
-               ol ol ol ol {
-               list-style-type: upper-alpha;
-               }
-
-               tt i {
-               font-family: serif;
-               }
-
-               .verbatim em {
-               font-family: serif;
-               }
-
-               /*
-               .verbatim {
-               color: #4d0000;
-               }
-               */
-
-               .scheme em {
-               color: black;
-               font-family: serif;
-               }
-
-               .scheme {
-               color: brown;
-               }
-
-               .scheme .keyword {
-               color: #990000;
-               font-weight: bold;
-               }
-
-               .scheme .builtin {
-               color: #990000;
-               }
-
-               .scheme .variable {
-               color: navy;
-               }
-
-               .scheme .global {
-               color: purple;
-               }
-
-               .scheme .selfeval {
-               color: green;
-               }
-
-               .scheme .comment {
-               color:  teal;
-               }
-
-               .schemeresponse {
-               color: green;
-               }
-
-               .navigation {
-               color: red;
-               text-align: right;
-               font-size: medium;
-               font-style: italic;
-               }
-
-               .disable {
-               /* color: #e5e5e5; */
-               color: gray;
-               }
-
-               .smallcaps {
-               font-size: 75%;
-               }
-
-               .smallprint {
-               color: gray;
-               font-size: 75%;
-               text-align: right;
-               }
-
-               /*
-               .smallprint hr {
-               text-align: left;
-               width: 40%;
-               }
-               */
-
-               .footnoterule {
-               text-align: left;
-               width: 40%;
-               }
-
-               .colophon {
-               color: gray;
-               font-size: 80%;
-               font-style: italic;
-               text-align: right;
-               }
-
-               .colophon a {
-               color: gray;
-               }
-               
\ No newline at end of file
index 68b68ebed6ea8352f78739a182de860f5c353e11..3945ffc6d427dd9ca644d9f0f6ae5f0f80295496 100644 (file)
@@ -5,13 +5,10 @@ Sensors and Sensor Boards
 :TEP: 109
 :Group: Core Working Group 
 :Type: Documentary
-:Status: Draft
+:Status: Final
 :TinyOS-Version: 2.x
 :Author: David Gay, Philip Levis, Wei Hong, Joe Polastre, and Gilman Tolle
 
-:Draft-Created: 10-Jun-2006
-:Draft-Discuss: TinyOS Developer List <tinyos-devel at mail.millennium.berkeley.edu>
-
 .. Note::
 
    This memo documents a part of TinyOS for the TinyOS Community, and
index 8c2cb0964c919efee7a5844d714ea11d65047a0d..5b2a99f3634e1dccb01b679675edc498654fc7c2 100644 (file)
@@ -251,6 +251,14 @@ mcu_power_t means that this command can have fan-out calls.
 Section 5 describes one example use of McuPowerOverride, in the
 timer stack for the Atmega128 microcontroller family.
 
+As part of power state override, a platform MUST define the enum
+TOS_SLEEP_NONE in its hardware.h file. This enum defines the highest
+power state of the platform's microcontroller in a chip-independent
+way. If a component wires to McuPowerOverride and returns TOS_SLEEP_NONE,
+this will cause TinyOS to never put the microcontroller into a power
+saving state. This enum allows a component to prevent sleep in a
+platform-independent way.
+
 4. Peripherals and Subsystems
 ====================================================================
 
@@ -277,7 +285,7 @@ include power management into shared non-virtualized devices.
 An implementation of McuSleepC can be found in ``tinyos-2.x/tos/chips/atm128``, 
 ``tinyos-2.x/tos/chips/msp430``, and ``tinyos-2.x/tos/chips/px27ax``. 
 
-An example of a use of McuPowerOverride can be found in the atmega128 timer
+An example use of McuPowerOverride can be found in the atmega128 timer
 system. Because some low-power states have much longer wakeup latencies than
 others, the timer system does not allow long latencies if it has a timer
 that is going to fire soon.  The implementation can be found in 
@@ -285,6 +293,19 @@ that is going to fire soon.  The implementation can be found in
 ``tinyos-2.x/tos/chips/atm128/timer/HplAtm128Timer0AsyncC.nc`` automatically
 wires it to McuSleepC if it is included.
 
+For the atmega128 microcontroller, TOS_SLEEP_NONE is the "idle" power
+state.
+
+A second example use of McuPowerOverride is in the msp430 timer system.
+By default, the msp430 lowest power state is LPM4, which does not keep
+clocks enabled. If ``tinyos-2.x/tos/chips/msp430/timer/Msp430ClockC.nc''
+is included in the component graph, however, this configuration wires
+the McuPowerOverride of ``tinyos-2.x/tos/chips/msp430/timer/Msp430ClockP.nc``
+to McuSleepC. This implemementation of McuPowerOverride raises the lowest
+power state to LPM3, which keeps clocks enabled.
+
+For msp430 microcontrollers, TOS_SLEEP_NONE is the "active" power state.
+
 6. Author's Address
 ====================================================================
 
index 8291dd3464e341957e76c00b4f705f83f78110fe..f8723f317157eafe5cddea349275f5746332a008 100644 (file)
@@ -5,8 +5,8 @@ Collection
 :TEP: 119
 :Group: Net2 Working Group
 :Type: Documentary
-:Status: Draft
-:TinyOS-Version: 2.x
+:Status: Final
+:TinyOS-Version: > 2.1
 :Author: Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, and Philip Levis
 
 :Draft-Created: 09-Feb-2006
@@ -23,50 +23,52 @@ Abstract
 ====================================================================
 
 The memo documents the interfaces, components, and semantics used by
-collection protocol in TinyOS 2.x. Collection provides a best-effort,
-multihop delivery of packets to the root of a tree. There may be
-multiple tree roots in a network, and in this case the semantics
-are *anycast* delivery to at least one of the roots. A node sending
-a packet does not specify which root the packet is destined to.
+the collection protocols in TinyOS 2.x. Collection provides
+best-effort, multihop delivery of packets to one of a set of
+collection points.  There may be multiple collection points in a
+network, and in this case the semantics are *anycast* delivery to at
+least one of the collection points. A node sending a packet does not
+specify which of the collection points the packet is destined to.  The
+union of the paths from each node to one or more of the collection
+points forms a set of trees, and in this document we assume that
+collection points are the roots of these trees.
  
 
 1. Introduction
 ====================================================================
 
 Collecting data at a base station is a common requirement of sensor
-network applications. The general approach used is to build one
-or more collection *trees*, each of which is rooted at a base
-station. When a node has data which needs to be collected, it 
-sends the data up the tree, and it forwards collection data that
-other nodes send to it. Sometimes, depending on the form of data
-collection, systems need to be able to inspect packets as they go
-by, either to gather statistics, compute aggregates, or suppress
-redundant transmissions.
-
-When a network has multiple base stations that act as *root* nodes,
-rather than one tree, it has a *forest* of trees. By picking a 
-parent node, a collection protocol implicitly joins one of these
-trees. Collection provides a best-effort,
-multihop delivery of packets to one of a network's tree roots:
-it is an *anycast* protocol. The semantics is that the protocol
-will make a reasonable effort to deliver the message to at least
-one of the roots in the network. There are however no guarantees of 
-delivery, and there can be duplicates delivered to one or more
-roots. There is also no ordering guarantees.
-
-Given the limited state that nodes can store and a general need
-for distributed tree building algorithms, simple collection protocols
-encounter several challenges. These challenges are not unique to
-collection protocols. Instead, they represent a subset of common
-networking algorithmic edge cases that occur in this protocol
-family:
-
-  * Loop detection, detecting when a node selects one of its
-    descendants as a new parent.
-
-  * Duplicate suppression, detecting and dealing with when lost 
-    acknowledgments are causing packets to replicate in the 
-    network, wasting bandwidth.
+network applications. The general approach used is to build one or
+more collection trees, each of which is rooted at a base station. When
+a node has data which needs to be collected, it sends the data up the
+tree, and it forwards collection data that other nodes send to
+it. Sometimes, depending on the form of data collection, systems need
+to be able to inspect packets as they go by, either to gather
+statistics, compute aggregates, or suppress redundant transmissions.
+
+Collection provides best-effort, multihop delivery of packets to one
+of a network's tree roots: it is an *anycast* protocol. The
+semantics are that the protocol will make a reasonable effort to
+deliver the message to at least one of the roots in the network. By
+picking a parent node, a node implementing the collection protocol
+inductively joins the tree its parent has joined.  Delivery is best
+effort, and there can be duplicates delivered to one or more roots.
+Collection provides no ordering or real-time guarantees, although
+specific implementations may extend the basic functionality to do
+so.
+
+Given the limited state that nodes can store and a general need for
+distributed tree building algorithms, collection protocols encounter
+several challenges. These challenges are not unique to collection
+protocols. Instead, they represent a subset of common networking
+algorithmic edge cases that generally occur in wireless routing:
+
+  * Loop detection, for when a node selects one of its descendants as
+    a next hop.
+
+  * Duplicate suppression, detecting and dealing with lost
+    acknowledgments that can cause packets to replicate in the
+    network, wasting capacity.
 
   * Link estimation, evaluating the link quality to single-hop
     neighbors.
@@ -82,19 +84,21 @@ describes a set of components and interfaces for collection services.
 2. Collection interfaces
 ====================================================================
 
-A node can perform four different roles in collection: producer,
-snooper, in-network processor, and consumer. Depending on their role,
-the nodes use different interfaces to interact with the collection
-component. 
+A node can perform four different roles in collection: sender (or
+source), snooper, in-network processor, and receiver (or
+root). Depending on their role, the nodes use different interfaces to
+interact with the collection component.
 
 The collection infrastructure can be multiplexed among independent
-applications, by means of a *collection identifier*. It is important
-to note that the *data* traffic in the protocol is multiplexed,
-while the *control* traffic is not.
-
-The nodes that generate data to be sent to the root are *producers*.
-The producers use the Send interface [1_] to send data to the root
-of the collection tree.  The collection identifier is specified as a
+applications, by means of a collection identifier. The collection
+identifier is used to identify different data traffic at the sender,
+intermediate-nodes, or the receiver, much like port number in TCP. All
+data traffic, regardless of the collection identifier, use the same
+routing topology.
+
+The nodes that generate data to be sent to the root are *senders*.
+Senders use the Send interface [1_] to send data to the root of
+the collection tree.  The collection identifier is specified as a
 parameter to Send during instantiation.
 
 The nodes that overhear messages in transit are *snoopers*. The
@@ -102,11 +106,11 @@ snoopers use the Receive interface [1_] to receive a snooped
 message. The collection identifier is specified as a parameter
 to Receive during instantiation.
 
-The nodes can process a packet that are in transit. These in-network
-*processors* use the Intercept interface to receive
-and update a packet. The collection identifier is specified as a parameter
-to Intercept during instantiation. The Intercept interface has this
-signature:: 
+The nodes can process a packet that is in transit. These in-network
+*processors* use the Intercept interface to receive and update a
+packet. The collection identifier is specified as a parameter to
+Intercept during instantiation. The Intercept interface has this
+signature::
 
   interface Intercept {
     event bool forward(message_t* msg, void* payload, uint8_t len);
@@ -115,21 +119,24 @@ signature::
 Intercept has a single event, Intercept.forward(). A collection
 service SHOULD signal this event when it receives a packet to forward.
 If the return value of the event is FALSE, then the collection layer
-MUST NOT forward the packet. This interface allows a higher layer
-to inspect the internals of a packet and possibly suppress it if
-it is unnecessary or if its contents can be aggregated into an
-existing packet.
-
-Root nodes that receive data from the network are *consumers*. The
-consumers use the Receive interface [1_] to receive a message
-delivered by collection. The collection identifier is specified
-as a parameter to Receive during instantiation.
-
-The set of all roots and the paths that
-lead to them form the collection routing infrastructure in the network.
-For any connected set of nodes implementing the collection protocol 
-there is only one collection infrastructure, *i.e.*, all roots in this 
-set active at the same time are part of the same infrastructure.
+MUST NOT forward the packet. The Intercept interface allows a higher
+layer to inspect the internals of a packet and suppress it if needed.
+Intercept can be used for duplicate suppression, aggregation, and
+other higher-level services. As the handler of Intercept.forward()
+does not receive ownership of the packet, it MUST NOT modify the
+packet and MUST copy data out of the packet which it wishes to use
+after the event returns.
+
+Root nodes that receive data from the network are *receivers*. Roots
+use the Receive interface [1_] to receive a message delivered by
+collection. The collection identifier is specified as a parameter to
+Receive during instantiation.
+
+The set of all roots and the paths that lead to them form the
+collection routing infrastructure in the network.  For any connected
+set of nodes implementing the collection protocol there is only one
+collection infrastructure, *i.e.*, all roots in this set active at the
+same time are part of the same infrastructure.
 
 The RootControl interface configures whether a node is a
 root::
@@ -140,12 +147,12 @@ root::
     command bool isRoot();
   }
 
-Both commands MUST return SUCCESS if the node is now in the specified
-state, and FAIL otherwise. For example, if a node is already a root
-and an application calls RootControl.setRoot(), the call will
+The first two commands MUST return SUCCESS if the node is now in the
+specified state, and FAIL otherwise. For example, if a node is already
+a root and an application calls RootControl.setRoot(), the call will
 return SUCCESS. If setRoot() returns SUCCESS, then a subsequent call
-to isRoot() MUST return TRUE. If unsetRoot() returns SUCCESS, then
-a subsequent call to isRoot() MUST return FALSE. 
+to isRoot() MUST return TRUE. If unsetRoot() returns SUCCESS, then a
+subsequent call to isRoot() MUST return FALSE.
 
 3 Collection Services
 ====================================================================
@@ -170,10 +177,10 @@ which has the following signature::
   }
 
 
-CollectionC MAY have additional interfaces. These additional
-interfaces MUST have default functions on all outgoing invocations
-(commands for uses, events for provides) of those interfaces so that
-it can operate properly if they are not wired.
+CollectionC MAY have additional interfaces. All outgoing invocations
+(commands for uses, events for provides) of those interfaces MUST have
+default functions. Those default functions enable CollectionC to
+operate properly even when the additional interfaces are not wired.
 
 Components SHOULD NOT wire to CollectionC.Send. The generic
 component CollectionSenderC (described in section 3.1) provides
@@ -184,22 +191,25 @@ collection_id_t. Each collection_id_t corresponds to a different
 protocol operating on top of collection, in the same way that
 different am_id_t values represent different protocols operating on
 top of active messages. All packets sent with a particular
-collection_id_t generally have the same payload format, so that
-snoopers, intercepters, and receivers can parse it properly.
+collection_id_t generally SHOULD have the same payload format, so that
+snoopers, intercepters, and receivers can parse them properly.
 
 ColletionC MUST NOT signal Receive.receive on non-root
-nodes. CollectionC MAY signal Receive.receive on a root node when
-a data packet successfully arrives at that node. If a root node calls
-Send, CollectionC MUST treat it as it if were a received packet.
-Note that the buffer swapping semantics of Receive.receive, when
-combined with the pass semantics of Send, require that CollectionC
-make a copy of the buffer if it signals Receive.receive.
-
-If CollectionC receives a data packet to forward and it is not a
-root node, it MAY signal Intercept.forward.
-
-If CollectionC receives a data packet that a different node
-is supposed to forward, it MAY signal Snoop.receive.
+nodes. CollectionC MUST signal Receive.receive on a root node when a
+unique (non-duplicate) data packet successfully arrives at that
+node. It MAY signal Receive.receive when a duplicate data packet
+successfully arrives. If a root node calls Send, CollectionC MUST
+treat it as it if were a received packet.  Note that the buffer
+swapping semantics of Receive.receive, when combined with the pass
+semantics of Send, require that CollectionC make a copy of the buffer
+if it signals Receive.receive.
+
+If CollectionC receives a data packet to forward and it is not a root
+node, it MAY signal Intercept.forward. CollectionC MAY signal
+Snoop.receive when it hears a packet which a different node is
+supposed to forward. For any given packet it receives, CollectionC
+MUST NOT signal more than one of the Snoop.receive, Receive.receive,
+and Intercept.forward events.
 
 RootControl allows a node to be made a collection tree root.
 CollectionC SHOULD NOT configure a node as a root by default.
@@ -224,231 +234,16 @@ This abstraction follows a similar virtualization approach to
 AMSenderC [1_], except that it is parameterized by a collection_id_t
 rather than an am_id_t. As with am_id_t, every collection_id_t SHOULD
 have a single packet format, so that receivers can parse a packet
-based on its collection ID and contents.
+based on its collection ID and contents. 
   
-4 Implementation
+4. Implementation
 ====================================================================
 
-An implementation of this TEP can be found in
-``tinyos-2.x/tos/lib/net/ctp`` and ``tinyos-2.x/tos/lib/net/4bitle``, in
-the CTP protocol. It is beyond the scope of this document to fully
-describe CTP, but we outline its main components. CTP will be
-described in an upcoming TEP [2_].  This implementation is a
-reference implementation, and is not the only possibility.  It
-consists of three major components, which are wired together to form
-a CollectionC: LinkEstimatorP, CtpRoutingEngineP, and
-CtpForwardingEngineP. 
-
-This decomposition tries to encourage evolution of components and
-ease of use through modularization. Neighbor management and link
-estimation are decoupled from the routing protocol. Furthermore, the
-routing protocol and route selection are decoupled from the
-forwarding policies, such as queueing and timing.
-
-4.1 LinkEstimatorP
---------------------------------------------------------------------
-
-LinkEstimatorP estimates the quality of link to or from each
-neighbor. In this TEP, we briefly describe the reference
-implementation in ''tinyos-2.x/tos/lib/4bitle'' and refer the readers
-to [3]_ for a detailed description of the estimator.
-
-Link estimation is decoupled from the establishment of routes. There
-is a narrow interface -- LinkEstimator and CompareBit -- between the
-link estimator and the routing engine. A smaller return value from
-LinkEstimator.getLinkQuality() implies that the link to the neighbor
-is estimated to be of a higher quality than the one that results in a
-larger return value. Radio provided values such as LQI or RSI, beacon
-based link estimation to compute ETX, or their combination are some
-possible approaches to estimating link qualities. LinkEstimatorP
-returns (ETX-1)*10 as the link quality. The routing engine instructs
-LinkEstimatorP to insert the neighbor, through which a high quality
-path to the root can be constructed, into the neighbor table by
-returning TRUE when LinkEstimatorP signals Comparebit.shouldInsert()
-for the newly discovered neighbor.
-
-LinkEstimatorP does not generate its own control messages to compute
-link qualities. When a user of LinkEstimatorP (CtpRoutingEngineP, for
-example) sends a packet using the Send interface provided by
-LinkEstimatorP, link estimation information is also sent with the
-packet as described in an upcoming TEP [4_]. LinkEstimatorP provides
-calls (txAck(), txNoAck(), and clearDLQ()) to update the link
-estimates based on successful or unsuccessful data transmission to the
-neighbors. LinkEstimatorP uses the LinkPacketMetadata interface to
-determine if the channel was of high quality when a packet is received
-from a neighbor to consider the link to that neighbor for insertion
-into the neighbor table.
-
-The user of LinkEstimatorP can call insertNeighbor() to manually
-insert a node in the neighbor table, pinNeighbor() to prevent a
-neighbor from being evicted, and unpinNeighbor() to restore eviction
-policy::
-
-  typedef uint16_t neighbor_table_entry_t
-
-  LinkEstimatorP {
-    provides {
-      interface StdControl;
-      interface AMSend as Send;
-      interface Receive;
-      interface LinkEstimator;
-      interface Init;
-      interface Packet;
-      interface CompareBit;
-    }
-    uses {
-      interface AMSend;
-      interface AMPacket as SubAMPacket;
-      interface Packet as SubPacket;
-      interface Receive as SubReceive;
-      interface LinkPacketMetadata;
-      interface Random;
-    }
-  }
-
-  interface CompareBit {
-    event bool shouldInsert(message_t *msg, void* payload, uint8_t len, bool white_bit);
-  }
-
-  interface LinkEstimator {
-    command uint16_t getLinkQuality(uint16_t neighbor);
-    command error_t insertNeighbor(am_addr_t neighbor);
-    command error_t pinNeighbor(am_addr_t neighbor);
-    command error_t unpinNeighbor(am_addr_t neighbor);
-    command error_t txAck(am_addr_t neighbor);
-    command error_t txNoAck(am_addr_t neighbor);
-    command error_t clearDLQ(am_addr_t neighbor);
-    event void evicted(am_addr_t neighbor);
-  }
-
-
-
-4.2 CtpRoutingEngineP
---------------------------------------------------------------------
-
-CtpRoutingEngineP is responsible for computing routes to the roots of a
-tree. In traditional networking terminology, this is part of the
-control plane of the network, and is does not directly forward any
-data packets, which is the responsibility of CtpForwardingEngineP. 
-The main interface between the two is UnicastNameFreeRouting.
-
-CtpRoutingEngineP uses the LinkEstimator interface to learn about the
-nodes in the neighbor table maintained by LinkEstimatorP and the
-quality of links to and from the neighbors. The routing protocol on
-which collection is implemented computes a routing tree with a single
-or multiple roots. CtpRoutingEngineP allows a node to be configured as
-a root or a non-root node dynamically. CtpRoutingEngineP maintains
-multiple candidate next hops::
-
-  generic module CtpRoutingEngineP(uint8_t routingTableSize, 
-                                   uint16_t minInterval, 
-                                   uint16_t maxInterval) {
-      provides {
-          interface UnicastNameFreeRouting as Routing;
-          interface RootControl;
-          interface CtpInfo;
-          interface StdControl;
-          interface CtpRoutingPacket;
-          interface Init;
-      } 
-      uses {
-          interface AMSend as BeaconSend;
-          interface Receive as BeaconReceive;
-          interface LinkEstimator;
-          interface AMPacket;
-          interface SplitControl as RadioControl;
-          interface Timer<TMilli> as BeaconTimer;
-          interface Timer<TMilli> as RouteTimer;
-          interface Random;
-          interface CollectionDebug;
-          interface CtpCongestion;
-          interface Comparebit;
-      }
-  }
-
-
-::
-
- interface UnicastNameFreeRouting {
-   command am_addr_t nextHop();
-
-   command bool hasRoute();
-   event void routeFound();
-   event void noRoute();
- }
-
-
-
-4.3 CtpForwardingEngineP
---------------------------------------------------------------------
-
-The CtpForwardingEngineP component provides all the top level interfaces
-(except RootControl) which CollectionC provides and an application 
-uses. It deals with retransmissions, duplicate suppression, packet
-timing, loop detection, and also informs the LinkEstimator of the
-outcome of attempted transmissions.::
-
-  generic module CtpForwardingEngineP() {
-    provides {
-      interface Init;
-      interface StdControl;
-      interface Send[uint8_t client];
-      interface Receive[collection_id_t id];
-      interface Receive as Snoop[collection_id_t id];
-      interface Intercept[collection_id_t id];
-      interface Packet;
-      interface CollectionPacket;
-      interface CtpPacket;
-      interface CtpCongestion;
-    }
-    uses {
-      interface SplitControl as RadioControl;
-      interface AMSend as SubSend;
-      interface Receive as SubReceive;
-      interface Receive as SubSnoop;
-      interface Packet as SubPacket;
-      interface UnicastNameFreeRouting;
-      interface Queue<fe_queue_entry_t*> as SendQueue;
-      interface Pool<fe_queue_entry_t> as QEntryPool;
-      interface Pool<message_t> as MessagePool;
-      interface Timer<TMilli> as RetxmitTimer;
-      interface LinkEstimator;
-      interface Timer<TMilli> as CongestionTimer;
-      interface Cache<message_t*> as SentCache;
-      interface CtpInfo;
-      interface PacketAcknowledgements;
-      interface Random;
-      interface RootControl;
-      interface CollectionId[uint8_t client];
-      interface AMPacket;
-      interface CollectionDebug;
-    }
-  }
-
-
-CtpForwardingEngineP uses a large number of interfaces, which can be
-broken up into a few groups of functionality:
-
-  * Single hop communication: SubSend, SubReceive, SubSnoop,
-    SubPacket, PacketAcknowledgments, AMPacket
-  * Routing: UnicastNameFreeRouting, RootControl, CtpInfo,
-    CollectionId, SentCache
-  * Queue and buffer management: SendQueue, MessagePool,
-    QEntryPool
-  * Packet timing: Random, RetxmitTimer
-
-4.4 MultihopLqi
-====================================================================
-
-There is another implementation of collection in ``tos/lib/net/lqi``.
-Its software structure is similar, with the exception that it does
-not have a separate link estimator. MultihopLqi only works on
-platforms that have a CC2420 radio, as it uses a special piece
-of physical layer data the radio provides (the LQI value).
-The three major components of the MultihopLqi implementation
-are the modules LqiForwardingEngineP and  LqiRoutingEngineP, as
-well as the configuration MultihopLqiP.
-
+Implementations of collection can be found in
+``tinyos-2.x/tos/lib/net/ctp`` and ``tinyos-2.x/tos/lib/net/lqi``.
+The former is the Collection Tree Protocol (CTP), described in TEP 123
+[2_]. The latter is a TinyOS 2.x port of MultihopLqi, a
+CC2420-specific collection protocol in TinyOS 1.x.
 
 5. Author Addresses
 ====================================================================
@@ -491,10 +286,7 @@ well as the configuration MultihopLqiP.
 6. Citations
 ====================================================================
 
-.. [1] TEP 116: Packet Protocols
-
-.. [2] TEP 123: The Collection Tree Protocol (CTP) 
+.. [1] TEP 116: Packet Protocols.
 
-.. [3] Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, and Philip Levis. "Four Bit Wireless Link Estimation." In Proceedings of the Sixth Workshop on Hot Topics in Networks (HotNets VI), November 2007
+.. [2] TEP 123: The Collection Tree Protocol (CTP).
 
-.. [4] TEP 124: The Link Estimation Exchange Protocol (LEEP)
index 477d87dc30f3645e81918cea8f646445705e6db2..6e294177eba04fe4275ab238c7de80dbfca90d94 100644 (file)
@@ -5,8 +5,8 @@ The Collection Tree Protocol (CTP)
 :TEP: 123
 :Group: Network Working Group 
 :Type: Documentary
-:Status: Draft
-:TinyOS-Version: 2.x
+:Status: Final
+:TinyOS-Version: > 2.1
 :Author: Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, Sukun Kim, Philip Levis, and Alec Woo
 
 :Draft-Created: 3-Aug-2006
@@ -31,6 +31,21 @@ collection roots in a network.
 1. Introduction
 ==============================================================================
 
+A collection protocol delivers data to one of possibly several data
+sinks, providing a many-to-one network layer. Collection is a
+fundamental component of most sensor network applications. The
+Collection Tree Protocol (CTP) is a reference Collection protocol in
+TinyOS 2.x. The users use Collection interfaces described in TEP 119
+[3]_ to use CTP in their applications.
+
+In this TEP, after a brief discussion of Collection and CTP, we
+specify the CTP routing and data frames. CTP uses routing frames to
+update and build collection tree in the network. CTP uses data frames
+to deliver application payload to the sink and to probe topology
+inconsistencies.
+
+All fields in this specification are in network byte order.
+
 2. Assumptions and Limitations
 ==============================================================================
 
@@ -47,20 +62,24 @@ The CTP protocol assumes that the data link layer provides four things:
  2) Provides synchronous acknowledgments for unicast packets.
  3) Provides a protocol dispatch field to support multiple higher-level
     protocols.
- 4) Has single-hop source and destination fields.
+ 4) Has single-hop 16-bit source and destination fields.
 
 CTP assumes that it has link quality estimates of some number of nearby 
 neighbors. These provide an estimate of the number of transmissions it 
 takes for the node to send a unicast packet whose acknowledgment is
 successfully received.
 
-CTP has several mechanisms in order to improve delivery reliability,
-but it does not promise 100\% reliable delivery. It is best effort, but
-a best effort that *tries very hard.*
+CTP has several mechanisms in order to achieve high delivery
+reliability, but it does not promise 100\% reliable delivery. It is a
+best effort protocol.
 
-CTP is designed for relatively low traffic rates. Bandwidth-limited systems
-might benefit from a different protocol, which can, for example, pack
-multiple small frames into a single data-link packet.
+CTP is designed for relatively low traffic rates such that there is
+enough space in the channel to transmit and receive routing frames
+even when the network is forwarding collection data
+frames. Bandwidth-limited systems or high data rate applications might
+benefit from a different protocol, which can, for example, pack
+multiple small frames into a single data-link packet or employ rate
+control mechanisms.
 
 
 3. Collection and CTP
@@ -71,8 +90,8 @@ has an ETX of 0.  The ETX of a node is the ETX of its parent plus the
 ETX of its link to its parent. This additive measure assumes that
 nodes use link-level retransmissions.  Given a choice of valid routes,
 CTP SHOULD choose the one with the lowest ETX value. CTP represents
-ETX values as 16-bit fixed-point real numbers with a precision of
-hundredths. An ETX value of 45, for example, represents an ETX of 4.5,
+ETX values as 16-bit decimal fixed-point real numbers with a precision
+of tenths. An ETX value of 45, for example, represents an ETX of 4.5,
 while an ETX value of 10 represents an ETX of 1.
 
 Routing loops are a problem that can emerge in a CTP network. Routing
@@ -93,13 +112,17 @@ is to not consider routes with an ETX higher than a reasonable constant.
 The value of this constant is implementation dependent.
 
 Packet duplication is an additional problem that can occur in CTP.
-Packet duplication occurs when a node receives a data frame successfully
-and transmits an ACK, but the ACK is not received. The sender retransmits
-the packet, and the receiver receives it a second time. This can have
-disasterous effects over multiple hops, as the duplication is exponential.
-For example, if each hop on average produces one duplicate, then on the
-first hop there will be two packets, on the second there will be four,
-on the third there will be eight, etc.
+Packet duplication occurs when a node receives a data frame
+successfully and transmits an ACK, but the ACK is not received. The
+sender retransmits the packet, and the receiver receives it a second
+time. This can have disasterous effects over multiple hops, as the
+duplication is exponential.  For example, if each hop on average
+produces one duplicate, then on the first hop there will be two
+packets, on the second there will be four, on the third there will be
+eight, etc. CTP keeps a small cache of packet signature for the
+packets it has seen to detect packet duplicates. When a new packet
+arrives, if its signature results in cache hit, CTP drops the packet
+because it is a duplicate.
 
 Routing loops complicate duplicate suppression, as a routing loop may
 cause a node to legitimately receive a packet more than once. Therefore,
@@ -131,14 +154,14 @@ The CTP data frame format is as follows::
 
 Field definitions are as follows:
 
-  * P: Routing pull. The P bit allows nodes to request routing information from other nodes. If a node with a valid route hears a packet with the P bit set, it SHOULD transmit a routing frame in the near future.
+  * P: Routing pull. The P bit allows nodes to request routing information from other nodes. If the unicast destination of the data frame with a valid route hears a packet with the P bit set, it SHOULD transmit a routing frame in the near future. Nodes other than the link-layer destination of the data frame MAY respond to the P bit in the data frame.
   * C: Congestion notification. If a node drops a CTP data frame, it MUST set the C field on the next data frame it transmits.
   * THL: Time Has Lived. When a node generates a CTP data frame, it MUST set THL to 0. When a node receives a CTP data frame, it MUST increment the THL. If a node receives a THL of 255, it increments it to 0.
   * ETX: The ETX routing metric of the single-hop sender. When a node transmits a CTP data frame, it MUST put the ETX value of its route through the single-hop destination in the ETX field.  If a node receives a packet with a lower gradient than its own, then it MUST schedule a routing frame in the near future.
   * origin: The originating address of the packet. A node forwarding a data frame MUST NOT modify the origin field.
   * seqno: Origin sequence number. The originating node sets this field, and a node forwarding a data frame MUST NOT modify it. 
   * collect_id: Higher-level protocol identifier. The origin sets this field, and a node forwarding a data frame MUST NOT modify it.
-  * data: the data payload, of zero or more bytes. A node forwarding a data frame MUST NOT modify the data payload.
+  * data: the data payload, of zero or more bytes. A node forwarding a data frame MUST NOT modify the data payload. The length of the data field is computed by subtracting the size of the CTP header from the size of the link layer payload provided by the link layer.
 
 Together, the origin, seqno and collect_id fields denote a unique 
 ***origin packet.*** Together, the origin, seqno, collect_id, and
@@ -147,7 +170,7 @@ distinction is important for duplicate suppression in the presence
 of routing loops. If a node suppresses origin packets, then if
 asked to forward the same packet twice due to a routing loop, it will
 drop the packet. However, if it suppresses packet instances, then it
-will route succesfully in the presence of transient loops unless the
+will route successfully in the presence of transient loops unless the
 THL happens to wrap around to a forwarded packet instance.
 
 A node MUST send CTP data frames as unicast messages with link-layer 
@@ -170,7 +193,7 @@ The CTP routing frame format is as follows::
 
 The fields are as follows:
   
-  * P: Same as data frame.
+  * P: Same as data frame with one difference: Routing frames are broadcast so multiple nodes respond to the P bit in the routing frame.
   * C: Congestion notification. If a node drops a CTP data frame, it MUST set the C field on the next routing frame it transmits.
   * parent: The node's current parent.
   * metric: The node's current routing metric value.
@@ -185,6 +208,8 @@ below its own. When a parent hears a child advertise an ETX below its
 own, it MUST schedule a routing frame for transmission in the near
 future.
 
+A node MUST send CTP routing frames as broadcast messages.
+
 6. Implementation
 ==============================================================================
 
@@ -219,12 +244,12 @@ increasing randomized timer. The implementation resets the timer to a
 small value when one or more of the following conditions are met:
 
  1) The routing table is empty (this also sets the P bit)
- 2) The node's routing ETX increases by >= 1 trasmission
+ 2) The node's routing ETX increases by >= 1 transmission
  3) The node hears a packet with the P bit set
 
 The implementation augments the LEEP link estimates with data
 transmissions. This is a direct measure of ETX. Whenever the data path
-transmits a packet, it tells the link estimator the destimation and
+transmits a packet, it tells the link estimator the destination and
 whether it was successfully acknowledged. The estimator produces an
 ETX estimate every 5 such transmissions, where 0 successes has an ETX
 of 6.
@@ -238,8 +263,9 @@ the rate at which CTP collects data estimates is proportional to
 the transmission rate, then it can quickly detect a broken link and
 switch to another candidate neighbor.
 
-The component ``tos/lib/net/le/LinkEstimatorP`` implements the
-link estimator. It couples LEEP-based and data-based estimates.
+The component ``tos/lib/net/4bitle/LinkEstimatorP`` implements the
+link estimator. It couples LEEP-based and data-based estimates as
+described in [4]_.
 
 6.2 Routing Engine
 ------------------------------------------------------------------------------
@@ -256,7 +282,7 @@ implements the routing engine.
 ------------------------------------------------------------------------------
 
 The component ``tos/lib/net/ctp/CtpForwardingEngineP`` implements the
-forwarding engine. It has five repsonsibilities:
+forwarding engine. It has five responsibilities:
 
  1) Transmitting packets to the next hop, retransmitting when necessary, and
     passing acknowledgment based information to the link estimator
@@ -332,6 +358,24 @@ along the path.
 |
 | phone - +1 650 725 9046
 | email - pal@cs.stanford.edu
+|
+|
+| Alec Woo
+| Arch Rock Corporation
+| 501 2nd St. Ste 410
+| San Francisco, CA 94107-4132
+|
+| email - awoo@archrock.com
+|
+|
+| Sukun Kim
+| Samsung Electronics
+| 416 Maetan-3-dong, Yeongtong-Gu
+| Suwon, Gyeonggi 443-742
+| Korea, Republic of
+|
+| phone - +82 10 3065 6836
+| email - sukun.kim@samsung.com
 
 8. Citations
 ====================================================================
@@ -341,7 +385,7 @@ along the path.
        Self-Regulating Algorithm for Code Maintenance and Propagation
        in Wireless Sensor Networks." In Proceedings of the First USENIX
        Conference on Networked Systems Design and Implementation (NSDI), 2004.
-       
-
-
+.. [3] TEP 119: Collection.
+.. [4] Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, and Philip Levis.
+       "Four Bit Wireless Link Estimation." In Proceedings of the Sixth Workshop
+       on Hot Topics in Networks (HotNets VI), November 2007.
index 3a16cfe9128ce91d86f7327015a9af3ee91ba97e..b57e503668d1beaa8f08bba427c1695645ef9396 100644 (file)
@@ -5,8 +5,8 @@ The Link Estimation Exchange Protocol (LEEP)
 :TEP: 124 
 :Group: Network Protocol Working Group 
 :Type: Documentary
-:Status: Draft
-:TinyOS-Version: 2.x
+:Status: Final
+:TinyOS-Version: > 2.1
 :Author: Omprakash Gnawali
 
 :Draft-Created: 05-Feb-2006
@@ -34,36 +34,33 @@ links to the neighbors.
 Routing protocols often require bi-directional link qualities to
 compute the routes. Nodes can estimate the quality of the in-bound
 link from a neighbor by estimating the ratio of successfully received
-messages and the total transmitted messages. LEEP appends in-bound
-packet reception rate (PRR) estimates to packets. Other nodes hearing 
+messages to the total transmitted messages. LEEP appends in-bound
+packet reception rate (PRR) estimates to packets. Other nodes hearing
 these packets can combine the in-bound PRR values with their own
-in-bound values to compute bi-directional link quality.
+in-bound values to compute bi-directional link quality. Thus, LEEP is
+a discovery and link table bootstrapping mechanism. The link quality
+is often fine-tuned using different mechanisms.
+
+Link quality estimates obtained using LEEP are often used as
+bootstrapping values in the link quality table; data transmission
+statistics can later be used to make these estimates more accurate.
 
 2. Definitions
 ============================================================================
 
-2.1 Link Quality
---------------------------------------------------------------------
-
-The link quality between a directed node pair (A,B) is the probability
-that a packet transmitted by A will be successfully received by B. The
-bidirectional link quality of an undirected node pair (A,B) is the 
-product of the link quality of (A,B) and (B,A). This definition
-assumes independent link losses. It also includes the case when
-the link quality of (A,B) and (B,A) are different; this can occur
-due to local interference or noise.
-
-2.2 In-bound Link Quality
+2.1 In-bound Link Quality
 --------------------------------------------------------------------
 
 In a node pair (A,B), with B as the node of reference, in-bound link
 quality is a value in the range of 0 to 255 that describes the quality
-of the link from A to B estimated by B by counting the successfully
-received packets from A among all the transmitted packets or using
-link quality indicators such as LQI and RSSI provided by the radio on
-the node B, or some other methods.
-
-2.3 Out-bound Link Quality
+of the link from A to B estimated by B as the ratio of successfully
+received to all packets transmitted by A. Thus, in-bound link quality
+is the empirical probability that a packet will be successfully
+received on a given link. A value of 255 represents a probability of 1
+and a value of 0 represents a probability of 0 of successfully
+receiving a packet on a given link.
+
+2.2 Out-bound Link Quality
 --------------------------------------------------------------------
 
 In a node pair (A,B), with B as the node of reference, out-bound link
@@ -72,6 +69,17 @@ determine the out-bound link quality if A advertises its in-bound link
 qualities. LEEP is the protocol that is used to exchange the in-bound
 link qualities.
 
+2.3 Bi-directional Link Quality
+--------------------------------------------------------------------
+
+LEEP does not define or compute bi-directional link quality. LEEP
+provides a way to exchange sufficient information to compute in-bound
+and out-bound link qualities. These two link qualities can be used to
+compute the bi-directional link quality. Routing protocols often
+compute the bi-directional link quality of a node pair (A,B) as a
+function (product, min, etc.) of the link quality of (A,B) and (B,A).
+
+
 2.4 Link Information Entry
 --------------------------------------------------------------------
 
@@ -103,7 +111,17 @@ link quality from the transmitter. LEEP MUST transmit Link Information
 entries describing the in-bound link qualities for a subset of its
 neighbors. The Link Information entry on the LEEP frame allows the
 receiver node to find the out-bound link quality to the transmitter
-node identified by the data link source address.
+node identified by the data link source address. Thus, LEEP is also a
+way for nodes to discover new nodes and links in the network.
+
+Link quality estimation is inherently imperfect - data transmission
+and link quality estimation might be done at different timescales. The
+PRR for LEEP frames (broadcast) and data frames (unicast) might be
+different. So LEEP is better used as a link quality bootstrapping
+mechanism. The link quality estimate can be made more accurate later
+using data transmission statistics.
+
+
 
 3.3 LEEP Frame
 --------------------------------------------------------------------
@@ -179,6 +197,10 @@ the entries to be exchanged that could not fit in the previous LEEP
 frame. The LEEP frames are transmitted whenever the CTP [1]_ beacons,
 sent as a LEEP payload, are sent.
 
+Another reference implementation resides in
+``tinyos-2.x/tos/lib/net/4bitle``. This implementation is described in
+detail in [2]_.
+
 5. Author's Address
 ============================================================================
 
@@ -195,3 +217,6 @@ sent as a LEEP payload, are sent.
 ============================================================================
 
 .. [1] TEP 123: The Collection Tree Protocol.
+.. [2] Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, and Philip Levis.
+       "Four Bit Wireless Link Estimation." In Proceedings of the Sixth Workshop
+       on Hot Topics in Networks (HotNets VI), November 2007.
index f5c605c415794d7dbd149e73343b6818cc002142..66689ceab24d774fbea665f05474c3c9ae55a3c8 100644 (file)
@@ -60,7 +60,7 @@ Here is a list of allocations for TinyOS 2.1::
     0x74 - AM_LQI_DATA_MSG MultiHopLQI (Data packets)
     0x75 - AM_LQI_DEBUG MultiHopLQI (Debug messages)
 
-  * 0x60 - 0x62 are reserved for dissemination protocols [TEP_118]_
+  * 0x60 - 0x63 are reserved for dissemination protocols [TEP_118]_
     maintained by the Network Protocol Working Group.
 
     For Drip (''tos/lib/net/drip'')
@@ -70,6 +70,9 @@ Here is a list of allocations for TinyOS 2.1::
     For DIP (''tos/lib/net/dip'')
     0x62 - AM_DIP 
 
+    For DHV (''tos/lib/net/dhv'')
+    0x63 - AM_DHV
+
   * 0x50 - 0x54 are reserved for Deluge (''tos/lib/net/Deluge'')
     maintained by the Network Protocol Working Group.
 
@@ -79,6 +82,9 @@ Here is a list of allocations for TinyOS 2.1::
     0x53 - DELUGE_AM_FLASH_VOL_MANAGER (Flash volume manager)
     0x54 - DELUGE_AM_DELUGE_MANAGER (Deluge manger)
 
+  * 0x3D - TIMESYNC_AMTYPE for Packet Level Time Synchronization
+    (''TimeSyncMessageC'') reserved by the Core Working Group.
+
   * 0x3E - AM_TIMESYNCMSG for FTSP (''tos/lib/ftsp'') reserved by the
     Core Working Group.
 
@@ -90,12 +96,13 @@ Here is a list of allocations for TinyOS 2.1::
 ====================================================================
 
 | Omprakash Gnawali
-| Ronald Tutor Hall (RTH) 418 
-| 3710 S. McClintock Avenue
-| Los Angeles, CA 90089 
+| 318 Campus Drive, S255
+| Computer Science Department
+| Stanford University
+| Stanford, CA 94305
 |
-| phone - +1 213 821-5627
-| email - gnawali@usc.edu
+| phone - +1 650 725 6086
+| email - gnawali@cs.stanford.edu
 
 5. Citations
 ====================================================================
diff --git a/doc/txt/tep136.txt b/doc/txt/tep136.txt
new file mode 100644 (file)
index 0000000..03198b4
--- /dev/null
@@ -0,0 +1,291 @@
+================================
+Roadmap to an IP Stack in TinyOS
+================================
+
+:TEP: 136
+:Group: Network Protocol Working Group
+:Type: Informational
+:Status: Draft
+:TinyOS-Version: > 2.1
+:Author: Stephen Dawson-Haggerty, Matus Harvan, and Omprakash Gnawali
+
+Abstract
+============================================================================
+
+Recently, there has been renewed interest in the applicability of Internet
+Protocol-based networking for low power, embedded devices.  This interest is
+being driven by several sources.  One, emerging standards from the IETF are
+beginning to make it possible to design efficient, compatible
+implementations of IP for this class of resource-constrained device.  Two,
+there has been an emergence of a significant number of both open and closed IP
+embedded IP stacks which demonstrate the applicability of this model of
+networking.  Third, a set of recent academic papers have made the case that
+this network architecture is a significant research enabler and shown in more
+detail the structure of a full stack.
+
+In this TEP, we briefly explain how IP mechanisms map onto the well-studied
+problems of the sensor network community like collection routing and local
+aggregation.  Next, we discuss the current "state of the standards."  Finally,
+we propose a path for the adoption of IP within TinyOS.
+
+1. IP Requirements and Mechanisms 
+============================================================================
+
+There are two versions of IP: IPv4 (RFCXXX) and IPv6 (RFCXXX).  Previous
+studies have indicated that IPv6 is more applicable to the low-power, embedded
+space then IPv4 for various reasons; most standardization efforts have focused
+on adapting IPv6 to these devices.  Therefore, we consider only IPv6.
+
+
+1.1 IPv6 Routing
+----------------------------------------------------------------------------
+
+A central question for implementing IPv6 in sensor networks is what has become
+know as "route over" vs. "mesh under" in the IETF.  In mesh under networking,
+routing is done on layer two addresses, and every host is one hop from every
+other.  Although this is the most compatible with existing assumptions about
+subnet design, it leads to significant redundancies and inefficiencies in this
+space.  The alternative, so called route-over exposes the radio topology at
+the IP layer.  While not strictly compatible with some IPv6 mechanisms, this
+is becomming the favored approach since a single set of tools can be used to
+debug.  For the rest of this TEP we assume that route over is the model.
+
+There are a number of existing routing protocols for IPv6, some targeted at
+wireless links.  However, IPv6 itself does not require any particular routing
+protocol to be used with a domain; common choices in wired networks are OSPF
+and IS-IS.  Recent study in the IETF has indicated that existing protocols are
+probably not appropriate for this space [draft-ietf-roll-protocols-02], and so
+further work is needed on this point.  Existing protocols with TinyOS
+implementations such as DYMO or S4 may be appropriate for this task;
+collection and dissemination protocols like CTP or Drip are probably not
+directly applicable since they are address-free, although the insight gained
+from their implementations may be transferable.
+
+1.2 Addressing
+----------------------------------------------------------------------------
+
+The most well-known property of IPv6 is probably it's address length.  An IPv6
+address is 128 bits long.  Within this space, IPv6 defines unicast, anycast,
+and multicast address ranges; each of these ranges further have properties of
+their own.  For a full explaination of IPv6 addressing we refer the reader to,
+for example, [OReilly, RFC], we cover briefly some of the important details.
+
+1.2.1 Unicast Addressing
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Unicast addresses in IPv6 consist of two parts: the network identifier (the
+first 64 bits), and the interface identifier (the second).  The interface
+identifier is a flat space, and may be derived from the interface's MAC
+address, a random number, or other mechanism.  IPv6 contains mechanisms to
+ensure that the interface ID is unique within the subnet.  The network
+may be assigned using many different mechanisms, but some network identifiers
+are special.
+
+Unlike IPv4, each interface in IPv6 is multihomed: it is expected to have
+multiple IPv6 addresses.  When an interface is brought up, IPv6 contains
+mechanisms to configure the interface with a locally unique, non-routable
+address known as the link-local address.  This address has the network
+identifier fe80::, and can be used for communication between hosts in the same
+subnet.
+
+In a TinyOS IPv6 stack, this address range might be used to allow TinyOS nodes
+to communicate locally without routing, for instance to enable local
+aggregation.  If the TinyOS hosts can assign themselves link-local addresses
+derived from their IEEE802.15.4 16-bit short id, or full 64-bit EUID.  For
+instance, a node with short ID 16 might assign the address fe80::10 to its
+802.15.4 interface.  These addresses would not be routed; an IP stack would
+send directly to the short id 0x10 contained in the address.
+
+IPv6 also contains several mechanisms to allow a host to obtain a
+publicly-routable network identifier.  TinyOS hosts communicating with these
+addresses could contact nodes in other sensor networks or on the internet; the
+fact that they are multihomed allows them to use both public and link-local
+addresses simultaneously.
+
+1.2.2 Multicast Addressing
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+IPv6 contains a multicast address range; addresses beginning with the byte
+containing all ones (0xff) are multicast addresses.  Following this byte are
+four bits of flags and four bits of "scope".  For instance, scope 1 is
+node-local, and scope 2 is link local.  IPv6 defines many well-known multicast
+groups [http://www.iana.org/assignments/ipv6-multicast-addresses]; of most interest here are the "link-local all nodes" and "link
+local all-routers" addresses: ff02::1 and ff02::2, respectively.  Depending on
+weather TinyOS IP hosts are also IP routers, these addresses are effecitvely
+link-local broadcast addresses which might be mapped into the layer 2
+broadcast address (0xffff).  Thus IPv6 contains mechanisms for local
+broadcast.
+
+There is also a site-local scope defined in IPv6 (5) with a similar ff05::2
+address.  "Site local" is an administratively defined scope in IPv6, and might
+naturally consist of an entire sensor network.  Thus, sending to this address
+would correspond to disseminating a value to each node in the network and
+could be implemented with a trickle-based algorithm.
+
+Futhermore, the TinyOS community could develop additional conventions to
+provide and address for scoped flooding or delivery to nodes with particular
+capabilities.  A full IP multicast implementation within the sensor network
+could be used for many things including control applications or
+publish-subscribe network layers which have previously been special purpose.
+
+1.2.3 Anycast Addressing
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Anycast addresses indicate that the packet should be delivered to at least one
+host with the anycast address.  This seems initially similar to the model for
+collection routing such as MultiHopLQI or CTP, in that a collection report is
+delivered to a single root.  However, it is more likeley that those
+"collection roots" in an IP-based infrastructure are not actually the final
+destination for the data; they are likely to only be intermediate routers who
+send the data on to a final destination.  Therefore, while there may be
+applications for anycast addressing, we do not believe this addressing mode to
+be appropriate in the common case.
+
+1.3 IPv6 Configuration Mechanisms
+----------------------------------------------------------------------------
+
+As alluded to earlier, IPv6 contains two mechanisms to allow internet hosts to
+become associated with a public network identifier.  These methods are
+stateless autoconfiguration and DHCPv6.  Stateless autoconfiguration defines
+Router Solicitations and Router Advertisements.  A host joining a network
+sends router solicitations to the link-local all-routers address (ff02::2)
+using his link-local address as the source address.  Routers respond with a
+Router Advertisement containing, among other things, a public network
+identifier which the host may use.
+
+In a TinyOS IP implementation, router solicitations and advertisements might
+be used for default route selection on the hosts, as well as neighbor
+discovery.
+
+1.4 Extension Mechanisms
+----------------------------------------------------------------------------
+
+A common idiom in TinyOS is to provide "stacked" headers by implementing a
+series of components, all of which implement the Packet interface.  IPv6
+supports this a more flexible way with options headers.  These headers fall
+into one of two categories: hop-by-hop options headers and destination option
+headers.  These headers are chained together with small, two-octet common
+header fields which identifiy the header type of the next header, and the
+length of that options header.  This allows hosts to process a header chain
+even if they do not know how to interpret all of the options headers.
+
+These headers are commonly used for protocol options, or to piggyback data on
+outgoing packets.  For instance, a link estimator component could add an extra
+"link options" header to occasional outgoing packets as an options header,
+while avoiding the overhead when it is not necessary to do so.  This header
+architecture is significantly more flexible then the existing TinyOS packet
+architecture, although it does come at the slight cost of complexity.
+
+2. The State of the Standards
+============================================================================
+
+All of the previously defined mechanisms are well defined for IPv6 in various
+RFCs.  However, most nodes running TinyOS are significantly more
+resource-constrained then typical IPv6 hosts.  Thus, there is ongoing work on
+adapting these mechanisms to the characteristics of embedded devices.
+
+2.1 Header Compression
+----------------------------------------------------------------------------
+
+The first issue which must be addressed is the sheer size of the IPv6 header:
+40 octets.  Of this, 32 octets are the source and destination addresses of the
+packet.  The IETF has published RFC4944 which describes a header compression
+technique known as HC1.  However, this scheme has significant problems, most
+importantly the inability to take advantage of 16-bit short identifiers when
+available.  There have been a sequence of internet drafts proposing improved
+techinques such as HC1g, and HC.  The most recent version of these drafts is
+draft-hui-6lowpan-hc-02, and there are strong indications that the working
+group will depreciate HC1 from RFC4944 in the future.
+
+2.2 MTU
+----------------------------------------------------------------------------
+
+IPv6 requires a minimum link MTU of 1280 octets in RFCXXX.  Clearly, this is
+much larger then the IEEE802.15.4 link MTU of 127 octets.  RFC4944 defines 
+"layer 2.5" fragmentation which allow packets up to this MTU to be transfered
+over small MTU links.  While there are some issues have been raised with this
+scheme, it seems likely to remain relatively unaltered.
+
+2.3 Autoconfiguration
+----------------------------------------------------------------------------
+
+IPv6 stateless autoconfiguration as originally defined has some problems,
+expecially once a "route over" network topology is established; for instance,
+Duplicate Address Detection is likely to require some changes.  A subcomittee
+of the 6lowpan working group is currently investigating these issues is is
+likely to propose adaptation mechanisms but they are currently in flux.
+
+2.4 Routing
+----------------------------------------------------------------------------
+
+It is currently not possible to develop a standards-compliant routing layer,
+as the relevant standards do not exist.  Work in this direction is occuring in
+the Roll working group, but a full specification is likely some way off.
+
+3. The TinyOS Way
+============================================================================
+
+As the previous sections have shown, many sensor network abstractions map well
+into IPv6 mechanisms, with a significant gain in clarity of abstraction.
+However, standards are currently unavailable to specifiy exactly how this
+should be accomplished.  Therefor, our position is that TinyOS should move
+quickly to incorporate existing techinques and standards into an IPv6 stack
+where possible, while taking liberties with the standards when doing so
+improves performance or simplifies implementation.  Given that the standards
+themselves are in a state of flux, having an open implementation which
+demonstrates challenges and feasible mechaninisms is likely to be of
+significant value.
+
+The most important places where it may be necessary to move ahead of the
+standards are the routing; an IPv6 stack with no routing will not be as useful
+as one with it.  One open question is weather we choose a routing algorithm
+which functions in a completly decentralized fashion like AODV, OLSR, DYMO,
+S4, or many existing protocols or choose one which imposes more hierarchy on
+deployments.  We do note that existing standards like Zigbee and WirelessHART
+both contain multi-tier architectures with devices of differing capabilities.
+This has also been a common deployment model in many applications, but it
+limits the utility to places where this is possible.  The correct long-term
+answer is probably to support both types of routing.
+
+4. Conclusion
+============================================================================
+
+This document is meant to introduce readers to the ways in which IPv6
+mechanisms can be used in a TinyOS-based sensor network deployment, and how
+they relate to previous work.  It does not address any implementation issues,
+which will be presented in a later TEP.
+
+5. Authors
+============================================================================
+
+| Stephen Dawson-Haggerty
+| Computer Science Division
+| University of California, Berkeley
+| 410 Soda Hall
+| Berkeley, CA 94701
+| 
+| stevedh@eecs.berkeley.edu
+|
+|
+| Matus Harvan
+| Information Security
+| IFW C 48.1
+| ETH Zentrum
+| Haldeneggsteig 4
+| 8092 Zurich
+| Switzerland
+|
+| phone - +41 44 63 26876
+| email - mharvan@inf.ethz.ch
+|
+|
+| Omprakash Gnawali
+| Ronald Tutor Hall (RTH) 418 
+| 3710 S. McClintock Avenue
+| Los Angeles, CA 90089 
+|
+| phone - +1 213 821-5627
+| email - gnawali@usc.edu
+
+6. References
+============================================================================
diff --git a/doc/txt/tep137.txt b/doc/txt/tep137.txt
new file mode 100644 (file)
index 0000000..5aa6dde
--- /dev/null
@@ -0,0 +1,266 @@
+====================================================================
+Traffic Control
+====================================================================
+
+:TEP: 137
+:Group: Core Working Group 
+:Type: Documentary
+:Status: Draft
+:TinyOS-Version: 2.x
+:Author: David Moss, Mark Hays, and Mark Siner
+
+:Draft-Created: 3-Sept-2009
+:Draft-Version: $Revision$
+:Draft-Modified: $Date$
+:Draft-Discuss: TinyOS Developer List <tinyos-devel at mail.millennium.berkeley.edu>
+
+.. Note::
+
+   This memo documents a part of TinyOS for the TinyOS Community, and
+   requests discussion and suggestions for improvements.  Distribution
+   of this memo is unlimited. This memo is in full compliance with
+   TEP 1.
+
+Abstract
+====================================================================
+
+This memo proposes traffic control interfaces to be provided by an optional 
+traffic control layer integrated at the highest levels of communication
+stacks. These traffic control mechanisms are targeted to help improve acknowledgment
+success rate, energy efficiency, fairness, and routing reliability on 
+any wireless platform. The available reference implementation is a platform
+independent radio stack layer designed to consume a very small memory footprint.
+
+
+1. Introduction
+====================================================================
+
+As the traffic rate of a wireless sensor network increases, the probability
+of collision, dropped packets, and missed acknowledgments also increases, 
+even with sophisticated CSMA/CA implementations.
+
+It is important, especially in the case mesh networks, for packets to be 
+delivered reliably and acknowledgments to be returned successfully on a hop-by-
+hop basis. One method to improve reliability is to reduce the rate of 
+transmissions from each node within the network.
+
+Traffic Control has been in use for years in many different wired and wireless
+applications[1]_,[2]_,[3]_.  TinyOS already has traffic control
+mechanisms integrated directly into some networking libraries, such as CTP[4]_
+and Dissemination[5]_.  The use of Trickle[6]_ algorithms, also used 
+within CTP and Dissemination, further reduces the rate of traffic throughout a 
+network to improve delivery performance and prevent livelock. There has
+yet to be a centralized method of traffic control that throttles traffic
+generated from any component of a user's application.
+
+The traffic control interfaces proposed in this TEP are very basic, and are 
+intended to support many different traffic control implementations.
+Two interfaces assist the application layer in controlling behavior: 
+TrafficControl and TrafficPriority.  
+
+The reference implementation presented here is integrated as a optional and 
+generic radio stack layer (providing a Send and using a SubSend interface) and 
+uses acknowledgments to dynamically adjust the transmit throttle. Other traffic 
+control implementations could employ more sophisticated techniques to control 
+throughput, but likely at the cost of a larger memory footprint.
+
+The ultimate goal is to allow developers to use mesh networking protocols and/or
+their own protocols without having to worry about implementing any kind of
+traffic control timer mechanism for each separate component. 
+
+2. Desired Behavior
+====================================================================
+
+Ideally, a traffic control layer SHOULD attempt to balance the rate of 
+transmissions from a single node with the channel throughput capacity.
+This implies an adaptive control mechanism. If the channel is 
+busy, nodes should add delay between packets to let other nodes transmit.
+Similarly, if the channel is not busy, a node should be allowed access to
+the channel more often to prevent inefficient channel downtime.  Traffic
+control SHOULD NOT listen to the channel for long periods of time to determine
+the appropriate access rates, because that defeats the purpose of low power 
+communications layers used elsewhere.
+
+The traffic control implementation SHOULD have the option to be activated or 
+deactivated on a system-wide level as well as a packet level. This allows for 
+individual high or low priority packets. Traffic control SHOULD be deactivated 
+by default, until the application or networking layers explicitly enable it.
+
+Finally, the traffic control mechanism SHOULD be small in code size to fit 
+on the limited program memory available on most wireless platforms. There
+SHOULD NOT be additions or modifications to a packet's metadata structure 
+that enables or disables traffic control on a per-packet basis; 
+instead, per-packet priorities SHOULD be performed with a request/call back 
+procedure. This keeps RAM requirements low and can be optimized out at compile 
+time if those functions are not used.
+
+We also recommend any traffic control layer be implemented as an optional
+compile time add-on to a core radio stack or within the ActiveMessageC platform 
+communication stack definition. This allows applications that do not require
+traffic control to remove its memory footprint from the system.
+
+3. TrafficControlC Component Signature
+====================================================================
+
+The signature of TrafficControlC is RECOMMENDED as follows::
+
+  
+  configuration TrafficControlC {
+    provides {
+      interface Send;
+      interface TrafficControl;
+      interface TrafficPriority[am_id_t amId];
+    }
+    
+    uses {
+      interface Send as SubSend;
+    }
+  }
+
+The Send interface provided on top and SubSend interface used underneath
+allow the TrafficControlC component to be integrated as a generic layer
+within any radio stack.
+
+4. TrafficControl Interface
+====================================================================
+
+The TrafficControl interface allows the application layer to enable or
+disable traffic control from a system-wide level.  It also
+allows an application to set and get the current delay between packets.
+For most systems, we expect that the setDelay() and getDelay() commands may not be 
+used often and will most likely get optimized out at compile time; however, some
+systems may care to explicitly increase or decrease the delay between packets or 
+collect statistics on how the traffic control layer is performing.
+
+The TEP proposes the following TrafficControl interface::
+
+  
+  interface TrafficControl {
+  
+    command void enable(bool active);
+    
+    command void setDelay(uint16_t delay);
+    
+    command uint16_t getDelay();
+    
+  }
+
+5. TrafficPriority Interface
+====================================================================
+
+The TrafficPriority interface is parameterized by active message ID.  It is a
+simple request / call back interface that allows components in the application layer to 
+configure individual packets for priorities on a scale from 0 (lowest priority, default) to
+5 (highest priority, get the packet out immediately). There are several advantages 
+to this call back method. Metadata does not need to be added
+to the end of every message_t. Additionally, a component that captures a requestPriority(...)
+event is not required to adjust the priority as it would if the event returned 
+a value.
+
+When a packet enters the traffic control layer, and traffic control is
+enabled, the TrafficPriority interface MUST signal out the event
+requestPriority(...).  This event, with all the extra information it provides,
+allows the application layer to decide whether the packet is a high priority
+packet or not.  Calling the setPriority(uint8_t priority) command within the 
+requestPriority(...) event MAY adjust the traffic control mechanisms applied
+to the current packet.  To aid in the definition of priority, two definitions
+are available in TrafficControl.h::
+
+  
+  enum {
+    TRAFFICPRIORITY_LOWEST = 0,
+    TRAFFICPRIORITY_HIGHEST = 5,
+  };
+
+It is up to the traffic control implementation to define the meaning of each priority
+level. In the reference implementation, a priority of 0 
+is the default low priority level that employs the full traffic control delays.
+Anything above 0 in the reference implementation is considered to be at the
+highest priority.
+
+If no areas of the application layer care to change the
+packet's priority, a default event handler will capture the requestPriority(...)
+event and do nothing. This would result in all packets being sent at a low 
+priority with full traffic control mechanisms enforced.
+
+The TEP proposes the following TrafficPriority interface, to be provided as an 
+interface parameterized by AM type::
+  
+  interface TrafficPriority {
+  
+    event void requestPriority(am_addr_t destination, message_t \*msg);
+    
+    command void setPriority(uint8_t priority);
+    
+  }
+
+
+6. Reference Implementation
+====================================================================
+
+An implementation of the proposed traffic control layer can be found in the
+CCxx00 radio stack in 
+tinyos-2.x-contrib/blaze/tos/chips/ccxx00_addons/trafficcontrol, with
+interfaces located in 
+tinyos-2.x-contrib/blaze/tos/chips/ccxx00_single/interfaces and a dummy
+implementation located in
+tinyos-2.x-contrib/blaze/tos/chips/ccxx00_single/traffic.
+
+In this implementation, the default core radio stack (ccxx00_single) includes 
+an empty stub for traffic control. Users that wish to include the
+traffic control implementation in their systems simply override the default 
+stub component with the ccxx00_addons/trafficcontrol directory.  
+
+The reference implementation works as follows. All nodes start with a default
+of 4 seconds between each packet. Changes are made to the time between outbound
+packets only when a unicast packet is sent with the request for acknowledgment 
+flag set.  The reception of an acknowledgment is used as a basic indicator of 
+channel activity.  For each acknowledgment received, the amount of time between
+packets is decreased so the next packet will get sent faster.  For each dropped 
+acknowledgment, the amount of time between packets increases, causing the
+next packet to be sent later.  
+
+When the transmission rate reaches a boundary (1 second per packet per node
+fastest, 10 seconds per packet per node slowest), it is reset to the default 
+rate of 4 seconds per packet per node. This prevents nodes from unfairly 
+capturing the channel.
+
+Testing this traffic control layer in a congested test bed setting of 16 nodes
+with multiple hidden terminals resulted in the acknowledgment success rate 
+moving from 27-50% without traffic control to 90-100% with traffic control.
+The memory footprint increased by 260 bytes ROM / 16 bytes RAM with the 
+inclusion of the traffic control layer.
+
+
+5. Author Addresses
+====================================================================
+
+| David Moss
+| Rincon Research Corporation
+| 101 N. Wilmot Suite 101
+| Tucson AZ  85750
+| email: mossmoss at gmail dot com
+|
+| Mark Hays
+| Rincon Research Corporation
+| 101 N. Wilmot Suite 101
+| Tucson AZ  85750
+| email: mhh at rincon dot com
+|
+| Mark Siner
+| Rincon Research Corporation
+| 101 N. Wilmot, Suite 101
+| Tucson, AZ  85750
+| email: mks at rincon dot com
+
+
+
+6. Citations
+====================================================================
+.. [1] Bret Hull, Kyle Jamieson, Hari Balakrishnan. "Mitigating Congestion in Wireless Sensor Networks." In the Proceedings of the ACM Sensys Conference 2004
+.. [2] Wan, C.-Y., Eisenman, S., and Campbell, A. "CODA: Congestion Detection and Avoidance in Sensor Networks." In the Proceedings of the ACM Sensys Conference 2003
+.. [3] Woo, A., and Culler, D. "A Transmission Control Scheme for Media Access in Sensor Networks." In ACM MOBICOM 2001
+.. [4] Rodrigo Fonseca, Omprakash Gnawali, Kyle Jamieson, Sukun Kim, Philip Levis, and Alec Woo.. "TEP123: Collection Tree Protocol" 
+.. [5] Philip Levis and Gilman Tolle. "TEP118: Dissemination of Small Values." 
+.. [6] Philip Levis, Neil Patel, David Culler, and Scott Shenker. "Trickle: A Self-Regulating Algorithm for Code Maintenance and Propagation in Wireless Sensor Networks." In Proceedings of the First USENIX/ACM Symposium on Networked Systems Design and Implementation (NSDI 2004).
+
index 818aa36cdb14ed4bc21a7e0b91347de24628b573..6a3d0cc69e37fe041d255e0fd333ba3d170656a5 100644 (file)
@@ -101,7 +101,7 @@ Directory structure
        chip-independent.
     - `tos/chips/`.  Contains code specific to particular chips and to
        chips on particular platforms.
-    - `tos/libs/`.  Contains interfaces and components which extend the
+    - `tos/lib/`.  Contains interfaces and components which extend the
        usefulness of TinyOS but which are not viewed as essential to its
        operation.  Libraries will likely contain subdirectories.
     - `apps/`, `apps/demos`, `apps/tests`, `apps/tutorials`.  Contain
@@ -110,7 +110,7 @@ Directory structure
   - It is not necessary that packages other than the core break up their
     components and their interfaces.  The core should allow overrides of
     components fairly easily however.
-  - Each directory should have a README describing its purpose.
+  - Each directory should have a README.txt describing its purpose.
 
 
 Language Conventions
index 7e5d1e3bd7e8826885b18768845552c232f2b88a..39009d286ac2e59781a75de81351e0b557bae1f9 100644 (file)
@@ -5,8 +5,8 @@ Active Message ID Allocation for Network Protocols and Applications
 :TEP: 4
 :Group: Network Protocol Working Group 
 :Type: Best Current Practice
-:Status: Draft
-:TinyOS-Version: 2.x
+:Status: Final
+:TinyOS-Version: > 2.1
 :Author: Omprakash Gnawali
 
 :Draft-Created: 07-May-2008
diff --git a/licenses/INTEL-LICENSE.txt b/licenses/INTEL-LICENSE.txt
new file mode 100644 (file)
index 0000000..2ac0257
--- /dev/null
@@ -0,0 +1,28 @@
+Intel Open Source License 
+
+Copyright (c) 2002-2009 Intel Corporation 
+All rights reserved. 
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+       Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+       Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+    Neither the name of the Intel Corporation nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE INTEL OR ITS
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/overall-todo.txt b/overall-todo.txt
deleted file mode 100644 (file)
index 55e2545..0000000
+++ /dev/null
@@ -1,119 +0,0 @@
-nesC: 
-- David Gay's todo list
-- everyone: use, report problems, improvement requests (minor only, please)
-
-tools:
-- select, patch, build, package tools (Kristin)
-  Java, cygwin, avr+msp gcc+gdb+binutils+libc, graphviz, avarice
-  support using JREs rather than only JDKs
-- javax.comm replacement (Cory)
-- build-system (tools/make) (Cory)
-
-packaging:
-- cleanup the tinyos tools story (tinyos-1.x/tools), make into cleanly
-  compilable + installable package
-    initial setup: Phil B.
-- cleanup our jar story (aka, no more giant CLASSPATH)
-  drop useless stuff, merge into single jar?
-- tinyos RPMs should come with compiled .class files (see JRE requirement)
-  (alternately, they could all be placed in the single jar file...)
-- source vs binary rpms? (i.e., provide binary-only rpms if possible)
-
-regression testing:
-- from 1.2 (Ion)
-
-TinyOS core (platform-independent):
-- booting (Phil L.)
-- scheduler (Phil L.)
-- routing
-  - protocols, implementations
-- SNMS (Gil)
-- Deluge (Jonathan)
-- OSKI (Phil L.)
-- protocol stack
-- tinyos 1.x compatibility layer
-
-Apps:
-- tests
-- tutorial apps (see tutorial)
-- surge-like
-- TOSBase
-
-Tutorial:
-- update, write apps, you name it
-
-mica2/mica2dot/micaz:
-- booting (Martin)
-- adc (Hu)
-- timer (Martin)
-- storage (David G.)
-- hardware id (Martin)
-- built-in sensors [dropped]
-
-storage:
-- at45db (David G.)
-- stm25p (Jonathan)
-- intel mote (Lama)
-
-csma radio:
-- cc1000 (Joe, David G.???)
-- cc2420 (Joe)
-- infineon (TU Berlin)
-
-security:
-- cc1000, tinysec
-- cc2420
-
-buses:
-- i2c (Joe: doc+msp430) (need: other platforms)
-- spi (Joe: doc+msp430) (need: other platforms?)
-- bus sharing/allocation (Joe, Vlado?)
-
-msp430:
-- booting (done)
-- adc (TU Berlin)
-- timer (Cory)
-
-telos a/b:
-- booting
-- hardware id (Gil)
-- built-in sensors
-
-eyes:
-- booting
-- hardware id
-
-intel mote 2:
-- booting (Phil B.)
-- timer
-- storage (Lama)
-- hardware id
-
-sensor boards:
-- micasb
-- basicsb
-- any others?? (mts400 (weather), mda300ca (data ack), telos?, eyes?)
-
-PC-side java:
-- guis for standard apps
-- net.tinyos.message (mig-support)
-- net.tinyos.packet (r/w TinyOS packets)
-- net.tinyos.mcenter
-- net.tinyos.sf (serial forwarder)
-- net.tinyos.sim (tossim)
-- net.tinyos.tools (basic user tools)
-- net.tinyos.util (utility classes)
-
-PC-side other:
-- XML mig / ncg-like (based on new nesC attribute stuff?)
-- matlab
-- C support for:
-  - serial protocol (over serial ports and tcp sockets)
-  - serial forwarder protocol (over tcp sockets)
-  - serial forwarder
-  - simple listening
-  - mig / ncg
-- other-language support for:
-  - serial forwarder protocol (over tcp sockets)
-  - mig / ncg
-  - which languages? (python, perl?)
index a8b4d97485a67f787be0b7d47007156524a27293..b5d7753aa2119be9c2b2db3736c44c9d4c62969f 100644 (file)
@@ -1,5 +1,25 @@
 These release notes are as of: $Date$
 
+Current:
+  Added support for automatic default LPL interval
+  Added platform-indepdent TOS_SLEEP_NONE for McuPowerOverride
+  Added support for mulle platform
+  Added support for epic platform
+  Added support for shimmer2 platform
+  Added DHV dissemination protocol in lib/net/dhv
+  Added 6lowpan/IP support in lib/net/blip
+  Improved CTP forwarder code to save code and RAM
+  Improved MSP430 sleep code to default to LPM4
+  Improved TOSSIM PRR curve to prevent very low SNR packets
+  Improved Queue performance by changing % to inequality test
+  Improved TOSThreads tutorials and documentation
+  Improved python sdk
+  Refactored AM layer to better support 6lowpan
+  Fixed TOSSIM bug where nodes could receive while transmitting
+  Fixed TOSSIM ack bug for nodes that change their AM id at runtime
+  Fixed Trickle bugs that could cause timers to fire slightly off 
+  Fixed Pool bug that did not allow large (> 127 element) pools
+
 2.1:
   Added support for iris platform
   Added support for shimmer platform
index 6c48f9a0522bdfc1c972d011912e5a3ffcb55a86..6850fb1376b36c179da878bc4452a0f29c4eab1b 100644 (file)
@@ -49,7 +49,9 @@ TINYOS_MAKELOCAL ?= $(TINYOS_MAKE_PATH)/Makelocal
 TINYOS_MAKEDEFAULTS ?= $(TINYOS_MAKE_PATH)/Makedefaults
 
 #  Allow users to specify additional directories to find TOSMake files.
-TOSMAKE_PATH += $(TINYOS_MAKE_PATH)
+TOSMAKE_TEMP_PATH := $(TOSMAKE_PATH)
+TOSMAKE_PATH = $(TINYOS_MAKE_PATH) 
+TOSMAKE_PATH += $(TOSMAKE_TEMP_PATH)
 
 #  Save makecmdgoals (a read only var) to goals so that we can modify it.
 GOALS += $(MAKECMDGOALS)
diff --git a/support/make/avr/avr-studio-debug.extra b/support/make/avr/avr-studio-debug.extra
new file mode 100644 (file)
index 0000000..e77ed8d
--- /dev/null
@@ -0,0 +1,23 @@
+#-*-Makefile-*- vim:syntax=make
+#$Id$
+
+BUILD_DEPS = srec tosimage bytes $(POST_BUILD_EXTRA_DEPS) buildelf
+APPC_WINPATH = $(BUILDDIR)/app-winpath.c
+MAIN_ELF = $(BUILDDIR)/main.elf
+
+# no inlining or optimizations
+OPTFLAGS += -O0 -fnesc-no-inline
+
+# produce dwarf-2 debug information for AVR Studio
+OPTFLAGS += -gdwarf-2
+
+# we use ncc to invoke gcc thus need to allow dollars in identifiers
+#OPTFLAGS += -fdollars-in-identifiers
+
+# alternatively, we can use a different separator
+PFLAGS += -fnesc-separator=__
+
+buildelf: FORCE
+       @echo "    building ELF output $(MAIN_ELF) for debugging in AVR Studio"
+       @perl -pe 's/#(.*)\"(.*)\"/ "#$$1\"".`cygpath -ma $$2`."\""/e; s/\n\"/\"/;' $(BUILDDIR)/app.c > $(APPC_WINPATH)
+       @$(NCC) -o $(MAIN_ELF) $(NCC_SAFE_TINYOS_FLAGS) $(OPTFLAGS) $(PFLAGS) $(CFLAGS) $(APPC_WINPATH) $(LIBS) $(LDFLAGS)
index 03b089ffd7157892e2ff36c8fee23c6cdf1c9fbf..a8c5d025884e010d877fcdd857d93649df303bba 100644 (file)
@@ -7,13 +7,12 @@ define AVR_HELP
 
    debug    : compile with minimal optimization and debug symbols
    debugopt : compile with debug symbols
-   xnp      : compile for network programming
 
  Programmer options:
 
    dapa         : (default) use parallel port programmer
    mib510,<dev> : use MIB510/MIB520 serial port programming board at port <dev>
-   eprb,<host> : use EPRB at hostname <host>
+   eprb,<host> : use EPRB (MIB600) at hostname <host>
    avrisp,<dev> : use AVRISP serial programmer at port <dev>
 
    The dev or host parameter for the programmer option need not be specified,
@@ -24,7 +23,7 @@ endef
 HELP += $(AVR_HELP)
 
 ifdef MAKE_DEPUTY_FLAG
-        NCC_SAFE_TINYOS_FLAGS = -DSAFE_TINYOS -fnesc-deputy -fnesc-deputy-args='-I$(TOSDIR)/lib/safe/include --FLIDs=build/$(PLATFORM)/flids.txt --envmachine -DSAFE_TINYOS --nolib ' $(TOSDIR)/lib/safe/avr/fail.c 
+        NCC_SAFE_TINYOS_FLAGS = -DSAFE_TINYOS -I$(TOSDIR)/lib/safe -fnesc-deputy -fnesc-deputy-args='-I$(TOSDIR)/lib/safe/include --FLIDs=build/$(PLATFORM)/flids.txt --envmachine -DSAFE_TINYOS --nolib '
 else
         NCC_SAFE_TINYOS_FLAGS =
 endif
@@ -36,11 +35,13 @@ PROGRAMMER ?= uisp
 NCC = ncc
 LIBS = -lm
 
-AMADDR = ActiveMessageAddressC\$$addr
-# Uncomment the next two lines if you have a toolchain without the dollar sign
-# patch. This needs nesc 1.2.8 or newer (1.2.9 is recommended).
-#PFLAGS += -fnesc-separator=__
-#AMADDR = ActiveMessageAddressC__addr
+# Use __ as the separator - requires nesC 1.2.9 or later
+ifneq ($(filter sim,$(GOALS)),sim)
+ifneq ($(filter sim-sf,$(GOALS)),sim-sf)
+       PFLAGS += -fnesc-separator=__
+endif
+endif
+AMADDR = ActiveMessageAddressC__addr
 BUILDDIR ?= build/$(PLATFORM)
 MAIN_EXE = $(BUILDDIR)/main.exe
 MAIN_SREC = $(BUILDDIR)/main.srec
@@ -67,6 +68,9 @@ else
 endif
 
 ifeq ($(PROGRAMMER),avrdude)
+  ifeq ($(findstring Darwin, $(shell uname)), Darwin)
+    AVRDUDE_CONF ?= /opt/local/etc/avrdude.conf
+  endif
   AVRDUDE_CONF ?= /etc/avrdude/avrdude.conf
   ifeq ($(shell [ -f /bin/cygwin1.dll ] && echo cygwin),cygwin)
     AVRDUDE_CONF := $(shell cygpath -m $(AVRDUDE_CONF))
@@ -141,6 +145,11 @@ exe0: builddir $(BUILD_EXTRA_DEPS) FORCE
        $(NCC) -o $(MAIN_EXE) $(NCC_SAFE_TINYOS_FLAGS) $(OPTFLAGS) $(PFLAGS) $(CFLAGS) $(WIRING_CHECK_FLAGS) $(COMPONENT).nc $(LIBS) $(LDFLAGS)
 ifdef WIRING_CHECK_FILE
        @nescc-wiring $(WIRING_CHECK_FILE)
+endif
+ifdef STACK_CHECK
+       @echo
+       @-tos-ramsize $(PLATFORM) $(MAIN_EXE)
+       @echo
 endif
        @echo "    compiled $(COMPONENT) to $(MAIN_EXE)"
 
index 875cb329d6065e1374f9612525cbe9fc71349ab5..d0911ca72718fdaf85add9319d25267851fddc80 100644 (file)
@@ -13,7 +13,7 @@ ifeq ($(PROGRAMMER),avrdude)
         BOOTLOADER_IMG := $(shell cygpath -m $(BOOTLOADER_IMG))
       endif
     endif
-    PROGRAMMER_FLAGS = -cstk500 -P$(MIB510) -U hfuse:w:$(AVR_FUSE_H):m $(PROGRAMMER_PART) $(PROGRAMMER_EXTRA_FLAGS) $(PROGRAMMER_EXTRA_FLAGS_AVRISP)
+    PROGRAMMER_FLAGS = -cstk500 -P$(AVRISP) -U hfuse:w:$(AVR_FUSE_H):m $(PROGRAMMER_PART) $(PROGRAMMER_EXTRA_FLAGS) $(PROGRAMMER_EXTRA_FLAGS_AVRISP)
     PROGRAMMER_INSTALL_SREC_FLAGS = -U flash:w:$(INSTALL_SREC):a
     PROGRAMMER_INSTALL_BOOTLOADER_FLAGS = -V -D -U flash:w:$(BOOTLOADER_IMG):a
 endif
diff --git a/support/make/avr/avrispmkii.extra b/support/make/avr/avrispmkii.extra
new file mode 100644 (file)
index 0000000..6097dc1
--- /dev/null
@@ -0,0 +1,31 @@
+#-*-Makefile-*- vim:syntax=make
+#$Id$
+
+ifeq ($(AVRISPMKII),)
+$(error AVRISPMKII must be defined, try "make $(TARGETS) help")
+endif
+
+PROGRAM = avrispmkii
+
+ifeq ($(PROGRAMMER),avrdude)
+    ifdef BOOTLOADER_IMG
+      ifeq ($(shell [ -f /bin/cygwin1.dll ] && echo cygwin),cygwin)
+        BOOTLOADER_IMG := $(shell cygpath -m $(BOOTLOADER_IMG))
+      endif
+    endif
+    PROGRAMMER_FLAGS = -cavrispmkII -P$(AVRISPMKII) -U hfuse:w:$(AVR_FUSE_H):m $(PROGRAMMER_PART) $(PROGRAMMER_EXTRA_FLAGS) $(PROGRAMMER_EXTRA_FLAGS_AVRISPMKII)
+    PROGRAMMER_INSTALL_SREC_FLAGS = -U flash:w:$(INSTALL_SREC):a
+    PROGRAMMER_INSTALL_BOOTLOADER_FLAGS = -V -D -U flash:w:$(BOOTLOADER_IMG):a
+endif
+
+ifeq ($(PROGRAMMER),uisp)
+    $(error uisp is not supported, please use avrdude")
+endif
+
+program: FORCE
+       @echo "    installing $(PLATFORM) binary using avrispmkii"
+       $(PROGRAMMER) $(PROGRAMMER_FLAGS) $(PROGRAMMER_INSTALL_SREC_FLAGS)
+
+program_bl: FORCE
+       @echo "    installing $(PLATFORM) bootloader using avrispmkii"
+       $(PROGRAMMER) $(PROGRAMMER_FLAGS) $(PROGRAMMER_INSTALL_BOOTLOADER_FLAGS)
index 974b0e26cc521ad248c375b7adf0ba58be9acfa2..a7c9376b34c75782e33b85d005b3fc5444ca96b8 100644 (file)
@@ -8,6 +8,9 @@ endif
 PROGRAM = mib510
 
 ifeq ($(PROGRAMMER),avrdude)
+    ifeq ($(shell [ -f /bin/cygwin1.dll ] && echo cygwin),cygwin)
+      MIB510 := '\\.\$(MIB510)'
+    endif
     ifdef BOOTLOADER_IMG
       ifeq ($(shell [ -f /bin/cygwin1.dll ] && echo cygwin),cygwin)
         BOOTLOADER_IMG := $(shell cygpath -m $(BOOTLOADER_IMG))
diff --git a/support/make/avr/xnp.extra b/support/make/avr/xnp.extra
deleted file mode 100644 (file)
index f1543bc..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-#-*-Makefile-*- vim:syntax=make
-#$Id$
-
-# This is for network reprogramming
-# If XNP is an extra, add the network reprogramming related files
-# to the search path and generate a timestamp to make each build unique.
-XNP_DIR := $(TOSDIR)/lib/Xnp
-PFLAGS := -I$(XNP_DIR) $(shell $(XNP_DIR)/ident.pl .ident_install_id $(COMPONENT)) $(PFLAGS)
-
diff --git a/support/make/blip.extra b/support/make/blip.extra
new file mode 100644 (file)
index 0000000..d3deaca
--- /dev/null
@@ -0,0 +1,33 @@
+# -*- makefile -*-
+
+# radio stack defs
+PFLAGS += -DPACKET_LINK -DDEF_MEMCPY
+PFLAGS += -DENABLE_SPI0_DMA -DBLIP_MULTICAST
+PFLAGS += -DCC2420_HW_ACKNOWLEDGEMENTS
+
+ifdef BLIP_L2_MTU
+       PFLAGS += -DTOSH_DATA_LENGTH=$(BLIP_L2_MTU)
+else
+       PFLAGS += -DTOSH_DATA_LENGTH=102
+endif
+
+ifndef LOWPAN_ROOT
+  LOWPAN_ROOT=$(TOSROOT)
+endif
+
+PFLAGS+=-I$(TOSROOT)/tos/lib/net/
+PFLAGS+=-I$(LOWPAN_ROOT)/support/sdk/c/blip/lib6lowpan/
+PFLAGS+=-I$(LOWPAN_ROOT)/support/sdk/c/blip/libtcp/
+PFLAGS+=-I$(LOWPAN_ROOT)/tos/lib/net/blip/
+PFLAGS+=-I$(LOWPAN_ROOT)/tos/lib/net/blip/interfaces/ 
+PFLAGS+=-I$(LOWPAN_ROOT)/tos/lib/net/blip/nwprog/
+PFLAGS+=-I$(LOWPAN_ROOT)/tos/lib/net/blip/shell/
+PFLAGS+=-I$(LOWPAN_ROOT)/tos/lib/net/blip/serial/
+PFLAGS+=-I$(LOWPAN_ROOT)/tos/lib/net/blip/platform/
+
+PFLAGS+=$(LOWPAN_ROOT)/support/sdk/c/blip/lib6lowpan/lib6lowpan.c 
+PFLAGS+=$(LOWPAN_ROOT)/support/sdk/c/blip/lib6lowpan/lib6lowpanIP.c
+PFLAGS+=$(LOWPAN_ROOT)/support/sdk/c/blip/lib6lowpan/lib6lowpanFrag.c
+PFLAGS+=$(LOWPAN_ROOT)/support/sdk/c/blip/lib6lowpan/in_cksum.c
+PFLAGS+=$(LOWPAN_ROOT)/support/sdk/c/blip/lib6lowpan/ip_malloc.c
+PFLAGS+=$(LOWPAN_ROOT)/tos/lib/net/blip/table.c
index 134795806dd83960698600c19b9d3762294e3176..f67069e3f2e78f16f902663465d6edb8c18df3fd 100644 (file)
@@ -5,3 +5,4 @@ clean: FORCE
        rm -rf build $(CLEAN_EXTRA) pp
        rm -rf _TOSSIMmodule.so TOSSIM.pyc TOSSIM.py app.xml simbuild
        rm -rf VolumeMapC.nc
+       rm -f $(COMPONENT).cmap $(COMPONENT).dot $(COMPONENT).html $(COMPONENT).png
index cb50e5f788b9559f03dd0e3e1fdfa8b3129ea1f5..e8b978acef06ad73dfc953ecf6e2fdaa677222db 100644 (file)
@@ -3,6 +3,7 @@
 
 #Get all the normal include directories for a threads build
 $(call TOSMake_include,threads.extra)
+PFLAGS += -DCTHREADS
 
 #Include directories required specifically for cthreads builds
 THREADS_CSYSTEM_DIR = $(TOS_THREADS_DIR)/csystem
index e22a40d7e1a2860cbb8e6bcbbb0c547d219d9038..02e3ee844239d9154857022f206b10f9f0de454d 100644 (file)
@@ -6,6 +6,7 @@ BUILD_DEPS = dynthreads_all
 
 #Get all the normal include directories for a cthreads build
 $(call TOSMake_include,cthreads.extra)
+PFLAGS += -DDYNTHREADS
 
 #Stuff to build dynamically loadable binary
 DYNLOAD_CFILE = $(TOSTHREAD_MAIN_PATH)
@@ -30,9 +31,15 @@ dynthreads_build: dynthreads_builddir build_storage
        $(DYNLOAD_OBJCOPY_COMMAND)
        $(DYNLOAD_GENTOS_COMMAND)
        
+ifneq ($(shell uname),Darwin)
+dynthreads_all: dynthreads_build
+       @echo "            $(shell stat -t $(DYNLOAD_TOSFILE) | perl -lane 'print $$F[1];') bytes in BINARY"
+       @echo "    writing TOS image"
+else
 dynthreads_all: dynthreads_build
        @echo "            $(shell stat -F $(DYNLOAD_TOSFILE) | perl -lane 'print $$F[4];') bytes in BINARY"
        @echo "    writing TOS image"
+endif
 
 dynthreads_builddir:
        mkdir -p $(BUILDDIR)
diff --git a/support/make/epic.target b/support/make/epic.target
new file mode 100644 (file)
index 0000000..c040c96
--- /dev/null
@@ -0,0 +1,27 @@
+#-*-Makefile-*-
+#$Id$
+
+PLATFORM ?= epic
+
+# Disable MSP430 hardware multiply because it makes MSPGCC die
+PFLAGS += -mdisable-hwmul
+# OPTFLAGS += -O
+
+# Default BSL assumes telosb-like programming interface
+MSP_BSL ?= tos-bsl
+MSP_BSL_FLAGS = --telosb
+
+VOLUME_FILE = volumes-at45db.xml
+VOLUME_ALLOCATOR ?= tos-storage-at45db
+
+ifdef CC2420_CHANNEL
+PFLAGS += -DCC2420_DEF_CHANNEL=$(CC2420_CHANNEL)
+endif
+
+# Include the epic-specific targets
+$(call TOSMake_include_platform,epic)
+# Include the msp extra targets
+$(call TOSMake_include_platform,msp)
+
+epic: $(BUILD_DEPS)
+       @:
diff --git a/support/make/epic/digi.extra b/support/make/epic/digi.extra
new file mode 100644 (file)
index 0000000..fdaa280
--- /dev/null
@@ -0,0 +1 @@
+MSP_BSL_FLAGS = --slow --swap-reset-test --invert-reset --invert-test
\ No newline at end of file
diff --git a/support/make/epic/epic.rules b/support/make/epic/epic.rules
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/support/make/epic/miniprog.extra b/support/make/epic/miniprog.extra
new file mode 100644 (file)
index 0000000..1cc4b8e
--- /dev/null
@@ -0,0 +1,5 @@
+#-*-Makefile-*-
+#$Id$
+
+# Special flags for Epic USB Mini Programmer
+MSP_BSL_FLAGS = --swap-reset-test --invert-reset --invert-test
index c0149bcdc7369cf2018078073167cc8648f3f1af..7fd9d64345f8ed3dc6cfd161b989de1d22437e3f 100644 (file)
@@ -5,11 +5,6 @@ PLATFORM = iris
 SENSORBOARD ?= micasb
 PROGRAMMER ?= avrdude
 
-AVRGCC_SUPPORTS_ATM1281 = $(shell avr-gcc --target-help 2>&1 | grep -c atmega1281)
-ifneq ($(AVRGCC_SUPPORTS_ATM1281),1)
-  $(error Found avr-gcc with no ATMega1281 support. For details on upgrading your toolchain, please see "http://www.isis.vanderbilt.edu/projects/NEST/tinyos-2.x-iris/doc/html/install-tinyos-iris.html")
-endif
-
 ifeq ($(PROGRAMMER),avrdude)
   PROGRAMMER_PART ?= -pm1281 -U efuse:w:0xff:m
 endif
diff --git a/support/make/m16c62p/crt.S b/support/make/m16c62p/crt.S
new file mode 100755 (executable)
index 0000000..14ea172
--- /dev/null
@@ -0,0 +1,196 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Per Lindgren
+ * @author Johan Eriksson
+ * @author Johan Nordlander
+ * @author Simon Aittamaa
+ */
+.set PM0, 0x04
+.set PRCR, 0x0a
+
+.text
+       .global __vector_default
+
+       .extern _main
+
+.section .init0,"ax",@progbits
+       .global _start
+
+_start:
+       /* Setup processor mode, single chip mode, and stack pointers */
+       ldc     #_istack, isp
+       mov.b   #0x02, PRCR
+       mov.b   #0x00, PM0
+       mov.b   #0x00, PRCR
+
+       /* Setup the FLG register to some sane defaults. */
+       ldc             #0, flg
+       fset    u
+       ldc     #_ustack, sp
+
+       /* Setup interrupt vector. */
+       ldc             #%hi16(_vectors_variable), intbh
+       ldc             #%lo16(_vectors_variable), intbl
+
+       /* Copy .data. */
+       mov.b   #%hi8(__data_start), r1h
+       mov.w   #%lo16(__data_start), a0
+       mov.w   #__ram_start, a1
+       mov.w   #__data_size, r3
+       smovf.b
+
+       /* Zero out .bss. */
+       mov.b   #0x00, R0L
+       mov.w   #__bss_size, r3
+       mov.w   #__bss_start, a1
+       sstr.b
+
+       /* Enter main(). */
+       jsr.a   _main
+
+       /* In case we return, should realy generate a reset :/ */
+       jmp.b   0
+
+/* We should probably not get here. */
+__vector_default:
+       jmp.a   __vector_default
+
+/* Fixed hardware vector table. */
+.section .vectors_fixed, "a",@progbits
+
+.size  _vectors_fixed, 36
+.type  _vectors_fixed, @object
+
+_vectors_fixed:
+
+.long  0 /* Undefined Instruction. */
+.long  0 /* Overflow INTO Instruction. */
+.long  0 /* BRK Instruction.*/
+.long  0 /* Address Match Interupt. */
+.long  0 /* Single Step Interrupt. */
+.long  0 /* Watchdog, Oscillation, Voltage Interrupt. */
+.long  0 /* DBC. */
+.long  0 /* NMI. */
+.long  _start /* Reset. */
+
+
+/* Boot args for tosboot. */
+.section .boot_args, "a",@progbits
+
+.size  _boot_args, 8
+.type  _boot_args, @object
+
+_boot_args:
+
+.long  0xFFFFFFFF 
+.long  0xFFFFFFFF
+
+/* Variable vector table. */
+.section .vectors_variable
+
+.size _vectors_variable, 256
+.type _vectors_variable, @object
+
+_vectors_variable:
+
+.long  __vector_0
+.long  __vector_1
+.long  __vector_2
+.long  __vector_3
+.long  __vector_4
+.long  __vector_5
+.long  __vector_6
+.long  __vector_7
+.long  __vector_8
+.long  __vector_9
+.long  __vector_10
+.long  __vector_11
+.long  __vector_12
+.long  __vector_13
+.long  __vector_14
+.long  __vector_15
+.long  __vector_16
+.long  __vector_17
+.long  __vector_18
+.long  __vector_19
+.long  __vector_20
+.long  __vector_21
+.long  __vector_22
+.long  __vector_23
+.long  __vector_24
+.long  __vector_25
+.long  __vector_26
+.long  __vector_27
+.long  __vector_28
+.long  __vector_29
+.long  __vector_30
+.long  __vector_31
+.long  __vector_32
+.long  __vector_33
+.long  __vector_34
+.long  __vector_35
+.long  __vector_36
+.long  __vector_37
+.long  __vector_38
+.long  __vector_39
+.long  __vector_40
+.long  __vector_41
+.long  __vector_42
+.long  __vector_43
+.long  __vector_44
+.long  __vector_45
+.long  __vector_46
+.long  __vector_47
+.long  __vector_48
+.long  __vector_49
+.long  __vector_50
+.long  __vector_51
+.long  __vector_52
+.long  __vector_53
+.long  __vector_54
+.long  __vector_55
+.long  __vector_56
+.long  __vector_57
+.long  __vector_58
+.long  __vector_59
+.long  __vector_60
+.long  __vector_61
+.long  __vector_62
+.long  __vector_63
diff --git a/support/make/m16c62p/debug.extra b/support/make/m16c62p/debug.extra
new file mode 100755 (executable)
index 0000000..b02de82
--- /dev/null
@@ -0,0 +1,4 @@
+#-*-Makefile-*- vim:syntax=make
+
+OPTFLAGS = -O1 -g -fnesc-no-inline
+
diff --git a/support/make/m16c62p/debugopt.extra b/support/make/m16c62p/debugopt.extra
new file mode 100755 (executable)
index 0000000..d150e3f
--- /dev/null
@@ -0,0 +1,4 @@
+#-*-Makefile-*- vim:syntax=make
+
+OPTFLAGS += -g
+
diff --git a/support/make/m16c62p/install.extra b/support/make/m16c62p/install.extra
new file mode 100755 (executable)
index 0000000..db314be
--- /dev/null
@@ -0,0 +1,10 @@
+#-#-Makefile-#- vim:syntax=make
+
+NODEID = $(INSTALL)
+BUILD_DEPS = srec tosimage bytes $(POST_BUILD_EXTRA_DEPS) setid program delsetid
+
+ifdef BOOTLOADER
+  ifeq ($(BOOTLOADER),tosboot)
+    BUILD_DEPS += program_bl
+  endif
+endif
diff --git a/support/make/m16c62p/m16c.x b/support/make/m16c62p/m16c.x
new file mode 100755 (executable)
index 0000000..a53e1a2
--- /dev/null
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Per Lindgren
+ * @author Johan Eriksson
+ * @author Johan Nordlander
+ * @author Simon Aittamaa
+ */
+
+ENTRY(_start)
+
+MEMORY {
+       ram (rw) : o = 0x0000400, l = 31k
+       flash (rx) : o = 0x00a0000, l = 384k
+}
+
+/* Provide any vector symbols not defined. */
+PROVIDE(__vector_0 = __vector_default);
+PROVIDE(__vector_1 = __vector_default);
+PROVIDE(__vector_2 = __vector_default);
+PROVIDE(__vector_3 = __vector_default);
+PROVIDE(__vector_4 = __vector_default);
+PROVIDE(__vector_5 = __vector_default);
+PROVIDE(__vector_6 = __vector_default);
+PROVIDE(__vector_7 = __vector_default);
+PROVIDE(__vector_8 = __vector_default);
+PROVIDE(__vector_9 = __vector_default);
+PROVIDE(__vector_10 = __vector_default);
+PROVIDE(__vector_11 = __vector_default);
+PROVIDE(__vector_12 = __vector_default);
+PROVIDE(__vector_13 = __vector_default);
+PROVIDE(__vector_14 = __vector_default);
+PROVIDE(__vector_15 = __vector_default);
+PROVIDE(__vector_16 = __vector_default);
+PROVIDE(__vector_17 = __vector_default);
+PROVIDE(__vector_18 = __vector_default);
+PROVIDE(__vector_19 = __vector_default);
+PROVIDE(__vector_20 = __vector_default);
+PROVIDE(__vector_21 = __vector_default);
+PROVIDE(__vector_22 = __vector_default);
+PROVIDE(__vector_23 = __vector_default);
+PROVIDE(__vector_24 = __vector_default);
+PROVIDE(__vector_25 = __vector_default);
+PROVIDE(__vector_26 = __vector_default);
+PROVIDE(__vector_27 = __vector_default);
+PROVIDE(__vector_28 = __vector_default);
+PROVIDE(__vector_29 = __vector_default);
+PROVIDE(__vector_30 = __vector_default);
+PROVIDE(__vector_31 = __vector_default);
+PROVIDE(__vector_32 = __vector_default);
+PROVIDE(__vector_33 = __vector_default);
+PROVIDE(__vector_34 = __vector_default);
+PROVIDE(__vector_35 = __vector_default);
+PROVIDE(__vector_36 = __vector_default);
+PROVIDE(__vector_37 = __vector_default);
+PROVIDE(__vector_38 = __vector_default);
+PROVIDE(__vector_39 = __vector_default);
+PROVIDE(__vector_40 = __vector_default);
+PROVIDE(__vector_41 = __vector_default);
+PROVIDE(__vector_42 = __vector_default);
+PROVIDE(__vector_43 = __vector_default);
+PROVIDE(__vector_44 = __vector_default);
+PROVIDE(__vector_45 = __vector_default);
+PROVIDE(__vector_46 = __vector_default);
+PROVIDE(__vector_47 = __vector_default);
+PROVIDE(__vector_48 = __vector_default);
+PROVIDE(__vector_49 = __vector_default);
+PROVIDE(__vector_50 = __vector_default);
+PROVIDE(__vector_51 = __vector_default);
+PROVIDE(__vector_52 = __vector_default);
+PROVIDE(__vector_53 = __vector_default);
+PROVIDE(__vector_54 = __vector_default);
+PROVIDE(__vector_55 = __vector_default);
+PROVIDE(__vector_56 = __vector_default);
+PROVIDE(__vector_57 = __vector_default);
+PROVIDE(__vector_58 = __vector_default);
+PROVIDE(__vector_59 = __vector_default);
+PROVIDE(__vector_60 = __vector_default);
+PROVIDE(__vector_61 = __vector_default);
+PROVIDE(__vector_62 = __vector_default);
+PROVIDE(__vector_63 = __vector_default);
+
+SECTIONS {
+       /*
+        * Ram starts at 0x400 but for some reason it does not allow med to
+        * start placing data at 0x400 since it's not into the ram... Life
+        * is great.
+        */
+       __ram_start = 0x500;
+       __ram_end = 0x400 + 31k - 1;
+        
+        .start : {
+                *(.init0);
+        } > flash
+
+       .data __ram_start :     {
+               *(.data);
+               *(.rodata);             /* Do NOT place in '.text'. */
+               *(.rodata.*);   /* Do NOT place in '.text'. */
+               *(.plt);                /* Do NOT place in '.text'. */
+       } > ram AT > flash
+
+       __data_start = LOADADDR(.data);
+       __data_size = SIZEOF(.data);
+
+       .bss : {
+               *(.bss);
+               *(COMMON);
+       } > ram
+
+       __bss_start = ADDR(.bss);
+       __bss_size = SIZEOF(.bss);
+        
+       .text /*0xc0000*/: {
+               *(.text);
+               *(.vectors_variable);
+       } > flash
+
+        .bootargs /*boot_args_address*/ : {
+                *(.boot_args);
+        } > flash
+
+       PROVIDE(_end = __bss_start + __bss_size);
+       
+       /* User Stack Pointer */
+       .ustack 0x00007000 :
+       {
+               _ustack = .;
+       } > ram
+       
+       /* Interrupt Stack Pointer */
+       .istack 0x00008000 :
+       {
+               _istack = .;
+       } > ram
+       
+       /* Vector offset is fixed. */
+       .vectors 0x000FFFDC : {
+               *(.vectors_fixed);
+       } > flash
+}
diff --git a/support/make/m16c62p/m16c62p.rules b/support/make/m16c62p/m16c62p.rules
new file mode 100755 (executable)
index 0000000..05e6601
--- /dev/null
@@ -0,0 +1,130 @@
+#-#-Makefile-#- vim:syntax=make
+
+define M16C62P_HELP
+
+ M16C/62P extras:
+
+   debug    : compile with minimal optimization and debug symbols
+   debugopt : compile with debug symbols
+
+ Programmer options:
+
+   sm16cf : use SM16CF programmer on port '/dev/ttyUSB0'.
+   sm16cf,<dev> : use SM16CF programmer on port <dev>.
+
+endef
+HELP += $(M16C62P_HELP)
+THIS_FOLDER = m16c62p
+
+#ifdef MAKE_DEPUTY_FLAG
+#        NCC_SAFE_TINYOS_FLAGS = -DSAFE_TINYOS -fnesc-deputy -fnesc-deputy-args='-I$(TOSDIR)/lib/safe/include --FLIDs=build/$(PLATFORM)/flids.txt --envmachine -DSAFE_TINYOS --nolib ' $(TOSDIR)/lib/safe/avr/fail.c 
+#else
+#        NCC_SAFE_TINYOS_FLAGS =
+#endif
+
+OBJCOPY = m32c-elf-objcopy
+OBJDUMP = m32c-elf-objdump
+SET_ID = tos-set-symbols
+NCC = ncc
+LIBS = -lm -lc -lgcc
+
+AMADDR = _ActiveMessageAddressC\$$addr
+# Uncomment the next two lines if you have a toolchain without the dollar sign
+# patch. This needs nesc 1.2.8 or newer (1.2.9 is recommended).
+#PFLAGS += -fnesc-separator=__
+#AMADDR = ActiveMessageAddressC__addr
+BUILDDIR ?= build/$(PLATFORM)
+MAIN_EXE = $(BUILDDIR)/main.exe
+MAIN_SREC = $(BUILDDIR)/main.srec
+MAIN_IHEX = $(BUILDDIR)/main.ihex
+INSTALL_SREC = $(MAIN_SREC).out$(if $(NODEID),-$(NODEID),)
+
+PFLAGS += -Wshadow $(NESC_FLAGS)
+PFLAGS += -target=$(PLATFORM) -fnesc-cfile=$(BUILDDIR)/app.c -board=$(SENSORBOARD)
+ifdef MSG_SIZE
+PFLAGS += -DTOSH_DATA_LENGTH=$(MSG_SIZE)
+endif
+ifdef DEFAULT_LOCAL_GROUP
+PFLAGS += -DDEFINED_TOS_AM_GROUP=$(DEFAULT_LOCAL_GROUP)
+endif
+
+# We need a different start address for the flash in the linker script when building TOSBoot.
+# Also program the boot_args address bytes with 0xFF so that we know if they are reprogrammable.
+ifeq ($(COMPONENT),TosBootC)
+$(shell sed -e "s/0x00a0000/0x00e0000/ig" $(TINYOS_MAKE_PATH)/$(THIS_FOLDER)/m16c.x > $(TINYOS_MAKE_PATH)/$(THIS_FOLDER)/m16c_bootloader.x)
+$(shell sed -e "s/\/\*boot_args_address\*\//0x00f0000/ig" $(TINYOS_MAKE_PATH)/$(THIS_FOLDER)/m16c_bootloader.x > $(TINYOS_MAKE_PATH)/$(THIS_FOLDER)/m16c_bootloader_args.x)
+LDFLAGS += -nostartfiles -T$(TINYOS_MAKE_PATH)/$(THIS_FOLDER)/m16c_bootloader_args.x  $(TINYOS_MAKE_PATH)/$(THIS_FOLDER)/crt.S
+else
+LDFLAGS += -nostartfiles -T$(TINYOS_MAKE_PATH)/$(THIS_FOLDER)/m16c.x  $(TINYOS_MAKE_PATH)/$(THIS_FOLDER)/crt.S
+endif
+
+# This is needed so that we know that the BusyWaitMicroC.BusyWait.wait()
+# function always gets aligned.
+CFLAGS += -falign-functions=2
+
+DEFAULT_PROGRAM ?= sm16cf
+
+# Use the 'if' function instead of the 'ifdef' construct because ifdef freaks
+# out with call in there.  I don't know why.
+$(if $(PROGRAM),,$(call TOSMake_include,$(THIS_FOLDER)/$(DEFAULT_PROGRAM).extra))
+
+# Build storage file if volumes.xml present
+ifneq ($(wildcard $(VOLUMEFILE)), )
+build_storage: $(BUILDDIR)/StorageVolumes.h
+
+exe0: build_storage
+
+VOLUME_ALLOCATOR_FLAGS ?= 
+$(BUILDDIR)/StorageVolumes.h: $(VOLUMEFILE)
+       $(VOLUME_ALLOCATOR) $(VOLUME_ALLOCATOR_FLAGS) $(PLATFORMDIR) <$(VOLUMEFILE) >$@ || rm -f $@
+
+PFLAGS += -I$(BUILDDIR)
+else
+
+build_storage:
+
+endif
+
+ifndef BUILD_DEPS
+  ifeq ($(filter $(BUILDLESS_DEPS),$(GOALS)),)
+    BUILD_DEPS = srec bytes tosimage $(POST_BUILD_EXTRA_DEPS)
+  endif
+endif
+
+setid: FORCE
+       @cmd () { echo "$$@"; $$@; }; if [ x = x$(NODEID) ]; then cmd cp $(MAIN_SREC) $(INSTALL_SREC); else cmd $(SET_ID) $(MAIN_SREC) $(INSTALL_SREC) _TOS_NODE_ID=$(NODEID) $(AMADDR)=$(NODEID) ; fi
+
+delsetid: FORCE
+       rm -f $(subst .srec.,.exe.,$(INSTALL_SREC)) $(INSTALL_SREC) 
+
+srec: exe FORCE
+       $(OBJCOPY) --output-target=srec $(MAIN_EXE) $(MAIN_SREC)
+
+tos_buildinfo: ihex build_buildinfo FORCE
+  @:
+  
+       # TODO(henrik) Remove interrupt vector table from the image.
+tosimage: ihex build_tosimage FORCE
+       @:
+
+ihex: exe FORCE
+       $(OBJCOPY) --output-target=ihex $(MAIN_EXE) $(MAIN_IHEX)
+
+exe: exe0 FORCE bytes
+       @:
+
+
+exe0: builddir $(BUILD_EXTRA_DEPS) FORCE
+       @echo "    compiling $(COMPONENT) to a $(PLATFORM) binary"
+       $(NCC) -o $(MAIN_EXE) $(NCC_SAFE_TINYOS_FLAGS) $(OPTFLAGS) $(PFLAGS) $(CFLAGS) $(WIRING_CHECK_FLAGS) $(COMPONENT).nc $(LIBS) $(LDFLAGS)
+ifdef WIRING_CHECK_FILE
+       @nescc-wiring $(WIRING_CHECK_FILE)
+endif
+       @echo "    compiled $(COMPONENT) to $(MAIN_EXE)"
+
+builddir: FORCE
+       mkdir -p $(BUILDDIR)
+# bug fix 2009-3-11 by ZHF, here display the ROM and RAM consumption information.
+bytes: FORCE
+       @$(OBJDUMP) -h $(MAIN_EXE) | perl -ne '$$b{$$1}=hex $$2 if /^\s*\d+\s*\.(text|data|bss)\s+(\S+)/; END { printf("%16d bytes in ROM\n%16d bytes in RAM\n",$$b{text}+$$b{data},$$b{data}+$$b{bss}); }'
+
diff --git a/support/make/m16c62p/reinstall.extra b/support/make/m16c62p/reinstall.extra
new file mode 100644 (file)
index 0000000..1d78c13
--- /dev/null
@@ -0,0 +1,6 @@
+#-*-Makefile-*- vim:syntax=make
+
+NODEID = $(REINSTALL)
+BUILD_DEPS = setid program
+
+
diff --git a/support/make/m16c62p/sm16cf.extra b/support/make/m16c62p/sm16cf.extra
new file mode 100755 (executable)
index 0000000..f83aa5f
--- /dev/null
@@ -0,0 +1,27 @@
+###
+ # @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ ##
+
+ifeq ($(SM16CF), )
+#$(error SM16CF must be defined, try "make $(TARGETS) help")
+SM16CF = /dev/ttyUSB0
+endif
+
+PROGRAM = sm16cf
+PROGRAMMER = sm16cf
+
+ifdef BOOTLOADER
+  program: FORCE
+       @echo "    installing $(PLATFORM) with bootloader using sm16cf"
+       srec_cat $(BOOTLOADER_IMG) $(INSTALL_SREC) -exclude 0x000FFFDC 0x00100000 -o $(BUILDDIR)/main_boot.srec -CRLF
+       sed '/S5/d' $(BUILDDIR)/main_boot.srec > $(BUILDDIR)/main_boot2.srec
+       $(PROGRAMMER) --device=$(SM16CF) --input-file=$(BUILDDIR)/main_boot2.srec --flash-program
+       rm $(BUILDDIR)/main_boot.srec
+       rm $(BUILDDIR)/main_boot2.srec
+else
+program: FORCE
+       @echo "    installing $(PLATFORM) using sm16cf"
+       $(PROGRAMMER) --device=$(SM16CF) --input-file=$(INSTALL_SREC) --flash-program
+endif
+
+program_bl: FORCE
index 04b090774595bfa8d43ec605c9fa1f56297ce2fb..0bab085a81954165c4f39898ddd819c51846fef6 100644 (file)
@@ -7,7 +7,6 @@ define MSP_HELP
 
    debug    : compile with minimal optimization and debug symbols
    debugopt : compile with debug symbols
-   xnp      : compile for network programming
 
  Programmer options:
 
@@ -23,7 +22,7 @@ endef
 HELP += $(MSP_HELP)
 
 ifdef MAKE_DEPUTY_FLAG
-        NCC_SAFE_TINYOS_FLAGS = -DSAFE_TINYOS -fnesc-deputy -fnesc-deputy-args='-I$(TOSDIR)/lib/safe/include --FLIDs=build/$(PLATFORM)/flids.txt --envmachine -DSAFE_TINYOS --nolib ' $(TOSDIR)/lib/safe/msp430/fail.c 
+        NCC_SAFE_TINYOS_FLAGS = -DSAFE_TINYOS -I$(TOSDIR)/lib/safe -fnesc-deputy -fnesc-deputy-args='-I$(TOSDIR)/lib/safe/include --FLIDs=build/$(PLATFORM)/flids.txt --envmachine -DSAFE_TINYOS --nolib '
 else
         NCC_SAFE_TINYOS_FLAGS =
 endif
@@ -39,7 +38,12 @@ SET_ID = tos-set-symbols
 NCC = ncc
 LIBS = -lm
 
-AMADDR = ActiveMessageAddressC\$$addr
+# Use __ as the separator - requires nesC 1.2.9 or later
+ifneq ($(filter sim,$(GOALS)),sim)
+        PFLAGS += -fnesc-separator=__
+endif
+
+AMADDR = ActiveMessageAddressC__addr
 BUILDDIR ?= build/$(PLATFORM)
 MAIN_EXE = $(BUILDDIR)/main.exe
 MAIN_IHEX = $(BUILDDIR)/main.ihex
diff --git a/support/make/mulle.target b/support/make/mulle.target
new file mode 100755 (executable)
index 0000000..37bbb17
--- /dev/null
@@ -0,0 +1,50 @@
+#-#-Makefile-#- vim:syntax=make
+##
+ # Copyright (c) 2009 Communication Group and Eislab at
+ # Lulea University of Technology
+ #
+ # Contact: Laurynas Riliskis, LTU
+ # Mail: laurynas.riliskis@ltu.se
+ # All rights reserved.
+ #
+ #
+ # Redistribution and use in source and binary forms, with or without
+ # modification, are permitted provided that the following conditions
+ # are met:
+ # - Redistributions of source code must retain the above copyright
+ #   notice, this list of conditions and the following disclaimer.
+ # - Redistributions in binary form must reproduce the above copyright
+ #   notice, this list of conditions and the following disclaimer in the
+ #   documentation and/or other materials provided with the
+ #   distribution.
+ # - Neither the name of Communication Group at Lulea University of Technology
+ #   nor the names of its contributors may be used to endorse or promote
+ #    products derived from this software without specific prior written permission.
+ #
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ # ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ # FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ # UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ # OF THE POSSIBILITY OF SUCH DAMAGE.
+ ##
+
+# @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+PLATFORM = mulle
+
+# Flash settings
+VOLUMEFILE = volumes-at45db.xml
+VOLUME_ALLOCATOR ?= tos-storage-at45db
+VOLUME_ALLOCATOR_FLAGS ?= -s 512 -f 4096
+
+$(call TOSMake_include_platform,m16c62p)
+
+mulle: $(BUILD_DEPS)
+       @:
+
index 58632258ea1efb344dcd616778fc1f48fa131586..6514cec517a410a14bff1d9f179648a4c5cc5606 100644 (file)
@@ -10,6 +10,7 @@ define NULL_HELP
 endef
 HELP += $(NULL_HELP)
 
+export GCC=gcc
 OBJCOPY = objcopy
 OBJDUMP = objdump
 NCC = ncc
@@ -23,7 +24,7 @@ INSTALL_SREC = $(MAIN_SREC).out$(if $(NODEID),-$(NODEID),)
 VOLUMEFILE = volumes-at45db.xml
 VOLUME_ALLOCATOR ?= tos-storage-at45db
 
-PFLAGS += -Wall -Wshadow $(NESC_FLAGS)
+PFLAGS += -Wall -Wshadow -fnesc-gcc=$(GCC) $(NESC_FLAGS)
 PFLAGS += -target=$(PLATFORM) -fnesc-cfile=$(BUILDDIR)/app.c
 ifdef MSG_SIZE
 PFLAGS += -DTOSH_DATA_LENGTH=$(MSG_SIZE)
@@ -31,6 +32,11 @@ endif
 ifdef DEFAULT_LOCAL_GROUP
 PFLAGS += -DDEFINED_TOS_AM_GROUP=$(DEFAULT_LOCAL_GROUP)
 endif
+ifeq ($(findstring Darwin, $(shell uname)), Darwin)
+  CFLAGS += -D_FORTIFY_SOURCE=0
+  OBJCOPY = /usr/bin/true
+  OBJDUMP = /usr/bin/true
+endif
 
 BUILDLESS_DEPS += bytes
 
@@ -69,5 +75,5 @@ builddir: FORCE
        mkdir -p $(BUILDDIR)
 
 bytes: FORCE
-       @objdump -h $(MAIN_EXE) | perl -ne '$$b{$$1}=hex $$2 if /^\s*\d+\s*\.(text|data|bss)\s+(\S+)/; END { printf("%16d bytes in ROM\n%16d bytes in RAM\n",$$b{text}+$$b{data},$$b{data}+$$b{bss}); }'
+       @$(OBJDUMP) -h $(MAIN_EXE) | perl -ne '$$b{$$1}=hex $$2 if /^\s*\d+\s*\.(text|data|bss)\s+(\S+)/; END { printf("%16d bytes in ROM\n%16d bytes in RAM\n",$$b{text}+$$b{data},$$b{data}+$$b{bss}); }'
 
index 583186f55be6fb9d270a5a05177f2d7ffc6d7d2a..b29429f85c417af150dcd23b8ca495ef0155fa29 100644 (file)
@@ -1,5 +1,5 @@
 #-*-Makefile-*-
 
 MAKE_DEPUTY_FLAG := 1
-export MAKE_DEPUTY_FLAG
+#export MAKE_DEPUTY_FLAG
 
index bee617b832126470626fe42af42d70951307ce68..2a872f8122eaf364b6eba8ce3bd09a07a1eac0a2 100644 (file)
@@ -1,17 +1,17 @@
-PLATFORM = shimmer\r
-\r
-# Disable MSP430 hardware multiply because it makes MSPGCC die\r
-PFLAGS += -mdisable-hwmul\r
-OPTFLAGS += -O\r
-\r
-MSP_BSL ?= tos-bsl\r
-MSP_BSL_FLAGS = --invert-test --invert-reset\r
-\r
-ifdef CC2420_CHANNEL\r
-PFLAGS += -DCC2420_DEF_CHANNEL=$(CC2420_CHANNEL)\r
-endif\r
-\r
-$(call TOSMake_include_platform,msp)\r
-\r
-shimmer: $(BUILD_DEPS)\r
-       @:\r
+PLATFORM = shimmer
+
+# Disable MSP430 hardware multiply because it makes MSPGCC die
+PFLAGS += -mdisable-hwmul
+OPTFLAGS += -O
+
+MSP_BSL ?= tos-bsl
+MSP_BSL_FLAGS = --invert-test --invert-reset
+
+ifdef CC2420_CHANNEL
+PFLAGS += -DCC2420_DEF_CHANNEL=$(CC2420_CHANNEL)
+endif
+
+$(call TOSMake_include_platform,msp)
+
+shimmer: $(BUILD_DEPS)
+       @:
diff --git a/support/make/shimmer2.target b/support/make/shimmer2.target
new file mode 100644 (file)
index 0000000..b58744c
--- /dev/null
@@ -0,0 +1,17 @@
+PLATFORM = shimmer2
+
+# Disable MSP430 hardware multiply because it makes MSPGCC die
+PFLAGS += -mdisable-hwmul
+OPTFLAGS += -O
+
+MSP_BSL ?= tos-bsl
+MSP_BSL_FLAGS = --invert-test --invert-reset
+
+ifdef CC2420_CHANNEL
+PFLAGS += -DCC2420_DEF_CHANNEL=$(CC2420_CHANNEL)
+endif
+
+$(call TOSMake_include_platform,msp)
+
+shimmer2: $(BUILD_DEPS)
+       @:
index 10ee519569f113b070ba3aba36605eae26d09223..8e6e92c5196a4fbb611bb37cd98a30cbb5854c0c 100644 (file)
@@ -1,11 +1,11 @@
 #-*-Makefile-*- vim:syntax=make
 #$Id$
 
-GCC=gcc
+export GCC=gcc
 GPP=g++
 OPTFLAGS = -g -O0
 LIBS = -lm -lstdc++ 
-PFLAGS += -tossim -fnesc-nido-tosnodes=1000 -fnesc-simulate -fnesc-nido-motenumber=sim_node\(\)  
+PFLAGS += -tossim -fnesc-nido-tosnodes=1000 -fnesc-simulate -fnesc-nido-motenumber=sim_node\(\) -fnesc-gcc=$(GCC)
 WFLAGS = -Wno-nesc-data-race
 PYTHON_VERSION=2.5
 
@@ -18,7 +18,7 @@ HASHFILE    = $(TOSDIR)/lib/tossim/hashtable.c
 HASHOBJFILE = $(BUILDDIR)/c-support.o
 PYFILE     = $(TOSDIR)/lib/tossim/tossim_wrap.cxx
 PYOBJFILE  = $(BUILDDIR)/pytossim.o
-PYDIR      =/usr/include/python$(PYTHON_VERSION)
+PYDIR      = $(shell python$(PYTHON_VERSION)-config --prefix)/include/python$(PYTHON_VERSION)
 SIMDIR     =$(TOSDIR)/lib/tossim
 XML        = app.xml
 DUMPTYPES = -fnesc-dump=components -fnesc-dump=variables -fnesc-dump=constants -fnesc-dump=typedefs -fnesc-dump=interfacedefs -fnesc-dump=tags
@@ -50,7 +50,7 @@ endif
 endif
 endif 
 ifdef SIM_DARWIN
-  PLATFORM_FLAGS=-fPIC
+  PLATFORM_FLAGS=-fPIC -D_FORTIFY_SOURCE=0
   PLATFORM_CC_FLAGS=-bundle
   SHARED_OBJECT=_TOSSIMmodule.so
   PLATFORM_BUILD_FLAGS=-flat_namespace -undefined suppress 
diff --git a/support/make/stack-check.extra b/support/make/stack-check.extra
new file mode 100644 (file)
index 0000000..b649d43
--- /dev/null
@@ -0,0 +1,3 @@
+#-*-Makefile-*- vim:syntax=make
+
+STACK_CHECK = 1
index 0024d3c148cc82108d6e535d5ea0959f64a6fdf6..b39a734fa9889104abb236e10ecd43c12975cd7a 100644 (file)
@@ -11,6 +11,7 @@ TOS_THREADS_DIR ?= $(TOSDIR)/lib/tosthreads
 CFLAGS += -I$(TOS_THREADS_DIR)/system
 CFLAGS += -I$(TOS_THREADS_DIR)/interfaces
 CFLAGS += -I$(TOS_THREADS_DIR)/types
+CFLAGS += -I$(TOS_THREADS_DIR)/lib/serial
 
 #Setup the thread scheduler for use by redefining the name of the task scheduler to use
 PFLAGS += -tosscheduler=TinyTaskSchedulerC,TinyTaskSchedulerC.TaskBasic,TaskBasic,TaskBasic,runTask,postTask
@@ -19,6 +20,7 @@ PFLAGS += -tosscheduler=TinyTaskSchedulerC,TinyTaskSchedulerC.TaskBasic,TaskBasi
 THREADS_MSP430_DIR = $(TOS_THREADS_DIR)/chips/msp430
 THREADS_MSP430_INCLUDE_DIRS = -I$(THREADS_MSP430_DIR)
 THREADS_MSP430_INCLUDE_DIRS += -I$(THREADS_MSP430_DIR)/adc12
+THREADS_MSP430_INCLUDE_DIRS += -I$(THREADS_MSP430_DIR)/sensors
 
 #Atm128 specific include directories on tested platforms
 THREADS_ATM128_DIR = $(TOS_THREADS_DIR)/chips/atm128
@@ -75,11 +77,25 @@ THREADS_EYES_INCLUDE_DIRS = -I$(TOS_THREADS_DIR)/platforms/eyesIFX
 #Shimmer specific include directories
 THREADS_SHIMMER_INCLUDE_DIRS = -I$(TOS_THREADS_DIR)/platforms/shimmer
 
+#Epic specific include directories
+THREADS_EPIC_INCLUDE_DIRS = -I$(TOS_THREADS_DIR)/platforms/epic
+
 #Add CFLAGS for supported platforms
 ifneq ($(filter telos telosa telosb tmote,$(MAKECMDGOALS)),)
   CFLAGS += $(THREADS_MSP430_INCLUDE_DIRS)
   CFLAGS += $(THREADS_CC2420_INCLUDE_DIRS)
   CFLAGS += $(THREADS_TELOS_INCLUDE_DIRS)
+  
+  #Since Telosb has some sensors not on other platforms, this helps us figure out
+  #what components should be included
+  ifneq ($(filter telosb,$(MAKECMDGOALS)),)
+    CFLAGS += -DPLATFORM_TELOSB
+  endif
+endif
+ifneq ($(filter epic,$(MAKECMDGOALS)),)
+  CFLAGS += $(THREADS_MSP430_INCLUDE_DIRS)
+  CFLAGS += $(THREADS_CC2420_INCLUDE_DIRS)
+  CFLAGS += $(THREADS_EPIC_INCLUDE_DIRS)
 endif
 ifneq ($(filter mica2,$(MAKECMDGOALS)),)
   CFLAGS += $(THREADS_ATM128_INCLUDE_DIRS)
@@ -118,4 +134,3 @@ ifneq ($(filter shimmer,$(MAKECMDGOALS)),)
   CFLAGS += $(THREADS_CC2420_INCLUDE_DIRS)
   CFLAGS += $(THREADS_SHIMMER_INCLUDE_DIRS)
 endif
-
index 2420fa9372fb992aedeaccff61e28f778b715b21..ddb928c01f387642c8e30dab41734d31b24a713a 100644 (file)
@@ -10,12 +10,19 @@ ifeq ($(BOOTLOADER),tosboot)
   CFLAGS += -DDELUGE
   CFLAGS += -I$(TOSDIR)/lib/net -I$(TOSDIR)/lib/net/drip -I$(DELUGE_DIR) -I$(DELUGE_DIR)/FlashVolumeManager -I$(DELUGE_DIR)/BlockStorageManager
 
-  ifneq ($(filter telosb tmote,$(TARGETS)),)
-    CFLAGS += -I$(DELUGE_EXTRA) -I$(DELUGE_EXTRA)/msp430 -I$(DELUGE_EXTRA)/telos -I$(DELUGE_EXTRA)/telosb
+  ifneq ($(filter telosb tmote epic,$(TARGETS)),)
+    CFLAGS += -I$(DELUGE_EXTRA) -I$(DELUGE_EXTRA)/msp430 -I$(DELUGE_EXTRA)/telos
     ifeq ($(filter docs,$(GOALS)),)
       CFLAGS += -Wl,--section-start=.text=0x4a00,--defsym=_reset_vector__=0x4000
     endif
-    BOOTLOADER_IMG ?= $(TOSBOOT_DIR)/telosb/main.ihex
+    ifeq ($(TARGETS),telosb)
+       CFLAGS += -I$(DELUGE_EXTRA)/telosb
+       BOOTLOADER_IMG ?= $(TOSBOOT_DIR)/telosb/main.ihex
+    endif
+    ifeq ($(TARGETS),epic)
+       CFLAGS += -I$(DELUGE_EXTRA)/epic
+       BOOTLOADER_IMG ?= $(TOSBOOT_DIR)/epic/main.ihex
+    endif
     ifeq ($(shell [ -f /bin/cygwin1.dll ] && echo cygwin),cygwin)
       BOOTLOADER_IMG := $(shell cygpath -m $(BOOTLOADER_IMG))
     endif
@@ -27,11 +34,25 @@ ifeq ($(BOOTLOADER),tosboot)
     AVR_FUSE_H ?= 0xda
   endif
 
+  ifeq ($(TARGETS),mulle)
+    CFLAGS += -I$(DELUGE_EXTRA) -I$(DELUGE_EXTRA)/mulle -I$(DELUGE_EXTRA)/m16c62p
+    BOOTLOADER_IMG ?= $(TOSBOOT_DIR)/mulle/main.srec
+  endif
+
   ifeq ($(TARGETS),iris)
     CFLAGS += -I$(DELUGE_EXTRA)/iris -I$(DELUGE_EXTRA)/micaz -I$(DELUGE_EXTRA)/mica2 -I$(DELUGE_EXTRA)/avr -I$(DELUGE_EXTRA)
     BOOTLOADER_IMG ?= $(TOSBOOT_DIR)/iris/main.ihex
     AVR_FUSE_H ?= 0xda
   endif
 
+   ifeq ($(TARGETS),tinynode)
+               CFLAGS += -I$(DELUGE_EXTRA)/tinynode
+               CFLAGS += -I$(DELUGE_EXTRA) -I$(DELUGE_EXTRA)/msp430 -I$(DELUGE_EXTRA)/msp430f1611 
+     ifeq ($(filter docs,$(GOALS)),)
+                       CFLAGS += -Wl,--section-start=.text=0x4a00,--defsym=_reset_vector__=0x4000
+     endif
+               BOOTLOADER_IMG ?= $(TOSBOOT_DIR)/tinynode/main.ihex
+   endif
+
 
 endif
diff --git a/support/sdk/c/blip/Makefile.am b/support/sdk/c/blip/Makefile.am
new file mode 100644 (file)
index 0000000..9049546
--- /dev/null
@@ -0,0 +1,3 @@
+
+SUBDIRS = lib6lowpan driver
+
diff --git a/support/sdk/c/blip/bootstrap.sh b/support/sdk/c/blip/bootstrap.sh
new file mode 100755 (executable)
index 0000000..c5a7472
--- /dev/null
@@ -0,0 +1,3 @@
+#!/bin/sh
+
+autoreconf --install
diff --git a/support/sdk/c/blip/configure.ac b/support/sdk/c/blip/configure.ac
new file mode 100644 (file)
index 0000000..38d485e
--- /dev/null
@@ -0,0 +1,20 @@
+AC_INIT([blip], [2.1], [stevedh@eecs.berkeley.edu])
+AM_INIT_AUTOMAKE([-Wall -Werror foreign])
+AC_PROG_RANLIB
+AC_PROG_CC
+AC_CONFIG_MACRO_DIR([m4])
+AC_CONFIG_HEADERS([config.h])
+AC_CONFIG_FILES([
+ Makefile
+ lib6lowpan/Makefile
+ driver/Makefile
+])
+
+AC_ARG_ENABLE([lpl],
+        [AS_HELP_STRING([--enable-lpl], [assume LPL is in use])],
+        AC_DEFINE([BLIP_L2_RETRIES], [1], [Number of link-layer retransmissions])
+        [])
+
+
+AC_CONFIG_SUBDIRS([driver/radvd-1.0])
+AC_OUTPUT
diff --git a/support/sdk/c/blip/driver/Makefile.am b/support/sdk/c/blip/driver/Makefile.am
new file mode 100644 (file)
index 0000000..0cf0826
--- /dev/null
@@ -0,0 +1,19 @@
+
+# SUBDIRS = radvd-1.0
+
+sbin_PROGRAMS = ip-driver
+
+radvddir = radvd-1.0
+ip_driver_SOURCES=serial_tun.c tun_dev.c hashtable.c routing.c nwstate.c \
+       logging.c config.c radvd-wrapper.c  vty/vty.c vty/vty-util.c vty/vty.h \
+       netlink.c mcast.c \
+  $(radvddir)/log.c $(radvddir)/socket.c $(radvddir)/recv.c $(radvddir)/util.c $(radvddir)/radvd.h \
+       $(radvddir)/defaults.h $(radvddir)/pathnames.h \
+       $(radvddir)/includes.h \
+  $(radvddir)/timer.c $(radvddir)/send.c $(radvddir)/process.c $(radvddir)/interface.c \
+  $(radvddir)/device.c $(radvddir)/device-common.c $(radvddir)/gram.h \
+       config.h  hashtable.h  hashtable_private.h  \
+       logging.h  mcast.h  netlink.h  nwstate.h  \
+       routing.h  tun_dev.h    
+ip_driver_CFLAGS = -DPC -D_GNU_SOURCE -I$(TOSROOT)/support/sdk/c/sf/ -I..
+LDADD = ../lib6lowpan/lib6lowpan.a $(TOSROOT)/support/sdk/c/sf/libmote.a
diff --git a/support/sdk/c/blip/driver/config.c b/support/sdk/c/blip/driver/config.c
new file mode 100644 (file)
index 0000000..a74bf61
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * @author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+
+#include <lib6lowpan/ip.h>
+#include "config.h"
+#include "logging.h"
+#include "vty/vty.h"
+
+#define BUF_LEN 200
+struct config *lastconfig;
+
+void rm_comment (char *buf) {
+  while (*buf != '#' && *buf != '\0')
+    buf++;
+  *buf = '\0';
+}
+
+void upd_start(char **buf) {
+  while ((**buf == ' ' || **buf == '\t' || **buf == '\n') && **buf != '\0')
+    *buf = (*buf) + 1;
+}
+
+int config_parse(const char *file, struct config *c) {
+  char *buf, real_buf[BUF_LEN], arg[BUF_LEN];
+  FILE *fp = fopen(file, "r");
+  int gotargs = 0;
+  if (fp == NULL) return 1;
+
+  // defaults
+  c->retries = BLIP_L2_RETRIES;
+
+  while (fgets(real_buf, BUF_LEN, fp) != NULL) {
+    buf = real_buf;
+    rm_comment(buf);
+    upd_start(&buf);
+    if (sscanf(buf, "addr %s\n", arg) > 0) {
+      inet_pton6(arg, &c->router_addr);
+      gotargs ++;
+    } else if (sscanf(buf, "proxy %s\n", c->proxy_dev) > 0) {
+      gotargs ++;
+    } else if (sscanf(buf, "channel %i\n", &c->channel) > 0) {
+      if (c->channel < 11 || c->channel > 26) {
+        fatal("Invalid channel specified in '%s'\n", file);
+        exit(1);
+      }
+      gotargs ++;
+    } else if (sscanf(buf, "log %s\n", arg) > 0) {
+      int i;
+      for (i = 0; i < 5; i++) {
+        if (strncmp(log_names[i], arg, strlen(log_names[i])) == 0) {
+          info("Read log level: %s\n", arg);
+          log_setlevel(i);
+          break;
+        }
+      }
+    } else if (sscanf(buf, "retry %i\n", &c->retries) > 0) {
+      if (c->retries <= 0 || c->retries > 25) {
+        warn("retry value set to %i: outside of the recommended range (0,25]\n", c->retries);
+      }
+    } else if (*buf != '\0') {
+      // anything else indicates that there's invalid input.
+      return 1;
+    }
+  }
+  fclose(fp);
+
+  if (gotargs != 3) return 1;
+
+  info("Read config from '%s'\r\n", file);
+  if (strncmp(c->proxy_dev, "lo", 3) != 0) {
+    info("Proxying neighbor advertisements to %s\r\n", c->proxy_dev);
+  }
+  info("Using channel %i\r\n", c->channel);
+  info("Retries: %i\r\n", c->retries);
+  lastconfig = c;
+  return 0;
+}
+
+#define STR(X) #X
+
+void config_print(int fd, int argc, char **argv) { //struct config *c) {
+  VTY_HEAD;
+  char buf[64];
+  VTY_printf ("configuration:\r\n");
+  inet_ntop(AF_INET6, &lastconfig->router_addr, buf, 64);
+  VTY_printf ("  router address: %s\r\n", buf);
+  VTY_printf("  proxy dev: %s\r\n", lastconfig->proxy_dev);
+  VTY_printf("  channel: %i\r\n", lastconfig->channel);
+  VTY_printf("  version: %s\r\n", " $Id: config.c,v 1.2 2009/08/09 23:36:05 sdhsdh Exp ");
+  VTY_printf("  retries: %i\r\n", lastconfig->retries);
+  VTY_flush();
+}
diff --git a/support/sdk/c/blip/driver/config.h b/support/sdk/c/blip/driver/config.h
new file mode 100644 (file)
index 0000000..3b1fdb9
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * @author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
+ */
+
+#ifndef _CONFIG_H
+#define _CONFIG_H
+
+#include <netinet/in.h>
+#include <net/if.h>
+
+struct config {
+  struct in6_addr router_addr;
+  char proxy_dev[IFNAMSIZ];
+  int channel;
+  int retries;
+};
+
+
+int config_parse(const char *file, struct config *c);
+void config_print(int fd, int argc, char **argv);
+
+#endif
diff --git a/support/sdk/c/blip/driver/hashtable.c b/support/sdk/c/blip/driver/hashtable.c
new file mode 100644 (file)
index 0000000..64f11f8
--- /dev/null
@@ -0,0 +1,276 @@
+/* Copyright (C) 2004 Christopher Clark <firstname.lastname@cl.cam.ac.uk> */
+
+#include "hashtable.h"
+#include "hashtable_private.h"
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+
+#define iceil(X)  ((unsigned int)((X) + 1))
+
+/*
+Credit for primes table: Aaron Krowne
+ http://br.endernet.org/~akrowne/
+ http://planetmath.org/encyclopedia/GoodHashTablePrimes.html
+*/
+static const unsigned int primes[] = {
+53, 97, 193, 389,
+769, 1543, 3079, 6151,
+12289, 24593, 49157, 98317,
+196613, 393241, 786433, 1572869,
+3145739, 6291469, 12582917, 25165843,
+50331653, 100663319, 201326611, 402653189,
+805306457, 1610612741
+};
+const unsigned int prime_table_length = sizeof(primes)/sizeof(primes[0]);
+const float max_load_factor = 0.65;
+
+/*****************************************************************************/
+struct hashtable *
+create_hashtable(unsigned int minsize,
+                 unsigned int (*hashf) (void*),
+                 int (*eqf) (void*,void*))
+{
+    struct hashtable *h;
+    unsigned int pindex, size = primes[0];
+    /* Check requested hashtable isn't too large */
+    if (minsize > (1u << 30)) return NULL;
+    /* Enforce size as prime */
+    for (pindex=0; pindex < prime_table_length; pindex++) {
+        if (primes[pindex] > minsize) { size = primes[pindex]; break; }
+    }
+    h = (struct hashtable *)malloc(sizeof(struct hashtable));
+    if (NULL == h) return NULL; /*oom*/
+    h->table = (struct entry **)malloc(sizeof(struct entry*) * size);
+    if (NULL == h->table) { free(h); return NULL; } /*oom*/
+    memset(h->table, 0, size * sizeof(struct entry *));
+    h->tablelength  = size;
+    h->primeindex   = pindex;
+    h->entrycount   = 0;
+    h->hashfn       = hashf;
+    h->eqfn         = eqf;
+    h->loadlimit    = (unsigned int) iceil(size * max_load_factor);
+    return h;
+}
+
+/*****************************************************************************/
+unsigned int
+hash(struct hashtable *h, void *k)
+{
+    /* Aim to protect against poor hash functions by adding logic here
+     * - logic taken from java 1.4 hashtable source */
+    unsigned int i = h->hashfn(k);
+    i += ~(i << 9);
+    i ^=  ((i >> 14) | (i << 18)); /* >>> */
+    i +=  (i << 4);
+    i ^=  ((i >> 10) | (i << 22)); /* >>> */
+    return i;
+}
+
+/*****************************************************************************/
+static int
+hashtable_expand(struct hashtable *h)
+{
+    /* Double the size of the table to accomodate more entries */
+    struct entry **newtable;
+    struct entry *e;
+    struct entry **pE;
+    unsigned int newsize, i, index;
+    /* Check we're not hitting max capacity */
+    if (h->primeindex == (prime_table_length - 1)) return 0;
+    newsize = primes[++(h->primeindex)];
+
+    newtable = (struct entry **)malloc(sizeof(struct entry*) * newsize);
+    if (NULL != newtable)
+    {
+        memset(newtable, 0, newsize * sizeof(struct entry *));
+        /* This algorithm is not 'stable'. ie. it reverses the list
+         * when it transfers entries between the tables */
+        for (i = 0; i < h->tablelength; i++) {
+            while (NULL != (e = h->table[i])) {
+                h->table[i] = e->next;
+                index = indexFor(newsize,e->h);
+                e->next = newtable[index];
+                newtable[index] = e;
+            }
+        }
+        free(h->table);
+        h->table = newtable;
+    }
+    /* Plan B: realloc instead */
+    else 
+    {
+        newtable = (struct entry **)
+                   realloc(h->table, newsize * sizeof(struct entry *));
+        if (NULL == newtable) { (h->primeindex)--; return 0; }
+        h->table = newtable;
+        memset(newtable[h->tablelength], 0, newsize - h->tablelength);
+        for (i = 0; i < h->tablelength; i++) {
+            for (pE = &(newtable[i]), e = *pE; e != NULL; e = *pE) {
+                index = indexFor(newsize,e->h);
+                if (index == i)
+                {
+                    pE = &(e->next);
+                }
+                else
+                {
+                    *pE = e->next;
+                    e->next = newtable[index];
+                    newtable[index] = e;
+                }
+            }
+        }
+    }
+    h->tablelength = newsize;
+    h->loadlimit   = (unsigned int) iceil(newsize * max_load_factor);
+    return -1;
+}
+
+/*****************************************************************************/
+unsigned int
+hashtable_count(struct hashtable *h)
+{
+    return h->entrycount;
+}
+
+/*****************************************************************************/
+int
+hashtable_insert(struct hashtable *h, void *k, void *v)
+{
+    /* This method allows duplicate keys - but they shouldn't be used */
+    unsigned int index;
+    struct entry *e;
+    if (++(h->entrycount) > h->loadlimit)
+    {
+        /* Ignore the return value. If expand fails, we should
+         * still try cramming just this value into the existing table
+         * -- we may not have memory for a larger table, but one more
+         * element may be ok. Next time we insert, we'll try expanding again.*/
+        hashtable_expand(h);
+    }
+    e = (struct entry *)malloc(sizeof(struct entry));
+    if (NULL == e) { --(h->entrycount); return 0; } /*oom*/
+    e->h = hash(h,k);
+    index = indexFor(h->tablelength,e->h);
+    e->k = k;
+    e->v = v;
+    e->next = h->table[index];
+    h->table[index] = e;
+    return -1;
+}
+
+/*****************************************************************************/
+void * /* returns value associated with key */
+hashtable_search(struct hashtable *h, void *k)
+{
+    struct entry *e;
+    unsigned int hashvalue, index;
+    hashvalue = hash(h,k);
+    index = indexFor(h->tablelength,hashvalue);
+    e = h->table[index];
+    while (NULL != e)
+    {
+        /* Check hash value to short circuit heavier comparison */
+        if ((hashvalue == e->h) && (h->eqfn(k, e->k))) return e->v;
+        e = e->next;
+    }
+    return NULL;
+}
+
+/*****************************************************************************/
+void * /* returns value associated with key */
+hashtable_remove(struct hashtable *h, void *k)
+{
+    /* TODO: consider compacting the table when the load factor drops enough,
+     *       or provide a 'compact' method. */
+
+    struct entry *e;
+    struct entry **pE;
+    void *v;
+    unsigned int hashvalue, index;
+
+    hashvalue = hash(h,k);
+    index = indexFor(h->tablelength,hash(h,k));
+    pE = &(h->table[index]);
+    e = *pE;
+    while (NULL != e)
+    {
+        /* Check hash value to short circuit heavier comparison */
+        if ((hashvalue == e->h) && (h->eqfn(k, e->k)))
+        {
+            *pE = e->next;
+            h->entrycount--;
+            v = e->v;
+            freekey(e->k);
+            free(e);
+            return v;
+        }
+        pE = &(e->next);
+        e = e->next;
+    }
+    return NULL;
+}
+
+/*****************************************************************************/
+/* destroy */
+void
+hashtable_destroy(struct hashtable *h, int free_values)
+{
+    unsigned int i;
+    struct entry *e, *f;
+    struct entry **table = h->table;
+    if (free_values)
+    {
+        for (i = 0; i < h->tablelength; i++)
+        {
+            e = table[i];
+            while (NULL != e)
+            { f = e; e = e->next; freekey(f->k); free(f->v); free(f); }
+        }
+    }
+    else
+    {
+        for (i = 0; i < h->tablelength; i++)
+        {
+            e = table[i];
+            while (NULL != e)
+            { f = e; e = e->next; freekey(f->k); free(f); }
+        }
+    }
+    free(h->table);
+    free(h);
+}
+
+/*
+ * Copyright (c) 2002, Christopher Clark
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 
+ * * Neither the name of the original author; nor the names of any contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ * 
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
diff --git a/support/sdk/c/blip/driver/hashtable.h b/support/sdk/c/blip/driver/hashtable.h
new file mode 100644 (file)
index 0000000..b90781a
--- /dev/null
@@ -0,0 +1,199 @@
+/* Copyright (C) 2002 Christopher Clark <firstname.lastname@cl.cam.ac.uk> */
+
+#ifndef __HASHTABLE_CWC22_H__
+#define __HASHTABLE_CWC22_H__
+
+struct hashtable;
+
+/* Example of use:
+ *
+ *      struct hashtable  *h;
+ *      struct some_key   *k;
+ *      struct some_value *v;
+ *
+ *      static unsigned int         hash_from_key_fn( void *k );
+ *      static int                  keys_equal_fn ( void *key1, void *key2 );
+ *
+ *      h = create_hashtable(16, hash_from_key_fn, keys_equal_fn);
+ *      k = (struct some_key *)     malloc(sizeof(struct some_key));
+ *      v = (struct some_value *)   malloc(sizeof(struct some_value));
+ *
+ *      (initialise k and v to suitable values)
+ * 
+ *      if (! hashtable_insert(h,k,v) )
+ *      {     exit(-1);               }
+ *
+ *      if (NULL == (found = hashtable_search(h,k) ))
+ *      {    printf("not found!");                  }
+ *
+ *      if (NULL == (found = hashtable_remove(h,k) ))
+ *      {    printf("Not found\n");                 }
+ *
+ */
+
+/* Macros may be used to define type-safe(r) hashtable access functions, with
+ * methods specialized to take known key and value types as parameters.
+ * 
+ * Example:
+ *
+ * Insert this at the start of your file:
+ *
+ * DEFINE_HASHTABLE_INSERT(insert_some, struct some_key, struct some_value);
+ * DEFINE_HASHTABLE_SEARCH(search_some, struct some_key, struct some_value);
+ * DEFINE_HASHTABLE_REMOVE(remove_some, struct some_key, struct some_value);
+ *
+ * This defines the functions 'insert_some', 'search_some' and 'remove_some'.
+ * These operate just like hashtable_insert etc., with the same parameters,
+ * but their function signatures have 'struct some_key *' rather than
+ * 'void *', and hence can generate compile time errors if your program is
+ * supplying incorrect data as a key (and similarly for value).
+ *
+ * Note that the hash and key equality functions passed to create_hashtable
+ * still take 'void *' parameters instead of 'some key *'. This shouldn't be
+ * a difficult issue as they're only defined and passed once, and the other
+ * functions will ensure that only valid keys are supplied to them.
+ *
+ * The cost for this checking is increased code size and runtime overhead
+ * - if performance is important, it may be worth switching back to the
+ * unsafe methods once your program has been debugged with the safe methods.
+ * This just requires switching to some simple alternative defines - eg:
+ * #define insert_some hashtable_insert
+ *
+ */
+
+/*****************************************************************************
+ * create_hashtable
+   
+ * @name                    create_hashtable
+ * @param   minsize         minimum initial size of hashtable
+ * @param   hashfunction    function for hashing keys
+ * @param   key_eq_fn       function for determining key equality
+ * @return                  newly created hashtable or NULL on failure
+ */
+
+struct hashtable *
+create_hashtable(unsigned int minsize,
+                 unsigned int (*hashfunction) (void*),
+                 int (*key_eq_fn) (void*,void*));
+
+/*****************************************************************************
+ * hashtable_insert
+   
+ * @name        hashtable_insert
+ * @param   h   the hashtable to insert into
+ * @param   k   the key - hashtable claims ownership and will free on removal
+ * @param   v   the value - does not claim ownership
+ * @return      non-zero for successful insertion
+ *
+ * This function will cause the table to expand if the insertion would take
+ * the ratio of entries to table size over the maximum load factor.
+ *
+ * This function does not check for repeated insertions with a duplicate key.
+ * The value returned when using a duplicate key is undefined -- when
+ * the hashtable changes size, the order of retrieval of duplicate key
+ * entries is reversed.
+ * If in doubt, remove before insert.
+ */
+
+int 
+hashtable_insert(struct hashtable *h, void *k, void *v);
+
+#define DEFINE_HASHTABLE_INSERT(fnname, keytype, valuetype) \
+int fnname (struct hashtable *h, keytype *k, valuetype *v) \
+{ \
+    return hashtable_insert(h,k,v); \
+}
+
+/*****************************************************************************
+ * hashtable_search
+   
+ * @name        hashtable_search
+ * @param   h   the hashtable to search
+ * @param   k   the key to search for  - does not claim ownership
+ * @return      the value associated with the key, or NULL if none found
+ */
+
+void *
+hashtable_search(struct hashtable *h, void *k);
+
+#define DEFINE_HASHTABLE_SEARCH(fnname, keytype, valuetype) \
+valuetype * fnname (struct hashtable *h, keytype *k) \
+{ \
+    return (valuetype *) (hashtable_search(h,k)); \
+}
+
+/*****************************************************************************
+ * hashtable_remove
+   
+ * @name        hashtable_remove
+ * @param   h   the hashtable to remove the item from
+ * @param   k   the key to search for  - does not claim ownership
+ * @return      the value associated with the key, or NULL if none found
+ */
+
+void * /* returns value */
+hashtable_remove(struct hashtable *h, void *k);
+
+#define DEFINE_HASHTABLE_REMOVE(fnname, keytype, valuetype) \
+valuetype * fnname (struct hashtable *h, keytype *k) \
+{ \
+    return (valuetype *) (hashtable_remove(h,k)); \
+}
+
+
+/*****************************************************************************
+ * hashtable_count
+   
+ * @name        hashtable_count
+ * @param   h   the hashtable
+ * @return      the number of items stored in the hashtable
+ */
+unsigned int
+hashtable_count(struct hashtable *h);
+
+
+/*****************************************************************************
+ * hashtable_destroy
+   
+ * @name        hashtable_destroy
+ * @param   h   the hashtable
+ * @param       free_values     whether to call 'free' on the remaining values
+ */
+
+void
+hashtable_destroy(struct hashtable *h, int free_values);
+
+#endif /* __HASHTABLE_CWC22_H__ */
+
+/*
+ * Copyright (c) 2002, Christopher Clark
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 
+ * * Neither the name of the original author; nor the names of any contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ * 
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
diff --git a/support/sdk/c/blip/driver/hashtable_private.h b/support/sdk/c/blip/driver/hashtable_private.h
new file mode 100644 (file)
index 0000000..f622701
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/* Copyright (C) 2002, 2004 Christopher Clark <firstname.lastname@cl.cam.ac.uk> */
+
+#ifndef __HASHTABLE_PRIVATE_CWC22_H__
+#define __HASHTABLE_PRIVATE_CWC22_H__
+
+#include "hashtable.h"
+
+/*****************************************************************************/
+struct entry
+{
+    void *k, *v;
+    unsigned int h;
+    struct entry *next;
+};
+
+struct hashtable {
+    unsigned int tablelength;
+    struct entry **table;
+    unsigned int entrycount;
+    unsigned int loadlimit;
+    unsigned int primeindex;
+    unsigned int (*hashfn) (void *k);
+    int (*eqfn) (void *k1, void *k2);
+};
+
+/*****************************************************************************/
+unsigned int
+hash(struct hashtable *h, void *k);
+
+/*****************************************************************************/
+/* indexFor */
+static inline unsigned int
+indexFor(unsigned int tablelength, unsigned int hashvalue) {
+    return (hashvalue % tablelength);
+};
+
+/* Only works if tablelength == 2^N */
+/*static inline unsigned int
+indexFor(unsigned int tablelength, unsigned int hashvalue)
+{
+    return (hashvalue & (tablelength - 1u));
+}
+*/
+
+/*****************************************************************************/
+#define freekey(X) free(X)
+/*define freekey(X) ; */
+
+
+/*****************************************************************************/
+
+#endif /* __HASHTABLE_PRIVATE_CWC22_H__*/
+
+/*
+ * Copyright (c) 2002, Christopher Clark
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 
+ * * Neither the name of the original author; nor the names of any contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ * 
+ * 
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
diff --git a/support/sdk/c/blip/driver/logging.c b/support/sdk/c/blip/driver/logging.c
new file mode 100644 (file)
index 0000000..610055c
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#include <stdio.h>
+#include <errno.h>
+#include <string.h>
+#include <time.h>
+#include <sys/time.h>
+#include <stdarg.h>
+#include "logging.h"
+
+
+loglevel_t log_level;
+FILE *log_dest;
+
+
+const char *log_names[5] = {"DEBUG",
+                            "INFO",
+                            "WARN",
+                            "ERROR",
+                            "FATAL"};
+
+static void timestamp(){
+  struct timeval tv;
+  struct tm *ltime;
+  gettimeofday(&tv, NULL);
+  // automatically calls tzset()
+  ltime = localtime(&tv.tv_sec);
+  fprintf(log_dest, ISO8601_FMT(ltime, &tv));
+  fprintf(log_dest, ": ");
+}
+
+loglevel_t log_setlevel(loglevel_t l) {
+  loglevel_t old_lvl = log_level;
+  log_level = l;
+  return old_lvl;
+}
+
+loglevel_t log_getlevel() {
+  return log_level;
+}
+
+void log_init() {
+  log_level = LOGLVL_INFO;
+  log_dest = stderr;
+}
+
+void log_log  (loglevel_t level, const char *fmt, ...) {
+    if (log_level > level) return;
+    va_list ap;
+    va_start(ap, fmt);
+    timestamp();
+    fprintf(log_dest, "%s: ", log_names[level]);
+    vfprintf(log_dest, fmt, ap);
+    va_end(ap);
+}
+
+void log_fatal_perror(const char *msg) {
+  int in_errno = errno;
+  if (in_errno < 0) return;
+  timestamp();
+  fprintf(log_dest, "%s: ", log_names[LOGLVL_FATAL]);
+  if (msg != NULL) fprintf(log_dest, "%s: ", msg);
+  fprintf(log_dest, "%s\n", strerror(in_errno));
+}
+
+void log_clear (loglevel_t level, const char *fmt, ...) {
+  if (log_level > level) return;
+  va_list ap;
+  va_start(ap, fmt);
+  vfprintf(log_dest, fmt, ap);
+  va_end(ap);
+}
+
+/* print char* in hex format */
+void log_dump_serial_packet(unsigned char *packet, const int len) {
+    int i;
+    if (log_level > LOGLVL_DEBUG) return;
+
+    printf("len: %d\n", len);
+    if (!packet)
+       return;
+    for (i = 0; i < len; i++) {
+       printf("%02x ", packet[i]);
+       //printf("%02x(%c) ", packet[i], packet[i]);
+       //printf("%c", packet[i]);
+    }
+    putchar('\n');
+}
diff --git a/support/sdk/c/blip/driver/logging.h b/support/sdk/c/blip/driver/logging.h
new file mode 100644 (file)
index 0000000..9a33426
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef LOGGING_H_
+#define LOGGING_H_
+
+#include <stdio.h>
+
+// SDH : log levels defined here
+//      also edit the log names in logging.h
+typedef enum {
+  LOGLVL_DEBUG = 0,
+  LOGLVL_INFO = 1,
+  LOGLVL_WARN = 2,
+  LOGLVL_ERROR = 3,
+  LOGLVL_FATAL = 4,
+} loglevel_t;
+
+extern const char *log_names[5];
+extern loglevel_t log_level;
+extern FILE *log_dest;
+
+void log_init();
+
+loglevel_t log_setlevel(loglevel_t l);
+loglevel_t log_getlevel();
+
+void log_log  (loglevel_t level, const char *fmt, ...);
+void log_fatal_perror(const char *msg);
+void log_clear (loglevel_t level, const char *fmt, ...);
+
+#define debug(fmt, args...) \
+           log_log(LOGLVL_DEBUG, fmt, ## args)
+#define info(fmt, args...) \
+           log_log(LOGLVL_INFO, fmt, ## args)
+#define warn(fmt, args...) \
+           log_log(LOGLVL_WARN, fmt, ## args)
+#define error(fmt, args...) \
+           log_log(LOGLVL_ERROR, fmt, ## args)
+#define fatal(fmt, args...) \
+           log_log(LOGLVL_FATAL, fmt, ## args)
+
+#define log_fprintf(X, FMT, ...) ;
+
+
+#define ISO8601_FMT(ltime, tv) "%04d-%02d-%02dT%02d:%02d:%02d.%03d%s",   \
+    (ltime)->tm_year+1900, (ltime)->tm_mon+1, (ltime)->tm_mday,               \
+    (ltime)->tm_hour, (ltime)->tm_min, (ltime)->tm_sec, (int)(tv)->tv_usec/ 1000, \
+    tzname[0]
+
+void log_dump_serial_packet(unsigned char *packet, const int len);
+
+#endif
diff --git a/support/sdk/c/blip/driver/mcast.c b/support/sdk/c/blip/driver/mcast.c
new file mode 100644 (file)
index 0000000..4cd011b
--- /dev/null
@@ -0,0 +1,212 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include <net/if.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <arpa/inet.h>
+
+#include "mcast.h"
+#include "logging.h"
+
+int __mcast_sock;
+struct sockaddr_in6 __mcast_addr;
+char __mcast_dev[IFNAMSIZ];
+
+static int open_loopback(struct sockaddr_in6 *laddr) {
+
+  /* we need to send to the loopback address, not the group  */
+  memcpy(&__mcast_addr.sin6_addr, &in6addr_loopback, sizeof(struct in6_addr));
+  memcpy(&laddr->sin6_addr, &in6addr_loopback, sizeof(struct in6_addr));
+
+  /* bind to the local address (we're already BINDTODEVICE, so this
+     might be redundant)  */
+  if (bind(__mcast_sock, (struct sockaddr *)laddr, sizeof(struct sockaddr_in6)) < 0) {
+    log_fatal_perror("binding multicast socket failed");
+    goto fail;
+  }
+
+  return __mcast_sock;
+ fail:
+  close(__mcast_sock);
+  return -1;
+}
+
+int mcast_start(char *dev) {
+  struct ipv6_mreq join;
+  struct ifreq ifr;
+  int opt;
+  int ifindex = if_nametoindex(dev);
+
+  __mcast_addr.sin6_family = AF_INET6;
+  inet_pton(AF_INET6, "ff12::cafe:babe", &__mcast_addr.sin6_addr);
+  __mcast_addr.sin6_port = htons(10023);
+  __mcast_addr.sin6_scope_id = ifindex;
+
+  strncpy(__mcast_dev, dev, IFNAMSIZ);
+
+  struct sockaddr_in6 laddr = {
+    .sin6_family = AF_INET6,
+    .sin6_port = __mcast_addr.sin6_port,
+    .sin6_addr = IN6ADDR_ANY_INIT,
+    .sin6_scope_id = ifindex,
+  };
+
+
+  /* get the socket */
+  if ((__mcast_sock = socket(PF_INET6, SOCK_DGRAM, 0)) < 0) {
+    log_fatal_perror("error opening socket");
+    return -1;
+  }
+
+  /* bind it to the device we're going to join the link-local
+     multicast group on */
+  memset(&ifr, 0, sizeof(struct ifreq));
+  strncpy(ifr.ifr_name, dev, IFNAMSIZ);
+  if (setsockopt(__mcast_sock, SOL_SOCKET, SO_BINDTODEVICE,
+                 (char *)&ifr, sizeof(struct ifreq)) < 0) {
+    log_fatal_perror("could not BINDTODEVICE");
+    goto fail;
+  }
+
+  /* the loopback on linux doesn't support multicast. that's okay,
+     though, since we can just attach to it and use it to feed routing
+     reports back into us.  */
+  if (strncmp(dev, "lo", 2) == 0) {
+    return open_loopback(&laddr);
+  }
+
+  /* receive messages we send */
+  opt = 1;
+  if (setsockopt(__mcast_sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &opt, sizeof(opt)) < 0) {
+    log_fatal_perror("setting loop failed");
+    goto fail;
+  }
+
+  opt = 1;
+  if (setsockopt(__mcast_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
+    log_fatal_perror("setting reuse failed");
+    goto fail;
+  }
+
+  /* bind to the local address (we're already BINDTODEVICE, so this
+     might be redundant)  */
+  if (bind(__mcast_sock, (struct sockaddr *)&laddr, sizeof(struct sockaddr_in6)) < 0) {
+    log_fatal_perror("binding multicast socket failed");
+    goto fail;
+  }
+
+  memset(&join, 0, sizeof(struct ipv6_mreq));
+  memcpy(&join.ipv6mr_multiaddr, &__mcast_addr.sin6_addr, sizeof(struct in6_addr));
+  join.ipv6mr_interface = ifindex;
+
+  if (setsockopt(__mcast_sock, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &join, sizeof(join)) < 0) {
+    log_fatal_perror("error joining group");
+    goto fail;
+  }
+
+  return __mcast_sock;
+ fail:
+  close(__mcast_sock);
+  return -1;
+}
+
+
+
+int mcast_recvfrom(struct sockaddr_in6 *from, void *buf, int len) {
+  int rc;
+  socklen_t fromlen = sizeof(struct sockaddr_in6);
+
+  if ((rc = recvfrom(__mcast_sock, buf, len, 0, (struct sockaddr *)from, &fromlen)) < 0) { 
+    log_fatal_perror("multicast receive");
+    return -1;
+  }
+  return rc;
+}
+
+int mcast_send(void *data, int len) {
+  int rc;
+
+  if ((rc = sendto(__mcast_sock, data, len, 0, (struct sockaddr *)&__mcast_addr, sizeof(struct sockaddr_in6))) < 0) {
+    log_fatal_perror("send failed");
+    return -1;
+  }
+  return 0;
+}
+
+#if 0
+int main(int argc, char **argv) {
+
+  char *dev = argv[1];
+  int fd;
+  struct sockaddr_in6 grp = {
+    .sin6_port = htons(10620),
+  };
+
+  if (argc < 2) {
+    printf("\n\t%s <iface>\n\n", argv[0]);
+    exit(1);
+  }
+
+  inet_pton(AF_INET6, "ff12::1abc", &grp.sin6_addr);
+
+  fd = mcast_start(&grp, dev);
+  printf("mcast start done: %i\n", fd);
+
+  struct sockaddr_in6 from;
+  char rxbuf[1024];
+  int len;
+
+  if (argc == 3 && strcmp(argv[2], "listen") == 0) {
+
+    printf("listening\n");
+
+    while (1) {
+      len = mcast_recvfrom(&from, rxbuf, 1024);
+      if (len > 0) {
+        rxbuf[len] = '\0';
+        puts(rxbuf);
+      }
+    }
+  } else {
+    char *msg = "hello, mcast world!";
+    while (1) {
+      mcast_send(msg, strlen(msg)+1);
+      sleep(1);
+      len = mcast_recvfrom(&from, rxbuf, 1024);
+      if (len > 0) {
+        rxbuf[len] = '\0';
+        puts(rxbuf);
+      }
+      
+    }
+  }
+}
+#endif
diff --git a/support/sdk/c/blip/driver/mcast.h b/support/sdk/c/blip/driver/mcast.h
new file mode 100644 (file)
index 0000000..a0b9b1c
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _MCAST_H
+#define _MCAST_H
+
+int mcast_start(char *dev);
+int mcast_recvfrom(struct sockaddr_in6 *from, void *buf, int len);
+int mcast_send(void *data, int len);
+
+#endif
+
diff --git a/support/sdk/c/blip/driver/netlink.c b/support/sdk/c/blip/driver/netlink.c
new file mode 100644 (file)
index 0000000..1ee1231
--- /dev/null
@@ -0,0 +1,213 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include <net/if.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <arpa/inet.h>
+
+#include "logging.h"
+
+static int __nl_sock;
+static int __if_index;
+
+/* 
+ * Start a netlink session.
+ *
+ */
+int nl_init() {
+  struct sockaddr_nl nladdr;
+
+  /* with any luck, we've constructed the message, can send it to the
+     kernel, and have a beer. */
+  if ((__nl_sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) < 0) {
+    log_fatal_perror("PACKETLINK socket");
+    return -1;
+  }
+
+  memset(&nladdr, 0, sizeof(nladdr));
+  nladdr.nl_family = AF_NETLINK;
+  nladdr.nl_groups = 0;
+  if (bind(__nl_sock, (struct sockaddr*)&nladdr, sizeof(nladdr)) < 0) {
+    close(__nl_sock);
+    log_fatal_perror("Cannot bind netlink socket");
+    return -1;
+  }
+  return 0;
+}
+
+int nl_shutdown() {
+  close(__nl_sock);
+  __nl_sock = __if_index = -1;
+  return 0;
+}
+
+/*
+ * Start proxying addr on device 'dev'
+ */
+static int nl_cmd(int type, int flags, struct in6_addr *addr, char *dev) {
+  static int seq;
+  struct {
+    struct nlmsghdr    n;
+    struct ndmsg               ndm;
+    char                       buf[256];
+  } req;
+  struct rtattr *rta;
+  struct sockaddr_nl nladdr;
+
+  memset(&req, 0, sizeof(req));
+  
+  /* set up our request packet with one request */
+  req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ndmsg));
+  req.n.nlmsg_flags = NLM_F_REQUEST | flags; 
+  req.n.nlmsg_type = type;
+  req.ndm.ndm_family = AF_INET6;
+  req.ndm.ndm_state = NUD_PERMANENT;
+  req.ndm.ndm_ifindex = if_nametoindex(dev);
+
+  /* add the actual address to the tail of the message  */
+  int nl_len = RTA_LENGTH(sizeof(struct in6_addr));
+  if (NLMSG_ALIGN(req.n.nlmsg_len) + RTA_ALIGN(nl_len) > sizeof(req)) {
+    fprintf(stderr, "message too long\n");
+    return -1;
+  }
+
+  rta = ((struct rtattr *) (((void *) (&req.n)) + NLMSG_ALIGN((req.n.nlmsg_len))));
+  rta->rta_type = NDA_DST;
+  rta->rta_len = nl_len;
+  memcpy(RTA_DATA(rta), addr, sizeof(struct in6_addr));
+  req.n.nlmsg_len = NLMSG_ALIGN(req.n.nlmsg_len) + RTA_ALIGN(nl_len);
+
+  struct iovec iov = {
+    .iov_base = (void*) &req.n,
+    .iov_len = req.n.nlmsg_len
+  };
+  struct msghdr msg = {
+    .msg_name = &nladdr,
+    .msg_namelen = sizeof(nladdr),
+    .msg_iov = &iov,
+    .msg_iovlen = 1,
+  };
+
+  memset(&nladdr, 0, sizeof(nladdr));
+  nladdr.nl_family = AF_NETLINK;
+  req.n.nlmsg_seq = seq++;
+  
+  if (sendmsg(__nl_sock, &msg, 0) < 0) {
+    log_fatal_perror("RTNETLINK");
+    return -1;
+  }
+  /* TODO : nonblocking receive to check for error? */
+
+
+  return 0;
+
+  ///
+
+  char buf[16384];
+
+       iov.iov_base = buf;
+       while (1) {
+               int status;
+               struct nlmsghdr *h;
+
+               iov.iov_len = sizeof(buf);
+               status = recvmsg(__nl_sock, &msg, 0);
+
+               if (status < 0) {
+                       if (errno == EINTR)
+                               continue;
+                       log_fatal_perror("OVERRUN");
+                       continue;
+               }
+
+               if (status == 0) {
+                       fprintf(stderr, "EOF on netlink\n");
+                       return -1;
+               }
+
+               h = (struct nlmsghdr*)buf;
+               while (NLMSG_OK(h, status)) {
+                       int err;
+
+                       if (nladdr.nl_pid != 0 ||
+                           h->nlmsg_pid != 0 ||
+                           h->nlmsg_seq != seq) {
+                                       if (err < 0)
+                                               return err;
+
+                               goto skip_it;
+                       }
+
+                       if (h->nlmsg_type == NLMSG_DONE)
+                               return 0;
+                       if (h->nlmsg_type == NLMSG_ERROR) {
+                               struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h);
+                               if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) {
+                                       fprintf(stderr, "ERROR truncated\n");
+                               } else {
+                                       errno = -err->error;
+                                       log_fatal_perror("RTNETLINK answers");
+                               }
+                               return -1;
+                       }
+skip_it:
+                       h = NLMSG_NEXT(h, status);
+               }
+               if (msg.msg_flags & MSG_TRUNC) {
+                       fprintf(stderr, "Message truncated\n");
+                       continue;
+               }
+               if (status) {
+                       fprintf(stderr, "!!!Remnant of size %d\n", status);
+                       exit(1);
+               }
+       }
+  return 0;
+}
+
+int nl_nd_add_neigh(struct in6_addr *addr, char *dev) {
+  return nl_cmd(RTM_NEWNEIGH, NLM_F_CREATE|NLM_F_REPLACE, addr, dev);
+}
+int nl_nd_del_neigh(struct in6_addr *addr, char *dev) {
+  return nl_cmd(RTM_DELNEIGH, 0, addr, dev);
+}
+int nl_nd_add_proxy(struct in6_addr *addr, char *dev) {
+  // SDH : shit, the netlink proxy doesn't work (the add neighbor
+  // did).  I WILL fix it... later.
+  char buf [100], cmd[256];
+  inet_ntop(AF_INET6, addr, buf, 100);
+  snprintf(cmd, sizeof(cmd), "ip neigh add proxy %s dev %s\n", buf, dev);
+  system(cmd);
+  return 0;
+
+  // return nl_cmd(RTM_NEWNEIGH, NLM_F_CREATE|NLM_F_EXCL|NTF_PROXY, addr, dev);
+}
diff --git a/support/sdk/c/blip/driver/netlink.h b/support/sdk/c/blip/driver/netlink.h
new file mode 100644 (file)
index 0000000..b6f03de
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _NETLINK_H
+#define _NETLINK_H
+
+/* 
+ * The netlink interface to the kernel is not the most concise one
+ * imaginable, but seems like the only way to manipulate the ND state
+ * from userland, at least as of 2.6.22.  
+ */
+
+int nl_init();
+int nl_shutdown();
+
+int nl_nd_add_neigh(struct in6_addr *addr, char *dev);
+int nl_nd_del_neigh(struct in6_addr *addr, char *dev);
+int nl_nd_add_proxy(struct in6_addr *addr, char *dev);
+
+
+#endif
+
diff --git a/support/sdk/c/blip/driver/nwstate.c b/support/sdk/c/blip/driver/nwstate.c
new file mode 100644 (file)
index 0000000..822b255
--- /dev/null
@@ -0,0 +1,630 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <float.h>
+#include <time.h>
+#include <sys/time.h>
+#include "lib6lowpan/lib6lowpan.h"
+
+#include "nwstate.h"
+#include "hashtable.h"
+#include "logging.h"
+#include "routing.h"
+#include "vty/vty.h"
+
+struct hashtable *links;
+struct hashtable *routers;
+
+router_t *router_list = NULL;
+int routes_out_of_date = 1;
+
+extern struct in6_addr __my_address;
+
+
+void compute_routes(node_id_t v1);
+//
+// general boilerplate
+// 
+
+static unsigned int hash_link(void *k) {
+  link_key_t *l = (link_key_t *)k;
+  if (l->r1 > l->r2)
+    return (l->r1 | (l->r2 << 16));
+  else
+    return (l->r2 | (l->r1 << 16));
+}
+static int link_equal(void *k1, void *k2) {
+  link_key_t *l1 = (link_key_t *)k1;
+  link_key_t *l2 = (link_key_t *)k2;
+  return ((l1->r1 == l2->r1 && l1->r2 == l2->r2) ||
+          (l1->r1 == l2->r2 && l1->r2 == l2->r1));
+}
+
+static unsigned int hash_router(void *k) {
+  return *((router_key_t *)k);
+}
+
+static int router_equal(void *k1, void *k2) {
+  return ((router_t *)k1)->id == ((router_t *)k2)->id;
+}
+
+int do_print = 0;
+int do_routes = 0;
+int printCount = 0;
+
+int nw_print_dotfile(char *filename) {
+  router_t *r;
+  link_t *e;
+  FILE *fp = fopen (filename, "w");
+  if (fp == NULL) return -1;
+  info("writing topology to '%s'\n", filename);
+  printCount ++;
+  fprintf(fp, "digraph Network {\n");
+  
+  for (r = router_list; r != NULL; r = r->next) {
+    for (e = r->links; e != NULL; e = e->next1) {
+      if (e->pc < printCount) {
+        fprintf(fp, "  \"0x%x\" -> \"0x%x\" [label=\"%f\"]\n", e->n1->id, e->n2->id, e->qual);
+        e->pc = printCount;
+      }
+    }
+    for (e = r->links; e != NULL; e = e->next2) {
+      if (e->pc < printCount) {
+        fprintf(fp, "  \"0x%x\" -> \"0x%x\" [label=\"%f\"]\n", e->n1->id, e->n2->id, e->qual);
+        e->pc = printCount;
+      }
+    }
+  }
+
+  fprintf(fp, "}\n");
+  fclose(fp);
+  return 0;
+}
+
+
+void nw_print_routes(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  router_t *r,*s;
+  for (r = router_list; r != NULL; r = r->next) {
+    VTY_printf("  0x%x: ", r->id);
+    for (s = r->sp.prev; s != NULL; s = s->sp.prev) {
+      VTY_printf("0x%x", s->id);
+      if (r->isController) VTY_printf("[C] ");
+      else VTY_printf(" ");
+    }
+    VTY_printf("\r\n");
+    VTY_flush();
+  }
+}
+
+void nw_test_routes(int fd, int argc, char **argv) {
+  node_id_t dest = ntohs(__my_address.s6_addr16[7]);
+  debug("nwstate: computing new routes (root: 0x%x)\n", ntohs(__my_address.s6_addr16[7]));
+  compute_routes(dest);
+}
+
+void nw_print_links(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  struct tm *ltime;
+  int target = -1;
+  router_t *r;
+  link_t *l;
+
+  if (argc == 2) {
+    if (sscanf(argv[1], "%i", &target) == 0) {
+      VTY_printf("invalid node\r\n");
+      VTY_flush();
+      return;
+    }
+  }
+
+  for (r = router_list; r != NULL; r = r->next) {
+    char flags[16]; int pos = 0;
+    if (target >= 0 && r->id != target) continue;
+
+    flags[0] = '\0';
+    if (r->isProxying || r->isController) {
+      flags[pos++] = '['; 
+      if (r->isController) flags[pos++] = 'C';
+      if (r->isProxying) flags[pos++] = 'P';
+      flags[pos++] = ']';
+      flags[pos++] = '\0';
+    }
+
+    VTY_printf(" 0x%x%s: dist: ", r->id, flags);
+    if (r->sp.dist == FLT_MAX)
+      VTY_printf("Inf");
+    else
+      VTY_printf("%.1f", r->sp.dist);
+    if (!r->isController) {
+      ltime = localtime(&r->lastReport.tv_sec);
+      VTY_printf(" reported: " ISO8601_FMT(ltime, &r->lastReport));
+    }
+
+    VTY_printf("\r\n");
+    for (l = r->links; l != NULL; l = (r == l->n1) ? l->next1 : l->next2) {
+      if (r == l->n1) {
+        VTY_printf("  --> 0x%x [%.1f]\r\n", l->n2->id, l->qual);
+      }
+    }
+    VTY_printf("\r\n");
+    VTY_flush();
+  }
+}
+
+void nw_add_sticky_edge(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  int v1, v2;
+  if (argc == 3) {
+    link_t *l;
+    struct topology_entry te;
+    v1 = atoi(argv[1]);
+    v2 = atoi(argv[2]);
+    VTY_printf("adding sticky edge between %i and %i\r\n", v1, v2);
+    te.etx = 10;
+    te.conf = 255;
+    te.hwaddr = htons(v2);
+    l = nw_add_incr_edge(v1, &te);
+    l->marked = L_STICKY;
+  } else {
+    VTY_printf("add a link: '%s <n1> <n2>'\r\n", argv[0]);
+  }
+  VTY_flush();
+}
+
+void nw_inval_node_sh(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  int int_arg;
+  if (argc == 2) {
+    int_arg = atoi(argv[1]);
+    VTY_printf("invalidating node 0x%x\n", int_arg);
+    nw_inval_node(int_arg);
+  }
+  VTY_flush();
+}
+//
+// helpers
+// 
+
+router_t *nw_get_router(node_id_t rid) {
+  return hashtable_search(routers, &rid);
+}
+
+router_t *get_insert_router(node_id_t rid) {
+  router_key_t *key;
+  router_t *ret = nw_get_router(rid);
+  if (ret == NULL) {
+    key = (router_key_t *)malloc(sizeof(router_key_t));
+    ret = (router_t *)malloc(sizeof(router_t));
+    memset(ret, 0, sizeof(router_t));
+
+    ret->id = rid;
+    ret->links = NULL;
+    ret->next = router_list;
+
+    ret->reports = 0;
+    ret->lastSeqno = -1;
+
+    ret->isProxying = FALSE;
+    ret->isController = FALSE;
+
+    ret->sp.dist = FLT_MAX;
+    ret->sp.prev = NULL;
+
+    router_list = ret;
+
+    *key = rid;
+    hashtable_insert(routers, key, ret);
+  }
+  return ret;
+}
+
+
+//
+// network state API impl.
+//
+
+int nw_init() {
+  router_t *r;
+  links   = create_hashtable(16, hash_link,   link_equal);
+  routers = create_hashtable(16, hash_router, router_equal);
+  r = get_insert_router(ntohs(__my_address.s6_addr16[7]));
+  r->isController = TRUE;
+  return 0;
+}
+
+/*
+ * Adds an observation of the link (v1, v2) to the database.  This
+ * implicitly adds the reverse edge for now, as well.
+ */
+link_t *nw_add_incr_edge(node_id_t v1, struct topology_entry *te) {
+  link_key_t key;
+  link_t *link_str;
+  node_id_t v2 = ntoh16(te->hwaddr);
+  key.r1 = v1;
+  key.r2 = v2;
+
+  link_str = hashtable_search(links, &key);
+  if (link_str == NULL) {
+    link_key_t *new_key = (link_key_t *)malloc(sizeof(link_key_t));
+    router_t *r1 = get_insert_router(v1);
+    router_t *r2 = get_insert_router(v2);
+    link_str = (link_t *)malloc(sizeof(link_t));
+    memset(link_str, 0, sizeof(link_t));
+
+    new_key->r1 = v1;
+    new_key->r2 = v2;
+
+    // point the links at their routers
+    link_str->n1 = r1;
+    link_str->n2 = r2;
+    // add this link to the head of the linked list of edges each router maintains
+    link_str->next1 = r1->links;
+    link_str->next2 = r2->links;
+
+    link_str->n1_reportcount = 0;
+    link_str->n2_reportcount = 0;
+    
+    r1->links = link_str;
+    r2->links = link_str;
+
+    link_str->pc = 0;
+
+    
+    hashtable_insert(links, new_key, link_str);
+
+  } 
+
+  link_str->marked = L_REPORTED;
+  link_str->qual = ((float)(te->etx)) / 10.0;
+  link_str->conf = te->conf;
+  debug("nw_add_incr_edge [%i -> %i]: qual: %f conf: %i\n", 
+        v1, v2, link_str->qual, link_str->conf);
+  (v1 == link_str->n1->id) ? link_str->n1_reportcount++ :
+    link_str->n2_reportcount++;
+
+  return link_str;
+}
+
+/*
+ * Returns a route from v1 to v2 as a linked list.
+ *
+ * quadratic-time dijkstra implementation: no priority queue
+ */
+/*
+ * relaxes the neighbors of cur
+ */
+float getMetric(link_t *l) {
+  return l->qual;
+  //return ((float)l->qual / 3000.0)  + 1.0;
+  //return (10. / (float)l->nobs);
+}
+void update_neighbors(router_t *cur) {
+  link_t *l;
+  router_t *otherguy;
+  // clunky iterator
+  for (l = cur->links; l != NULL; l = (cur == l->n1) ? l->next1 : l->next2) {
+    otherguy = (cur == l->n1) ? l->n2 : l->n1;
+    
+    if (cur->sp.dist + getMetric(l) < otherguy->sp.dist) {
+      otherguy->sp.dist = cur->sp.dist + getMetric(l);
+      otherguy->sp.prev = cur;
+    }
+  }
+}
+
+router_t *extract_min(router_t **list) {
+  router_t *r, *prev = NULL, *min = NULL, *prev_min = NULL;
+  float min_dist = FLT_MAX;
+  for (r = *list; r != NULL; r = r->sp.setptr) {
+    if (r->sp.dist < min_dist) {
+      min_dist = r->sp.dist;
+      min = r;
+      prev_min = prev;
+    }
+    prev = r;
+  }
+
+  if (min == NULL) {
+    // it might be the case that not everyone is reachable.  In that
+    // case, we'll just leave them unconnected.
+    *list = NULL;
+  } else if (prev_min == NULL) {
+    // the first element was the best, set list is pointed at the second element
+    *list = (*list)->sp.setptr;
+  } else {
+    // otherwise just remove the min element from the list
+    prev_min->sp.setptr = min->sp.setptr;
+  }
+
+  return min;
+}
+
+void age_routers() {
+  router_t *r;
+  int max_reports = 0;
+  for (r = router_list; r != NULL; r = r->next) {
+    if (r->reports > max_reports) {
+      max_reports = r->reports;
+    }
+    // debug("nwstate: node: %i reports: %i\n", r->id, r->reports);
+  }
+  if (max_reports == 4) {
+    debug("age_routers: max: %i\n", max_reports);
+    for (r = router_list; r != NULL; r = r->next) {
+      if (r->reports > 0) {
+        r->reports = 0;
+      } else {
+        // debug("nwstate: removing router 0x%x due to age %i\n", r->id, r->reports);
+        // nw_inval_node(r->id);
+        r->reports = 0;
+      }
+    }
+  }
+}
+
+/*
+ * compute all destinations shortest path to node v1
+ */
+void compute_routes(node_id_t v1) {
+  router_t *r, *cur = NULL, *not_visited = NULL;
+  routes_out_of_date = 0;
+
+  for (r = router_list; r != NULL; r = r->next) {
+    r->sp.dist = FLT_MAX;
+    r->sp.prev = NULL;
+    if (r->id == v1) {
+      cur = r;
+    } else {
+      r->sp.setptr = not_visited;
+      not_visited = r;
+    }
+  }
+  if (cur == NULL) return;
+  cur->sp.dist = 0;
+
+  while (not_visited != NULL) {
+    update_neighbors(cur);
+    cur = extract_min (&not_visited);
+  }
+  // all the prev and distance pointers are now valid.
+}
+
+path_t *nw_get_route(node_id_t v1, node_id_t v2) {
+  router_t *r, *from, *to;
+  path_t *ret = NULL, *new;
+
+  from = hashtable_search(routers, &v1);
+  to   = hashtable_search(routers, &v2);
+
+  if (from == NULL || to == NULL) return NULL;
+
+  if (to->sp.prev == NULL || from->sp.prev != NULL || routes_out_of_date) {
+    // the current set of shortest paths do not end at node v2, if we
+    // haven't computed any paths yet, we will do that when the next
+    // test fails.
+    debug("nw_get_route: computing new routes\n");
+    compute_routes(v1);
+  }
+  if (to->sp.prev == NULL) return NULL;
+
+  // now the routes should be valid;
+  for (r = to; r != NULL; r = r->sp.prev) {
+    // this both constructs the return value and reverses the path,
+    // since the prev pointers will give you the reverse path.
+
+    // in the future routes will probably be cached.
+    
+    if (r != from) {
+      new = (path_t *)malloc(sizeof(path_t));
+      new->node = r->id;
+      new->next = ret;
+      new->length = (ret == NULL) ? 1 : ret->length + 1;
+      new->isController = r->isController;
+      ret = new;
+    }
+  }
+  return ret;
+}
+
+void nw_free_path(path_t *r) {
+  path_t *next;
+  while (r != NULL) {
+    next = r->next;
+    free(r);
+    r = next;
+  }
+}
+
+// remove link from the linked list of links owned by router.
+void remove_link(router_t *r, link_t *link) {
+  link_t *l;
+  link_t **prev = &r->links;
+  for (l = r->links; l != NULL; l = (r== l->n1) ? l->next1 : l->next2) {
+    if (l == link) {
+      *prev = (r == l->n1) ? l->next1 : l->next2;
+      return;
+    }
+    prev = (r == l->n1) ? &l->next1 : &l->next2;
+  }
+  warn("link_remove: link not removed (inconsistent state)?\n");
+}
+
+void nw_remove_link(node_id_t n1, node_id_t n2) {
+  router_t *r1 = nw_get_router(n1);
+  router_t *r2 = nw_get_router(n2);
+  link_t *link;
+  link_key_t key;
+
+  key.r1 = n1;
+  key.r2 = n2;
+  link = hashtable_search(links, &key);
+  if (link != NULL) {
+    routes_out_of_date = 1;
+
+    remove_link(r1, link);
+    remove_link(r2, link);
+    hashtable_remove(links, &key);
+    free(link);
+  }
+}
+
+void nw_inval_node(node_id_t v) {
+  router_t *cur;
+  link_t *l, *next;
+  router_t *otherguy;
+  link_key_t key;
+  routes_out_of_date = 1;
+
+  cur = hashtable_search(routers, &v);
+  if (cur == NULL) return;
+
+  // remove the links from the linked lists of the other guys,
+  // and delete them from the hashtable
+  for (l = cur->links; l != NULL; l = (cur == l->n1) ? l->next1 : l->next2) {
+    otherguy = (cur == l->n1) ? l->n2 : l->n1;
+    key.r1 = v;
+    key.r2 = otherguy->id;
+    remove_link(otherguy, l);
+    hashtable_remove(links, &key);
+  }
+  
+  // free the link structures
+  l = cur->links;
+  while (l != NULL) {
+    next = (cur == l->n1) ? l->next1 : l->next2;
+    free(l);
+    l = next;
+  }
+  cur->links = NULL;
+
+  // force a route recomputation when this node is used.
+  cur->sp.dist = FLT_MAX;
+  cur->sp.prev = NULL;
+}
+
+/*
+ * called before adding the topology from a node 
+ * unsets the marked bit * in the link structures to show that they
+ * have not been reported
+ */ 
+void nw_unmark_links(node_id_t v) {
+  router_t *cur;
+  link_t *l;
+  routes_out_of_date = 1;
+
+  cur = hashtable_search(routers, &v);
+  if (cur == NULL) return;
+
+  for (l = cur->links; l != NULL; l = (cur == l->n1) ? l->next1 : l->next2) {
+    if (l->marked == L_REPORTED) l->marked = L_UNREPORTED;
+  }
+
+}
+
+void nw_report_node(node_id_t v) {
+  router_t *cur;
+
+  cur = hashtable_search(routers, &v);
+  if (cur == NULL) return;
+  
+  cur->reports++;
+}
+
+/*
+ * called after processing a topology report
+ *
+ * removes links which were not contained by this topology report, and
+ * which were not reported by the router on the other end.
+ *
+ */
+void nw_clear_unmarked(node_id_t v) {
+  router_t *cur;
+  link_key_t key;
+  link_t *l, *next;
+  key.r1 = v;
+
+  cur = hashtable_search(routers, &v);
+  if (cur == NULL) return;
+
+  for (l = cur->links; l != NULL; l = (cur == l->n1) ? l->next1 : l->next2) {
+    if (l->marked == L_UNREPORTED) {
+      // it's not marked, so it wasn't contained in the topology report
+      if (((cur == l->n1) ? l->n2_reportcount : l->n1_reportcount) == 0) {
+        // it has never been reported by the router on the other end, so we
+        // remove the link from the topology data
+        router_t *otherguy = (cur == l->n1) ? l->n2 : l->n1;
+        key.r2 = otherguy->id;
+        remove_link(otherguy, l);
+        hashtable_remove(links, &key);
+        //info("removing unmarked link, 0x%x -> 0x%x\n", cur->id, otherguy->id);
+        // remove it from our own linked list
+      } else {
+        // it has been reported by the other size, so we just set its
+        // observation count to zero.
+        if (cur == l->n1)  l->n1_reportcount = 0 ;
+        else l->n2_reportcount = 0;
+        l->marked = L_REPORTED;
+        // router_t *otherguy = (cur == l->n1) ? l->n2 : l->n1;
+        //debug("unseting obs count on 0x%x -> 0x%x\n", cur->id, otherguy->id);
+      }
+    }
+  }
+
+  // free the links no longer in use
+  l = cur->links;
+  while (l != NULL) {
+    next = (cur == l->n1) ? l->next1 : l->next2;
+    // if its still umarked, we mean to remove it from the graph
+    if (l->marked == 0) {
+      remove_link(cur, l);
+      free(l);
+    }
+    l = next;
+  }
+
+
+  age_routers();
+}
+
+
+void nw_add_controller(node_id_t node) {
+  router_t *r, *thisController;
+
+  struct topology_entry te;
+  te.etx = 1;
+  te.conf = 255;
+
+  thisController = nw_get_router(node);
+  if (!thisController) return;
+
+  thisController->isController = TRUE;
+  for (r = router_list; r != NULL; r = r->next) {
+    if (r->isController && r != thisController) {
+      te.hwaddr = htons(r->id);
+      nw_add_incr_edge(node, &te);
+    }
+  }
+}
diff --git a/support/sdk/c/blip/driver/nwstate.h b/support/sdk/c/blip/driver/nwstate.h
new file mode 100644 (file)
index 0000000..be7cfe3
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef NWSTATE_H
+#define NWSTATE_H
+
+#include <lib6lowpan/6lowpan.h>
+/*
+ * Defines a programatic representation of the link state of the network.
+ * Also tracks observable statistics about the links present.
+ *
+ */
+
+enum {
+  L_UNREPORTED,
+  L_REPORTED,
+  L_STICKY,
+};
+
+typedef uint16_t node_id_t;
+
+struct route_path {
+  uint16_t len;
+  ieee154_saddr_t path[0];
+};
+
+typedef struct {
+  node_id_t r1;
+  node_id_t r2;
+} link_key_t;
+
+struct router;
+struct link;
+
+typedef struct link {
+  struct router *n1;
+  struct router *n2;
+
+  struct link *next1;
+  struct link *next2;
+
+  int n1_reportcount;
+  int n2_reportcount;
+
+  int marked;
+
+  float qual;
+  int conf;
+  int pc;
+} link_t;
+
+typedef node_id_t router_key_t;
+
+typedef enum bool {
+  FALSE,
+  TRUE,
+} bool_t;
+
+typedef struct router {
+  node_id_t id;
+  link_t *links;
+  struct router *next;
+
+  int reports;
+  int lastSeqno;
+  struct timeval lastReport;
+
+  bool_t isProxying;
+  bool_t isController;
+
+  
+
+  // fields for shortest path
+  // computation
+  struct {
+    // the current estimate of the 
+    // distance to the source
+    float dist;
+    // the current prev pointer
+    struct router *prev;
+    // used for maintaining a list of
+    // vertices we have not yet visited
+    struct router *setptr;
+  } sp;
+} router_t;
+
+typedef struct path {
+  node_id_t node;
+  int length;
+  bool_t isController;
+  struct path *next;
+} path_t;
+
+int nw_init();
+link_t *nw_add_incr_edge(node_id_t v1, struct topology_entry *v2);
+void nw_report_node(node_id_t v);
+path_t *nw_get_route(node_id_t v1, node_id_t v2);
+void nw_free_path(path_t *path);
+void nw_inval_node(node_id_t v);
+router_t *nw_get_router(node_id_t rid);
+router_t *get_insert_router(node_id_t rid);
+void nw_add_controller(node_id_t node);
+void nw_remove_link(node_id_t n1, node_id_t n2);
+
+void nw_unmark_links(node_id_t v);
+void nw_clear_unmarked(node_id_t v);
+
+int  nw_print_dotfile(char *filename);
+void nw_print_routes(int fd, int argc, char **argv);
+void nw_print_links(int fd, int argc, char **argv);
+void nw_test_routes(int fd, int argc, char **argv);
+void nw_add_sticky_edge(int fd, int argc, char **argv);
+void nw_inval_node_sh(int fd, int argc, char **argv);
+
+#endif
diff --git a/support/sdk/c/blip/driver/radvd-1.0/CHANGES b/support/sdk/c/blip/driver/radvd-1.0/CHANGES
new file mode 100644 (file)
index 0000000..2165e2e
--- /dev/null
@@ -0,0 +1,346 @@
+$Id$
+
+11/01/2006     Release 1.0.
+
+10/09/2006     Perform a static/dynamic code audit; plug some minor
+               bugs (see CVS changelogs for more information) and
+               perform minor clean-up.
+
+08/07/2006     Implement MAX_INITIAL_RTR_ADVERT_INTERVAL handling,
+               patch from Yoshifuji Hideaki / USAGI.
+
+05/23/2006     Unblock SIGALRM signals at startup.  Some scripts/programs
+               seem to run radvd from ALRM-blocked context which breaks
+               the timers.
+
+05/23/2006     Redefined IgnoreIfMissing: by default, radvd will now
+               try to reinitialize failed interfaces automatically.
+               IgnoreIfMissing is still needed if radvd is started when the
+               interface isn't up, and it also quenches some messages
+               relating to missing interfaces.
+
+03/29/2006     Implement RDNSS draft, using non-allocated
+               IANA ND type value 25, by Lauréline Provost,
+                Mickaël Guérin, Adrien Clerc, Gaetan Eleouet,
+                Bahattin Demirplak, Lionel Guilmin (at the
+                ENSEEIHT, Toulouse)
+
+03/06/2006     Fix the default STDERR+syslog logging methods, so
+               we don't try to unnecessarily log to STDERR after
+               forking.
+
+01/18/2006     radvd-0.9.1 did not initialize AdvDefaultLifetime (etc.)
+               appropriately, unbreak the "clean-up".
+
+01/13/2006     Release 0.9.1.
+
+12/30/2005     Great cleanup of signed/unsigned values, add
+               -Wall and a number of other warnings to CFLAGS
+               by default.  Do not allow signed values for
+               HomeAgentPreference anymore.
+
+12/30/2005     Fix a couple of  IPv6 Ready Logo Phase-2 IPv6 Core
+               Protocols Self Test issues, patches from Yoshifuji
+               Hideaki / USAGI.
+
+11/13/2005     Create a short FAQ in README file.
+
+10/28/2005     Get interface MTU automatically, so that you can
+               use jumboframes and advertise MTU >1500.
+
+10/19/2005     Release 0.9.
+
+10/18/2005     Transfer sole maintainership of radvd to Pekka Savola.
+
+10/18/2005     Make the radvd.conf syntax dump default
+               in radvdump and remove the previous default to
+               reduce code duplication.
+
+09/28/2005     Add NEMO Basic support (RFC3961) and fix default
+               HomeAgentLifetime, from Ville Nuorvala.
+
+08/18/2005     Implement more robust timer handler, especially
+               because some Linux kernels don't seem to behave
+               all that well; see http://lkml.org/lkml/2005/4/29/163.
+               Based on extensive testing & reports by
+               Tomasz Grobelny.  NB: the bug report was caused by
+               a bad timer patch in PLD's kernel package, and this
+               should not occur often with standard kernels.
+
+07/24/2005     Implement a new logging method "stderr_syslog" which is
+               now also the default.  Everything is logged on syslog,
+               while the most important messages (i.e., start-up failures)
+               are also logged on stderr.
+
+07/08/2005     Release 0.8.
+
+07/05/2005     Change the more-specific route ND option code
+               from de-facto '9' to the official '24'.  Change
+               back in defaults.h if you need old behaviour.
+
+07/05/2005     Fix wrongly calculated prefix with Base6to4Interface
+                on ppc and maybe other big endian arches, from
+               Debian #301543 by Sam Hathaway.
+
+07/05/2005     Fix Linux-2.6.12-bk4+ error with HUP signal,
+               from YOSHIFUJI Hideaki / USAGI.
+
+03/29/2005     Merge a part of MIPv6/non-MIPv6 code, make printing
+               error messages nicer.
+
+03/22/2005     Be a bit more informative about config file parsing
+               errors.
+
+02/21/2005     Release 0.7.3.
+
+02/19/2005     Fix crash when reloading config with AdvSendAdvert off.
+
+02/15/2005     Merge a few fixes and improvements from USAGI:
+                - support microsecond scheduling and fix RA intervals
+                - send zero router lifetime when forwarding is disabled
+                - use a more flexible inter-RA delay
+
+01/07/2005     Accomodate interface indexes > 9999, from Hagen Fritsch.
+
+12/15/2004     Advertise zero Router Lifetime when shutting down;
+               implements a SHOULD in RFC2461 section 6.2.5.
+
+10/16/2004     Update Mobile IPv6 to match RFC 3775, from Greg Daley.
+
+08/20/2004     Minor documentation cleanups.
+
+03/09/2004      Implement "IgnoreIfMissing" interface flag, which can be
+                used on interfaces which aren't enabled when radvd starts
+                but will later become available (e.g., Bluetooth) --
+                and then you wish to send HUP to radvd to activate the
+                configs.
+
+02/21/2004      Further cleanups, to fix autoconf/autoheader problems
+                with newer toolchain; mostly by Marko Myllynen.
+
+02/20/2004      Clean up a bit: remove old junk from configure.in,
+                rename "log()" to "flog()" to satisfy newer GCCs,
+                allow underscores in the interface names (the last two
+                fixes already committed earlier).
+                                                                                
+01/19/2004      Make radvd check for forwarding status using procfs on
+                Linux; needed with 2.6 kernels.  Loosely based on
+                a patch by USAGI.
+
+11/21/2003     Add support for Router Preferences and More Specific
+               Routes from Markku Savela <msa@burp.tkv.asdf.org>.
+               NOTE! The specification is not final yet, there will be
+               changes!  (Man page, documentation and radvdump support
+               by Pekka Savola.)
+
+09/11/2003     When starting up, check if the MAC address is all zero
+               (could happen e.g. with bridge interfaces with no attached
+               physical interfaces), and warn if so. For more information,
+               http://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=103469
+
+06/10/2003     When chrooting, check the possible return code 
+               from chdir("/").
+
+03/08/2003     Add patch from MAEDA Naoaki <maeda.naoaki@jp.fujitsu.com>
+               to discard RS's from the unspecied source address with
+               link-layer address option, as required by RFC2461.
+
+10/28/2002     Release 0.7.2:
+                - add support for VLANs (from USAGI)
+                - make it compile better on newer NetBSD's (NetBSD)
+                - fix a syntax error in radvd.conf(5) sample documentation
+                - use IPV6_RECV{HOPLIMIT,PKTINFO} not 
+                       IPV6_{HOPLIMIT,PKTINFO} if supported
+                - (in Red Hat spec file) don't create radvd gid explicitly
+                - a lot of coding style cleanups
+
+01/16/2002     Release 0.7.1.
+
+01/12/2002     Update config.{guess,sub} from ftp.gnu.org; update INTRO.
+               Marko Myllynen and Debian bug #115992.
+
+01/02/2002     Ensure NULL-termination with strncpy.
+
+12/31/2001     Radvdump fixes: eliminate a warning of Prefix Information
+               sections with '-d -f'; add a note that
+               {Min,Max}RtrAdvInterval cannot be obtained with '-f';
+               implement '-e' to be used with '-f' which omits all
+               advertised default settings. Mostly by Marko Myllynen.
+
+12/28/2001     Small cleanups.  AdvSendAdvert is implicitly off by
+               default.  Check configuration file permissions; must
+               not be writable by others, and if non-root,
+               not by self/own group.  By Marko Myllynen.
+
+12/21/2001     Check via sysctl that IPv6 forwarding is enabled;
+               exit unless debugging is enabled.  Triggered by
+               Marko Myllynen.
+
+11/22/2001     MinRtrAdvInterval for MIPv6 is 0.05 seconds, not 0.5.
+               (Note: untested).
+
+11/20/2001     Rework BSD device memory management a bit, minor cleanups.
+               Version bumped to 0.7.0.
+
+11/14/2001     Maintainership of radvd transferred from Lars Fenneberg
+               to Pekka Savola and Nathan Lutchansky.  Lars' CVS
+               repository adopted, and changes merged from the -pX
+               branch.
+
+08/29/2001     Minor change for NetBSD 1.5.1 compatibility.
+               (Nathan Lutchansky)
+
+07/20/2001     Support for non-multicast links, like ISATAP.
+               (Nathan Lutchansky)
+
+07/03/2001     Minimum MTU has been changed to 1280 in the latest RFC's.
+               (Pekka Savola)
+
+06/30/2001     Check for possible buffer overflows; replace strcpy with
+               strncpy.  No fatals found.  Remove redunant radvd -t check.
+               (Pekka Savola)
+
+06/24/2001     Fix 1-byte overflow in /proc/net/igmp6 handling,
+                clean out possible memory garbage when sending RA's
+               (patch from <yoshfuji@linux-ipv6.org>).
+
+06/19/2001     When dropping root, also set up supplementary groups
+               properly.  On Linux, when sending RA's, check that the
+               interface has joined all-routers multicast group.  Add a few
+               RFC2461 MUST sanity checks when receiving datagrams.  Clean
+               out non-EUI64 addressing scheme and other minor bits.
+               (Pekka Savola)
+
+04/28/2001     Misc cleanup and bugfixes, automake support.
+
+03/28/2001     Grammar cleanup. Integrated 6to4 support through
+               "Base6to4Interface" option in prefix configuration. Signal
+               handling fixed by blocking on select() rather than recvmsg()
+               so SIGTERM/HUP take effect immediately now. (Nathan Lutchansky)
+
+03/27/2001     Security fixes: close stdin/out and chdir("/") via
+               daemon() to prevent possible exploits, and a flag to allow
+               radvd to set[ug]id to an unprivileged user (from Pekka Savola).
+
+02/01/2001     scope_id is not supported in glibc2.1. So it is now
+               compiled conditionally.
+
+01/31/2001     Add CC variable to Makefile. Fix bug with IPV6_ADD_MEMBERSHIP
+               handling. Set scope_id when sending packets.
+
+12/02/2000     man pages update, rewritten pid file handling, rewritten
+               signal handling (SIGHUP and SIGTERM), gcc warnings cleanup,
+               new radvdump option -f: print received RAs in config file
+               format (by Marko)
+
+11/19/2000     integrated the last two change entries into the main source
+               (patches by Marko Myllynen), fixed bug in log.c, fixed file
+               description leak in readin_config, rewrote code in timer.c,
+               updated man pages again (from Marko Myllynen, too), PID
+               file support (patch from Marko Myllynen, based on a patch
+               from Tommi.Komulainen@iki.fi)
+
+15/08/2000     RFC 2461 updates, Mobile IPv6 extensions added
+
+14/07/2000     added RA interval option and modified some default values
+               for timers
+
+06/15/99       changed to run with glibc 2.1 on RedHat 6.0.
+
+03/03/98       radvd now joins ipv6-allrouters on Linux.  Fix contributed
+               by A.N.Kuznetsov <kuznet@ms2.inr.ac.ru>.
+
+10/23/97       radvd will now accept any prefix length in its config
+               file but will warn about unusual ones
+
+10/19/97       removed backwards compatibility code in recv.c.
+               IPV6_HOPLIMIT support is now assumed to exist.
+
+10/19/97       fixed alignment problems in recv.c and send.c.
+
+10/16/97       the Makefile install target now uses mkinstalldirs.
+
+10/16/97       changed all u_int*_t to uint*_t for better POSIX
+               compliance and portability. Needs 2.1.57-CVS or glibc.
+               BSD seems to need patches.
+
+10/16/97       more intelligent configure; tries to figure out
+               where the IPv6 libraries and inclues are (if not in
+               the standard places). Searches in /usr/inet6 and /usr/ipv6.
+
+10/15/97       integrated small patches for glibc and BSD from Craig and
+               Philip
+
+09/14/97       EUI-64 "support"
+
+09/01/97       centralized all includes into includes.h for easier
+               maintainance
+
+08/25/97       changed all occurences of IPV6_TXINFO/IPV6_RXINFO
+               to IPV6_PKTINFO
+
+08/25/97       removed some compatibility stuff for older Linux kernels
+
+03/17/97       changed linux/if_arp.h to net/if_arp.h in device-linux.c
+               and configure.in (for glibc compatibility)
+
+03/17/97       integrated patch from Philip Blundell <pjb27@cam.ac.uk>
+               into configure.in to check for inet_* in libc first and
+               then for libinet6 (for glibc compatibility).
+
+03/16/97       corrected small error in radvd.conf(5) man page and other
+               small changes
+
+03/16/97       removed linklocal.c source file from the distribution
+               because it wasn't used anymore
+
+03/16/97       added html version of the INTRO, removed ascii version.
+
+02/12/97       missing directories are now created on make install
+
+01/19/97       now also the rest of a line followed by a '#' is treated
+               as a comment in the config file
+
+01/16/97       added IPPROTO_IPV6/IPV6_HOPLIMIT support, so now incoming
+               RS' and RAs are checked if there hoplimit is 255 (on Linux
+               this only works with kernel version 2.1.21 and above)
+
+01/15/97       lots of portability cleanups; radvd is now using autoconf
+               for automatic configuration; removed support for the
+               in. prefix
+
+01/05/97       integrated BSD 4.4 patches from Craig <cmetz@inner.net>
+
+12/21/96       release of version 0.3
+
+12/15/96       the AdvSendAdvert flag works now
+
+12/14/96       added radvdump, dumps all received RAs in a human
+               readable form   
+
+12/13/96       rewrote radvd to use new advanced API headers
+
+12/08/96       added radvd.conf(5) man page
+
+12/03/96       changed RAW_CHECKSUM to IPV6_CHECKSUM for kernels
+               2.1.14 and above
+
+11/24/96       added checking of received RAs according to RFC 1970
+
+11/20/96       rewrote the default handling, now it should conform
+               to RFC 1970
+
+11/17/96       release of version 0.2
+       
+11/17/96       added -h (--help) and -f (--facility) option
+
+11/17/96       added setsockopt(..., SOL_IPV6, IPV6_MULTICAST_HOPS), so
+               that radvd works for kernel versions >2.1.7 (without this
+               you get "NDISC: fake router advertisment received" on your
+               hosts)
+       
+11/17/96       added a man page for radvd(8)
+
+11/17/96       some minor filename changes
+
+11/13/96       first release of this version of in.radvd (0.1)
diff --git a/support/sdk/c/blip/driver/radvd-1.0/COPYRIGHT b/support/sdk/c/blip/driver/radvd-1.0/COPYRIGHT
new file mode 100644 (file)
index 0000000..1f464b0
--- /dev/null
@@ -0,0 +1,37 @@
+  The author(s) grant permission for redistribution and use in source and
+binary forms, with or without modification, of the software and documentation
+provided that the following conditions are met:
+
+0. If you receive a version of the software that is specifically labelled
+   as not being for redistribution (check the version message and/or README),
+   you are not permitted to redistribute that version of the software in any
+   way or form.
+1. All terms of all other applicable copyrights and licenses must be
+   followed.
+2. Redistributions of source code must retain the authors' copyright
+   notice(s), this list of conditions, and the following disclaimer.
+3. Redistributions in binary form must reproduce the authors' copyright
+   notice(s), this list of conditions, and the following disclaimer in the
+   documentation and/or other materials provided with the distribution.
+4. All advertising materials mentioning features or use of this software
+   must display the following acknowledgement with the name(s) of the
+   authors as specified in the copyright notice(s) substituted where
+   indicated:
+
+        This product includes software developed by the authors which are 
+       mentioned at the start of the source files and other contributors.
+
+5. Neither the name(s) of the author(s) nor the names of its contributors
+   may be used to endorse or promote products derived from this software
+   without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY ITS AUTHORS AND CONTRIBUTORS ``AS IS'' AND ANY
+EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/support/sdk/c/blip/driver/radvd-1.0/INTRO.html b/support/sdk/c/blip/driver/radvd-1.0/INTRO.html
new file mode 100644 (file)
index 0000000..29ea681
--- /dev/null
@@ -0,0 +1,142 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
+<!-- $Id$ -->
+<html lang="en">
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+<title>RADVD Introduction</title>
+</head>
+
+<body>
+<h1>RADVD Introduction</h1>
+
+<p>
+by <a href="mailto:lf@elemental.net">Lars Fenneberg</a> et al. Updated
+2002-01-12.
+</p>
+
+<p>
+<a href="http://www.ietf.org/rfc/rfc2460.txt">IPv6</a> has a lot more
+support for autoconfiguration than
+<a href="http://www.ietf.org/rfc/rfc791.txt">IPv4</a>. But for this
+autoconfiguration to work on the hosts of a network, the <em>routers</em>
+of the local network have to run a program which answers the
+autoconfiguration requests of the hosts.
+</p>
+
+<p>
+On Linux this program is called
+<a href="http://v6web.litech.org/radvd/">radvd</a>, which stands for
+Router ADVertisement Daemon. This daemon listens to Router Solicitations
+(RS) and answers with Router Advertisement (RA). Furthermore unsolicited
+RAs are also send from time to time.
+<a href="http://www.ietf.org/rfc/rfc2461.txt">RFC 2461</a> defines most
+functions of radvd.
+</p>
+
+<p>
+Router Advertisements contain information, which is used by hosts to
+configure their interfaces. This information includes address prefixes,
+the MTU of the link and information about default routers.
+</p>
+
+<p>
+Of course the routers can't autoconfigure themselves, so the information
+on the routers has to be provided by the administrator of the system.
+This is done by manually configuring the interfaces and routes and by
+configuring the router advertisement daemon.
+</p>
+
+<p>
+A small and simple configuration file for radvd might look like this:
+</p>
+
+<p>
+<pre>
+
+interface eth0
+{
+        AdvSendAdvert on;
+        prefix 2001:db8:0:1::/64
+        {
+                AdvOnLink on;
+                AdvAutonomous on;
+        };
+};
+
+</pre>
+
+<p>
+It says that radvd should advertise (AdvSendAdvert on) the prefix
+2001:db8:0:1:: which has a lenght of 64 on the interface eth0.
+Also the prefix is marked as autonomous (AdvAutonomous on) and as on-link
+(AdvOnLink on). The both currently default to enabled but are included
+here for introductory purposes; it isn't necessary to define them.
+All the other options are left on their default values.
+</p>
+
+<p>
+Autonomous means that the prefix can be used for automatic address
+configuration and on-link means that the hosts can assume that all the hosts
+which use this prefix are reachable via the interface on which the host
+received this RA.
+</p>
+
+<p>
+The prefix must be 64 bits long (apart from very few exceptions), as dictated by
+<a href="http://www.ietf.org/rfc/rfc2464.txt">RFC 2464</a> and other
+standards for different link-layer technologies. For more
+details, see <a href="http://www.ietf.org/rfc/rfc2462.txt">RFC 2462</a>
+(IPv6 Stateless Address Autoconfiguration) and
+<a href="http://www.ietf.org/rfc/rfc2464.txt">RFC 2464</a>
+(Transmission of IPv6 Packets over Ethernet Networks). For more information
+on configuring radvd please look at the manual pages which are included in
+the radvd distribution.
+</p>
+
+<p>
+So, when an interface on a hosts is UPed and a RA is received, the host
+can configure an address on the interface by using the prefix and
+appending the EUI-64 identifier derived from the hardware address
+(also called link-layer token). The EUI-64 identifier is simply appended
+after the prefix. For example:
+</p>
+
+<p>
+<pre>
+
+   Announced prefix:    2001:db8:0:1::
+
+   MAC address:         00:07:E9:7B:02:59
+
+   EUI-64 identifier:   0207:e9ff:fe7b:259
+
+   Configured address:  2001:db8:0:1:207:e9ff:fe7b:259
+
+</pre>
+
+<p>
+The host can also choose a default router by examining the RA.
+the rest works automatically.
+</p>
+
+<p>
+So now we've configured radvd, but we still need to configure the interfaces
+and set the routes (on the router).  There's a lot of good material on
+setting up IPv6, and the reader is encouraged to have a look
+at it; for example:
+</p>
+
+<p>
+<ul>
+<li><a href="http://www.bieringer.de/linux/IPv6/IPv6-HOWTO/IPv6-HOWTO.html">http://www.bieringer.de/linux/IPv6/IPv6-HOWTO/IPv6-HOWTO.html</a></li>
+<li><a href="http://people.debian.org/~csmall/ipv6/setup.html">http://people.debian.org/~csmall/ipv6/setup.html</a> (for non-Debian too)</li>
+</ul>
+
+<hr>
+
+<p>
+Copyright &copy; 1997 <a href="mailto:lf@elemental.net">Lars Fenneberg</a>
+</p>
+
+</body>
+</html>
diff --git a/support/sdk/c/blip/driver/radvd-1.0/Makefile.am b/support/sdk/c/blip/driver/radvd-1.0/Makefile.am
new file mode 100644 (file)
index 0000000..11ce3ad
--- /dev/null
@@ -0,0 +1,63 @@
+#
+#   $Id$
+#
+#   Authors:
+#    Lars Fenneberg            <lf@elemental.net>       
+#
+#   This software is Copyright 1996,1997 by the above mentioned author(s), 
+#   All Rights Reserved.
+#
+#   The license which is distributed with this software in the file COPYRIGHT
+#   applies to this software. If your distribution is missing this file, you
+#   may request it from <pekkas@netcore.fi>.
+#
+
+AUTOMAKE_OPTIONS = 1.2 foreign
+
+DEFS=  -DPATH_RADVD_CONF=\"$(PATH_RADVD_CONF)\" \
+       -DPATH_RADVD_LOG=\"$(PATH_RADVD_LOG)\" -DLOG_FACILITY=$(LOG_FACILITY) \
+       -DPATH_RADVD_PID=\"$(PATH_RADVD_PID)\" \
+       -DVERSION=\"$(VERSION)\" -DINET6=1
+INCLUDES=-I$(srcdir) -I.
+
+########################################################################
+
+COMMON_SRC = log.c socket.c recv.c util.c radvd.h defaults.h pathnames.h \
+       includes.h
+
+sbin_PROGRAMS = radvd radvdump
+
+radvd_SOURCES = $(COMMON_SRC) radvd.c timer.c send.c process.c interface.c \
+       device.c device-common.c gram.y gram.h scanner.l
+radvd_LDADD = -lfl
+EXTRA_radvd_SOURCES = device-linux.c device-bsd44.c
+YFLAGS = -d
+CFLAGS = @CFLAGS@ -Wall -Wpointer-arith  -Wcast-qual -Wcast-align -Wconversion \
+       -Wstrict-prototypes -Wmissing-prototypes -Wmissing-declarations -D_GNU_SOURCE
+
+radvdump_SOURCES = $(COMMON_SRC) radvdump.c
+
+man_MANS = radvd.8 radvdump.8 radvd.conf.5
+EXTRA_DIST = radvd.8.man radvdump.8.man radvd.conf.5.man VERSION CHANGES \
+       COPYRIGHT INTRO.html copyright.blurb radvd.conf.example
+BUILT_SOURCES = device.c
+
+CLEANFILES = radvd.8 radvdump.8 radvd.conf.5
+DISTCLEANFILES = device.c
+
+SUFFIXES = .man
+
+.man:
+       $(SED)  -e 's,@''VERSION''@,$(VERSION),g' \
+               -e 's,@''sbindir''@,$(sbindir),g' \
+               -e 's,@''PATH_RADVD_CONF''@,$(PATH_RADVD_CONF),g' \
+               -e 's,@''PATH_RADVD_PID''@,$(PATH_RADVD_PID),g' \
+               -e 's,@''PATH_RADVD_LOG''@,$(PATH_RADVD_LOG),g' \
+               -e 's,@''LOG_FACILITY''@,$(LOG_FACILITY),g' \
+               $< > $@
+
+dist-hook:
+       rm -f $(distdir)/device.c       
+       mkdir $(distdir)/redhat
+       cp -p $(srcdir)/redhat/radvd.init $(srcdir)/redhat/radvd.spec \
+               $(srcdir)/redhat/radvd.sysconfig $(distdir)/redhat
diff --git a/support/sdk/c/blip/driver/radvd-1.0/README b/support/sdk/c/blip/driver/radvd-1.0/README
new file mode 100644 (file)
index 0000000..98a722e
--- /dev/null
@@ -0,0 +1,61 @@
+$Id$
+
+Installation:
+=============
+
+Run configure, e.g.
+
+./configure --prefix=/usr/local --sysconfdir=/etc --mandir=/usr/share/man
+
+See configure --help for additional command line arguments.
+
+Run 'make' and 'make install'.  On BSD, you may need to use 'gmake'.
+
+Configuration:
+==============
+
+See INTRO.html, radvd.conf(8) and radvd.conf.example.
+
+Frequently Asked Questions:
+===========================
+
+Setting up radvd is very simple, so the most frequently asked
+questions have been about what radvd _doesn't_ do...
+
+ 1. How do I set up the router running radvd to automatically
+    configure an address from the prefix advertised in Route
+    Advertisements from upstream?
+
+    -- You don't.  By the specification, routers ignore RAs.
+    You'll probably need to use manual configuration.  But you
+    can't use the same prefix on two links in any case unless you
+    use something like proxy-ND (draft-ietf-ipv6-ndproxy-04.txt).
+    You may need to re-think your topology; prefix delegation
+    (e.g., manually or with RFC3633) may help.
+
+ 2. How do I set up the router running radvd to automatically
+    configure the interfaces to use an EUI64-based address?
+
+    -- You don't.  The design philosophy of radvd is that it's
+    not the _router's_ configuration tool, but a route advertising
+    daemon.  You'll need to set up all the addresses, routes, etc.
+    yourself.  These tasks are something that system initscripts
+    could possibly do instead.
+
+ 3. I have a dynamic /48 prefix.  How do I set up radvd to:
+    a) set up interface addresses and routes on downstream
+       interfaces, and
+    b) advertise /64 prefixes from the /48 on downstream interfaces?
+
+    -- For a), this isn't supported. For b), radvd includes special
+    support for 6to4 upstream interface but assumes that the interface
+    addresses/routes are set up manually.  This should probably
+    be done in the initscripts or manually. (Though if someone were
+    to send a patch for b), it might be incorporated.)  
+
+ 4. How do I set up radvd to do either unicast or multicast routing?
+
+    -- You don't.  Radvd is not a routing or forwarding daemon.
+    You need to set any appropriate routing/forwarding first,
+    and then radvd to only advertise the prefixes to hosts as
+    appropriate.
diff --git a/support/sdk/c/blip/driver/radvd-1.0/TODO b/support/sdk/c/blip/driver/radvd-1.0/TODO
new file mode 100644 (file)
index 0000000..d1444a7
--- /dev/null
@@ -0,0 +1,59 @@
+$Id$
+
+                       NOTE WELL
+                       =========
+
+       *NONE* of the items are being actively worked on.
+        So, if you're interested in one of these features,
+        it means you'll have to submit a patch... :-)
+
+
+read list of interfaces with SIOCGIFCONF (AF_INET6 support in the kernel would
+be nice) or from /proc
+
+Quoting Peter Bieringer (peter@bieringer.de):
+> Das war's schon. Ach ja, wenn Du mal eine neue Version machst, kannst Du
+> noch einen Schalter einbauen, damit radvd trotz debug-level >0 auf Wunsch
+> als daemon in den Hintergrund starten kann?
+[ Peter wants that a debugging level greater than 0 doesn't stop radvd
+from forking.]
+
+support for few protocol constants defined in RFC 2461 Sec 10 is missing.
+
+consider whether UnicastOnly flag should be detected by radvdump.
+
+read the man pages one more time and make sure their are understandable
+and English is correct
+
+The following parts of RFC2461(bis) are not implemented:
+ - section 6.2.1: Adv{Valid,Preferred}Lifetime that decrements in real time,
+   that is, one that will result in a Lifetime of zero at the specified time in
+   the future. (MUST)
+ - section 6.2.5: when AdvSendAdvertisements changes to FALSE, we don't send 
+   a final RA with zero Router Lifetime (we just send it when shutting down).
+   (SHOULD)
+ - section 6.2.8: if the link-local address of the router changes, it should
+   multicast a few RAs from the old address with zero router lifetime, and a
+   few from the new address. (SHOULD).
+
+Consider whether to support RFC 4286 (Multicast Router Discovery).
+
+Consider whether to support multiple IPv4 addresses with Base6to4Interface
+(currently the code just uses the first one).
+
+Consider whether to support a generalization of Base6to4Interface for
+arbitrary IPv6 prefixes, to be used for automatic generation of downstream
+prefixes.  Also consider whether this would need to support multiple IPv6
+prefixes on the upstream interfaces.  See question 3 in README for more on
+this.
+
+Use getifaddrs() instead of ioctl SIOCGIFADDR and other friends.  The
+problem with this is that e.g. RHL73's glibc didn't support getifaddrs(),
+and before glibc 2.3.3 getifaddrs() didn't use netlink so it didn't work
+well with IPv6.  So, some kind of compat library would be needed if this
+would be used...
+
+Consider whether radvd should work around missing/broken interfaces by
+default, especially if a previously working interface gets disabled.
+
+Implement Secure Neighbor Discovery (RFC 3971).
diff --git a/support/sdk/c/blip/driver/radvd-1.0/VERSION b/support/sdk/c/blip/driver/radvd-1.0/VERSION
new file mode 100644 (file)
index 0000000..9fb98e8
--- /dev/null
@@ -0,0 +1,6 @@
+#
+# $Id$
+#
+# this file is automatically processed by configure
+#
+1.0
diff --git a/support/sdk/c/blip/driver/radvd-1.0/config.guess b/support/sdk/c/blip/driver/radvd-1.0/config.guess
new file mode 100755 (executable)
index 0000000..aa6ea3f
--- /dev/null
@@ -0,0 +1,1319 @@
+#! /bin/sh
+# Attempt to guess a canonical system name.
+#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+#   2000, 2001, 2002 Free Software Foundation, Inc.
+
+timestamp='2002-01-10'
+
+# This file is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+#
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# Originally written by Per Bothner <per@bothner.com>.
+# Please send patches to <config-patches@gnu.org>.  Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# This script attempts to guess a canonical system name similar to
+# config.sub.  If it succeeds, it prints the system name on stdout, and
+# exits with 0.  Otherwise, it exits with 1.
+#
+# The plan is that this can be called by configure scripts if you
+# don't specify an explicit build system type.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION]
+
+Output the configuration name of the system \`$me' is run on.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.guess ($timestamp)
+
+Originally written by Per Bothner.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions.  There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit 0 ;;
+    --version | -v )
+       echo "$version" ; exit 0 ;;
+    --help | --h* | -h )
+       echo "$usage"; exit 0 ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )        # Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help" >&2
+       exit 1 ;;
+    * )
+       break ;;
+  esac
+done
+
+if test $# != 0; then
+  echo "$me: too many arguments$help" >&2
+  exit 1
+fi
+
+
+dummy=dummy-$$
+trap 'rm -f $dummy.c $dummy.o $dummy.rel $dummy; exit 1' 1 2 15
+
+# CC_FOR_BUILD -- compiler used by this script.
+# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still
+# use `HOST_CC' if defined, but it is deprecated.
+
+set_cc_for_build='case $CC_FOR_BUILD,$HOST_CC,$CC in
+ ,,)    echo "int dummy(){}" > $dummy.c ;
+       for c in cc gcc c89 ; do
+         ($c $dummy.c -c -o $dummy.o) >/dev/null 2>&1 ;
+         if test $? = 0 ; then
+            CC_FOR_BUILD="$c"; break ;
+         fi ;
+       done ;
+       rm -f $dummy.c $dummy.o $dummy.rel ;
+       if test x"$CC_FOR_BUILD" = x ; then
+         CC_FOR_BUILD=no_compiler_found ;
+       fi
+       ;;
+ ,,*)   CC_FOR_BUILD=$CC ;;
+ ,*,*)  CC_FOR_BUILD=$HOST_CC ;;
+esac'
+
+# This is needed to find uname on a Pyramid OSx when run in the BSD universe.
+# (ghazi@noc.rutgers.edu 1994-08-24)
+if (test -f /.attbin/uname) >/dev/null 2>&1 ; then
+       PATH=$PATH:/.attbin ; export PATH
+fi
+
+UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown
+UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown
+UNAME_SYSTEM=`(uname -s) 2>/dev/null`  || UNAME_SYSTEM=unknown
+UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown
+
+# Note: order is significant - the case branches are not exclusive.
+
+case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in
+    *:NetBSD:*:*)
+       # NetBSD (nbsd) targets should (where applicable) match one or
+       # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*,
+       # *-*-netbsdecoff* and *-*-netbsd*.  For targets that recently
+       # switched to ELF, *-*-netbsd* would select the old
+       # object file format.  This provides both forward
+       # compatibility and a consistent mechanism for selecting the
+       # object file format.
+       #
+       # Note: NetBSD doesn't particularly care about the vendor
+       # portion of the name.  We always set it to "unknown".
+       UNAME_MACHINE_ARCH=`(uname -p) 2>/dev/null` || \
+           UNAME_MACHINE_ARCH=unknown
+       case "${UNAME_MACHINE_ARCH}" in
+           arm*) machine=arm-unknown ;;
+           sh3el) machine=shl-unknown ;;
+           sh3eb) machine=sh-unknown ;;
+           *) machine=${UNAME_MACHINE_ARCH}-unknown ;;
+       esac
+       # The Operating System including object format, if it has switched
+       # to ELF recently, or will in the future.
+       case "${UNAME_MACHINE_ARCH}" in
+           arm*|i386|m68k|ns32k|sh3*|sparc|vax)
+               eval $set_cc_for_build
+               if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \
+                       | grep __ELF__ >/dev/null
+               then
+                   # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout).
+                   # Return netbsd for either.  FIX?
+                   os=netbsd
+               else
+                   os=netbsdelf
+               fi
+               ;;
+           *)
+               os=netbsd
+               ;;
+       esac
+       # The OS release
+       release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'`
+       # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM:
+       # contains redundant information, the shorter form:
+       # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used.
+       echo "${machine}-${os}${release}"
+       exit 0 ;;
+    amiga:OpenBSD:*:*)
+       echo m68k-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    arc:OpenBSD:*:*)
+       echo mipsel-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    hp300:OpenBSD:*:*)
+       echo m68k-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    mac68k:OpenBSD:*:*)
+       echo m68k-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    macppc:OpenBSD:*:*)
+       echo powerpc-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    mvme68k:OpenBSD:*:*)
+       echo m68k-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    mvme88k:OpenBSD:*:*)
+       echo m88k-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    mvmeppc:OpenBSD:*:*)
+       echo powerpc-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    pmax:OpenBSD:*:*)
+       echo mipsel-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    sgi:OpenBSD:*:*)
+       echo mipseb-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    sun3:OpenBSD:*:*)
+       echo m68k-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    wgrisc:OpenBSD:*:*)
+       echo mipsel-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    *:OpenBSD:*:*)
+       echo ${UNAME_MACHINE}-unknown-openbsd${UNAME_RELEASE}
+       exit 0 ;;
+    alpha:OSF1:*:*)
+       if test $UNAME_RELEASE = "V4.0"; then
+               UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'`
+       fi
+       # A Vn.n version is a released version.
+       # A Tn.n version is a released field test version.
+       # A Xn.n version is an unreleased experimental baselevel.
+       # 1.2 uses "1.2" for uname -r.
+       cat <<EOF >$dummy.s
+       .data
+\$Lformat:
+       .byte 37,100,45,37,120,10,0     # "%d-%x\n"
+
+       .text
+       .globl main
+       .align 4
+       .ent main
+main:
+       .frame \$30,16,\$26,0
+       ldgp \$29,0(\$27)
+       .prologue 1
+       .long 0x47e03d80 # implver \$0
+       lda \$2,-1
+       .long 0x47e20c21 # amask \$2,\$1
+       lda \$16,\$Lformat
+       mov \$0,\$17
+       not \$1,\$18
+       jsr \$26,printf
+       ldgp \$29,0(\$26)
+       mov 0,\$16
+       jsr \$26,exit
+       .end main
+EOF
+       eval $set_cc_for_build
+       $CC_FOR_BUILD $dummy.s -o $dummy 2>/dev/null
+       if test "$?" = 0 ; then
+               case `./$dummy` in
+                       0-0)
+                               UNAME_MACHINE="alpha"
+                               ;;
+                       1-0)
+                               UNAME_MACHINE="alphaev5"
+                               ;;
+                       1-1)
+                               UNAME_MACHINE="alphaev56"
+                               ;;
+                       1-101)
+                               UNAME_MACHINE="alphapca56"
+                               ;;
+                       2-303)
+                               UNAME_MACHINE="alphaev6"
+                               ;;
+                       2-307)
+                               UNAME_MACHINE="alphaev67"
+                               ;;
+                       2-1307)
+                               UNAME_MACHINE="alphaev68"
+                               ;;
+               esac
+       fi
+       rm -f $dummy.s $dummy
+       echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[VTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+       exit 0 ;;
+    Alpha\ *:Windows_NT*:*)
+       # How do we know it's Interix rather than the generic POSIX subsystem?
+       # Should we change UNAME_MACHINE based on the output of uname instead
+       # of the specific Alpha model?
+       echo alpha-pc-interix
+       exit 0 ;;
+    21064:Windows_NT:50:3)
+       echo alpha-dec-winnt3.5
+       exit 0 ;;
+    Amiga*:UNIX_System_V:4.0:*)
+       echo m68k-unknown-sysv4
+       exit 0;;
+    *:[Aa]miga[Oo][Ss]:*:*)
+       echo ${UNAME_MACHINE}-unknown-amigaos
+       exit 0 ;;
+    *:[Mm]orph[Oo][Ss]:*:*)
+       echo ${UNAME_MACHINE}-unknown-morphos
+       exit 0 ;;
+    *:OS/390:*:*)
+       echo i370-ibm-openedition
+       exit 0 ;;
+    arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*)
+       echo arm-acorn-riscix${UNAME_RELEASE}
+       exit 0;;
+    SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*)
+       echo hppa1.1-hitachi-hiuxmpp
+       exit 0;;
+    Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*)
+       # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE.
+       if test "`(/bin/universe) 2>/dev/null`" = att ; then
+               echo pyramid-pyramid-sysv3
+       else
+               echo pyramid-pyramid-bsd
+       fi
+       exit 0 ;;
+    NILE*:*:*:dcosx)
+       echo pyramid-pyramid-svr4
+       exit 0 ;;
+    sun4H:SunOS:5.*:*)
+       echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+       exit 0 ;;
+    sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*)
+       echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+       exit 0 ;;
+    i86pc:SunOS:5.*:*)
+       echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+       exit 0 ;;
+    sun4*:SunOS:6*:*)
+       # According to config.sub, this is the proper way to canonicalize
+       # SunOS6.  Hard to guess exactly what SunOS6 will be like, but
+       # it's likely to be more like Solaris than SunOS4.
+       echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+       exit 0 ;;
+    sun4*:SunOS:*:*)
+       case "`/usr/bin/arch -k`" in
+           Series*|S4*)
+               UNAME_RELEASE=`uname -v`
+               ;;
+       esac
+       # Japanese Language versions have a version number like `4.1.3-JL'.
+       echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'`
+       exit 0 ;;
+    sun3*:SunOS:*:*)
+       echo m68k-sun-sunos${UNAME_RELEASE}
+       exit 0 ;;
+    sun*:*:4.2BSD:*)
+       UNAME_RELEASE=`(head -1 /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null`
+       test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3
+       case "`/bin/arch`" in
+           sun3)
+               echo m68k-sun-sunos${UNAME_RELEASE}
+               ;;
+           sun4)
+               echo sparc-sun-sunos${UNAME_RELEASE}
+               ;;
+       esac
+       exit 0 ;;
+    aushp:SunOS:*:*)
+       echo sparc-auspex-sunos${UNAME_RELEASE}
+       exit 0 ;;
+    # The situation for MiNT is a little confusing.  The machine name
+    # can be virtually everything (everything which is not
+    # "atarist" or "atariste" at least should have a processor
+    # > m68000).  The system name ranges from "MiNT" over "FreeMiNT"
+    # to the lowercase version "mint" (or "freemint").  Finally
+    # the system name "TOS" denotes a system which is actually not
+    # MiNT.  But MiNT is downward compatible to TOS, so this should
+    # be no problem.
+    atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*)
+        echo m68k-atari-mint${UNAME_RELEASE}
+       exit 0 ;;
+    atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*)
+       echo m68k-atari-mint${UNAME_RELEASE}
+        exit 0 ;;
+    *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*)
+        echo m68k-atari-mint${UNAME_RELEASE}
+       exit 0 ;;
+    milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*)
+        echo m68k-milan-mint${UNAME_RELEASE}
+        exit 0 ;;
+    hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*)
+        echo m68k-hades-mint${UNAME_RELEASE}
+        exit 0 ;;
+    *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*)
+        echo m68k-unknown-mint${UNAME_RELEASE}
+        exit 0 ;;
+    powerpc:machten:*:*)
+       echo powerpc-apple-machten${UNAME_RELEASE}
+       exit 0 ;;
+    RISC*:Mach:*:*)
+       echo mips-dec-mach_bsd4.3
+       exit 0 ;;
+    RISC*:ULTRIX:*:*)
+       echo mips-dec-ultrix${UNAME_RELEASE}
+       exit 0 ;;
+    VAX*:ULTRIX*:*:*)
+       echo vax-dec-ultrix${UNAME_RELEASE}
+       exit 0 ;;
+    2020:CLIX:*:* | 2430:CLIX:*:*)
+       echo clipper-intergraph-clix${UNAME_RELEASE}
+       exit 0 ;;
+    mips:*:*:UMIPS | mips:*:*:RISCos)
+       eval $set_cc_for_build
+       sed 's/^        //' << EOF >$dummy.c
+#ifdef __cplusplus
+#include <stdio.h>  /* for printf() prototype */
+       int main (int argc, char *argv[]) {
+#else
+       int main (argc, argv) int argc; char *argv[]; {
+#endif
+       #if defined (host_mips) && defined (MIPSEB)
+       #if defined (SYSTYPE_SYSV)
+         printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0);
+       #endif
+       #if defined (SYSTYPE_SVR4)
+         printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0);
+       #endif
+       #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD)
+         printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0);
+       #endif
+       #endif
+         exit (-1);
+       }
+EOF
+       $CC_FOR_BUILD $dummy.c -o $dummy \
+         && ./$dummy `echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` \
+         && rm -f $dummy.c $dummy && exit 0
+       rm -f $dummy.c $dummy
+       echo mips-mips-riscos${UNAME_RELEASE}
+       exit 0 ;;
+    Motorola:PowerMAX_OS:*:*)
+       echo powerpc-motorola-powermax
+       exit 0 ;;
+    Night_Hawk:Power_UNIX:*:*)
+       echo powerpc-harris-powerunix
+       exit 0 ;;
+    m88k:CX/UX:7*:*)
+       echo m88k-harris-cxux7
+       exit 0 ;;
+    m88k:*:4*:R4*)
+       echo m88k-motorola-sysv4
+       exit 0 ;;
+    m88k:*:3*:R3*)
+       echo m88k-motorola-sysv3
+       exit 0 ;;
+    AViiON:dgux:*:*)
+        # DG/UX returns AViiON for all architectures
+        UNAME_PROCESSOR=`/usr/bin/uname -p`
+       if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ]
+       then
+           if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \
+              [ ${TARGET_BINARY_INTERFACE}x = x ]
+           then
+               echo m88k-dg-dgux${UNAME_RELEASE}
+           else
+               echo m88k-dg-dguxbcs${UNAME_RELEASE}
+           fi
+       else
+           echo i586-dg-dgux${UNAME_RELEASE}
+       fi
+       exit 0 ;;
+    M88*:DolphinOS:*:*)        # DolphinOS (SVR3)
+       echo m88k-dolphin-sysv3
+       exit 0 ;;
+    M88*:*:R3*:*)
+       # Delta 88k system running SVR3
+       echo m88k-motorola-sysv3
+       exit 0 ;;
+    XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3)
+       echo m88k-tektronix-sysv3
+       exit 0 ;;
+    Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD)
+       echo m68k-tektronix-bsd
+       exit 0 ;;
+    *:IRIX*:*:*)
+       echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'`
+       exit 0 ;;
+    ????????:AIX?:[12].1:2)   # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX.
+       echo romp-ibm-aix      # uname -m gives an 8 hex-code CPU id
+       exit 0 ;;              # Note that: echo "'`uname -s`'" gives 'AIX '
+    i*86:AIX:*:*)
+       echo i386-ibm-aix
+       exit 0 ;;
+    ia64:AIX:*:*)
+       if [ -x /usr/bin/oslevel ] ; then
+               IBM_REV=`/usr/bin/oslevel`
+       else
+               IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+       fi
+       echo ${UNAME_MACHINE}-ibm-aix${IBM_REV}
+       exit 0 ;;
+    *:AIX:2:3)
+       if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then
+               eval $set_cc_for_build
+               sed 's/^                //' << EOF >$dummy.c
+               #include <sys/systemcfg.h>
+
+               main()
+                       {
+                       if (!__power_pc())
+                               exit(1);
+                       puts("powerpc-ibm-aix3.2.5");
+                       exit(0);
+                       }
+EOF
+               $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0
+               rm -f $dummy.c $dummy
+               echo rs6000-ibm-aix3.2.5
+       elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then
+               echo rs6000-ibm-aix3.2.4
+       else
+               echo rs6000-ibm-aix3.2
+       fi
+       exit 0 ;;
+    *:AIX:*:[45])
+       IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | head -1 | awk '{ print $1 }'`
+       if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then
+               IBM_ARCH=rs6000
+       else
+               IBM_ARCH=powerpc
+       fi
+       if [ -x /usr/bin/oslevel ] ; then
+               IBM_REV=`/usr/bin/oslevel`
+       else
+               IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE}
+       fi
+       echo ${IBM_ARCH}-ibm-aix${IBM_REV}
+       exit 0 ;;
+    *:AIX:*:*)
+       echo rs6000-ibm-aix
+       exit 0 ;;
+    ibmrt:4.4BSD:*|romp-ibm:BSD:*)
+       echo romp-ibm-bsd4.4
+       exit 0 ;;
+    ibmrt:*BSD:*|romp-ibm:BSD:*)            # covers RT/PC BSD and
+       echo romp-ibm-bsd${UNAME_RELEASE}   # 4.3 with uname added to
+       exit 0 ;;                           # report: romp-ibm BSD 4.3
+    *:BOSX:*:*)
+       echo rs6000-bull-bosx
+       exit 0 ;;
+    DPX/2?00:B.O.S.:*:*)
+       echo m68k-bull-sysv3
+       exit 0 ;;
+    9000/[34]??:4.3bsd:1.*:*)
+       echo m68k-hp-bsd
+       exit 0 ;;
+    hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*)
+       echo m68k-hp-bsd4.4
+       exit 0 ;;
+    9000/[34678]??:HP-UX:*:*)
+       HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+       case "${UNAME_MACHINE}" in
+           9000/31? )            HP_ARCH=m68000 ;;
+           9000/[34]?? )         HP_ARCH=m68k ;;
+           9000/[678][0-9][0-9])
+               if [ -x /usr/bin/getconf ]; then
+                   sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null`
+                    sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null`
+                    case "${sc_cpu_version}" in
+                      523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0
+                      528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1
+                      532)                      # CPU_PA_RISC2_0
+                        case "${sc_kernel_bits}" in
+                          32) HP_ARCH="hppa2.0n" ;;
+                          64) HP_ARCH="hppa2.0w" ;;
+                         '') HP_ARCH="hppa2.0" ;;   # HP-UX 10.20
+                        esac ;;
+                    esac
+               fi
+               if [ "${HP_ARCH}" = "" ]; then
+                   eval $set_cc_for_build
+                   sed 's/^              //' << EOF >$dummy.c
+
+              #define _HPUX_SOURCE
+              #include <stdlib.h>
+              #include <unistd.h>
+
+              int main ()
+              {
+              #if defined(_SC_KERNEL_BITS)
+                  long bits = sysconf(_SC_KERNEL_BITS);
+              #endif
+                  long cpu  = sysconf (_SC_CPU_VERSION);
+
+                  switch (cpu)
+               {
+               case CPU_PA_RISC1_0: puts ("hppa1.0"); break;
+               case CPU_PA_RISC1_1: puts ("hppa1.1"); break;
+               case CPU_PA_RISC2_0:
+              #if defined(_SC_KERNEL_BITS)
+                   switch (bits)
+                       {
+                       case 64: puts ("hppa2.0w"); break;
+                       case 32: puts ("hppa2.0n"); break;
+                       default: puts ("hppa2.0"); break;
+                       } break;
+              #else  /* !defined(_SC_KERNEL_BITS) */
+                   puts ("hppa2.0"); break;
+              #endif
+               default: puts ("hppa1.0"); break;
+               }
+                  exit (0);
+              }
+EOF
+                   (CCOPTS= $CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null) && HP_ARCH=`./$dummy`
+                   if test -z "$HP_ARCH"; then HP_ARCH=hppa; fi
+                   rm -f $dummy.c $dummy
+               fi ;;
+       esac
+       echo ${HP_ARCH}-hp-hpux${HPUX_REV}
+       exit 0 ;;
+    ia64:HP-UX:*:*)
+       HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'`
+       echo ia64-hp-hpux${HPUX_REV}
+       exit 0 ;;
+    3050*:HI-UX:*:*)
+       eval $set_cc_for_build
+       sed 's/^        //' << EOF >$dummy.c
+       #include <unistd.h>
+       int
+       main ()
+       {
+         long cpu = sysconf (_SC_CPU_VERSION);
+         /* The order matters, because CPU_IS_HP_MC68K erroneously returns
+            true for CPU_PA_RISC1_0.  CPU_IS_PA_RISC returns correct
+            results, however.  */
+         if (CPU_IS_PA_RISC (cpu))
+           {
+             switch (cpu)
+               {
+                 case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break;
+                 case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break;
+                 case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break;
+                 default: puts ("hppa-hitachi-hiuxwe2"); break;
+               }
+           }
+         else if (CPU_IS_HP_MC68K (cpu))
+           puts ("m68k-hitachi-hiuxwe2");
+         else puts ("unknown-hitachi-hiuxwe2");
+         exit (0);
+       }
+EOF
+       $CC_FOR_BUILD $dummy.c -o $dummy && ./$dummy && rm -f $dummy.c $dummy && exit 0
+       rm -f $dummy.c $dummy
+       echo unknown-hitachi-hiuxwe2
+       exit 0 ;;
+    9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* )
+       echo hppa1.1-hp-bsd
+       exit 0 ;;
+    9000/8??:4.3bsd:*:*)
+       echo hppa1.0-hp-bsd
+       exit 0 ;;
+    *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*)
+       echo hppa1.0-hp-mpeix
+       exit 0 ;;
+    hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* )
+       echo hppa1.1-hp-osf
+       exit 0 ;;
+    hp8??:OSF1:*:*)
+       echo hppa1.0-hp-osf
+       exit 0 ;;
+    i*86:OSF1:*:*)
+       if [ -x /usr/sbin/sysversion ] ; then
+           echo ${UNAME_MACHINE}-unknown-osf1mk
+       else
+           echo ${UNAME_MACHINE}-unknown-osf1
+       fi
+       exit 0 ;;
+    parisc*:Lites*:*:*)
+       echo hppa1.1-hp-lites
+       exit 0 ;;
+    C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*)
+       echo c1-convex-bsd
+        exit 0 ;;
+    C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*)
+       if getsysinfo -f scalar_acc
+       then echo c32-convex-bsd
+       else echo c2-convex-bsd
+       fi
+        exit 0 ;;
+    C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*)
+       echo c34-convex-bsd
+        exit 0 ;;
+    C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*)
+       echo c38-convex-bsd
+        exit 0 ;;
+    C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*)
+       echo c4-convex-bsd
+        exit 0 ;;
+    CRAY*X-MP:*:*:*)
+       echo xmp-cray-unicos
+        exit 0 ;;
+    CRAY*Y-MP:*:*:*)
+       echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+       exit 0 ;;
+    CRAY*[A-Z]90:*:*:*)
+       echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \
+       | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \
+             -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \
+             -e 's/\.[^.]*$/.X/'
+       exit 0 ;;
+    CRAY*TS:*:*:*)
+       echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+       exit 0 ;;
+    CRAY*T3D:*:*:*)
+       echo alpha-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+       exit 0 ;;
+    CRAY*T3E:*:*:*)
+       echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+       exit 0 ;;
+    CRAY*SV1:*:*:*)
+       echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/'
+       exit 0 ;;
+    CRAY-2:*:*:*)
+       echo cray2-cray-unicos
+        exit 0 ;;
+    F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*)
+       FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'`
+        FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'`
+        FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'`
+        echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}"
+        exit 0 ;;
+    i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*)
+       echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE}
+       exit 0 ;;
+    sparc*:BSD/OS:*:*)
+       echo sparc-unknown-bsdi${UNAME_RELEASE}
+       exit 0 ;;
+    *:BSD/OS:*:*)
+       echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE}
+       exit 0 ;;
+    *:FreeBSD:*:*)
+       echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`
+       exit 0 ;;
+    i*:CYGWIN*:*)
+       echo ${UNAME_MACHINE}-pc-cygwin
+       exit 0 ;;
+    i*:MINGW*:*)
+       echo ${UNAME_MACHINE}-pc-mingw32
+       exit 0 ;;
+    i*:PW*:*)
+       echo ${UNAME_MACHINE}-pc-pw32
+       exit 0 ;;
+    x86:Interix*:3*)
+       echo i386-pc-interix3
+       exit 0 ;;
+    i*:Windows_NT*:* | Pentium*:Windows_NT*:*)
+       # How do we know it's Interix rather than the generic POSIX subsystem?
+       # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we
+       # UNAME_MACHINE based on the output of uname instead of i386?
+       echo i386-pc-interix
+       exit 0 ;;
+    i*:UWIN*:*)
+       echo ${UNAME_MACHINE}-pc-uwin
+       exit 0 ;;
+    p*:CYGWIN*:*)
+       echo powerpcle-unknown-cygwin
+       exit 0 ;;
+    prep*:SunOS:5.*:*)
+       echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'`
+       exit 0 ;;
+    *:GNU:*:*)
+       echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'`
+       exit 0 ;;
+    i*86:Minix:*:*)
+       echo ${UNAME_MACHINE}-pc-minix
+       exit 0 ;;
+    arm*:Linux:*:*)
+       echo ${UNAME_MACHINE}-unknown-linux-gnu
+       exit 0 ;;
+    ia64:Linux:*:*)
+       echo ${UNAME_MACHINE}-unknown-linux
+       exit 0 ;;
+    m68*:Linux:*:*)
+       echo ${UNAME_MACHINE}-unknown-linux-gnu
+       exit 0 ;;
+    mips:Linux:*:*)
+       eval $set_cc_for_build
+       sed 's/^        //' << EOF >$dummy.c
+       #undef CPU
+       #undef mips
+       #undef mipsel
+       #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) 
+       CPU=mipsel 
+       #else
+       #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) 
+       CPU=mips
+       #else
+       CPU=
+       #endif
+       #endif 
+EOF
+       eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^CPU=`
+       rm -f $dummy.c
+       test x"${CPU}" != x && echo "${CPU}-pc-linux-gnu" && exit 0
+       ;;
+    ppc:Linux:*:*)
+       echo powerpc-unknown-linux-gnu
+       exit 0 ;;
+    ppc64:Linux:*:*)
+       echo powerpc64-unknown-linux-gnu
+       exit 0 ;;
+    alpha:Linux:*:*)
+       case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in
+         EV5)   UNAME_MACHINE=alphaev5 ;;
+         EV56)  UNAME_MACHINE=alphaev56 ;;
+         PCA56) UNAME_MACHINE=alphapca56 ;;
+         PCA57) UNAME_MACHINE=alphapca56 ;;
+         EV6)   UNAME_MACHINE=alphaev6 ;;
+         EV67)  UNAME_MACHINE=alphaev67 ;;
+         EV68*) UNAME_MACHINE=alphaev68 ;;
+        esac
+       objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null
+       if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi
+       echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC}
+       exit 0 ;;
+    parisc:Linux:*:* | hppa:Linux:*:*)
+       # Look for CPU level
+       case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in
+         PA7*) echo hppa1.1-unknown-linux-gnu ;;
+         PA8*) echo hppa2.0-unknown-linux-gnu ;;
+         *)    echo hppa-unknown-linux-gnu ;;
+       esac
+       exit 0 ;;
+    parisc64:Linux:*:* | hppa64:Linux:*:*)
+       echo hppa64-unknown-linux-gnu
+       exit 0 ;;
+    s390:Linux:*:* | s390x:Linux:*:*)
+       echo ${UNAME_MACHINE}-ibm-linux
+       exit 0 ;;
+    sh*:Linux:*:*)
+       echo ${UNAME_MACHINE}-unknown-linux-gnu
+       exit 0 ;;
+    sparc:Linux:*:* | sparc64:Linux:*:*)
+       echo ${UNAME_MACHINE}-unknown-linux-gnu
+       exit 0 ;;
+    x86_64:Linux:*:*)
+       echo x86_64-unknown-linux-gnu
+       exit 0 ;;
+    i*86:Linux:*:*)
+       # The BFD linker knows what the default object file format is, so
+       # first see if it will tell us. cd to the root directory to prevent
+       # problems with other programs or directories called `ld' in the path.
+       ld_supported_targets=`cd /; ld --help 2>&1 \
+                        | sed -ne '/supported targets:/!d
+                                   s/[         ][      ]*/ /g
+                                   s/.*supported targets: *//
+                                   s/ .*//
+                                   p'`
+        case "$ld_supported_targets" in
+         elf32-i386)
+               TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu"
+               ;;
+         a.out-i386-linux)
+               echo "${UNAME_MACHINE}-pc-linux-gnuaout"
+               exit 0 ;;               
+         coff-i386)
+               echo "${UNAME_MACHINE}-pc-linux-gnucoff"
+               exit 0 ;;
+         "")
+               # Either a pre-BFD a.out linker (linux-gnuoldld) or
+               # one that does not give us useful --help.
+               echo "${UNAME_MACHINE}-pc-linux-gnuoldld"
+               exit 0 ;;
+       esac
+       # Determine whether the default compiler is a.out or elf
+       eval $set_cc_for_build
+       sed 's/^        //' << EOF >$dummy.c
+       #include <features.h>
+       #ifdef __ELF__
+       # ifdef __GLIBC__
+       #  if __GLIBC__ >= 2
+       LIBC=gnu
+       #  else
+       LIBC=gnulibc1
+       #  endif
+       # else
+       LIBC=gnulibc1
+       # endif
+       #else
+       LIBC=gnuaout
+       #endif
+EOF
+       eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep ^LIBC=`
+       rm -f $dummy.c
+       test x"${LIBC}" != x && echo "${UNAME_MACHINE}-pc-linux-${LIBC}" && exit 0
+       test x"${TENTATIVE}" != x && echo "${TENTATIVE}" && exit 0
+       ;;
+    i*86:DYNIX/ptx:4*:*)
+       # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there.
+       # earlier versions are messed up and put the nodename in both
+       # sysname and nodename.
+       echo i386-sequent-sysv4
+       exit 0 ;;
+    i*86:UNIX_SV:4.2MP:2.*)
+        # Unixware is an offshoot of SVR4, but it has its own version
+        # number series starting with 2...
+        # I am not positive that other SVR4 systems won't match this,
+       # I just have to hope.  -- rms.
+        # Use sysv4.2uw... so that sysv4* matches it.
+       echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION}
+       exit 0 ;;
+    i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*)
+       UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'`
+       if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then
+               echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL}
+       else
+               echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL}
+       fi
+       exit 0 ;;
+    i*86:*:5:[78]*)
+       case `/bin/uname -X | grep "^Machine"` in
+           *486*)           UNAME_MACHINE=i486 ;;
+           *Pentium)        UNAME_MACHINE=i586 ;;
+           *Pent*|*Celeron) UNAME_MACHINE=i686 ;;
+       esac
+       echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION}
+       exit 0 ;;
+    i*86:*:3.2:*)
+       if test -f /usr/options/cb.name; then
+               UNAME_REL=`sed -n 's/.*Version //p' </usr/options/cb.name`
+               echo ${UNAME_MACHINE}-pc-isc$UNAME_REL
+       elif /bin/uname -X 2>/dev/null >/dev/null ; then
+               UNAME_REL=`(/bin/uname -X|egrep Release|sed -e 's/.*= //')`
+               (/bin/uname -X|egrep i80486 >/dev/null) && UNAME_MACHINE=i486
+               (/bin/uname -X|egrep '^Machine.*Pentium' >/dev/null) \
+                       && UNAME_MACHINE=i586
+               (/bin/uname -X|egrep '^Machine.*Pent ?II' >/dev/null) \
+                       && UNAME_MACHINE=i686
+               (/bin/uname -X|egrep '^Machine.*Pentium Pro' >/dev/null) \
+                       && UNAME_MACHINE=i686
+               echo ${UNAME_MACHINE}-pc-sco$UNAME_REL
+       else
+               echo ${UNAME_MACHINE}-pc-sysv32
+       fi
+       exit 0 ;;
+    i*86:*DOS:*:*)
+       echo ${UNAME_MACHINE}-pc-msdosdjgpp
+       exit 0 ;;
+    pc:*:*:*)
+       # Left here for compatibility:
+        # uname -m prints for DJGPP always 'pc', but it prints nothing about
+        # the processor, so we play safe by assuming i386.
+       echo i386-pc-msdosdjgpp
+        exit 0 ;;
+    Intel:Mach:3*:*)
+       echo i386-pc-mach3
+       exit 0 ;;
+    paragon:*:*:*)
+       echo i860-intel-osf1
+       exit 0 ;;
+    i860:*:4.*:*) # i860-SVR4
+       if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then
+         echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4
+       else # Add other i860-SVR4 vendors below as they are discovered.
+         echo i860-unknown-sysv${UNAME_RELEASE}  # Unknown i860-SVR4
+       fi
+       exit 0 ;;
+    mini*:CTIX:SYS*5:*)
+       # "miniframe"
+       echo m68010-convergent-sysv
+       exit 0 ;;
+    M68*:*:R3V[567]*:*)
+       test -r /sysV68 && echo 'm68k-motorola-sysv' && exit 0 ;;
+    3[34]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0)
+       OS_REL=''
+       test -r /etc/.relid \
+       && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid`
+       /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+         && echo i486-ncr-sysv4.3${OS_REL} && exit 0
+       /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \
+         && echo i586-ncr-sysv4.3${OS_REL} && exit 0 ;;
+    3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*)
+        /bin/uname -p 2>/dev/null | grep 86 >/dev/null \
+          && echo i486-ncr-sysv4 && exit 0 ;;
+    m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*)
+       echo m68k-unknown-lynxos${UNAME_RELEASE}
+       exit 0 ;;
+    mc68030:UNIX_System_V:4.*:*)
+       echo m68k-atari-sysv4
+       exit 0 ;;
+    i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*)
+       echo i386-unknown-lynxos${UNAME_RELEASE}
+       exit 0 ;;
+    TSUNAMI:LynxOS:2.*:*)
+       echo sparc-unknown-lynxos${UNAME_RELEASE}
+       exit 0 ;;
+    rs6000:LynxOS:2.*:*)
+       echo rs6000-unknown-lynxos${UNAME_RELEASE}
+       exit 0 ;;
+    PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*)
+       echo powerpc-unknown-lynxos${UNAME_RELEASE}
+       exit 0 ;;
+    SM[BE]S:UNIX_SV:*:*)
+       echo mips-dde-sysv${UNAME_RELEASE}
+       exit 0 ;;
+    RM*:ReliantUNIX-*:*:*)
+       echo mips-sni-sysv4
+       exit 0 ;;
+    RM*:SINIX-*:*:*)
+       echo mips-sni-sysv4
+       exit 0 ;;
+    *:SINIX-*:*:*)
+       if uname -p 2>/dev/null >/dev/null ; then
+               UNAME_MACHINE=`(uname -p) 2>/dev/null`
+               echo ${UNAME_MACHINE}-sni-sysv4
+       else
+               echo ns32k-sni-sysv
+       fi
+       exit 0 ;;
+    PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort
+                      # says <Richard.M.Bartel@ccMail.Census.GOV>
+        echo i586-unisys-sysv4
+        exit 0 ;;
+    *:UNIX_System_V:4*:FTX*)
+       # From Gerald Hewes <hewes@openmarket.com>.
+       # How about differentiating between stratus architectures? -djm
+       echo hppa1.1-stratus-sysv4
+       exit 0 ;;
+    *:*:*:FTX*)
+       # From seanf@swdc.stratus.com.
+       echo i860-stratus-sysv4
+       exit 0 ;;
+    *:VOS:*:*)
+       # From Paul.Green@stratus.com.
+       echo hppa1.1-stratus-vos
+       exit 0 ;;
+    mc68*:A/UX:*:*)
+       echo m68k-apple-aux${UNAME_RELEASE}
+       exit 0 ;;
+    news*:NEWS-OS:6*:*)
+       echo mips-sony-newsos6
+       exit 0 ;;
+    R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*)
+       if [ -d /usr/nec ]; then
+               echo mips-nec-sysv${UNAME_RELEASE}
+       else
+               echo mips-unknown-sysv${UNAME_RELEASE}
+       fi
+        exit 0 ;;
+    BeBox:BeOS:*:*)    # BeOS running on hardware made by Be, PPC only.
+       echo powerpc-be-beos
+       exit 0 ;;
+    BeMac:BeOS:*:*)    # BeOS running on Mac or Mac clone, PPC only.
+       echo powerpc-apple-beos
+       exit 0 ;;
+    BePC:BeOS:*:*)     # BeOS running on Intel PC compatible.
+       echo i586-pc-beos
+       exit 0 ;;
+    SX-4:SUPER-UX:*:*)
+       echo sx4-nec-superux${UNAME_RELEASE}
+       exit 0 ;;
+    SX-5:SUPER-UX:*:*)
+       echo sx5-nec-superux${UNAME_RELEASE}
+       exit 0 ;;
+    Power*:Rhapsody:*:*)
+       echo powerpc-apple-rhapsody${UNAME_RELEASE}
+       exit 0 ;;
+    *:Rhapsody:*:*)
+       echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE}
+       exit 0 ;;
+    *:Darwin:*:*)
+       echo `uname -p`-apple-darwin${UNAME_RELEASE}
+       exit 0 ;;
+    *:procnto*:*:* | *:QNX:[0123456789]*:*)
+       if test "${UNAME_MACHINE}" = "x86pc"; then
+               UNAME_MACHINE=pc
+       fi
+       echo `uname -p`-${UNAME_MACHINE}-nto-qnx
+       exit 0 ;;
+    *:QNX:*:4*)
+       echo i386-pc-qnx
+       exit 0 ;;
+    NSR-[GKLNPTVW]:NONSTOP_KERNEL:*:*)
+       echo nsr-tandem-nsk${UNAME_RELEASE}
+       exit 0 ;;
+    *:NonStop-UX:*:*)
+       echo mips-compaq-nonstopux
+       exit 0 ;;
+    BS2000:POSIX*:*:*)
+       echo bs2000-siemens-sysv
+       exit 0 ;;
+    DS/*:UNIX_System_V:*:*)
+       echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE}
+       exit 0 ;;
+    *:Plan9:*:*)
+       # "uname -m" is not consistent, so use $cputype instead. 386
+       # is converted to i386 for consistency with other x86
+       # operating systems.
+       if test "$cputype" = "386"; then
+           UNAME_MACHINE=i386
+       else
+           UNAME_MACHINE="$cputype"
+       fi
+       echo ${UNAME_MACHINE}-unknown-plan9
+       exit 0 ;;
+    i*86:OS/2:*:*)
+       # If we were able to find `uname', then EMX Unix compatibility
+       # is probably installed.
+       echo ${UNAME_MACHINE}-pc-os2-emx
+       exit 0 ;;
+    *:TOPS-10:*:*)
+       echo pdp10-unknown-tops10
+       exit 0 ;;
+    *:TENEX:*:*)
+       echo pdp10-unknown-tenex
+       exit 0 ;;
+    KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*)
+       echo pdp10-dec-tops20
+       exit 0 ;;
+    XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*)
+       echo pdp10-xkl-tops20
+       exit 0 ;;
+    *:TOPS-20:*:*)
+       echo pdp10-unknown-tops20
+       exit 0 ;;
+    *:ITS:*:*)
+       echo pdp10-unknown-its
+       exit 0 ;;
+    i*86:XTS-300:*:STOP)
+       echo ${UNAME_MACHINE}-unknown-stop
+       exit 0 ;;
+    i*86:atheos:*:*)
+       echo ${UNAME_MACHINE}-unknown-atheos
+       exit 0 ;;
+esac
+
+#echo '(No uname command or uname output not recognized.)' 1>&2
+#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2
+
+eval $set_cc_for_build
+cat >$dummy.c <<EOF
+#ifdef _SEQUENT_
+# include <sys/types.h>
+# include <sys/utsname.h>
+#endif
+main ()
+{
+#if defined (sony)
+#if defined (MIPSEB)
+  /* BFD wants "bsd" instead of "newsos".  Perhaps BFD should be changed,
+     I don't know....  */
+  printf ("mips-sony-bsd\n"); exit (0);
+#else
+#include <sys/param.h>
+  printf ("m68k-sony-newsos%s\n",
+#ifdef NEWSOS4
+          "4"
+#else
+         ""
+#endif
+         ); exit (0);
+#endif
+#endif
+
+#if defined (__arm) && defined (__acorn) && defined (__unix)
+  printf ("arm-acorn-riscix"); exit (0);
+#endif
+
+#if defined (hp300) && !defined (hpux)
+  printf ("m68k-hp-bsd\n"); exit (0);
+#endif
+
+#if defined (NeXT)
+#if !defined (__ARCHITECTURE__)
+#define __ARCHITECTURE__ "m68k"
+#endif
+  int version;
+  version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`;
+  if (version < 4)
+    printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version);
+  else
+    printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version);
+  exit (0);
+#endif
+
+#if defined (MULTIMAX) || defined (n16)
+#if defined (UMAXV)
+  printf ("ns32k-encore-sysv\n"); exit (0);
+#else
+#if defined (CMU)
+  printf ("ns32k-encore-mach\n"); exit (0);
+#else
+  printf ("ns32k-encore-bsd\n"); exit (0);
+#endif
+#endif
+#endif
+
+#if defined (__386BSD__)
+  printf ("i386-pc-bsd\n"); exit (0);
+#endif
+
+#if defined (sequent)
+#if defined (i386)
+  printf ("i386-sequent-dynix\n"); exit (0);
+#endif
+#if defined (ns32000)
+  printf ("ns32k-sequent-dynix\n"); exit (0);
+#endif
+#endif
+
+#if defined (_SEQUENT_)
+    struct utsname un;
+
+    uname(&un);
+
+    if (strncmp(un.version, "V2", 2) == 0) {
+       printf ("i386-sequent-ptx2\n"); exit (0);
+    }
+    if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */
+       printf ("i386-sequent-ptx1\n"); exit (0);
+    }
+    printf ("i386-sequent-ptx\n"); exit (0);
+
+#endif
+
+#if defined (vax)
+# if !defined (ultrix)
+#  include <sys/param.h>
+#  if defined (BSD)
+#   if BSD == 43
+      printf ("vax-dec-bsd4.3\n"); exit (0);
+#   else
+#    if BSD == 199006
+      printf ("vax-dec-bsd4.3reno\n"); exit (0);
+#    else
+      printf ("vax-dec-bsd\n"); exit (0);
+#    endif
+#   endif
+#  else
+    printf ("vax-dec-bsd\n"); exit (0);
+#  endif
+# else
+    printf ("vax-dec-ultrix\n"); exit (0);
+# endif
+#endif
+
+#if defined (alliant) && defined (i860)
+  printf ("i860-alliant-bsd\n"); exit (0);
+#endif
+
+  exit (1);
+}
+EOF
+
+$CC_FOR_BUILD $dummy.c -o $dummy 2>/dev/null && ./$dummy && rm -f $dummy.c $dummy && exit 0
+rm -f $dummy.c $dummy
+
+# Apollos put the system type in the environment.
+
+test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit 0; }
+
+# Convex versions that predate uname can use getsysinfo(1)
+
+if [ -x /usr/convex/getsysinfo ]
+then
+    case `getsysinfo -f cpu_type` in
+    c1*)
+       echo c1-convex-bsd
+       exit 0 ;;
+    c2*)
+       if getsysinfo -f scalar_acc
+       then echo c32-convex-bsd
+       else echo c2-convex-bsd
+       fi
+       exit 0 ;;
+    c34*)
+       echo c34-convex-bsd
+       exit 0 ;;
+    c38*)
+       echo c38-convex-bsd
+       exit 0 ;;
+    c4*)
+       echo c4-convex-bsd
+       exit 0 ;;
+    esac
+fi
+
+cat >&2 <<EOF
+$0: unable to guess system type
+
+This script, last modified $timestamp, has failed to recognize
+the operating system you are using. It is advised that you
+download the most up to date version of the config scripts from
+
+    ftp://ftp.gnu.org/pub/gnu/config/
+
+If the version you run ($0) is already up to date, please
+send the following data and any information you think might be
+pertinent to <config-patches@gnu.org> in order to provide the needed
+information to handle your system.
+
+config.guess timestamp = $timestamp
+
+uname -m = `(uname -m) 2>/dev/null || echo unknown`
+uname -r = `(uname -r) 2>/dev/null || echo unknown`
+uname -s = `(uname -s) 2>/dev/null || echo unknown`
+uname -v = `(uname -v) 2>/dev/null || echo unknown`
+
+/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null`
+/bin/uname -X     = `(/bin/uname -X) 2>/dev/null`
+
+hostinfo               = `(hostinfo) 2>/dev/null`
+/bin/universe          = `(/bin/universe) 2>/dev/null`
+/usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null`
+/bin/arch              = `(/bin/arch) 2>/dev/null`
+/usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null`
+/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null`
+
+UNAME_MACHINE = ${UNAME_MACHINE}
+UNAME_RELEASE = ${UNAME_RELEASE}
+UNAME_SYSTEM  = ${UNAME_SYSTEM}
+UNAME_VERSION = ${UNAME_VERSION}
+EOF
+
+exit 1
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/support/sdk/c/blip/driver/radvd-1.0/config.h.in b/support/sdk/c/blip/driver/radvd-1.0/config.h.in
new file mode 100644 (file)
index 0000000..faa79eb
--- /dev/null
@@ -0,0 +1,95 @@
+/* config.h.in.  Generated from configure.in by autoheader.  */
+
+/* Define to 1 if you have the <getopt.h> header file. */
+#undef HAVE_GETOPT_H
+
+/* Define to 1 if you have the `getopt_long' function. */
+#undef HAVE_GETOPT_LONG
+
+/* whether struct in6_addr has u6_addrXX and defines s6_addrXX */
+#undef HAVE_IN6_ADDR_S6_ADDR
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#undef HAVE_INTTYPES_H
+
+/* Define to 1 if you have the `c' library (-lc). */
+#undef HAVE_LIBC
+
+/* Define to 1 if you have the <machine/limits.h> header file. */
+#undef HAVE_MACHINE_LIMITS_H
+
+/* Define to 1 if you have the <machine/param.h> header file. */
+#undef HAVE_MACHINE_PARAM_H
+
+/* Define to 1 if you have the <memory.h> header file. */
+#undef HAVE_MEMORY_H
+
+/* Define to 1 if you have the <net/if_arp.h> header file. */
+#undef HAVE_NET_IF_ARP_H
+
+/* Define to 1 if you have the <net/if_dl.h> header file. */
+#undef HAVE_NET_IF_DL_H
+
+/* Define to 1 if you have the <net/if_types.h> header file. */
+#undef HAVE_NET_IF_TYPES_H
+
+/* whether struct sockaddr_in6 has sin6_scope_id */
+#undef HAVE_SIN6_SCOPE_ID
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#undef HAVE_STDINT_H
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#undef HAVE_STDLIB_H
+
+/* Define to 1 if you have the <strings.h> header file. */
+#undef HAVE_STRINGS_H
+
+/* Define to 1 if you have the <string.h> header file. */
+#undef HAVE_STRING_H
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#undef HAVE_SYS_PARAM_H
+
+/* Define to 1 if you have the <sys/sockio.h> header file. */
+#undef HAVE_SYS_SOCKIO_H
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#undef HAVE_SYS_STAT_H
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#undef HAVE_SYS_TIME_H
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#undef HAVE_SYS_TYPES_H
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#undef HAVE_UNISTD_H
+
+/* Define to the address where bug reports for this package should be sent. */
+#undef PACKAGE_BUGREPORT
+
+/* Define to the full name of this package. */
+#undef PACKAGE_NAME
+
+/* Define to the full name and version of this package. */
+#undef PACKAGE_STRING
+
+/* Define to the one symbol short name of this package. */
+#undef PACKAGE_TARNAME
+
+/* Define to the version of this package. */
+#undef PACKAGE_VERSION
+
+/* Define to 1 if you have the ANSI C header files. */
+#undef STDC_HEADERS
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#undef TIME_WITH_SYS_TIME
+
+/* Define to 1 if `lex' declares `yytext' as a `char *' by default, not a
+   `char[]'. */
+#undef YYTEXT_POINTER
+
+/* Define to empty if `const' does not conform to ANSI C. */
+#undef const
diff --git a/support/sdk/c/blip/driver/radvd-1.0/config.sub b/support/sdk/c/blip/driver/radvd-1.0/config.sub
new file mode 100755 (executable)
index 0000000..1657334
--- /dev/null
@@ -0,0 +1,1440 @@
+#! /bin/sh
+# Configuration validation subroutine script.
+#   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
+#   2000, 2001, 2002 Free Software Foundation, Inc.
+
+timestamp='2002-01-02'
+
+# This file is (in principle) common to ALL GNU software.
+# The presence of a machine in this file suggests that SOME GNU software
+# can handle that machine.  It does not imply ALL GNU software can.
+#
+# This file is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# Please send patches to <config-patches@gnu.org>.  Submit a context
+# diff and a properly formatted ChangeLog entry.
+#
+# Configuration subroutine to validate and canonicalize a configuration type.
+# Supply the specified configuration type as an argument.
+# If it is invalid, we print an error message on stderr and exit with code 1.
+# Otherwise, we print the canonical config type on stdout and succeed.
+
+# This file is supposed to be the same for all GNU packages
+# and recognize all the CPU types, system types and aliases
+# that are meaningful with *any* GNU software.
+# Each package is responsible for reporting which valid configurations
+# it does not support.  The user should be able to distinguish
+# a failure to support a valid configuration from a meaningless
+# configuration.
+
+# The goal of this file is to map all the various variations of a given
+# machine specification into a single specification in the form:
+#      CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM
+# or in some cases, the newer four-part form:
+#      CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM
+# It is wrong to echo any other type of specification.
+
+me=`echo "$0" | sed -e 's,.*/,,'`
+
+usage="\
+Usage: $0 [OPTION] CPU-MFR-OPSYS
+       $0 [OPTION] ALIAS
+
+Canonicalize a configuration name.
+
+Operation modes:
+  -h, --help         print this help, then exit
+  -t, --time-stamp   print date of last modification, then exit
+  -v, --version      print version number, then exit
+
+Report bugs and patches to <config-patches@gnu.org>."
+
+version="\
+GNU config.sub ($timestamp)
+
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001
+Free Software Foundation, Inc.
+
+This is free software; see the source for copying conditions.  There is NO
+warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."
+
+help="
+Try \`$me --help' for more information."
+
+# Parse command line
+while test $# -gt 0 ; do
+  case $1 in
+    --time-stamp | --time* | -t )
+       echo "$timestamp" ; exit 0 ;;
+    --version | -v )
+       echo "$version" ; exit 0 ;;
+    --help | --h* | -h )
+       echo "$usage"; exit 0 ;;
+    -- )     # Stop option processing
+       shift; break ;;
+    - )        # Use stdin as input.
+       break ;;
+    -* )
+       echo "$me: invalid option $1$help"
+       exit 1 ;;
+
+    *local*)
+       # First pass through any local machine types.
+       echo $1
+       exit 0;;
+
+    * )
+       break ;;
+  esac
+done
+
+case $# in
+ 0) echo "$me: missing argument$help" >&2
+    exit 1;;
+ 1) ;;
+ *) echo "$me: too many arguments$help" >&2
+    exit 1;;
+esac
+
+# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any).
+# Here we must recognize all the valid KERNEL-OS combinations.
+maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'`
+case $maybe_os in
+  nto-qnx* | linux-gnu* | storm-chaos* | os2-emx* | windows32-*)
+    os=-$maybe_os
+    basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'`
+    ;;
+  *)
+    basic_machine=`echo $1 | sed 's/-[^-]*$//'`
+    if [ $basic_machine != $1 ]
+    then os=`echo $1 | sed 's/.*-/-/'`
+    else os=; fi
+    ;;
+esac
+
+### Let's recognize common machines as not being operating systems so
+### that things like config.sub decstation-3100 work.  We also
+### recognize some manufacturers as not being operating systems, so we
+### can provide default operating systems below.
+case $os in
+       -sun*os*)
+               # Prevent following clause from handling this invalid input.
+               ;;
+       -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \
+       -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \
+       -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \
+       -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\
+       -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \
+       -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \
+       -apple | -axis)
+               os=
+               basic_machine=$1
+               ;;
+       -sim | -cisco | -oki | -wec | -winbond)
+               os=
+               basic_machine=$1
+               ;;
+       -scout)
+               ;;
+       -wrs)
+               os=-vxworks
+               basic_machine=$1
+               ;;
+       -chorusos*)
+               os=-chorusos
+               basic_machine=$1
+               ;;
+       -chorusrdb)
+               os=-chorusrdb
+               basic_machine=$1
+               ;;
+       -hiux*)
+               os=-hiuxwe2
+               ;;
+       -sco5)
+               os=-sco3.2v5
+               basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+               ;;
+       -sco4)
+               os=-sco3.2v4
+               basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+               ;;
+       -sco3.2.[4-9]*)
+               os=`echo $os | sed -e 's/sco3.2./sco3.2v/'`
+               basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+               ;;
+       -sco3.2v[4-9]*)
+               # Don't forget version if it is 3.2v4 or newer.
+               basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+               ;;
+       -sco*)
+               os=-sco3.2v2
+               basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+               ;;
+       -udk*)
+               basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+               ;;
+       -isc)
+               os=-isc2.2
+               basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+               ;;
+       -clix*)
+               basic_machine=clipper-intergraph
+               ;;
+       -isc*)
+               basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'`
+               ;;
+       -lynx*)
+               os=-lynxos
+               ;;
+       -ptx*)
+               basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'`
+               ;;
+       -windowsnt*)
+               os=`echo $os | sed -e 's/windowsnt/winnt/'`
+               ;;
+       -psos*)
+               os=-psos
+               ;;
+       -mint | -mint[0-9]*)
+               basic_machine=m68k-atari
+               os=-mint
+               ;;
+esac
+
+# Decode aliases for certain CPU-COMPANY combinations.
+case $basic_machine in
+       # Recognize the basic CPU types without company name.
+       # Some are omitted here because they have special meanings below.
+       1750a | 580 \
+       | a29k \
+       | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \
+       | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \
+       | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr \
+       | c4x | clipper \
+       | d10v | d30v | dsp16xx \
+       | fr30 \
+       | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \
+       | i370 | i860 | i960 | ia64 \
+       | m32r | m68000 | m68k | m88k | mcore \
+       | mips16 | mips64 | mips64el | mips64orion | mips64orionel \
+       | mips64vr4100 | mips64vr4100el | mips64vr4300 \
+       | mips64vr4300el | mips64vr5000 | mips64vr5000el \
+       | mipsbe | mipseb | mipsel | mipsle | mipstx39 | mipstx39el \
+       | mipsisa32 \
+       | mn10200 | mn10300 \
+       | ns16k | ns32k \
+       | openrisc \
+       | pdp10 | pdp11 | pj | pjl \
+       | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \
+       | pyramid \
+       | sh | sh[34] | sh[34]eb | shbe | shle \
+       | sparc | sparc64 | sparclet | sparclite | sparcv9 | sparcv9b \
+       | strongarm \
+       | tahoe | thumb | tic80 | tron \
+       | v850 | v850e \
+       | we32k \
+       | x86 | xscale | xstormy16 | xtensa \
+       | z8k)
+               basic_machine=$basic_machine-unknown
+               ;;
+       m6811 | m68hc11 | m6812 | m68hc12)
+               # Motorola 68HC11/12.
+               basic_machine=$basic_machine-unknown
+               os=-none
+               ;;
+       m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k)
+               ;;
+
+       # We use `pc' rather than `unknown'
+       # because (1) that's what they normally are, and
+       # (2) the word "unknown" tends to confuse beginning users.
+       i*86 | x86_64)
+         basic_machine=$basic_machine-pc
+         ;;
+       # Object if more than one company name word.
+       *-*-*)
+               echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+               exit 1
+               ;;
+       # Recognize the basic CPU types with company name.
+       580-* \
+       | a29k-* \
+       | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \
+       | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \
+       | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \
+       | arm-*  | armbe-* | armle-* | armv*-* \
+       | avr-* \
+       | bs2000-* \
+       | c[123]* | c30-* | [cjt]90-* | c54x-* \
+       | clipper-* | cray2-* | cydra-* \
+       | d10v-* | d30v-* \
+       | elxsi-* \
+       | f30[01]-* | f700-* | fr30-* | fx80-* \
+       | h8300-* | h8500-* \
+       | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \
+       | i*86-* | i860-* | i960-* | ia64-* \
+       | m32r-* \
+       | m68000-* | m680[01234]0-* | m68360-* | m683?2-* | m68k-* \
+       | m88110-* | m88k-* | mcore-* \
+       | mips-* | mips16-* | mips64-* | mips64el-* | mips64orion-* \
+       | mips64orionel-* | mips64vr4100-* | mips64vr4100el-* \
+       | mips64vr4300-* | mips64vr4300el-* | mipsbe-* | mipseb-* \
+       | mipsle-* | mipsel-* | mipstx39-* | mipstx39el-* \
+       | none-* | np1-* | ns16k-* | ns32k-* \
+       | orion-* \
+       | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \
+       | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \
+       | pyramid-* \
+       | romp-* | rs6000-* \
+       | sh-* | sh[34]-* | sh[34]eb-* | shbe-* | shle-* \
+       | sparc-* | sparc64-* | sparc86x-* | sparclite-* \
+       | sparcv9-* | sparcv9b-* | strongarm-* | sv1-* \
+       | t3e-* | tahoe-* | thumb-* | tic30-* | tic54x-* | tic80-* | tron-* \
+       | v850-* | v850e-* | vax-* \
+       | we32k-* \
+       | x86-* | x86_64-* | xmp-* | xps100-* | xscale-* | xstormy16-* \
+       | xtensa-* \
+       | ymp-* \
+       | z8k-*)
+               ;;
+       # Recognize the various machine names and aliases which stand
+       # for a CPU type and a company and sometimes even an OS.
+       386bsd)
+               basic_machine=i386-unknown
+               os=-bsd
+               ;;
+       3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc)
+               basic_machine=m68000-att
+               ;;
+       3b*)
+               basic_machine=we32k-att
+               ;;
+       a29khif)
+               basic_machine=a29k-amd
+               os=-udi
+               ;;
+       adobe68k)
+               basic_machine=m68010-adobe
+               os=-scout
+               ;;
+       alliant | fx80)
+               basic_machine=fx80-alliant
+               ;;
+       altos | altos3068)
+               basic_machine=m68k-altos
+               ;;
+       am29k)
+               basic_machine=a29k-none
+               os=-bsd
+               ;;
+       amdahl)
+               basic_machine=580-amdahl
+               os=-sysv
+               ;;
+       amiga | amiga-*)
+               basic_machine=m68k-unknown
+               ;;
+       amigaos | amigados)
+               basic_machine=m68k-unknown
+               os=-amigaos
+               ;;
+       amigaunix | amix)
+               basic_machine=m68k-unknown
+               os=-sysv4
+               ;;
+       apollo68)
+               basic_machine=m68k-apollo
+               os=-sysv
+               ;;
+       apollo68bsd)
+               basic_machine=m68k-apollo
+               os=-bsd
+               ;;
+       aux)
+               basic_machine=m68k-apple
+               os=-aux
+               ;;
+       balance)
+               basic_machine=ns32k-sequent
+               os=-dynix
+               ;;
+       convex-c1)
+               basic_machine=c1-convex
+               os=-bsd
+               ;;
+       convex-c2)
+               basic_machine=c2-convex
+               os=-bsd
+               ;;
+       convex-c32)
+               basic_machine=c32-convex
+               os=-bsd
+               ;;
+       convex-c34)
+               basic_machine=c34-convex
+               os=-bsd
+               ;;
+       convex-c38)
+               basic_machine=c38-convex
+               os=-bsd
+               ;;
+       cray | ymp)
+               basic_machine=ymp-cray
+               os=-unicos
+               ;;
+       cray2)
+               basic_machine=cray2-cray
+               os=-unicos
+               ;;
+       [cjt]90)
+               basic_machine=${basic_machine}-cray
+               os=-unicos
+               ;;
+       crds | unos)
+               basic_machine=m68k-crds
+               ;;
+       cris | cris-* | etrax*)
+               basic_machine=cris-axis
+               ;;
+       da30 | da30-*)
+               basic_machine=m68k-da30
+               ;;
+       decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn)
+               basic_machine=mips-dec
+               ;;
+       decsystem10* | dec10*)
+               basic_machine=pdp10-dec
+               os=-tops10
+               ;;
+       decsystem20* | dec20*)
+               basic_machine=pdp10-dec
+               os=-tops20
+               ;;
+       delta | 3300 | motorola-3300 | motorola-delta \
+             | 3300-motorola | delta-motorola)
+               basic_machine=m68k-motorola
+               ;;
+       delta88)
+               basic_machine=m88k-motorola
+               os=-sysv3
+               ;;
+       dpx20 | dpx20-*)
+               basic_machine=rs6000-bull
+               os=-bosx
+               ;;
+       dpx2* | dpx2*-bull)
+               basic_machine=m68k-bull
+               os=-sysv3
+               ;;
+       ebmon29k)
+               basic_machine=a29k-amd
+               os=-ebmon
+               ;;
+       elxsi)
+               basic_machine=elxsi-elxsi
+               os=-bsd
+               ;;
+       encore | umax | mmax)
+               basic_machine=ns32k-encore
+               ;;
+       es1800 | OSE68k | ose68k | ose | OSE)
+               basic_machine=m68k-ericsson
+               os=-ose
+               ;;
+       fx2800)
+               basic_machine=i860-alliant
+               ;;
+       genix)
+               basic_machine=ns32k-ns
+               ;;
+       gmicro)
+               basic_machine=tron-gmicro
+               os=-sysv
+               ;;
+       go32)
+               basic_machine=i386-pc
+               os=-go32
+               ;;
+       h3050r* | hiux*)
+               basic_machine=hppa1.1-hitachi
+               os=-hiuxwe2
+               ;;
+       h8300hms)
+               basic_machine=h8300-hitachi
+               os=-hms
+               ;;
+       h8300xray)
+               basic_machine=h8300-hitachi
+               os=-xray
+               ;;
+       h8500hms)
+               basic_machine=h8500-hitachi
+               os=-hms
+               ;;
+       harris)
+               basic_machine=m88k-harris
+               os=-sysv3
+               ;;
+       hp300-*)
+               basic_machine=m68k-hp
+               ;;
+       hp300bsd)
+               basic_machine=m68k-hp
+               os=-bsd
+               ;;
+       hp300hpux)
+               basic_machine=m68k-hp
+               os=-hpux
+               ;;
+       hp3k9[0-9][0-9] | hp9[0-9][0-9])
+               basic_machine=hppa1.0-hp
+               ;;
+       hp9k2[0-9][0-9] | hp9k31[0-9])
+               basic_machine=m68000-hp
+               ;;
+       hp9k3[2-9][0-9])
+               basic_machine=m68k-hp
+               ;;
+       hp9k6[0-9][0-9] | hp6[0-9][0-9])
+               basic_machine=hppa1.0-hp
+               ;;
+       hp9k7[0-79][0-9] | hp7[0-79][0-9])
+               basic_machine=hppa1.1-hp
+               ;;
+       hp9k78[0-9] | hp78[0-9])
+               # FIXME: really hppa2.0-hp
+               basic_machine=hppa1.1-hp
+               ;;
+       hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893)
+               # FIXME: really hppa2.0-hp
+               basic_machine=hppa1.1-hp
+               ;;
+       hp9k8[0-9][13679] | hp8[0-9][13679])
+               basic_machine=hppa1.1-hp
+               ;;
+       hp9k8[0-9][0-9] | hp8[0-9][0-9])
+               basic_machine=hppa1.0-hp
+               ;;
+       hppa-next)
+               os=-nextstep3
+               ;;
+       hppaosf)
+               basic_machine=hppa1.1-hp
+               os=-osf
+               ;;
+       hppro)
+               basic_machine=hppa1.1-hp
+               os=-proelf
+               ;;
+       i370-ibm* | ibm*)
+               basic_machine=i370-ibm
+               ;;
+# I'm not sure what "Sysv32" means.  Should this be sysv3.2?
+       i*86v32)
+               basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+               os=-sysv32
+               ;;
+       i*86v4*)
+               basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+               os=-sysv4
+               ;;
+       i*86v)
+               basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+               os=-sysv
+               ;;
+       i*86sol2)
+               basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'`
+               os=-solaris2
+               ;;
+       i386mach)
+               basic_machine=i386-mach
+               os=-mach
+               ;;
+       i386-vsta | vsta)
+               basic_machine=i386-unknown
+               os=-vsta
+               ;;
+       iris | iris4d)
+               basic_machine=mips-sgi
+               case $os in
+                   -irix*)
+                       ;;
+                   *)
+                       os=-irix4
+                       ;;
+               esac
+               ;;
+       isi68 | isi)
+               basic_machine=m68k-isi
+               os=-sysv
+               ;;
+       m88k-omron*)
+               basic_machine=m88k-omron
+               ;;
+       magnum | m3230)
+               basic_machine=mips-mips
+               os=-sysv
+               ;;
+       merlin)
+               basic_machine=ns32k-utek
+               os=-sysv
+               ;;
+       mingw32)
+               basic_machine=i386-pc
+               os=-mingw32
+               ;;
+       miniframe)
+               basic_machine=m68000-convergent
+               ;;
+       *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*)
+               basic_machine=m68k-atari
+               os=-mint
+               ;;
+       mipsel*-linux*)
+               basic_machine=mipsel-unknown
+               os=-linux-gnu
+               ;;
+       mips*-linux*)
+               basic_machine=mips-unknown
+               os=-linux-gnu
+               ;;
+       mips3*-*)
+               basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`
+               ;;
+       mips3*)
+               basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown
+               ;;
+       mmix*)
+               basic_machine=mmix-knuth
+               os=-mmixware
+               ;;
+       monitor)
+               basic_machine=m68k-rom68k
+               os=-coff
+               ;;
+       morphos)
+               basic_machine=powerpc-unknown
+               os=-morphos
+               ;;
+       msdos)
+               basic_machine=i386-pc
+               os=-msdos
+               ;;
+       mvs)
+               basic_machine=i370-ibm
+               os=-mvs
+               ;;
+       ncr3000)
+               basic_machine=i486-ncr
+               os=-sysv4
+               ;;
+       netbsd386)
+               basic_machine=i386-unknown
+               os=-netbsd
+               ;;
+       netwinder)
+               basic_machine=armv4l-rebel
+               os=-linux
+               ;;
+       news | news700 | news800 | news900)
+               basic_machine=m68k-sony
+               os=-newsos
+               ;;
+       news1000)
+               basic_machine=m68030-sony
+               os=-newsos
+               ;;
+       news-3600 | risc-news)
+               basic_machine=mips-sony
+               os=-newsos
+               ;;
+       necv70)
+               basic_machine=v70-nec
+               os=-sysv
+               ;;
+       next | m*-next )
+               basic_machine=m68k-next
+               case $os in
+                   -nextstep* )
+                       ;;
+                   -ns2*)
+                     os=-nextstep2
+                       ;;
+                   *)
+                     os=-nextstep3
+                       ;;
+               esac
+               ;;
+       nh3000)
+               basic_machine=m68k-harris
+               os=-cxux
+               ;;
+       nh[45]000)
+               basic_machine=m88k-harris
+               os=-cxux
+               ;;
+       nindy960)
+               basic_machine=i960-intel
+               os=-nindy
+               ;;
+       mon960)
+               basic_machine=i960-intel
+               os=-mon960
+               ;;
+       nonstopux)
+               basic_machine=mips-compaq
+               os=-nonstopux
+               ;;
+       np1)
+               basic_machine=np1-gould
+               ;;
+       nsr-tandem)
+               basic_machine=nsr-tandem
+               ;;
+       op50n-* | op60c-*)
+               basic_machine=hppa1.1-oki
+               os=-proelf
+               ;;
+       OSE68000 | ose68000)
+               basic_machine=m68000-ericsson
+               os=-ose
+               ;;
+       os68k)
+               basic_machine=m68k-none
+               os=-os68k
+               ;;
+       pa-hitachi)
+               basic_machine=hppa1.1-hitachi
+               os=-hiuxwe2
+               ;;
+       paragon)
+               basic_machine=i860-intel
+               os=-osf
+               ;;
+       pbd)
+               basic_machine=sparc-tti
+               ;;
+       pbb)
+               basic_machine=m68k-tti
+               ;;
+        pc532 | pc532-*)
+               basic_machine=ns32k-pc532
+               ;;
+       pentium | p5 | k5 | k6 | nexgen | viac3)
+               basic_machine=i586-pc
+               ;;
+       pentiumpro | p6 | 6x86 | athlon)
+               basic_machine=i686-pc
+               ;;
+       pentiumii | pentium2)
+               basic_machine=i686-pc
+               ;;
+       pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*)
+               basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'`
+               ;;
+       pentiumpro-* | p6-* | 6x86-* | athlon-*)
+               basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+               ;;
+       pentiumii-* | pentium2-*)
+               basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'`
+               ;;
+       pn)
+               basic_machine=pn-gould
+               ;;
+       power)  basic_machine=power-ibm
+               ;;
+       ppc)    basic_machine=powerpc-unknown
+               ;;
+       ppc-*)  basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'`
+               ;;
+       ppcle | powerpclittle | ppc-le | powerpc-little)
+               basic_machine=powerpcle-unknown
+               ;;
+       ppcle-* | powerpclittle-*)
+               basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'`
+               ;;
+       ppc64)  basic_machine=powerpc64-unknown
+               ;;
+       ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+               ;;
+       ppc64le | powerpc64little | ppc64-le | powerpc64-little)
+               basic_machine=powerpc64le-unknown
+               ;;
+       ppc64le-* | powerpc64little-*)
+               basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'`
+               ;;
+       ps2)
+               basic_machine=i386-ibm
+               ;;
+       pw32)
+               basic_machine=i586-unknown
+               os=-pw32
+               ;;
+       rom68k)
+               basic_machine=m68k-rom68k
+               os=-coff
+               ;;
+       rm[46]00)
+               basic_machine=mips-siemens
+               ;;
+       rtpc | rtpc-*)
+               basic_machine=romp-ibm
+               ;;
+       s390 | s390-*)
+               basic_machine=s390-ibm
+               ;;
+       s390x | s390x-*)
+               basic_machine=s390x-ibm
+               ;;
+       sa29200)
+               basic_machine=a29k-amd
+               os=-udi
+               ;;
+       sequent)
+               basic_machine=i386-sequent
+               ;;
+       sh)
+               basic_machine=sh-hitachi
+               os=-hms
+               ;;
+       sparclite-wrs | simso-wrs)
+               basic_machine=sparclite-wrs
+               os=-vxworks
+               ;;
+       sps7)
+               basic_machine=m68k-bull
+               os=-sysv2
+               ;;
+       spur)
+               basic_machine=spur-unknown
+               ;;
+       st2000)
+               basic_machine=m68k-tandem
+               ;;
+       stratus)
+               basic_machine=i860-stratus
+               os=-sysv4
+               ;;
+       sun2)
+               basic_machine=m68000-sun
+               ;;
+       sun2os3)
+               basic_machine=m68000-sun
+               os=-sunos3
+               ;;
+       sun2os4)
+               basic_machine=m68000-sun
+               os=-sunos4
+               ;;
+       sun3os3)
+               basic_machine=m68k-sun
+               os=-sunos3
+               ;;
+       sun3os4)
+               basic_machine=m68k-sun
+               os=-sunos4
+               ;;
+       sun4os3)
+               basic_machine=sparc-sun
+               os=-sunos3
+               ;;
+       sun4os4)
+               basic_machine=sparc-sun
+               os=-sunos4
+               ;;
+       sun4sol2)
+               basic_machine=sparc-sun
+               os=-solaris2
+               ;;
+       sun3 | sun3-*)
+               basic_machine=m68k-sun
+               ;;
+       sun4)
+               basic_machine=sparc-sun
+               ;;
+       sun386 | sun386i | roadrunner)
+               basic_machine=i386-sun
+               ;;
+       sv1)
+               basic_machine=sv1-cray
+               os=-unicos
+               ;;
+       symmetry)
+               basic_machine=i386-sequent
+               os=-dynix
+               ;;
+       t3e)
+               basic_machine=t3e-cray
+               os=-unicos
+               ;;
+       tic54x | c54x*)
+               basic_machine=tic54x-unknown
+               os=-coff
+               ;;
+       tx39)
+               basic_machine=mipstx39-unknown
+               ;;
+       tx39el)
+               basic_machine=mipstx39el-unknown
+               ;;
+       toad1)
+               basic_machine=pdp10-xkl
+               os=-tops20
+               ;;
+       tower | tower-32)
+               basic_machine=m68k-ncr
+               ;;
+       udi29k)
+               basic_machine=a29k-amd
+               os=-udi
+               ;;
+       ultra3)
+               basic_machine=a29k-nyu
+               os=-sym1
+               ;;
+       v810 | necv810)
+               basic_machine=v810-nec
+               os=-none
+               ;;
+       vaxv)
+               basic_machine=vax-dec
+               os=-sysv
+               ;;
+       vms)
+               basic_machine=vax-dec
+               os=-vms
+               ;;
+       vpp*|vx|vx-*)
+               basic_machine=f301-fujitsu
+               ;;
+       vxworks960)
+               basic_machine=i960-wrs
+               os=-vxworks
+               ;;
+       vxworks68)
+               basic_machine=m68k-wrs
+               os=-vxworks
+               ;;
+       vxworks29k)
+               basic_machine=a29k-wrs
+               os=-vxworks
+               ;;
+       w65*)
+               basic_machine=w65-wdc
+               os=-none
+               ;;
+       w89k-*)
+               basic_machine=hppa1.1-winbond
+               os=-proelf
+               ;;
+       windows32)
+               basic_machine=i386-pc
+               os=-windows32-msvcrt
+               ;;
+       xmp)
+               basic_machine=xmp-cray
+               os=-unicos
+               ;;
+        xps | xps100)
+               basic_machine=xps100-honeywell
+               ;;
+       z8k-*-coff)
+               basic_machine=z8k-unknown
+               os=-sim
+               ;;
+       none)
+               basic_machine=none-none
+               os=-none
+               ;;
+
+# Here we handle the default manufacturer of certain CPU types.  It is in
+# some cases the only manufacturer, in others, it is the most popular.
+       w89k)
+               basic_machine=hppa1.1-winbond
+               ;;
+       op50n)
+               basic_machine=hppa1.1-oki
+               ;;
+       op60c)
+               basic_machine=hppa1.1-oki
+               ;;
+       mips)
+               if [ x$os = x-linux-gnu ]; then
+                       basic_machine=mips-unknown
+               else
+                       basic_machine=mips-mips
+               fi
+               ;;
+       romp)
+               basic_machine=romp-ibm
+               ;;
+       rs6000)
+               basic_machine=rs6000-ibm
+               ;;
+       vax)
+               basic_machine=vax-dec
+               ;;
+       pdp10)
+               # there are many clones, so DEC is not a safe bet
+               basic_machine=pdp10-unknown
+               ;;
+       pdp11)
+               basic_machine=pdp11-dec
+               ;;
+       we32k)
+               basic_machine=we32k-att
+               ;;
+       sh3 | sh4 | sh3eb | sh4eb)
+               basic_machine=sh-unknown
+               ;;
+       sparc | sparcv9 | sparcv9b)
+               basic_machine=sparc-sun
+               ;;
+        cydra)
+               basic_machine=cydra-cydrome
+               ;;
+       orion)
+               basic_machine=orion-highlevel
+               ;;
+       orion105)
+               basic_machine=clipper-highlevel
+               ;;
+       mac | mpw | mac-mpw)
+               basic_machine=m68k-apple
+               ;;
+       pmac | pmac-mpw)
+               basic_machine=powerpc-apple
+               ;;
+       c4x*)
+               basic_machine=c4x-none
+               os=-coff
+               ;;
+       *-unknown)
+               # Make sure to match an already-canonicalized machine name.
+               ;;
+       *)
+               echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2
+               exit 1
+               ;;
+esac
+
+# Here we canonicalize certain aliases for manufacturers.
+case $basic_machine in
+       *-digital*)
+               basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'`
+               ;;
+       *-commodore*)
+               basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'`
+               ;;
+       *)
+               ;;
+esac
+
+# Decode manufacturer-specific aliases for certain operating systems.
+
+if [ x"$os" != x"" ]
+then
+case $os in
+        # First match some system type aliases
+        # that might get confused with valid system types.
+       # -solaris* is a basic system type, with this one exception.
+       -solaris1 | -solaris1.*)
+               os=`echo $os | sed -e 's|solaris1|sunos4|'`
+               ;;
+       -solaris)
+               os=-solaris2
+               ;;
+       -svr4*)
+               os=-sysv4
+               ;;
+       -unixware*)
+               os=-sysv4.2uw
+               ;;
+       -gnu/linux*)
+               os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'`
+               ;;
+       # First accept the basic system types.
+       # The portable systems comes first.
+       # Each alternative MUST END IN A *, to match a version number.
+       # -sysv* is not here because it comes later, after sysvr4.
+       -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \
+             | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\
+             | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \
+             | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \
+             | -aos* \
+             | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \
+             | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \
+             | -hiux* | -386bsd* | -netbsd* | -openbsd* | -freebsd* | -riscix* \
+             | -lynxos* | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \
+             | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \
+             | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \
+             | -chorusos* | -chorusrdb* \
+             | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \
+             | -mingw32* | -linux-gnu* | -uxpv* | -beos* | -mpeix* | -udk* \
+             | -interix* | -uwin* | -rhapsody* | -darwin* | -opened* \
+             | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \
+             | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \
+             | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* | -morphos*)
+       # Remember, each alternative MUST END IN *, to match a version number.
+               ;;
+       -qnx*)
+               case $basic_machine in
+                   x86-* | i*86-*)
+                       ;;
+                   *)
+                       os=-nto$os
+                       ;;
+               esac
+               ;;
+       -nto*)
+               os=-nto-qnx
+               ;;
+       -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \
+             | -windows* | -osx | -abug | -netware* | -os9* | -beos* \
+             | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*)
+               ;;
+       -mac*)
+               os=`echo $os | sed -e 's|mac|macos|'`
+               ;;
+       -linux*)
+               os=`echo $os | sed -e 's|linux|linux-gnu|'`
+               ;;
+       -sunos5*)
+               os=`echo $os | sed -e 's|sunos5|solaris2|'`
+               ;;
+       -sunos6*)
+               os=`echo $os | sed -e 's|sunos6|solaris3|'`
+               ;;
+       -opened*)
+               os=-openedition
+               ;;
+       -wince*)
+               os=-wince
+               ;;
+       -osfrose*)
+               os=-osfrose
+               ;;
+       -osf*)
+               os=-osf
+               ;;
+       -utek*)
+               os=-bsd
+               ;;
+       -dynix*)
+               os=-bsd
+               ;;
+       -acis*)
+               os=-aos
+               ;;
+       -atheos*)
+               os=-atheos
+               ;;
+       -386bsd)
+               os=-bsd
+               ;;
+       -ctix* | -uts*)
+               os=-sysv
+               ;;
+       -ns2 )
+               os=-nextstep2
+               ;;
+       -nsk*)
+               os=-nsk
+               ;;
+       # Preserve the version number of sinix5.
+       -sinix5.*)
+               os=`echo $os | sed -e 's|sinix|sysv|'`
+               ;;
+       -sinix*)
+               os=-sysv4
+               ;;
+       -triton*)
+               os=-sysv3
+               ;;
+       -oss*)
+               os=-sysv3
+               ;;
+       -svr4)
+               os=-sysv4
+               ;;
+       -svr3)
+               os=-sysv3
+               ;;
+       -sysvr4)
+               os=-sysv4
+               ;;
+       # This must come after -sysvr4.
+       -sysv*)
+               ;;
+       -ose*)
+               os=-ose
+               ;;
+       -es1800*)
+               os=-ose
+               ;;
+       -xenix)
+               os=-xenix
+               ;;
+        -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+               os=-mint
+               ;;
+       -none)
+               ;;
+       *)
+               # Get rid of the `-' at the beginning of $os.
+               os=`echo $os | sed 's/[^-]*-//'`
+               echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2
+               exit 1
+               ;;
+esac
+else
+
+# Here we handle the default operating systems that come with various machines.
+# The value should be what the vendor currently ships out the door with their
+# machine or put another way, the most popular os provided with the machine.
+
+# Note that if you're going to try to match "-MANUFACTURER" here (say,
+# "-sun"), then you have to tell the case statement up towards the top
+# that MANUFACTURER isn't an operating system.  Otherwise, code above
+# will signal an error saying that MANUFACTURER isn't an operating
+# system, and we'll never get to this point.
+
+case $basic_machine in
+       *-acorn)
+               os=-riscix1.2
+               ;;
+       arm*-rebel)
+               os=-linux
+               ;;
+       arm*-semi)
+               os=-aout
+               ;;
+       # This must come before the *-dec entry.
+       pdp10-*)
+               os=-tops20
+               ;;
+        pdp11-*)
+               os=-none
+               ;;
+       *-dec | vax-*)
+               os=-ultrix4.2
+               ;;
+       m68*-apollo)
+               os=-domain
+               ;;
+       i386-sun)
+               os=-sunos4.0.2
+               ;;
+       m68000-sun)
+               os=-sunos3
+               # This also exists in the configure program, but was not the
+               # default.
+               # os=-sunos4
+               ;;
+       m68*-cisco)
+               os=-aout
+               ;;
+       mips*-cisco)
+               os=-elf
+               ;;
+       mips*-*)
+               os=-elf
+               ;;
+       *-tti)  # must be before sparc entry or we get the wrong os.
+               os=-sysv3
+               ;;
+       sparc-* | *-sun)
+               os=-sunos4.1.1
+               ;;
+       *-be)
+               os=-beos
+               ;;
+       *-ibm)
+               os=-aix
+               ;;
+       *-wec)
+               os=-proelf
+               ;;
+       *-winbond)
+               os=-proelf
+               ;;
+       *-oki)
+               os=-proelf
+               ;;
+       *-hp)
+               os=-hpux
+               ;;
+       *-hitachi)
+               os=-hiux
+               ;;
+       i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent)
+               os=-sysv
+               ;;
+       *-cbm)
+               os=-amigaos
+               ;;
+       *-dg)
+               os=-dgux
+               ;;
+       *-dolphin)
+               os=-sysv3
+               ;;
+       m68k-ccur)
+               os=-rtu
+               ;;
+       m88k-omron*)
+               os=-luna
+               ;;
+       *-next )
+               os=-nextstep
+               ;;
+       *-sequent)
+               os=-ptx
+               ;;
+       *-crds)
+               os=-unos
+               ;;
+       *-ns)
+               os=-genix
+               ;;
+       i370-*)
+               os=-mvs
+               ;;
+       *-next)
+               os=-nextstep3
+               ;;
+        *-gould)
+               os=-sysv
+               ;;
+        *-highlevel)
+               os=-bsd
+               ;;
+       *-encore)
+               os=-bsd
+               ;;
+        *-sgi)
+               os=-irix
+               ;;
+        *-siemens)
+               os=-sysv4
+               ;;
+       *-masscomp)
+               os=-rtu
+               ;;
+       f30[01]-fujitsu | f700-fujitsu)
+               os=-uxpv
+               ;;
+       *-rom68k)
+               os=-coff
+               ;;
+       *-*bug)
+               os=-coff
+               ;;
+       *-apple)
+               os=-macos
+               ;;
+       *-atari*)
+               os=-mint
+               ;;
+       *)
+               os=-none
+               ;;
+esac
+fi
+
+# Here we handle the case where we know the os, and the CPU type, but not the
+# manufacturer.  We pick the logical manufacturer.
+vendor=unknown
+case $basic_machine in
+       *-unknown)
+               case $os in
+                       -riscix*)
+                               vendor=acorn
+                               ;;
+                       -sunos*)
+                               vendor=sun
+                               ;;
+                       -aix*)
+                               vendor=ibm
+                               ;;
+                       -beos*)
+                               vendor=be
+                               ;;
+                       -hpux*)
+                               vendor=hp
+                               ;;
+                       -mpeix*)
+                               vendor=hp
+                               ;;
+                       -hiux*)
+                               vendor=hitachi
+                               ;;
+                       -unos*)
+                               vendor=crds
+                               ;;
+                       -dgux*)
+                               vendor=dg
+                               ;;
+                       -luna*)
+                               vendor=omron
+                               ;;
+                       -genix*)
+                               vendor=ns
+                               ;;
+                       -mvs* | -opened*)
+                               vendor=ibm
+                               ;;
+                       -ptx*)
+                               vendor=sequent
+                               ;;
+                       -vxsim* | -vxworks*)
+                               vendor=wrs
+                               ;;
+                       -aux*)
+                               vendor=apple
+                               ;;
+                       -hms*)
+                               vendor=hitachi
+                               ;;
+                       -mpw* | -macos*)
+                               vendor=apple
+                               ;;
+                       -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*)
+                               vendor=atari
+                               ;;
+                       -vos*)
+                               vendor=stratus
+                               ;;
+               esac
+               basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"`
+               ;;
+esac
+
+echo $basic_machine$os
+exit 0
+
+# Local variables:
+# eval: (add-hook 'write-file-hooks 'time-stamp)
+# time-stamp-start: "timestamp='"
+# time-stamp-format: "%:y-%02m-%02d"
+# time-stamp-end: "'"
+# End:
diff --git a/support/sdk/c/blip/driver/radvd-1.0/configure.in b/support/sdk/c/blip/driver/radvd-1.0/configure.in
new file mode 100644 (file)
index 0000000..39ea262
--- /dev/null
@@ -0,0 +1,157 @@
+dnl
+dnl  $Id$
+dnl
+dnl   Authors:
+dnl    Lars Fenneberg          <lf@elemental.net>       
+dnl
+dnl   This software is Copyright 1996-2000 by the above mentioned author(s), 
+dnl   All Rights Reserved.
+dnl
+dnl   The license which is distributed with this software in the file COPYRIGHT
+dnl   applies to this software. If your distribution is missing this file, you
+dnl   may request it from <pekkas@netcore.fi>.
+dnl
+dnl
+
+AC_REVISION ($Id$)
+AC_INIT(radvd.c)
+
+AC_CANONICAL_SYSTEM
+VERSION=`cat ${srcdir}/VERSION | grep -v '^#' | tr -d '\012'`
+AM_INIT_AUTOMAKE(radvd,$VERSION,true)
+
+echo $ac_n "building for architecture""... $ac_c" 1>&6
+case "$target" in
+       *linux*)
+               AC_MSG_RESULT(linux)
+                arch=linux
+        ;;
+        *bsd*)
+               AC_MSG_RESULT(bsd44)
+                arch=bsd44
+        ;;
+        *)      
+               AC_MSG_RESULT(unknown)
+               AC_MSG_ERROR(
+[currently only Linux and BSD 4.4 with NRL's IPv6 code are
+supported. If you have such a system and it is not guessed correctly 
+you must specifiy it with --target on the configure command line])
+        ;;
+esac
+
+dnl Determine CC and preset CFLAGS
+AC_PROG_CC
+
+dnl Needed for normal compile
+AC_PROG_INSTALL
+AC_PATH_PROG(RM, rm, NOTFOUND)
+if test "x$RM" = xNOTFOUND; then
+       AC_MSG_ERROR(can't find rm in your path - check PATH)
+fi
+AC_PATH_PROG(SED, sed, NOTFOUND)
+if test "x$SED" = xNOTFOUND; then
+       AC_MSG_ERROR(can't find sed in your path - check PATH)
+fi
+dnl Not needed
+AC_PATH_PROG(LN, ln)
+AC_PROG_YACC
+AM_PROG_LEX
+AC_PATH_PROG(TAR, tar)
+AC_PATH_PROG(GZIP, gzip)
+
+dnl Check where to put the logfile
+AC_MSG_CHECKING(where to put logfile)
+AC_ARG_WITH(logfile,
+[  --with-logfile          Path to the radvd logfile [/var/log/radvd.log]],
+       PATH_RADVD_LOG=$withval,
+       PATH_RADVD_LOG=/var/log/radvd.log)
+AC_MSG_RESULT($PATH_RADVD_LOG)
+
+dnl Check where to put the pidfile
+AC_MSG_CHECKING(where to put pidfile)
+AC_ARG_WITH(pidfile,
+[  --with-pidfile          Path to the radvd pidfile [/var/run/radvd.pid]],
+       PATH_RADVD_PID=$withval,
+       PATH_RADVD_PID=/var/run/radvd.pid)
+AC_MSG_RESULT($PATH_RADVD_PID)
+
+dnl Check where to put the configfile
+AC_MSG_CHECKING(where to find configfile)
+AC_ARG_WITH(configfile,
+[  --with-configfile       Path to the radvd config file [SYSCONF/radvd.conf]],
+       PATH_RADVD_CONF=$withval,
+       PATH_RADVD_CONF=${sysconfdir}/radvd.conf)
+AC_MSG_RESULT($PATH_RADVD_CONF)
+
+dnl Checking which syslog facility to use
+AC_MSG_CHECKING(which syslog facility to use)
+AC_ARG_WITH(facility,
+[  --with-facility         Syslog facility to use when using syslog logging],
+       LOG_FACILITY=$withval,
+       LOG_FACILITY=LOG_DAEMON)
+AC_MSG_RESULT($LOG_FACILITY)
+
+dnl Checks for libraries.
+
+AC_CHECK_LIB(c, inet_ntop,,
+ AC_CHECK_LIB(inet6, inet_ntop,
+  LIBS="$LIBS -linet6"
+  ,
+    AC_MSG_ERROR(can't continue without libinet6.a library - check your LDFLAGS)
+ )
+)
+# prevent caching
+unset ac_cv_lib_inet6_inet_ntop
+
+dnl Checks for header files.
+AC_HEADER_STDC
+AC_CHECK_HEADERS(sys/time.h)
+AC_HEADER_TIME
+
+AC_CHECK_HEADER(netinet/ip6.h, hdrfound=yes, hdrfound=no)
+if test "$hdrfound" = no
+then
+ # deprecated
+ AC_CHECK_HEADER(netinet/ipv6.h, hdrfound=yes)
+fi
+if test "$hdrfound" = no
+then
+   AC_MSG_RESULT(no)
+fi
+unset hdrfound
+
+AC_CHECK_HEADERS(sys/sockio.h getopt.h inttypes.h)
+AC_CHECK_HEADERS(net/if_dl.h net/if_types.h net/if_arp.h)
+AC_CHECK_HEADERS(sys/param.h)
+AC_CHECK_HEADERS(machine/param.h)
+AC_CHECK_HEADERS(machine/limits.h)
+
+dnl Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+
+AC_MSG_CHECKING(whether struct sockaddr_in6 has sin6_scope_id)
+AC_TRY_COMPILE([#include <sys/types.h>
+#include <netinet/in.h>], [static struct sockaddr_in6 ac_sin6; int ac_size = 
+sizeof (ac_sin6.sin6_scope_id);], [AC_MSG_RESULT(yes); AC_DEFINE([HAVE_SIN6_SCOPE_ID],
+1, [whether struct sockaddr_in6 has sin6_scope_id])],
+AC_MSG_RESULT(no))
+
+AC_MSG_CHECKING(whether struct in6_addr has u6_addrXX and defines s6_addrXX)
+AC_TRY_COMPILE([#include <netinet/in.h>], [static struct in6_addr in6_u; 
+int u =  in6_u.s6_addr16;], [AC_MSG_RESULT(yes); AC_DEFINE([HAVE_IN6_ADDR_S6_ADDR],
+1, [whether struct in6_addr has u6_addrXX and defines s6_addrXX])],
+AC_MSG_RESULT(no))
+
+dnl Checks for library functions.
+AC_CHECK_FUNCS(getopt_long)
+
+AC_LINK_FILES(device-${arch}.c, device.c)
+
+AC_SUBST(VERSION)
+AC_SUBST(PATH_RADVD_CONF)
+AC_SUBST(PATH_RADVD_PID)
+AC_SUBST(PATH_RADVD_LOG)
+AC_SUBST(LOG_FACILITY)
+
+AM_CONFIG_HEADER(config.h)
+AC_OUTPUT(Makefile)
diff --git a/support/sdk/c/blip/driver/radvd-1.0/copyright.blurb b/support/sdk/c/blip/driver/radvd-1.0/copyright.blurb
new file mode 100644 (file)
index 0000000..51923b7
--- /dev/null
@@ -0,0 +1,14 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
diff --git a/support/sdk/c/blip/driver/radvd-1.0/defaults.h b/support/sdk/c/blip/driver/radvd-1.0/defaults.h
new file mode 100644 (file)
index 0000000..acb2b2b
--- /dev/null
@@ -0,0 +1,226 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#ifndef DEFAULTS_H
+#define DEFAULTS_H
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+
+/* maximum message size for incoming and outgoing RSs and RAs */
+
+#define MSG_SIZE                       4096
+
+#define MAX2(X,Y) ( (( X ) >=  ( Y )) ? ( X ) : ( Y ))
+
+
+/* Router Configuration Variables: */
+
+/* For each multicast interface: */
+
+#define DFLT_IgnoreIfMissing           0
+#define DFLT_AdvSendAdv                        0
+#define DFLT_MaxRtrAdvInterval         600
+#define DFLT_MinRtrAdvInterval(iface)  (0.33 * (iface)->MaxRtrAdvInterval)
+#define DFLT_AdvManagedFlag            0
+#define DFLT_AdvOtherConfigFlag                0
+#define DFLT_AdvLinkMTU                        0
+#define DFLT_AdvReachableTime          0
+#define DFLT_AdvRetransTimer           0
+#define DFLT_AdvCurHopLimit            64      /* as per RFC 1700 or the 
+                                                  next incarnation of it :) */
+#define DFLT_AdvDefaultLifetime(iface) MAX2(1, (int)(3.0 * (iface)->MaxRtrAdvInterval))
+#define DFLT_MinDelayBetweenRAs                MIN_DELAY_BETWEEN_RAS
+#define DFLT_AdvDefaultPreference      0
+
+/* Options sent with RA */
+
+#define DFLT_AdvSourceLLAddress                1
+
+/* Each prefix has an associated: */
+
+#define DFLT_AdvValidLifetime          2592000 /* seconds */
+#define DFLT_AdvOnLinkFlag             1
+#define DFLT_AdvPreferredLifetime      604800 /* seconds */
+#define DFLT_AdvAutonomousFlag         1
+
+/* Each route has an associated: */
+#define DFLT_AdvRouteLifetime(iface)   (3 * (iface)->MaxRtrAdvInterval)
+
+#define DFLT_AdvRoutePreference                0 /* medium*/
+
+/* RDNSS */
+#define DFLT_AdvRDNSSPreference                                8 /* medium */
+#define DFLT_AdvRDNSSOpenFlag                          0
+#define DFLT_AdvRDNSSLifetime(iface)                   (iface)->MaxRtrAdvInterval
+
+/* Protocol (RFC2461) constants: */
+
+/* Router constants: */
+
+#define MAX_INITIAL_RTR_ADVERT_INTERVAL        16
+#define MAX_INITIAL_RTR_ADVERTISEMENTS 3
+#define MAX_FINAL_RTR_ADVERTISEMENTS   3
+#define MIN_DELAY_BETWEEN_RAS          3.0
+#define MIN_DELAY_BETWEEN_RAS_MIPv6     (30.0/1000.0)
+#define MAX_RA_DELAY_TIME              (1000.0/2.0) /* milliseconds */
+
+/* Host constants: */
+
+#define MAX_RTR_SOLICITATION_DELAY     1
+#define RTR_SOLICITATION_INTERVAL      4
+#define MAX_RTR_SOLICITATIONS          3
+
+/* Node constants: */
+
+#define MAX_MULTICAST_SOLICIT          3
+#define MAX_UNICAST_SOLICIT            3
+#define MAX_ANYCAST_DELAY_TIME         1
+#define MAX_NEIGHBOR_ADVERTISEMENT     3
+#define REACHABLE_TIME                 30000 /* milliseconds */
+#define RETRANS_TIMER                  1000 /* milliseconds */
+#define DELAY_FIRST_PROBE_TIME         5
+#define MIN_RANDOM_FACTOR              (1.0/2.0)
+#define MAX_RANDOM_FACTOR              (3.0/2.0)
+
+/* MAX and MIN (RFC2461), Mobile IPv6 extensions will override if in use */
+
+#define MIN_MaxRtrAdvInterval          4
+#define MAX_MaxRtrAdvInterval          1800
+
+#define MIN_MinRtrAdvInterval          3
+#define MAX_MinRtrAdvInterval(iface)   (0.75 * (iface)->MaxRtrAdvInterval)
+
+#define MIN_AdvDefaultLifetime(iface)  (MAX2(1,(iface)->MaxRtrAdvInterval))
+#define MAX_AdvDefaultLifetime         9000
+
+#define        MIN_AdvLinkMTU                  1280
+
+#define MAX_AdvReachableTime           3600000 /* 1 hour in milliseconds */
+
+#define MAX_AdvCurHopLimit             255
+
+#define MAX_PrefixLen                  128
+
+/*
+ * Mobile IPv6 extensions, off by default
+ */
+
+#define DFLT_AdvRouterAddr             0
+#define DFLT_AdvHomeAgentFlag          0
+#define DFLT_AdvIntervalOpt            0
+#define DFLT_AdvHomeAgentInfo          0
+
+/* Option types (defined also at least in glibc 2.2's netinet/icmp6.h) */
+
+#ifndef ND_OPT_RTR_ADV_INTERVAL
+#define ND_OPT_RTR_ADV_INTERVAL         7
+#endif
+#ifndef ND_OPT_HOME_AGENT_INFO
+#define ND_OPT_HOME_AGENT_INFO          8
+#endif
+
+/* de-facto codepoint used by many implementations was '9',
+   the official IANA assignment will be '24' */
+#undef ND_OPT_ROUTE_INFORMATION
+#define  ND_OPT_ROUTE_INFORMATION      24
+
+/* XXX: some libc's like KAME already had nd_opt_route_info! */
+struct nd_opt_route_info_local     /* route information */
+  {
+    uint8_t   nd_opt_ri_type;
+    uint8_t   nd_opt_ri_len;
+    uint8_t   nd_opt_ri_prefix_len;
+    uint8_t   nd_opt_ri_flags_reserved;
+    uint32_t  nd_opt_ri_lifetime;
+    struct in6_addr  nd_opt_ri_prefix;
+  };
+
+/* the reserved field is 8 bits and we're interested of the middle two: 000xx000 */
+#define ND_OPT_RI_PRF_SHIFT    3
+#define ND_OPT_RI_PRF_MASK     (3 << ND_OPT_RI_PRF_SHIFT) /* 00011000 = 0x18 */
+
+#undef ND_OPT_RDNSS_INFORMATION
+#define  ND_OPT_RDNSS_INFORMATION      25
+
+/* */
+struct nd_opt_rdnss_info_local
+{
+       uint8_t                         nd_opt_rdnssi_type;
+       uint8_t                         nd_opt_rdnssi_len;
+       uint16_t                        nd_opt_rdnssi_pref_flag_reserved;
+       uint32_t                        nd_opt_rdnssi_lifetime;
+       struct in6_addr         nd_opt_rdnssi_addr1;
+       struct in6_addr         nd_opt_rdnssi_addr2;
+       struct in6_addr         nd_opt_rdnssi_addr3;
+};
+/* pref/flag/reserved field : yyyyx00000000000 (big endian) - 00000000yyyyx000 (little indian); where yyyy = pref, x = flag */
+#if BYTE_ORDER == BIG_ENDIAN
+#define ND_OPT_RDNSSI_PREF_SHIFT       12
+#else
+#define ND_OPT_RDNSSI_PREF_SHIFT       4
+#endif
+#define ND_OPT_RDNSSI_PREF_MASK                (0xf << ND_OPT_RDNSSI_PREF_SHIFT)
+
+/* Flags */
+
+#ifndef ND_RA_FLAG_HOME_AGENT
+#define ND_RA_FLAG_HOME_AGENT          0x20
+#endif
+#ifndef ND_OPT_PI_FLAG_RADDR
+#define ND_OPT_PI_FLAG_RADDR           0x20
+#endif
+#ifndef ND_OPT_RDNSSI_FLAG_S
+#if BYTE_ORDER == BIG_ENDIAN
+#define ND_OPT_RDNSSI_FLAG_S         0x0800
+#else
+#define ND_OPT_RDNSSI_FLAG_S         0x0008
+#endif
+#endif
+
+/* Configurable values */
+
+#define DFLT_HomeAgentPreference       0
+#define DFLT_HomeAgentLifetime(iface)  ((iface)->AdvDefaultLifetime)
+
+/* Other */
+
+#define MIN_MinRtrAdvInterval_MIPv6    (3.0/100.0)
+#define MIN_MaxRtrAdvInterval_MIPv6    (7.0/100.0)
+#define RTR_SOLICITATION_INTERVAL_MIPv6        1 /* Recommended value by MIPv6 */
+
+#define Cautious_MaxRtrAdvInterval      (2.0/10.0)
+#define Cautious_MaxRtrAdvInterval_Leeway      (2.0/100.0)
+
+#define MIN_HomeAgentLifetime          1 /* 0 must NOT be used */
+#define MAX_HomeAgentLifetime          65520 /* 18.2 hours in secs */
+
+/* #define MAX_RTR_SOLICITATIONS This MAY be ignored by MIPv6 */
+
+/* NEMO extensions, off by default */
+#define DFLT_AdvMobRtrSupportFlag              0
+
+/* Flags */
+
+#ifndef ND_OPT_HAI_FLAG_SUPPORT_MR
+#if BYTE_ORDER == BIG_ENDIAN
+#define ND_OPT_HAI_FLAG_SUPPORT_MR     0x8000
+#else /* BYTE_ORDER == LITTLE_ENDIAN */
+#define ND_OPT_HAI_FLAG_SUPPORT_MR     0x0080
+#endif
+#endif
+
+#endif
diff --git a/support/sdk/c/blip/driver/radvd-1.0/depcomp b/support/sdk/c/blip/driver/radvd-1.0/depcomp
new file mode 100755 (executable)
index 0000000..edb5d38
--- /dev/null
@@ -0,0 +1,479 @@
+#! /bin/sh
+
+# depcomp - compile a program generating dependencies as side-effects
+# Copyright 1999, 2000, 2003 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+# 02111-1307, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+# Originally written by Alexandre Oliva <oliva@dcc.unicamp.br>.
+
+if test -z "$depmode" || test -z "$source" || test -z "$object"; then
+  echo "depcomp: Variables source, object and depmode must be set" 1>&2
+  exit 1
+fi
+# `libtool' can also be set to `yes' or `no'.
+
+if test -z "$depfile"; then
+   base=`echo "$object" | sed -e 's,^.*/,,' -e 's,\.\([^.]*\)$,.P\1,'`
+   dir=`echo "$object" | sed 's,/.*$,/,'`
+   if test "$dir" = "$object"; then
+      dir=
+   fi
+   # FIXME: should be _deps on DOS.
+   depfile="$dir.deps/$base"
+fi
+
+tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`}
+
+rm -f "$tmpdepfile"
+
+# Some modes work just like other modes, but use different flags.  We
+# parameterize here, but still list the modes in the big case below,
+# to make depend.m4 easier to write.  Note that we *cannot* use a case
+# here, because this file can only contain one case statement.
+if test "$depmode" = hp; then
+  # HP compiler uses -M and no extra arg.
+  gccflag=-M
+  depmode=gcc
+fi
+
+if test "$depmode" = dashXmstdout; then
+   # This is just like dashmstdout with a different argument.
+   dashmflag=-xM
+   depmode=dashmstdout
+fi
+
+case "$depmode" in
+gcc3)
+## gcc 3 implements dependency tracking that does exactly what
+## we want.  Yay!  Note: for some reason libtool 1.4 doesn't like
+## it if -MD -MP comes after the -MF stuff.  Hmm.
+  "$@" -MT "$object" -MD -MP -MF "$tmpdepfile"
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  mv "$tmpdepfile" "$depfile"
+  ;;
+
+gcc)
+## There are various ways to get dependency output from gcc.  Here's
+## why we pick this rather obscure method:
+## - Don't want to use -MD because we'd like the dependencies to end
+##   up in a subdir.  Having to rename by hand is ugly.
+##   (We might end up doing this anyway to support other compilers.)
+## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like
+##   -MM, not -M (despite what the docs say).
+## - Using -M directly means running the compiler twice (even worse
+##   than renaming).
+  if test -z "$gccflag"; then
+    gccflag=-MD,
+  fi
+  "$@" -Wp,"$gccflag$tmpdepfile"
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
+## The second -e expression handles DOS-style file names with drive letters.
+  sed -e 's/^[^:]*: / /' \
+      -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile"
+## This next piece of magic avoids the `deleted header file' problem.
+## The problem is that when a header file which appears in a .P file
+## is deleted, the dependency causes make to die (because there is
+## typically no way to rebuild the header).  We avoid this by adding
+## dummy dependencies for each header file.  Too bad gcc doesn't do
+## this for us directly.
+  tr ' ' '
+' < "$tmpdepfile" |
+## Some versions of gcc put a space before the `:'.  On the theory
+## that the space means something, we add a space to the output as
+## well.
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly.  Breaking it into two sed invocations is a workaround.
+    sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+hp)
+  # This case exists only to let depend.m4 do its work.  It works by
+  # looking at the text of this script.  This case will never be run,
+  # since it is checked for above.
+  exit 1
+  ;;
+
+sgi)
+  if test "$libtool" = yes; then
+    "$@" "-Wp,-MDupdate,$tmpdepfile"
+  else
+    "$@" -MDupdate "$tmpdepfile"
+  fi
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+
+  if test -f "$tmpdepfile"; then  # yes, the sourcefile depend on other files
+    echo "$object : \\" > "$depfile"
+
+    # Clip off the initial element (the dependent).  Don't try to be
+    # clever and replace this with sed code, as IRIX sed won't handle
+    # lines with more than a fixed number of characters (4096 in
+    # IRIX 6.2 sed, 8192 in IRIX 6.5).  We also remove comment lines;
+    # the IRIX cc adds comments like `#:fec' to the end of the
+    # dependency line.
+    tr ' ' '
+' < "$tmpdepfile" \
+    | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \
+    tr '
+' ' ' >> $depfile
+    echo >> $depfile
+
+    # The second pass generates a dummy entry for each header file.
+    tr ' ' '
+' < "$tmpdepfile" \
+   | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \
+   >> $depfile
+  else
+    # The sourcefile does not contain any dependencies, so just
+    # store a dummy comment line, to avoid errors with the Makefile
+    # "include basename.Plo" scheme.
+    echo "#dummy" > "$depfile"
+  fi
+  rm -f "$tmpdepfile"
+  ;;
+
+aix)
+  # The C for AIX Compiler uses -M and outputs the dependencies
+  # in a .u file.  In older versions, this file always lives in the
+  # current directory.  Also, the AIX compiler puts `$object:' at the
+  # start of each line; $object doesn't have directory information.
+  # Version 6 uses the directory in both cases.
+  stripped=`echo "$object" | sed 's/\(.*\)\..*$/\1/'`
+  tmpdepfile="$stripped.u"
+  if test "$libtool" = yes; then
+    "$@" -Wc,-M
+  else
+    "$@" -M
+  fi
+  stat=$?
+
+  if test -f "$tmpdepfile"; then :
+  else
+    stripped=`echo "$stripped" | sed 's,^.*/,,'`
+    tmpdepfile="$stripped.u"
+  fi
+
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+
+  if test -f "$tmpdepfile"; then
+    outname="$stripped.o"
+    # Each line is of the form `foo.o: dependent.h'.
+    # Do two passes, one to just change these to
+    # `$object: dependent.h' and one to simply `dependent.h:'.
+    sed -e "s,^$outname:,$object :," < "$tmpdepfile" > "$depfile"
+    sed -e "s,^$outname: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile"
+  else
+    # The sourcefile does not contain any dependencies, so just
+    # store a dummy comment line, to avoid errors with the Makefile
+    # "include basename.Plo" scheme.
+    echo "#dummy" > "$depfile"
+  fi
+  rm -f "$tmpdepfile"
+  ;;
+
+icc)
+  # Intel's C compiler understands `-MD -MF file'.  However on
+  #    icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c
+  # ICC 7.0 will fill foo.d with something like
+  #    foo.o: sub/foo.c
+  #    foo.o: sub/foo.h
+  # which is wrong.  We want:
+  #    sub/foo.o: sub/foo.c
+  #    sub/foo.o: sub/foo.h
+  #    sub/foo.c:
+  #    sub/foo.h:
+  # ICC 7.1 will output
+  #    foo.o: sub/foo.c sub/foo.h
+  # and will wrap long lines using \ :
+  #    foo.o: sub/foo.c ... \
+  #     sub/foo.h ... \
+  #     ...
+
+  "$@" -MD -MF "$tmpdepfile"
+  stat=$?
+  if test $stat -eq 0; then :
+  else
+    rm -f "$tmpdepfile"
+    exit $stat
+  fi
+  rm -f "$depfile"
+  # Each line is of the form `foo.o: dependent.h',
+  # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'.
+  # Do two passes, one to just change these to
+  # `$object: dependent.h' and one to simply `dependent.h:'.
+  sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile"
+  # Some versions of the HPUX 10.20 sed can't process this invocation
+  # correctly.  Breaking it into two sed invocations is a workaround.
+  sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" |
+    sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+tru64)
+   # The Tru64 compiler uses -MD to generate dependencies as a side
+   # effect.  `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'.
+   # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put
+   # dependencies in `foo.d' instead, so we check for that too.
+   # Subdirectories are respected.
+   dir=`echo "$object" | sed -e 's|/[^/]*$|/|'`
+   test "x$dir" = "x$object" && dir=
+   base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'`
+
+   if test "$libtool" = yes; then
+      tmpdepfile1="$dir.libs/$base.lo.d"
+      tmpdepfile2="$dir.libs/$base.d"
+      "$@" -Wc,-MD
+   else
+      tmpdepfile1="$dir$base.o.d"
+      tmpdepfile2="$dir$base.d"
+      "$@" -MD
+   fi
+
+   stat=$?
+   if test $stat -eq 0; then :
+   else
+      rm -f "$tmpdepfile1" "$tmpdepfile2"
+      exit $stat
+   fi
+
+   if test -f "$tmpdepfile1"; then
+      tmpdepfile="$tmpdepfile1"
+   else
+      tmpdepfile="$tmpdepfile2"
+   fi
+   if test -f "$tmpdepfile"; then
+      sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile"
+      # That's a tab and a space in the [].
+      sed -e 's,^.*\.[a-z]*:[   ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile"
+   else
+      echo "#dummy" > "$depfile"
+   fi
+   rm -f "$tmpdepfile"
+   ;;
+
+#nosideeffect)
+  # This comment above is used by automake to tell side-effect
+  # dependency tracking mechanisms from slower ones.
+
+dashmstdout)
+  # Important note: in order to support this mode, a compiler *must*
+  # always write the preprocessed file to stdout, regardless of -o.
+  "$@" || exit $?
+
+  # Remove the call to Libtool.
+  if test "$libtool" = yes; then
+    while test $1 != '--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+
+  # Remove `-o $object'.
+  IFS=" "
+  for arg
+  do
+    case $arg in
+    -o)
+      shift
+      ;;
+    $object)
+      shift
+      ;;
+    *)
+      set fnord "$@" "$arg"
+      shift # fnord
+      shift # $arg
+      ;;
+    esac
+  done
+
+  test -z "$dashmflag" && dashmflag=-M
+  # Require at least two characters before searching for `:'
+  # in the target name.  This is to cope with DOS-style filenames:
+  # a dependency such as `c:/foo/bar' could be seen as target `c' otherwise.
+  "$@" $dashmflag |
+    sed 's:^[  ]*[^: ][^:][^:]*\:[    ]*:'"$object"'\: :' > "$tmpdepfile"
+  rm -f "$depfile"
+  cat < "$tmpdepfile" > "$depfile"
+  tr ' ' '
+' < "$tmpdepfile" | \
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly.  Breaking it into two sed invocations is a workaround.
+    sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+dashXmstdout)
+  # This case only exists to satisfy depend.m4.  It is never actually
+  # run, as this mode is specially recognized in the preamble.
+  exit 1
+  ;;
+
+makedepend)
+  "$@" || exit $?
+  # Remove any Libtool call
+  if test "$libtool" = yes; then
+    while test $1 != '--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+  # X makedepend
+  shift
+  cleared=no
+  for arg in "$@"; do
+    case $cleared in
+    no)
+      set ""; shift
+      cleared=yes ;;
+    esac
+    case "$arg" in
+    -D*|-I*)
+      set fnord "$@" "$arg"; shift ;;
+    # Strip any option that makedepend may not understand.  Remove
+    # the object too, otherwise makedepend will parse it as a source file.
+    -*|$object)
+      ;;
+    *)
+      set fnord "$@" "$arg"; shift ;;
+    esac
+  done
+  obj_suffix="`echo $object | sed 's/^.*\././'`"
+  touch "$tmpdepfile"
+  ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@"
+  rm -f "$depfile"
+  cat < "$tmpdepfile" > "$depfile"
+  sed '1,2d' "$tmpdepfile" | tr ' ' '
+' | \
+## Some versions of the HPUX 10.20 sed can't process this invocation
+## correctly.  Breaking it into two sed invocations is a workaround.
+    sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile" "$tmpdepfile".bak
+  ;;
+
+cpp)
+  # Important note: in order to support this mode, a compiler *must*
+  # always write the preprocessed file to stdout.
+  "$@" || exit $?
+
+  # Remove the call to Libtool.
+  if test "$libtool" = yes; then
+    while test $1 != '--mode=compile'; do
+      shift
+    done
+    shift
+  fi
+
+  # Remove `-o $object'.
+  IFS=" "
+  for arg
+  do
+    case $arg in
+    -o)
+      shift
+      ;;
+    $object)
+      shift
+      ;;
+    *)
+      set fnord "$@" "$arg"
+      shift # fnord
+      shift # $arg
+      ;;
+    esac
+  done
+
+  "$@" -E |
+    sed -n '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' |
+    sed '$ s: \\$::' > "$tmpdepfile"
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  cat < "$tmpdepfile" >> "$depfile"
+  sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+msvisualcpp)
+  # Important note: in order to support this mode, a compiler *must*
+  # always write the preprocessed file to stdout, regardless of -o,
+  # because we must use -o when running libtool.
+  "$@" || exit $?
+  IFS=" "
+  for arg
+  do
+    case "$arg" in
+    "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI")
+       set fnord "$@"
+       shift
+       shift
+       ;;
+    *)
+       set fnord "$@" "$arg"
+       shift
+       shift
+       ;;
+    esac
+  done
+  "$@" -E |
+  sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile"
+  rm -f "$depfile"
+  echo "$object : \\" > "$depfile"
+  . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::   \1 \\:p' >> "$depfile"
+  echo "       " >> "$depfile"
+  . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile"
+  rm -f "$tmpdepfile"
+  ;;
+
+none)
+  exec "$@"
+  ;;
+
+*)
+  echo "Unknown depmode $depmode" 1>&2
+  exit 1
+  ;;
+esac
+
+exit 0
diff --git a/support/sdk/c/blip/driver/radvd-1.0/device-bsd44.c b/support/sdk/c/blip/driver/radvd-1.0/device-bsd44.c
new file mode 100644 (file)
index 0000000..b89ce31
--- /dev/null
@@ -0,0 +1,251 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Craig Metz               <cmetz@inner.net>
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include <config.h>
+#include <includes.h>
+#include <radvd.h>
+#include <defaults.h>
+#include <pathnames.h>         /* for PATH_PROC_NET_IF_INET6 */
+
+static uint8_t ll_prefix[] = { 0xfe, 0x80 };
+
+/*
+ * this function gets the hardware type and address of an interface,
+ * determines the link layer token length and checks it against
+ * the defined prefixes
+ */
+int
+setup_deviceinfo(int sock, struct Interface *iface)
+{
+       struct ifconf ifconf;
+       struct ifreq ifr;
+       unsigned int nlen;
+       uint8_t *p, *end;
+       struct AdvPrefix *prefix;
+       char zero[sizeof(iface->if_addr)];
+
+       /* just allocate 8192 bytes, should be more than enough.. */
+       if (!(ifconf.ifc_buf = malloc(ifconf.ifc_len = (32 << 8))))
+       {
+               flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+               goto ret;
+       }
+
+       if (ioctl(sock, SIOCGIFCONF, &ifconf) < 0)
+       {
+               flog(LOG_ERR, "ioctl(SIOCGIFCONF) failed: %s(%d)", strerror(errno), errno);
+               goto ret;
+       }
+
+       memset(&ifr, 0, sizeof(ifr));
+       strncpy(ifr.ifr_name, iface->Name, IFNAMSIZ-1);
+       ifr.ifr_name[IFNAMSIZ-1] = '\0';
+
+       if (ioctl(sock, SIOCGIFMTU, &ifr) < 0) {
+               flog(LOG_ERR, "ioctl(SIOCGIFMTU) failed for %s: %s", iface->Name, strerror(errno));
+               goto ret;
+       }       
+
+       dlog(LOG_DEBUG, 3, "mtu for %s is %d", iface->Name, ifr.ifr_mtu);
+       iface->if_maxmtu = ifr.ifr_mtu;
+
+       p = (uint8_t *)ifconf.ifc_buf;
+       end = p + ifconf.ifc_len;
+       nlen = strlen(iface->Name);
+
+       while(p < end)
+       {
+               p += IFNAMSIZ;
+               
+               if ((p + 2) >= end)
+                       break;
+                       
+               if ((p + *p) >= end)
+                       break;
+                       
+               if ((*(p + 1) == AF_LINK) &&
+                   (((struct sockaddr_dl *)p)->sdl_nlen == nlen) &&
+                   (!memcmp(iface->Name, ((struct sockaddr_dl *)p)->sdl_data, nlen)))
+               {
+               
+                       if (((struct sockaddr_dl *)p)->sdl_alen > sizeof(iface->if_addr))
+                       {
+                               flog(LOG_ERR, "address length %d too big for",
+                                       ((struct sockaddr_dl *)p)->sdl_alen,
+                                       iface->Name);
+                               goto ret;
+                       }
+               
+                       memcpy(iface->if_hwaddr, LLADDR((struct sockaddr_dl *)p), ((struct sockaddr_dl *)p)->sdl_alen);
+                       iface->if_hwaddr_len = ((struct sockaddr_dl *)p)->sdl_alen << 3;
+
+                       switch(((struct sockaddr_dl *)p)->sdl_type) {
+                       case IFT_ETHER:
+                       case IFT_ISO88023:
+                               iface->if_prefix_len = 64;
+                               break;
+                       case IFT_FDDI:
+                               iface->if_prefix_len = 64;
+                               break;
+                       default:
+                               iface->if_prefix_len = -1;
+                               iface->if_maxmtu = -1;
+                               break;
+                       }
+
+                       dlog(LOG_DEBUG, 3, "link layer token length for %s is %d", iface->Name,
+                               iface->if_hwaddr_len);
+
+                       dlog(LOG_DEBUG, 3, "prefix length for %s is %d", iface->Name,
+                               iface->if_prefix_len);
+
+                       if (iface->if_prefix_len != -1) {
+                               memset(zero, 0, ((struct sockaddr_dl *)p)->sdl_alen);
+                               if (!memcmp(iface->if_hwaddr, zero, ((struct sockaddr_dl *)p)->sdl_alen))
+                                       flog(LOG_WARNING, "WARNING, MAC address on %s is all zero!",
+                                               iface->Name);
+                       }
+                       
+                       prefix = iface->AdvPrefixList;
+                       while (prefix)
+                       {
+                               if ((iface->if_prefix_len != -1) &&
+                                       (iface->if_prefix_len != prefix->PrefixLen))
+                               {
+                                       flog(LOG_WARNING, "prefix length should be %d for %s",
+                                               iface->if_prefix_len, iface->Name);
+                               }
+                       
+                               prefix = prefix->next;
+                       }
+                       
+                       free(ifconf.ifc_buf);
+                       return 0;
+               }
+        
+               p += *p;        
+       }
+
+ret:
+       iface->if_maxmtu = -1;
+       iface->if_hwaddr_len = -1;
+       iface->if_prefix_len = -1;
+       free(ifconf.ifc_buf);
+       return -1;
+}
+
+int setup_linklocal_addr(int sock, struct Interface *iface)
+{
+       struct ifconf ifconf;
+       unsigned int nlen;
+       uint8_t *p, *end;
+       int index = 0;
+
+       /* just allocate 8192 bytes, should be more than enough.. */
+       if (!(ifconf.ifc_buf = malloc(ifconf.ifc_len = (32 << 8))))
+       {
+               flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+               goto ret;
+       }
+
+       if (ioctl(sock, SIOCGIFCONF, &ifconf) < 0)
+       {
+               flog(LOG_ERR, "ioctl(SIOCGIFCONF) failed: %s(%d)", strerror(errno), errno);
+               goto ret;
+       }
+
+       p = (uint8_t *)ifconf.ifc_buf;
+       end = p + ifconf.ifc_len;
+       nlen = strlen(iface->Name);
+
+       while(p < end)
+       {
+               p += IFNAMSIZ;
+       
+               if ((p + 2) >= end)
+                       break;
+                       
+               if ((p + *p) >= end)
+                       break;
+                       
+               if ((*(p + 1) == AF_LINK) &&
+                   (((struct sockaddr_dl *)p)->sdl_nlen == nlen) &&
+                   (!memcmp(iface->Name, ((struct sockaddr_dl *)p)->sdl_data, nlen)))
+               {
+                       index = ((struct sockaddr_dl *)p)->sdl_index;
+               }
+               
+               if (index && (*(p + 1) == AF_INET6))
+                 if (!memcmp(&((struct sockaddr_in6 *)p)->sin6_addr, ll_prefix, sizeof(ll_prefix)))
+                 {
+                       memcpy(&iface->if_addr, &((struct sockaddr_in6 *)p)->sin6_addr, sizeof(struct in6_addr));
+                       iface->if_index = index;
+
+                       free(ifconf.ifc_buf);
+                       return 0;
+                 }
+         
+               p += *p;
+
+       }
+
+ret:
+       flog(LOG_ERR, "no linklocal address configured for %s", iface->Name);
+       free(ifconf.ifc_buf);
+       return -1;
+}
+
+int setup_allrouters_membership(int sock, struct Interface *iface)
+{
+       return (0);
+}
+
+int check_allrouters_membership(int sock, struct Interface *iface)
+{
+       return (0);
+}
+
+int
+set_interface_linkmtu(const char *iface, uint32_t mtu)
+{
+       dlog(LOG_DEBUG, 4, "setting LinkMTU (%u) for %s is not supported",
+            mtu, iface);
+       return -1;
+}
+
+int
+set_interface_curhlim(const char *iface, uint8_t hlim)
+{
+       dlog(LOG_DEBUG, 4, "setting CurHopLimit (%u) for %s is not supported",
+            hlim, iface);
+       return -1;
+}
+
+int
+set_interface_reachtime(const char *iface, uint32_t rtime)
+{
+       dlog(LOG_DEBUG, 4, "setting BaseReachableTime (%u) for %s is not supported",
+            rtime, iface);
+       return -1;
+}
+
+int
+set_interface_retranstimer(const char *iface, uint32_t rettimer)
+{
+       dlog(LOG_DEBUG, 4, "setting RetransTimer (%u) for %s is not supported",
+            rettimer, iface);
+       return -1;
+}
+
diff --git a/support/sdk/c/blip/driver/radvd-1.0/device-common.c b/support/sdk/c/blip/driver/radvd-1.0/device-common.c
new file mode 100644 (file)
index 0000000..527ba43
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+#include "defaults.h"
+
+int
+check_device(int sock, struct Interface *iface)
+{
+       struct ifreq    ifr;
+       
+       strncpy(ifr.ifr_name, iface->Name, IFNAMSIZ-1);
+       ifr.ifr_name[IFNAMSIZ-1] = '\0';
+
+       if (ioctl(sock, SIOCGIFFLAGS, &ifr) < 0)
+       {
+               if (!iface->IgnoreIfMissing)
+                       flog(LOG_ERR, "ioctl(SIOCGIFFLAGS) failed for %s: %s", 
+                               iface->Name, strerror(errno));
+               return (-1);
+       }
+
+       if (!(ifr.ifr_flags & IFF_UP))
+       {
+               if (!iface->IgnoreIfMissing)
+                       flog(LOG_ERR, "interface %s is not UP", iface->Name);
+               return (-1);
+       }
+       
+       if (! iface->UnicastOnly && !(ifr.ifr_flags & IFF_MULTICAST))
+       {
+               flog(LOG_WARNING, "interface %s does not support multicast",
+                       iface->Name);
+               flog(LOG_WARNING, "   do you need to add the UnicastOnly flag?");
+       }
+
+#if 0
+        /* SDH : ignore these warnings...  */
+       if (! iface->UnicastOnly && !(ifr.ifr_flags & IFF_BROADCAST))
+       {
+               flog(LOG_WARNING, "interface %s does not support broadcast",
+                       iface->Name);
+               flog(LOG_WARNING, "   do you need to add the UnicastOnly flag?");
+       }
+#endif
+
+       return 0;
+}
+
+int
+get_v4addr(const char *ifn, unsigned int *dst)
+{
+        struct ifreq    ifr;
+        struct sockaddr_in *addr;
+        int fd;
+
+        if( ( fd = socket(AF_INET,SOCK_DGRAM,0) ) < 0 )
+        {
+                flog(LOG_ERR, "create socket for IPv4 ioctl failed for %s: %s",
+                        ifn, strerror(errno));
+                return (-1);
+        }
+
+        memset(&ifr, 0, sizeof(ifr));
+        strncpy(ifr.ifr_name, ifn, IFNAMSIZ-1);
+        ifr.ifr_name[IFNAMSIZ-1] = '\0';
+        ifr.ifr_addr.sa_family = AF_INET;
+
+        if (ioctl(fd, SIOCGIFADDR, &ifr) < 0)
+        {
+                flog(LOG_ERR, "ioctl(SIOCGIFADDR) failed for %s: %s",
+                        ifn, strerror(errno));
+                close( fd );
+                return (-1);
+        }
+
+        addr = (struct sockaddr_in *)(&ifr.ifr_addr);
+
+        dlog(LOG_DEBUG, 3, "IPv4 address for %s is %s", ifn,
+                inet_ntoa( addr->sin_addr ) );
+
+        *dst = addr->sin_addr.s_addr;
+
+        close( fd );
+
+        return 0;
+}
diff --git a/support/sdk/c/blip/driver/radvd-1.0/device-linux.c b/support/sdk/c/blip/driver/radvd-1.0/device-linux.c
new file mode 100644 (file)
index 0000000..85579d3
--- /dev/null
@@ -0,0 +1,298 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+#include "defaults.h"
+#include "pathnames.h"         /* for PATH_PROC_NET_IF_INET6 */
+
+#ifndef IPV6_ADDR_LINKLOCAL
+#define IPV6_ADDR_LINKLOCAL   0x0020U
+#endif
+
+/*
+ * this function gets the hardware type and address of an interface,
+ * determines the link layer token length and checks it against
+ * the defined prefixes
+ */
+int
+setup_deviceinfo(int sock, struct Interface *iface)
+{
+       struct ifreq    ifr;
+       struct AdvPrefix *prefix;
+       char zero[sizeof(iface->if_addr)];
+       
+       strncpy(ifr.ifr_name, iface->Name, IFNAMSIZ-1);
+       ifr.ifr_name[IFNAMSIZ-1] = '\0';
+
+       if (ioctl(sock, SIOCGIFMTU, &ifr) < 0) {
+               flog(LOG_ERR, "ioctl(SIOCGIFMTU) failed for %s: %s",
+                       iface->Name, strerror(errno));
+               return (-1);
+       }
+
+       dlog(LOG_DEBUG, 3, "mtu for %s is %d", iface->Name, ifr.ifr_mtu);
+       iface->if_maxmtu = ifr.ifr_mtu;
+
+       if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0)
+       {
+               flog(LOG_ERR, "ioctl(SIOCGIFHWADDR) failed for %s: %s",
+                       iface->Name, strerror(errno));
+               return (-1);
+       }
+
+       dlog(LOG_DEBUG, 3, "hardware type for %s is %d", iface->Name,
+               ifr.ifr_hwaddr.sa_family); 
+
+       switch(ifr.ifr_hwaddr.sa_family)
+        {
+       case ARPHRD_ETHER:
+               iface->if_hwaddr_len = 48;
+               iface->if_prefix_len = 64;
+               break;
+#ifdef ARPHRD_FDDI
+       case ARPHRD_FDDI:
+               iface->if_hwaddr_len = 48;
+               iface->if_prefix_len = 64;
+               break;
+#endif /* ARPHDR_FDDI */
+#ifdef ARPHRD_ARCNET
+       case ARPHRD_ARCNET:
+               iface->if_hwaddr_len = 8;
+               iface->if_prefix_len = -1;
+               iface->if_maxmtu = -1;
+               break;
+#endif /* ARPHDR_ARCNET */
+       default:
+               iface->if_hwaddr_len = -1;
+               iface->if_prefix_len = -1;
+               iface->if_maxmtu = -1;
+               break;
+       }
+
+       dlog(LOG_DEBUG, 3, "link layer token length for %s is %d", iface->Name,
+               iface->if_hwaddr_len);
+
+       dlog(LOG_DEBUG, 3, "prefix length for %s is %d", iface->Name,
+               iface->if_prefix_len);
+
+       if (iface->if_hwaddr_len != -1) {
+               unsigned int if_hwaddr_len_bytes = (iface->if_hwaddr_len + 7) >> 3;
+               
+               if (if_hwaddr_len_bytes > sizeof(iface->if_hwaddr)) {
+                       flog(LOG_ERR, "address length %d too big for %s", if_hwaddr_len_bytes, iface->Name);
+                       return(-2);
+               }
+               memcpy(iface->if_hwaddr, ifr.ifr_hwaddr.sa_data, if_hwaddr_len_bytes);
+
+               memset(zero, 0, sizeof(zero));
+               if (!memcmp(iface->if_hwaddr, zero, if_hwaddr_len_bytes))
+                       flog(LOG_WARNING, "WARNING, MAC address on %s is all zero!",
+                               iface->Name);
+       }
+
+       prefix = iface->AdvPrefixList;
+       while (prefix)
+       {
+               if ((iface->if_prefix_len != -1) &&
+                  (iface->if_prefix_len != prefix->PrefixLen))
+               {
+                       flog(LOG_WARNING, "prefix length should be %d for %s",
+                               iface->if_prefix_len, iface->Name);
+               }
+                       
+               prefix = prefix->next;
+       }
+                
+       return (0);
+}
+
+/*
+ * this function extracts the link local address and interface index
+ * from PATH_PROC_NET_IF_INET6.  Note: 'sock' unused in Linux.
+ */
+int setup_linklocal_addr(int sock, struct Interface *iface)
+{
+       FILE *fp;
+       char str_addr[40];
+       unsigned int plen, scope, dad_status, if_idx;
+       char devname[IFNAMSIZ];
+
+       if ((fp = fopen(PATH_PROC_NET_IF_INET6, "r")) == NULL)
+       {
+               flog(LOG_ERR, "can't open %s: %s", PATH_PROC_NET_IF_INET6,
+                       strerror(errno));
+               return (-1);    
+       }
+       
+       while (fscanf(fp, "%32s %x %02x %02x %02x %15s\n",
+                     str_addr, &if_idx, &plen, &scope, &dad_status,
+                     devname) != EOF)
+       {
+               if (scope == IPV6_ADDR_LINKLOCAL &&
+                   strcmp(devname, iface->Name) == 0)
+               {
+                       struct in6_addr addr;
+                       unsigned int ap;
+                       int i;
+                       
+                       for (i=0; i<16; i++)
+                       {
+                               sscanf(str_addr + i * 2, "%02x", &ap);
+                               addr.s6_addr[i] = (unsigned char)ap;
+                       }
+                       memcpy(&iface->if_addr, &addr, sizeof(iface->if_addr));
+
+                       iface->if_index = if_idx;
+                       fclose(fp);
+                       return 0;
+               }
+       }
+
+       flog(LOG_ERR, "no linklocal address configured for %s", iface->Name);
+       fclose(fp);
+       return (-1);
+}
+
+int setup_allrouters_membership(int sock, struct Interface *iface)
+{
+       struct ipv6_mreq mreq;                  
+       
+       memset(&mreq, 0, sizeof(mreq));                  
+       mreq.ipv6mr_interface = iface->if_index;
+       
+       /* ipv6-allrouters: ff02::2 */
+       mreq.ipv6mr_multiaddr.s6_addr32[0] = htonl(0xFF020000);                                          
+       mreq.ipv6mr_multiaddr.s6_addr32[3] = htonl(0x2);     
+
+       if (setsockopt(sock, SOL_IPV6, IPV6_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
+       {
+               /* linux-2.6.12-bk4 returns error with HUP signal but keep listening */
+               if (errno != EADDRINUSE)
+               {
+                       flog(LOG_ERR, "can't join ipv6-allrouters on %s", iface->Name);
+                       return (-1);
+               }
+       }
+
+       return (0);
+}
+
+int check_allrouters_membership(int sock, struct Interface *iface)
+{
+       #define ALL_ROUTERS_MCAST "ff020000000000000000000000000002"
+       
+       FILE *fp;
+       unsigned int if_idx, allrouters_ok=0;
+       char addr[32+1];
+       int ret=0;
+
+       if ((fp = fopen(PATH_PROC_NET_IGMP6, "r")) == NULL)
+       {
+               flog(LOG_ERR, "can't open %s: %s", PATH_PROC_NET_IGMP6,
+                       strerror(errno));
+               return (-1);    
+       }
+       
+       while ( (ret=fscanf(fp, "%u %*s %32[0-9A-Fa-f] %*x %*x %*x\n", &if_idx, addr)) != EOF) {
+               if (ret == 2) {
+                       if (iface->if_index == if_idx) {
+                               if (strncmp(addr, ALL_ROUTERS_MCAST, sizeof(addr)) == 0)
+                                       allrouters_ok = 1;
+                       }
+               }
+       }
+
+       fclose(fp);
+
+       if (!allrouters_ok) {
+               flog(LOG_WARNING, "resetting ipv6-allrouters membership on %s", iface->Name);
+               setup_allrouters_membership(sock, iface);
+       }       
+
+       return(0);
+}              
+
+static int
+set_interface_var(const char *iface,
+                 const char *var, const char *name,
+                 uint32_t val)
+{
+       FILE *fp;
+       char spath[64+IFNAMSIZ];        /* XXX: magic constant */
+       snprintf(spath, sizeof(spath), var, iface);
+
+       fp = fopen(spath, "w");
+       if (!fp) {
+               if (name)
+                       flog(LOG_ERR, "failed to set %s (%u) for %s",
+                            name, val, iface);
+               return -1;
+       }
+       fprintf(fp, "%u", val);
+       fclose(fp);
+
+       return 0;
+}
+
+int
+set_interface_linkmtu(const char *iface, uint32_t mtu)
+{
+       return set_interface_var(iface,
+                                PROC_SYS_IP6_LINKMTU, "LinkMTU",
+                                mtu);
+}
+
+int
+set_interface_curhlim(const char *iface, uint8_t hlim)
+{
+       return set_interface_var(iface,
+                                PROC_SYS_IP6_CURHLIM, "CurHopLimit",
+                                hlim);
+}
+
+int
+set_interface_reachtime(const char *iface, uint32_t rtime)
+{
+       int ret;
+       ret = set_interface_var(iface,
+                               PROC_SYS_IP6_BASEREACHTIME_MS,
+                               NULL,
+                               rtime);
+       if (ret)
+               ret = set_interface_var(iface,
+                                       PROC_SYS_IP6_BASEREACHTIME,
+                                       "BaseReachableTimer",
+                                       rtime / 1000);
+       return ret;
+}
+
+int
+set_interface_retranstimer(const char *iface, uint32_t rettimer)
+{
+       int ret;
+       ret = set_interface_var(iface,
+                               PROC_SYS_IP6_RETRANSTIMER_MS,
+                               NULL,
+                               rettimer);
+       if (ret)
+               ret = set_interface_var(iface,
+                                       PROC_SYS_IP6_RETRANSTIMER,
+                                       "RetransTimer",
+                                       rettimer / 1000);
+       return ret;
+}
+
diff --git a/support/sdk/c/blip/driver/radvd-1.0/gram.c b/support/sdk/c/blip/driver/radvd-1.0/gram.c
new file mode 100644 (file)
index 0000000..6f7d6d4
--- /dev/null
@@ -0,0 +1,2390 @@
+/* A Bison parser, made by GNU Bison 2.3.  */
+
+/* Skeleton implementation for Bison's Yacc-like parsers in C
+
+   Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
+   Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin Street, Fifth Floor,
+   Boston, MA 02110-1301, USA.  */
+
+/* As a special exception, you may create a larger work that contains
+   part or all of the Bison parser skeleton and distribute that work
+   under terms of your choice, so long as that work isn't itself a
+   parser generator using the skeleton or a modified version thereof
+   as a parser skeleton.  Alternatively, if you modify or redistribute
+   the parser skeleton itself, you may (at your option) remove this
+   special exception, which will cause the skeleton and the resulting
+   Bison output files to be licensed under the GNU General Public
+   License without this special exception.
+
+   This special exception was added by the Free Software Foundation in
+   version 2.2 of Bison.  */
+
+/* C LALR(1) parser skeleton written by Richard Stallman, by
+   simplifying the original so-called "semantic" parser.  */
+
+/* All symbols defined below should begin with yy or YY, to avoid
+   infringing on user name space.  This should be done even for local
+   variables, as they might otherwise be expanded by user macros.
+   There are some unavoidable exceptions within include files to
+   define necessary library symbols; they are noted "INFRINGES ON
+   USER NAME SPACE" below.  */
+
+/* Identify Bison output.  */
+#define YYBISON 1
+
+/* Bison version.  */
+#define YYBISON_VERSION "2.3"
+
+/* Skeleton name.  */
+#define YYSKELETON_NAME "yacc.c"
+
+/* Pure parsers.  */
+#define YYPURE 0
+
+/* Using locations.  */
+#define YYLSP_NEEDED 0
+
+
+
+/* Tokens.  */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+   /* Put the tokens into the symbol table, so that GDB and other debuggers
+      know about them.  */
+   enum yytokentype {
+     T_INTERFACE = 258,
+     T_PREFIX = 259,
+     T_ROUTE = 260,
+     T_RDNSS = 261,
+     STRING = 262,
+     NUMBER = 263,
+     SIGNEDNUMBER = 264,
+     DECIMAL = 265,
+     SWITCH = 266,
+     IPV6ADDR = 267,
+     INFINITY = 268,
+     T_IgnoreIfMissing = 269,
+     T_AdvSendAdvert = 270,
+     T_MaxRtrAdvInterval = 271,
+     T_MinRtrAdvInterval = 272,
+     T_MinDelayBetweenRAs = 273,
+     T_AdvManagedFlag = 274,
+     T_AdvOtherConfigFlag = 275,
+     T_AdvLinkMTU = 276,
+     T_AdvReachableTime = 277,
+     T_AdvRetransTimer = 278,
+     T_AdvCurHopLimit = 279,
+     T_AdvDefaultLifetime = 280,
+     T_AdvDefaultPreference = 281,
+     T_AdvSourceLLAddress = 282,
+     T_AdvOnLink = 283,
+     T_AdvAutonomous = 284,
+     T_AdvValidLifetime = 285,
+     T_AdvPreferredLifetime = 286,
+     T_AdvRouterAddr = 287,
+     T_AdvHomeAgentFlag = 288,
+     T_AdvIntervalOpt = 289,
+     T_AdvHomeAgentInfo = 290,
+     T_Base6to4Interface = 291,
+     T_UnicastOnly = 292,
+     T_HomeAgentPreference = 293,
+     T_HomeAgentLifetime = 294,
+     T_AdvRoutePreference = 295,
+     T_AdvRouteLifetime = 296,
+     T_AdvRDNSSPreference = 297,
+     T_AdvRDNSSOpenFlag = 298,
+     T_AdvRDNSSLifetime = 299,
+     T_AdvMobRtrSupportFlag = 300,
+     T_BAD_TOKEN = 301
+   };
+#endif
+/* Tokens.  */
+#define T_INTERFACE 258
+#define T_PREFIX 259
+#define T_ROUTE 260
+#define T_RDNSS 261
+#define STRING 262
+#define NUMBER 263
+#define SIGNEDNUMBER 264
+#define DECIMAL 265
+#define SWITCH 266
+#define IPV6ADDR 267
+#define INFINITY 268
+#define T_IgnoreIfMissing 269
+#define T_AdvSendAdvert 270
+#define T_MaxRtrAdvInterval 271
+#define T_MinRtrAdvInterval 272
+#define T_MinDelayBetweenRAs 273
+#define T_AdvManagedFlag 274
+#define T_AdvOtherConfigFlag 275
+#define T_AdvLinkMTU 276
+#define T_AdvReachableTime 277
+#define T_AdvRetransTimer 278
+#define T_AdvCurHopLimit 279
+#define T_AdvDefaultLifetime 280
+#define T_AdvDefaultPreference 281
+#define T_AdvSourceLLAddress 282
+#define T_AdvOnLink 283
+#define T_AdvAutonomous 284
+#define T_AdvValidLifetime 285
+#define T_AdvPreferredLifetime 286
+#define T_AdvRouterAddr 287
+#define T_AdvHomeAgentFlag 288
+#define T_AdvIntervalOpt 289
+#define T_AdvHomeAgentInfo 290
+#define T_Base6to4Interface 291
+#define T_UnicastOnly 292
+#define T_HomeAgentPreference 293
+#define T_HomeAgentLifetime 294
+#define T_AdvRoutePreference 295
+#define T_AdvRouteLifetime 296
+#define T_AdvRDNSSPreference 297
+#define T_AdvRDNSSOpenFlag 298
+#define T_AdvRDNSSLifetime 299
+#define T_AdvMobRtrSupportFlag 300
+#define T_BAD_TOKEN 301
+
+
+
+
+/* Copy the first part of user declarations.  */
+#line 16 "gram.y"
+
+#include <config.h>
+#include <includes.h>
+#include <radvd.h>
+#include <defaults.h>
+
+extern struct Interface *IfaceList;
+struct Interface *iface = NULL;
+struct AdvPrefix *prefix = NULL;
+struct AdvRoute *route = NULL;
+struct AdvRDNSS *rdnss = NULL;
+
+extern char *conf_file;
+extern int num_lines;
+extern char *yytext;
+extern int sock;
+
+static void cleanup(void);
+static void yyerror(char *msg);
+
+#if 0 /* no longer necessary? */
+#ifndef HAVE_IN6_ADDR_S6_ADDR
+# ifdef __FreeBSD__
+#  define s6_addr32 __u6_addr.__u6_addr32
+#  define s6_addr16 __u6_addr.__u6_addr16
+# endif
+#endif
+#endif
+
+#define ABORT  do { cleanup(); YYABORT; } while (0);
+
+
+
+/* Enabling traces.  */
+#ifndef YYDEBUG
+# define YYDEBUG 0
+#endif
+
+/* Enabling verbose error messages.  */
+#ifdef YYERROR_VERBOSE
+# undef YYERROR_VERBOSE
+# define YYERROR_VERBOSE 1
+#else
+# define YYERROR_VERBOSE 0
+#endif
+
+/* Enabling the token table.  */
+#ifndef YYTOKEN_TABLE
+# define YYTOKEN_TABLE 0
+#endif
+
+#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
+typedef union YYSTYPE
+#line 110 "gram.y"
+{
+       unsigned int            num;
+       int                     snum;
+       double                  dec;
+       int                     bool;
+       struct in6_addr         *addr;
+       char                    *str;
+       struct AdvPrefix        *pinfo;
+       struct AdvRoute         *rinfo;
+       struct AdvRDNSS         *rdnssinfo;
+}
+/* Line 187 of yacc.c.  */
+#line 233 "gram.c"
+       YYSTYPE;
+# define yystype YYSTYPE /* obsolescent; will be withdrawn */
+# define YYSTYPE_IS_DECLARED 1
+# define YYSTYPE_IS_TRIVIAL 1
+#endif
+
+
+
+/* Copy the second part of user declarations.  */
+
+
+/* Line 216 of yacc.c.  */
+#line 246 "gram.c"
+
+#ifdef short
+# undef short
+#endif
+
+#ifdef YYTYPE_UINT8
+typedef YYTYPE_UINT8 yytype_uint8;
+#else
+typedef unsigned char yytype_uint8;
+#endif
+
+#ifdef YYTYPE_INT8
+typedef YYTYPE_INT8 yytype_int8;
+#elif (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+typedef signed char yytype_int8;
+#else
+typedef short int yytype_int8;
+#endif
+
+#ifdef YYTYPE_UINT16
+typedef YYTYPE_UINT16 yytype_uint16;
+#else
+typedef unsigned short int yytype_uint16;
+#endif
+
+#ifdef YYTYPE_INT16
+typedef YYTYPE_INT16 yytype_int16;
+#else
+typedef short int yytype_int16;
+#endif
+
+#ifndef YYSIZE_T
+# ifdef __SIZE_TYPE__
+#  define YYSIZE_T __SIZE_TYPE__
+# elif defined size_t
+#  define YYSIZE_T size_t
+# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+#  include <stddef.h> /* INFRINGES ON USER NAME SPACE */
+#  define YYSIZE_T size_t
+# else
+#  define YYSIZE_T unsigned int
+# endif
+#endif
+
+#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
+
+#ifndef YY_
+# if YYENABLE_NLS
+#  if ENABLE_NLS
+#   include <libintl.h> /* INFRINGES ON USER NAME SPACE */
+#   define YY_(msgid) dgettext ("bison-runtime", msgid)
+#  endif
+# endif
+# ifndef YY_
+#  define YY_(msgid) msgid
+# endif
+#endif
+
+/* Suppress unused-variable warnings by "using" E.  */
+#if ! defined lint || defined __GNUC__
+# define YYUSE(e) ((void) (e))
+#else
+# define YYUSE(e) /* empty */
+#endif
+
+/* Identity function, used to suppress warnings about constant conditions.  */
+#ifndef lint
+# define YYID(n) (n)
+#else
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static int
+YYID (int i)
+#else
+static int
+YYID (i)
+    int i;
+#endif
+{
+  return i;
+}
+#endif
+
+#if ! defined yyoverflow || YYERROR_VERBOSE
+
+/* The parser invokes alloca or malloc; define the necessary symbols.  */
+
+# ifdef YYSTACK_USE_ALLOCA
+#  if YYSTACK_USE_ALLOCA
+#   ifdef __GNUC__
+#    define YYSTACK_ALLOC __builtin_alloca
+#   elif defined __BUILTIN_VA_ARG_INCR
+#    include <alloca.h> /* INFRINGES ON USER NAME SPACE */
+#   elif defined _AIX
+#    define YYSTACK_ALLOC __alloca
+#   elif defined _MSC_VER
+#    include <malloc.h> /* INFRINGES ON USER NAME SPACE */
+#    define alloca _alloca
+#   else
+#    define YYSTACK_ALLOC alloca
+#    if ! defined _ALLOCA_H && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+#     include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+#     ifndef _STDLIB_H
+#      define _STDLIB_H 1
+#     endif
+#    endif
+#   endif
+#  endif
+# endif
+
+# ifdef YYSTACK_ALLOC
+   /* Pacify GCC's `empty if-body' warning.  */
+#  define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
+#  ifndef YYSTACK_ALLOC_MAXIMUM
+    /* The OS might guarantee only one guard page at the bottom of the stack,
+       and a page size can be as small as 4096 bytes.  So we cannot safely
+       invoke alloca (N) if N exceeds 4096.  Use a slightly smaller number
+       to allow for a few compiler-allocated temporary stack slots.  */
+#   define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
+#  endif
+# else
+#  define YYSTACK_ALLOC YYMALLOC
+#  define YYSTACK_FREE YYFREE
+#  ifndef YYSTACK_ALLOC_MAXIMUM
+#   define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
+#  endif
+#  if (defined __cplusplus && ! defined _STDLIB_H \
+       && ! ((defined YYMALLOC || defined malloc) \
+            && (defined YYFREE || defined free)))
+#   include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
+#   ifndef _STDLIB_H
+#    define _STDLIB_H 1
+#   endif
+#  endif
+#  ifndef YYMALLOC
+#   define YYMALLOC malloc
+#   if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
+#   endif
+#  endif
+#  ifndef YYFREE
+#   define YYFREE free
+#   if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+void free (void *); /* INFRINGES ON USER NAME SPACE */
+#   endif
+#  endif
+# endif
+#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
+
+
+#if (! defined yyoverflow \
+     && (! defined __cplusplus \
+        || (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
+
+/* A type that is properly aligned for any stack member.  */
+union yyalloc
+{
+  yytype_int16 yyss;
+  YYSTYPE yyvs;
+  };
+
+/* The size of the maximum gap between one aligned stack and the next.  */
+# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
+
+/* The size of an array large to enough to hold all stacks, each with
+   N elements.  */
+# define YYSTACK_BYTES(N) \
+     ((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+      + YYSTACK_GAP_MAXIMUM)
+
+/* Copy COUNT objects from FROM to TO.  The source and destination do
+   not overlap.  */
+# ifndef YYCOPY
+#  if defined __GNUC__ && 1 < __GNUC__
+#   define YYCOPY(To, From, Count) \
+      __builtin_memcpy (To, From, (Count) * sizeof (*(From)))
+#  else
+#   define YYCOPY(To, From, Count)             \
+      do                                       \
+       {                                       \
+         YYSIZE_T yyi;                         \
+         for (yyi = 0; yyi < (Count); yyi++)   \
+           (To)[yyi] = (From)[yyi];            \
+       }                                       \
+      while (YYID (0))
+#  endif
+# endif
+
+/* Relocate STACK from its old location to the new one.  The
+   local variables YYSIZE and YYSTACKSIZE give the old and new number of
+   elements in the stack, and YYPTR gives the new location of the
+   stack.  Advance YYPTR to a properly aligned location for the next
+   stack.  */
+# define YYSTACK_RELOCATE(Stack)                                       \
+    do                                                                 \
+      {                                                                        \
+       YYSIZE_T yynewbytes;                                            \
+       YYCOPY (&yyptr->Stack, Stack, yysize);                          \
+       Stack = &yyptr->Stack;                                          \
+       yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
+       yyptr += yynewbytes / sizeof (*yyptr);                          \
+      }                                                                        \
+    while (YYID (0))
+
+#endif
+
+/* YYFINAL -- State number of the termination state.  */
+#define YYFINAL  7
+/* YYLAST -- Last index in YYTABLE.  */
+#define YYLAST   151
+
+/* YYNTOKENS -- Number of terminals.  */
+#define YYNTOKENS  51
+/* YYNNTS -- Number of nonterminals.  */
+#define YYNNTS  33
+/* YYNRULES -- Number of rules.  */
+#define YYNRULES  81
+/* YYNRULES -- Number of states.  */
+#define YYNSTATES  170
+
+/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX.  */
+#define YYUNDEFTOK  2
+#define YYMAXUTOK   301
+
+#define YYTRANSLATE(YYX)                                               \
+  ((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
+
+/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX.  */
+static const yytype_uint8 yytranslate[] =
+{
+       0,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,    50,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,    49,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,    47,     2,    48,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     2,     2,     2,     2,
+       2,     2,     2,     2,     2,     2,     1,     2,     3,     4,
+       5,     6,     7,     8,     9,    10,    11,    12,    13,    14,
+      15,    16,    17,    18,    19,    20,    21,    22,    23,    24,
+      25,    26,    27,    28,    29,    30,    31,    32,    33,    34,
+      35,    36,    37,    38,    39,    40,    41,    42,    43,    44,
+      45,    46
+};
+
+#if YYDEBUG
+/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
+   YYRHS.  */
+static const yytype_uint16 yyprhs[] =
+{
+       0,     0,     3,     6,     8,    14,    17,    19,    24,    25,
+      27,    28,    30,    31,    33,    34,    36,    39,    41,    45,
+      49,    53,    57,    61,    65,    69,    73,    77,    81,    85,
+      89,    93,    97,   101,   105,   109,   113,   117,   121,   125,
+     129,   133,   137,   139,   142,   148,   153,   154,   156,   159,
+     161,   165,   169,   173,   177,   181,   185,   187,   190,   196,
+     201,   202,   204,   207,   209,   213,   217,   219,   222,   228,
+     231,   233,   235,   238,   239,   241,   244,   246,   250,   254,
+     258,   260
+};
+
+/* YYRHS -- A `-1'-separated list of the rules' RHS.  */
+static const yytype_int8 yyrhs[] =
+{
+      52,     0,    -1,    52,    53,    -1,    53,    -1,    54,    47,
+      56,    48,    49,    -1,     3,    55,    -1,     7,    -1,    57,
+      58,    59,    60,    -1,    -1,    61,    -1,    -1,    63,    -1,
+      -1,    69,    -1,    -1,    75,    -1,    61,    62,    -1,    62,
+      -1,    17,     8,    49,    -1,    16,     8,    49,    -1,    18,
+       8,    49,    -1,    17,    10,    49,    -1,    16,    10,    49,
+      -1,    18,    10,    49,    -1,    14,    11,    49,    -1,    15,
+      11,    49,    -1,    19,    11,    49,    -1,    20,    11,    49,
+      -1,    21,     8,    49,    -1,    22,     8,    49,    -1,    23,
+       8,    49,    -1,    25,     8,    49,    -1,    26,     9,    49,
+      -1,    24,     8,    49,    -1,    27,    11,    49,    -1,    34,
+      11,    49,    -1,    35,    11,    49,    -1,    33,    11,    49,
+      -1,    38,     8,    49,    -1,    39,     8,    49,    -1,    37,
+      11,    49,    -1,    45,    11,    49,    -1,    64,    -1,    63,
+      64,    -1,    65,    47,    66,    48,    49,    -1,     4,    12,
+      50,     8,    -1,    -1,    67,    -1,    67,    68,    -1,    68,
+      -1,    28,    11,    49,    -1,    29,    11,    49,    -1,    32,
+      11,    49,    -1,    30,    83,    49,    -1,    31,    83,    49,
+      -1,    36,    55,    49,    -1,    70,    -1,    69,    70,    -1,
+      71,    47,    72,    48,    49,    -1,     5,    12,    50,     8,
+      -1,    -1,    73,    -1,    73,    74,    -1,    74,    -1,    40,
+       9,    49,    -1,    41,    83,    49,    -1,    76,    -1,    75,
+      76,    -1,    79,    47,    80,    48,    49,    -1,    77,    78,
+      -1,    78,    -1,    12,    -1,     6,    77,    -1,    -1,    81,
+      -1,    81,    82,    -1,    82,    -1,    42,     8,    49,    -1,
+      43,    11,    49,    -1,    44,    83,    49,    -1,     8,    -1,
+      13,    -1
+};
+
+/* YYRLINE[YYN] -- source line where rule number YYN was defined.  */
+static const yytype_uint16 yyrline[] =
+{
+       0,   124,   124,   125,   128,   172,   187,   194,   202,   203,
+     207,   210,   214,   217,   221,   224,   227,   228,   231,   235,
+     239,   243,   247,   251,   255,   259,   263,   267,   271,   275,
+     279,   283,   287,   291,   295,   299,   303,   307,   311,   315,
+     319,   323,   329,   333,   340,   371,   394,   395,   398,   399,
+     402,   406,   410,   414,   418,   422,   430,   434,   441,   449,
+     473,   474,   477,   478,   482,   486,   492,   496,   503,   510,
+     511,   514,   549,   558,   559,   562,   563,   567,   571,   575,
+     588,   592
+};
+#endif
+
+#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
+/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
+   First, the terminals, then, starting at YYNTOKENS, nonterminals.  */
+static const char *const yytname[] =
+{
+  "$end", "error", "$undefined", "T_INTERFACE", "T_PREFIX", "T_ROUTE",
+  "T_RDNSS", "STRING", "NUMBER", "SIGNEDNUMBER", "DECIMAL", "SWITCH",
+  "IPV6ADDR", "INFINITY", "T_IgnoreIfMissing", "T_AdvSendAdvert",
+  "T_MaxRtrAdvInterval", "T_MinRtrAdvInterval", "T_MinDelayBetweenRAs",
+  "T_AdvManagedFlag", "T_AdvOtherConfigFlag", "T_AdvLinkMTU",
+  "T_AdvReachableTime", "T_AdvRetransTimer", "T_AdvCurHopLimit",
+  "T_AdvDefaultLifetime", "T_AdvDefaultPreference", "T_AdvSourceLLAddress",
+  "T_AdvOnLink", "T_AdvAutonomous", "T_AdvValidLifetime",
+  "T_AdvPreferredLifetime", "T_AdvRouterAddr", "T_AdvHomeAgentFlag",
+  "T_AdvIntervalOpt", "T_AdvHomeAgentInfo", "T_Base6to4Interface",
+  "T_UnicastOnly", "T_HomeAgentPreference", "T_HomeAgentLifetime",
+  "T_AdvRoutePreference", "T_AdvRouteLifetime", "T_AdvRDNSSPreference",
+  "T_AdvRDNSSOpenFlag", "T_AdvRDNSSLifetime", "T_AdvMobRtrSupportFlag",
+  "T_BAD_TOKEN", "'{'", "'}'", "';'", "'/'", "$accept", "grammar",
+  "ifacedef", "ifacehead", "name", "ifaceparams", "optional_ifacevlist",
+  "optional_prefixlist", "optional_routelist", "optional_rdnsslist",
+  "ifacevlist", "ifaceval", "prefixlist", "prefixdef", "prefixhead",
+  "optional_prefixplist", "prefixplist", "prefixparms", "routelist",
+  "routedef", "routehead", "optional_routeplist", "routeplist",
+  "routeparms", "rdnsslist", "rdnssdef", "rdnssaddrs", "rdnssaddr",
+  "rdnsshead", "optional_rdnssplist", "rdnssplist", "rdnssparms",
+  "number_or_infinity", 0
+};
+#endif
+
+# ifdef YYPRINT
+/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
+   token YYLEX-NUM.  */
+static const yytype_uint16 yytoknum[] =
+{
+       0,   256,   257,   258,   259,   260,   261,   262,   263,   264,
+     265,   266,   267,   268,   269,   270,   271,   272,   273,   274,
+     275,   276,   277,   278,   279,   280,   281,   282,   283,   284,
+     285,   286,   287,   288,   289,   290,   291,   292,   293,   294,
+     295,   296,   297,   298,   299,   300,   301,   123,   125,    59,
+      47
+};
+# endif
+
+/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives.  */
+static const yytype_uint8 yyr1[] =
+{
+       0,    51,    52,    52,    53,    54,    55,    56,    57,    57,
+      58,    58,    59,    59,    60,    60,    61,    61,    62,    62,
+      62,    62,    62,    62,    62,    62,    62,    62,    62,    62,
+      62,    62,    62,    62,    62,    62,    62,    62,    62,    62,
+      62,    62,    63,    63,    64,    65,    66,    66,    67,    67,
+      68,    68,    68,    68,    68,    68,    69,    69,    70,    71,
+      72,    72,    73,    73,    74,    74,    75,    75,    76,    77,
+      77,    78,    79,    80,    80,    81,    81,    82,    82,    82,
+      83,    83
+};
+
+/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN.  */
+static const yytype_uint8 yyr2[] =
+{
+       0,     2,     2,     1,     5,     2,     1,     4,     0,     1,
+       0,     1,     0,     1,     0,     1,     2,     1,     3,     3,
+       3,     3,     3,     3,     3,     3,     3,     3,     3,     3,
+       3,     3,     3,     3,     3,     3,     3,     3,     3,     3,
+       3,     3,     1,     2,     5,     4,     0,     1,     2,     1,
+       3,     3,     3,     3,     3,     3,     1,     2,     5,     4,
+       0,     1,     2,     1,     3,     3,     1,     2,     5,     2,
+       1,     1,     2,     0,     1,     2,     1,     3,     3,     3,
+       1,     1
+};
+
+/* YYDEFACT[STATE-NAME] -- Default rule to reduce with in state
+   STATE-NUM when YYTABLE doesn't specify something else to do.  Zero
+   means the default is an error.  */
+static const yytype_uint8 yydefact[] =
+{
+       0,     0,     0,     3,     0,     6,     5,     1,     2,     8,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,    10,     9,    17,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,     0,     0,     0,     0,     0,     0,     0,     0,     0,
+       0,    12,    11,    42,     0,    16,    24,    25,    19,    22,
+      18,    21,    20,    23,    26,    27,    28,    29,    30,    33,
+      31,    32,    34,    37,    35,    36,    40,    38,    39,    41,
+       4,     0,     0,    14,    13,    56,     0,    43,    46,     0,
+       0,     0,     7,    15,    66,     0,    57,    60,     0,     0,
+       0,     0,     0,     0,     0,    47,    49,    45,     0,    71,
+      72,    70,    67,    73,     0,     0,     0,    61,    63,     0,
+       0,    80,    81,     0,     0,     0,     0,     0,    48,    59,
+      69,     0,     0,     0,     0,    74,    76,     0,     0,     0,
+      62,    50,    51,    53,    54,    52,    55,    44,     0,     0,
+       0,     0,    75,    64,    65,    58,    77,    78,    79,    68
+};
+
+/* YYDEFGOTO[NTERM-NUM].  */
+static const yytype_int16 yydefgoto[] =
+{
+      -1,     2,     3,     4,     6,    31,    32,    61,    93,   102,
+      33,    34,    62,    63,    64,   114,   115,   116,    94,    95,
+      96,   126,   127,   128,   103,   104,   120,   121,   105,   144,
+     145,   146,   133
+};
+
+/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
+   STATE-NUM.  */
+#define YYPACT_NINF -112
+static const yytype_int8 yypact[] =
+{
+       5,    26,     7,  -112,   -10,  -112,  -112,  -112,  -112,     1,
+      38,    39,    33,    34,    37,    40,    41,    45,    46,    47,
+      48,    49,    50,    51,    52,    53,    54,    55,    59,    60,
+      58,     0,    56,     1,  -112,     9,    12,    21,    22,    23,
+      24,    25,    27,    28,    29,    30,    31,    32,    35,    36,
+      42,    43,    44,    57,    61,    62,    63,    64,    65,    66,
+      70,    78,    56,  -112,    69,  -112,  -112,  -112,  -112,  -112,
+    -112,  -112,  -112,  -112,  -112,  -112,  -112,  -112,  -112,  -112,
+    -112,  -112,  -112,  -112,  -112,  -112,  -112,  -112,  -112,  -112,
+    -112,    67,    74,    81,    78,  -112,    71,  -112,   -27,    80,
+      72,    77,  -112,    81,  -112,    73,  -112,   -28,    79,    83,
+      -2,    -2,    84,    26,    75,   -27,  -112,  -112,    88,  -112,
+      77,  -112,  -112,   -13,    89,    -2,    76,   -28,  -112,    82,
+      85,  -112,  -112,    86,    87,    90,    91,    92,  -112,  -112,
+    -112,    93,    94,    -2,    95,   -13,  -112,    96,    97,    98,
+    -112,  -112,  -112,  -112,  -112,  -112,  -112,  -112,    99,   100,
+     101,   102,  -112,  -112,  -112,  -112,  -112,  -112,  -112,  -112
+};
+
+/* YYPGOTO[NTERM-NUM].  */
+static const yytype_int8 yypgoto[] =
+{
+    -112,  -112,   105,  -112,   -38,  -112,  -112,  -112,  -112,  -112,
+    -112,   104,  -112,    68,  -112,  -112,  -112,   -18,  -112,     6,
+    -112,  -112,  -112,   -25,  -112,    -4,  -112,   -17,  -112,  -112,
+    -112,   -41,  -111
+};
+
+/* YYTABLE[YYPACT[STATE-NUM]].  What to do in state STATE-NUM.  If
+   positive, shift that token.  If negative, reduce the rule which
+   number is the opposite.  If zero, do what YYDEFACT says.
+   If YYTABLE_NINF, syntax error.  */
+#define YYTABLE_NINF -1
+static const yytype_uint8 yytable[] =
+{
+     134,   108,   109,   110,   111,   112,   131,     7,     1,   113,
+       1,   132,   124,   125,   148,    10,    11,    12,    13,    14,
+      15,    16,    17,    18,    19,    20,    21,    22,    23,   141,
+     142,   143,   160,     5,    24,    25,    26,     9,    27,    28,
+      29,    37,    39,    38,    40,    41,    30,    42,    59,    35,
+      36,    43,    44,    45,    46,    47,    48,    49,    66,    50,
+      60,    67,    51,    52,    53,    54,    55,    56,    57,    58,
+      68,    69,    70,    71,    72,   136,    73,    74,    75,    76,
+      77,    78,    91,    92,    79,    80,   100,   101,   117,   119,
+     129,    81,    82,    83,   130,   135,   139,   138,   147,   122,
+     106,   158,   150,   140,   162,   159,    84,     8,     0,     0,
+      85,    86,    87,    88,    89,    90,    98,    99,   107,     0,
+     123,     0,   118,   137,   149,     0,     0,     0,     0,     0,
+      97,   151,     0,     0,   152,   153,   154,    65,     0,   155,
+     156,   157,     0,   161,     0,   163,   164,   165,   166,   167,
+     168,   169
+};
+
+static const yytype_int16 yycheck[] =
+{
+     111,    28,    29,    30,    31,    32,     8,     0,     3,    36,
+       3,    13,    40,    41,   125,    14,    15,    16,    17,    18,
+      19,    20,    21,    22,    23,    24,    25,    26,    27,    42,
+      43,    44,   143,     7,    33,    34,    35,    47,    37,    38,
+      39,     8,     8,    10,    10,     8,    45,    10,    48,    11,
+      11,    11,    11,     8,     8,     8,     8,     8,    49,     9,
+       4,    49,    11,    11,    11,    11,    11,     8,     8,    11,
+      49,    49,    49,    49,    49,   113,    49,    49,    49,    49,
+      49,    49,    12,     5,    49,    49,    12,     6,     8,    12,
+      11,    49,    49,    49,    11,    11,     8,   115,     9,   103,
+      94,     8,   127,   120,   145,    11,    49,     2,    -1,    -1,
+      49,    49,    49,    49,    49,    49,    47,    50,    47,    -1,
+      47,    -1,    50,    48,    48,    -1,    -1,    -1,    -1,    -1,
+      62,    49,    -1,    -1,    49,    49,    49,    33,    -1,    49,
+      49,    49,    -1,    48,    -1,    49,    49,    49,    49,    49,
+      49,    49
+};
+
+/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
+   symbol of state STATE-NUM.  */
+static const yytype_uint8 yystos[] =
+{
+       0,     3,    52,    53,    54,     7,    55,     0,    53,    47,
+      14,    15,    16,    17,    18,    19,    20,    21,    22,    23,
+      24,    25,    26,    27,    33,    34,    35,    37,    38,    39,
+      45,    56,    57,    61,    62,    11,    11,     8,    10,     8,
+      10,     8,    10,    11,    11,     8,     8,     8,     8,     8,
+       9,    11,    11,    11,    11,    11,     8,     8,    11,    48,
+       4,    58,    63,    64,    65,    62,    49,    49,    49,    49,
+      49,    49,    49,    49,    49,    49,    49,    49,    49,    49,
+      49,    49,    49,    49,    49,    49,    49,    49,    49,    49,
+      49,    12,     5,    59,    69,    70,    71,    64,    47,    50,
+      12,     6,    60,    75,    76,    79,    70,    47,    28,    29,
+      30,    31,    32,    36,    66,    67,    68,     8,    50,    12,
+      77,    78,    76,    47,    40,    41,    72,    73,    74,    11,
+      11,     8,    13,    83,    83,    11,    55,    48,    68,     8,
+      78,    42,    43,    44,    80,    81,    82,     9,    83,    48,
+      74,    49,    49,    49,    49,    49,    49,    49,     8,    11,
+      83,    48,    82,    49,    49,    49,    49,    49,    49,    49
+};
+
+#define yyerrok                (yyerrstatus = 0)
+#define yyclearin      (yychar = YYEMPTY)
+#define YYEMPTY                (-2)
+#define YYEOF          0
+
+#define YYACCEPT       goto yyacceptlab
+#define YYABORT                goto yyabortlab
+#define YYERROR                goto yyerrorlab
+
+
+/* Like YYERROR except do call yyerror.  This remains here temporarily
+   to ease the transition to the new meaning of YYERROR, for GCC.
+   Once GCC version 2 has supplanted version 1, this can go.  */
+
+#define YYFAIL         goto yyerrlab
+
+#define YYRECOVERING()  (!!yyerrstatus)
+
+#define YYBACKUP(Token, Value)                                 \
+do                                                             \
+  if (yychar == YYEMPTY && yylen == 1)                         \
+    {                                                          \
+      yychar = (Token);                                                \
+      yylval = (Value);                                                \
+      yytoken = YYTRANSLATE (yychar);                          \
+      YYPOPSTACK (1);                                          \
+      goto yybackup;                                           \
+    }                                                          \
+  else                                                         \
+    {                                                          \
+      yyerror (YY_("syntax error: cannot back up")); \
+      YYERROR;                                                 \
+    }                                                          \
+while (YYID (0))
+
+
+#define YYTERROR       1
+#define YYERRCODE      256
+
+
+/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
+   If N is 0, then set CURRENT to the empty location which ends
+   the previous symbol: RHS[0] (always defined).  */
+
+#define YYRHSLOC(Rhs, K) ((Rhs)[K])
+#ifndef YYLLOC_DEFAULT
+# define YYLLOC_DEFAULT(Current, Rhs, N)                               \
+    do                                                                 \
+      if (YYID (N))                                                    \
+       {                                                               \
+         (Current).first_line   = YYRHSLOC (Rhs, 1).first_line;        \
+         (Current).first_column = YYRHSLOC (Rhs, 1).first_column;      \
+         (Current).last_line    = YYRHSLOC (Rhs, N).last_line;         \
+         (Current).last_column  = YYRHSLOC (Rhs, N).last_column;       \
+       }                                                               \
+      else                                                             \
+       {                                                               \
+         (Current).first_line   = (Current).last_line   =              \
+           YYRHSLOC (Rhs, 0).last_line;                                \
+         (Current).first_column = (Current).last_column =              \
+           YYRHSLOC (Rhs, 0).last_column;                              \
+       }                                                               \
+    while (YYID (0))
+#endif
+
+
+/* YY_LOCATION_PRINT -- Print the location on the stream.
+   This macro was not mandated originally: define only if we know
+   we won't break user code: when these are the locations we know.  */
+
+#ifndef YY_LOCATION_PRINT
+# if YYLTYPE_IS_TRIVIAL
+#  define YY_LOCATION_PRINT(File, Loc)                 \
+     fprintf (File, "%d.%d-%d.%d",                     \
+             (Loc).first_line, (Loc).first_column,     \
+             (Loc).last_line,  (Loc).last_column)
+# else
+#  define YY_LOCATION_PRINT(File, Loc) ((void) 0)
+# endif
+#endif
+
+
+/* YYLEX -- calling `yylex' with the right arguments.  */
+
+#ifdef YYLEX_PARAM
+# define YYLEX yylex (YYLEX_PARAM)
+#else
+# define YYLEX yylex ()
+#endif
+
+/* Enable debugging if requested.  */
+#if YYDEBUG
+
+# ifndef YYFPRINTF
+#  include <stdio.h> /* INFRINGES ON USER NAME SPACE */
+#  define YYFPRINTF fprintf
+# endif
+
+# define YYDPRINTF(Args)                       \
+do {                                           \
+  if (yydebug)                                 \
+    YYFPRINTF Args;                            \
+} while (YYID (0))
+
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)                   \
+do {                                                                     \
+  if (yydebug)                                                           \
+    {                                                                    \
+      YYFPRINTF (stderr, "%s ", Title);                                          \
+      yy_symbol_print (stderr,                                           \
+                 Type, Value); \
+      YYFPRINTF (stderr, "\n");                                                  \
+    }                                                                    \
+} while (YYID (0))
+
+
+/*--------------------------------.
+| Print this symbol on YYOUTPUT.  |
+`--------------------------------*/
+
+/*ARGSUSED*/
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
+#else
+static void
+yy_symbol_value_print (yyoutput, yytype, yyvaluep)
+    FILE *yyoutput;
+    int yytype;
+    YYSTYPE const * const yyvaluep;
+#endif
+{
+  if (!yyvaluep)
+    return;
+# ifdef YYPRINT
+  if (yytype < YYNTOKENS)
+    YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
+# else
+  YYUSE (yyoutput);
+# endif
+  switch (yytype)
+    {
+      default:
+       break;
+    }
+}
+
+
+/*--------------------------------.
+| Print this symbol on YYOUTPUT.  |
+`--------------------------------*/
+
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep)
+#else
+static void
+yy_symbol_print (yyoutput, yytype, yyvaluep)
+    FILE *yyoutput;
+    int yytype;
+    YYSTYPE const * const yyvaluep;
+#endif
+{
+  if (yytype < YYNTOKENS)
+    YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
+  else
+    YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
+
+  yy_symbol_value_print (yyoutput, yytype, yyvaluep);
+  YYFPRINTF (yyoutput, ")");
+}
+
+/*------------------------------------------------------------------.
+| yy_stack_print -- Print the state stack from its BOTTOM up to its |
+| TOP (included).                                                   |
+`------------------------------------------------------------------*/
+
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yy_stack_print (yytype_int16 *bottom, yytype_int16 *top)
+#else
+static void
+yy_stack_print (bottom, top)
+    yytype_int16 *bottom;
+    yytype_int16 *top;
+#endif
+{
+  YYFPRINTF (stderr, "Stack now");
+  for (; bottom <= top; ++bottom)
+    YYFPRINTF (stderr, " %d", *bottom);
+  YYFPRINTF (stderr, "\n");
+}
+
+# define YY_STACK_PRINT(Bottom, Top)                           \
+do {                                                           \
+  if (yydebug)                                                 \
+    yy_stack_print ((Bottom), (Top));                          \
+} while (YYID (0))
+
+
+/*------------------------------------------------.
+| Report that the YYRULE is going to be reduced.  |
+`------------------------------------------------*/
+
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yy_reduce_print (YYSTYPE *yyvsp, int yyrule)
+#else
+static void
+yy_reduce_print (yyvsp, yyrule)
+    YYSTYPE *yyvsp;
+    int yyrule;
+#endif
+{
+  int yynrhs = yyr2[yyrule];
+  int yyi;
+  unsigned long int yylno = yyrline[yyrule];
+  YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
+            yyrule - 1, yylno);
+  /* The symbols being reduced.  */
+  for (yyi = 0; yyi < yynrhs; yyi++)
+    {
+      fprintf (stderr, "   $%d = ", yyi + 1);
+      yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
+                      &(yyvsp[(yyi + 1) - (yynrhs)])
+                                      );
+      fprintf (stderr, "\n");
+    }
+}
+
+# define YY_REDUCE_PRINT(Rule)         \
+do {                                   \
+  if (yydebug)                         \
+    yy_reduce_print (yyvsp, Rule); \
+} while (YYID (0))
+
+/* Nonzero means print parse trace.  It is left uninitialized so that
+   multiple parsers can coexist.  */
+int yydebug;
+#else /* !YYDEBUG */
+# define YYDPRINTF(Args)
+# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
+# define YY_STACK_PRINT(Bottom, Top)
+# define YY_REDUCE_PRINT(Rule)
+#endif /* !YYDEBUG */
+
+
+/* YYINITDEPTH -- initial size of the parser's stacks.  */
+#ifndef        YYINITDEPTH
+# define YYINITDEPTH 200
+#endif
+
+/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
+   if the built-in stack extension method is used).
+
+   Do not make this value too large; the results are undefined if
+   YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
+   evaluated with infinite-precision integer arithmetic.  */
+
+#ifndef YYMAXDEPTH
+# define YYMAXDEPTH 10000
+#endif
+
+\f
+
+#if YYERROR_VERBOSE
+
+# ifndef yystrlen
+#  if defined __GLIBC__ && defined _STRING_H
+#   define yystrlen strlen
+#  else
+/* Return the length of YYSTR.  */
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static YYSIZE_T
+yystrlen (const char *yystr)
+#else
+static YYSIZE_T
+yystrlen (yystr)
+    const char *yystr;
+#endif
+{
+  YYSIZE_T yylen;
+  for (yylen = 0; yystr[yylen]; yylen++)
+    continue;
+  return yylen;
+}
+#  endif
+# endif
+
+# ifndef yystpcpy
+#  if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
+#   define yystpcpy stpcpy
+#  else
+/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
+   YYDEST.  */
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static char *
+yystpcpy (char *yydest, const char *yysrc)
+#else
+static char *
+yystpcpy (yydest, yysrc)
+    char *yydest;
+    const char *yysrc;
+#endif
+{
+  char *yyd = yydest;
+  const char *yys = yysrc;
+
+  while ((*yyd++ = *yys++) != '\0')
+    continue;
+
+  return yyd - 1;
+}
+#  endif
+# endif
+
+# ifndef yytnamerr
+/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
+   quotes and backslashes, so that it's suitable for yyerror.  The
+   heuristic is that double-quoting is unnecessary unless the string
+   contains an apostrophe, a comma, or backslash (other than
+   backslash-backslash).  YYSTR is taken from yytname.  If YYRES is
+   null, do not copy; instead, return the length of what the result
+   would have been.  */
+static YYSIZE_T
+yytnamerr (char *yyres, const char *yystr)
+{
+  if (*yystr == '"')
+    {
+      YYSIZE_T yyn = 0;
+      char const *yyp = yystr;
+
+      for (;;)
+       switch (*++yyp)
+         {
+         case '\'':
+         case ',':
+           goto do_not_strip_quotes;
+
+         case '\\':
+           if (*++yyp != '\\')
+             goto do_not_strip_quotes;
+           /* Fall through.  */
+         default:
+           if (yyres)
+             yyres[yyn] = *yyp;
+           yyn++;
+           break;
+
+         case '"':
+           if (yyres)
+             yyres[yyn] = '\0';
+           return yyn;
+         }
+    do_not_strip_quotes: ;
+    }
+
+  if (! yyres)
+    return yystrlen (yystr);
+
+  return yystpcpy (yyres, yystr) - yyres;
+}
+# endif
+
+/* Copy into YYRESULT an error message about the unexpected token
+   YYCHAR while in state YYSTATE.  Return the number of bytes copied,
+   including the terminating null byte.  If YYRESULT is null, do not
+   copy anything; just return the number of bytes that would be
+   copied.  As a special case, return 0 if an ordinary "syntax error"
+   message will do.  Return YYSIZE_MAXIMUM if overflow occurs during
+   size calculation.  */
+static YYSIZE_T
+yysyntax_error (char *yyresult, int yystate, int yychar)
+{
+  int yyn = yypact[yystate];
+
+  if (! (YYPACT_NINF < yyn && yyn <= YYLAST))
+    return 0;
+  else
+    {
+      int yytype = YYTRANSLATE (yychar);
+      YYSIZE_T yysize0 = yytnamerr (0, yytname[yytype]);
+      YYSIZE_T yysize = yysize0;
+      YYSIZE_T yysize1;
+      int yysize_overflow = 0;
+      enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
+      char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
+      int yyx;
+
+# if 0
+      /* This is so xgettext sees the translatable formats that are
+        constructed on the fly.  */
+      YY_("syntax error, unexpected %s");
+      YY_("syntax error, unexpected %s, expecting %s");
+      YY_("syntax error, unexpected %s, expecting %s or %s");
+      YY_("syntax error, unexpected %s, expecting %s or %s or %s");
+      YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s");
+# endif
+      char *yyfmt;
+      char const *yyf;
+      static char const yyunexpected[] = "syntax error, unexpected %s";
+      static char const yyexpecting[] = ", expecting %s";
+      static char const yyor[] = " or %s";
+      char yyformat[sizeof yyunexpected
+                   + sizeof yyexpecting - 1
+                   + ((YYERROR_VERBOSE_ARGS_MAXIMUM - 2)
+                      * (sizeof yyor - 1))];
+      char const *yyprefix = yyexpecting;
+
+      /* Start YYX at -YYN if negative to avoid negative indexes in
+        YYCHECK.  */
+      int yyxbegin = yyn < 0 ? -yyn : 0;
+
+      /* Stay within bounds of both yycheck and yytname.  */
+      int yychecklim = YYLAST - yyn + 1;
+      int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
+      int yycount = 1;
+
+      yyarg[0] = yytname[yytype];
+      yyfmt = yystpcpy (yyformat, yyunexpected);
+
+      for (yyx = yyxbegin; yyx < yyxend; ++yyx)
+       if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR)
+         {
+           if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
+             {
+               yycount = 1;
+               yysize = yysize0;
+               yyformat[sizeof yyunexpected - 1] = '\0';
+               break;
+             }
+           yyarg[yycount++] = yytname[yyx];
+           yysize1 = yysize + yytnamerr (0, yytname[yyx]);
+           yysize_overflow |= (yysize1 < yysize);
+           yysize = yysize1;
+           yyfmt = yystpcpy (yyfmt, yyprefix);
+           yyprefix = yyor;
+         }
+
+      yyf = YY_(yyformat);
+      yysize1 = yysize + yystrlen (yyf);
+      yysize_overflow |= (yysize1 < yysize);
+      yysize = yysize1;
+
+      if (yysize_overflow)
+       return YYSIZE_MAXIMUM;
+
+      if (yyresult)
+       {
+         /* Avoid sprintf, as that infringes on the user's name space.
+            Don't have undefined behavior even if the translation
+            produced a string with the wrong number of "%s"s.  */
+         char *yyp = yyresult;
+         int yyi = 0;
+         while ((*yyp = *yyf) != '\0')
+           {
+             if (*yyp == '%' && yyf[1] == 's' && yyi < yycount)
+               {
+                 yyp += yytnamerr (yyp, yyarg[yyi++]);
+                 yyf += 2;
+               }
+             else
+               {
+                 yyp++;
+                 yyf++;
+               }
+           }
+       }
+      return yysize;
+    }
+}
+#endif /* YYERROR_VERBOSE */
+\f
+
+/*-----------------------------------------------.
+| Release the memory associated to this symbol.  |
+`-----------------------------------------------*/
+
+/*ARGSUSED*/
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+static void
+yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep)
+#else
+static void
+yydestruct (yymsg, yytype, yyvaluep)
+    const char *yymsg;
+    int yytype;
+    YYSTYPE *yyvaluep;
+#endif
+{
+  YYUSE (yyvaluep);
+
+  if (!yymsg)
+    yymsg = "Deleting";
+  YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
+
+  switch (yytype)
+    {
+
+      default:
+       break;
+    }
+}
+\f
+
+/* Prevent warnings from -Wmissing-prototypes.  */
+
+#ifdef YYPARSE_PARAM
+#if defined __STDC__ || defined __cplusplus
+int yyparse (void *YYPARSE_PARAM);
+#else
+int yyparse ();
+#endif
+#else /* ! YYPARSE_PARAM */
+#if defined __STDC__ || defined __cplusplus
+int yyparse (void);
+#else
+int yyparse ();
+#endif
+#endif /* ! YYPARSE_PARAM */
+
+
+
+/* The look-ahead symbol.  */
+int yychar;
+
+/* The semantic value of the look-ahead symbol.  */
+YYSTYPE yylval;
+
+/* Number of syntax errors so far.  */
+int yynerrs;
+
+
+
+/*----------.
+| yyparse.  |
+`----------*/
+
+#ifdef YYPARSE_PARAM
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+int
+yyparse (void *YYPARSE_PARAM)
+#else
+int
+yyparse (YYPARSE_PARAM)
+    void *YYPARSE_PARAM;
+#endif
+#else /* ! YYPARSE_PARAM */
+#if (defined __STDC__ || defined __C99__FUNC__ \
+     || defined __cplusplus || defined _MSC_VER)
+int
+yyparse (void)
+#else
+int
+yyparse ()
+
+#endif
+#endif
+{
+  
+  int yystate;
+  int yyn;
+  int yyresult;
+  /* Number of tokens to shift before error messages enabled.  */
+  int yyerrstatus;
+  /* Look-ahead token as an internal (translated) token number.  */
+  int yytoken = 0;
+#if YYERROR_VERBOSE
+  /* Buffer for error messages, and its allocated size.  */
+  char yymsgbuf[128];
+  char *yymsg = yymsgbuf;
+  YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
+#endif
+
+  /* Three stacks and their tools:
+     `yyss': related to states,
+     `yyvs': related to semantic values,
+     `yyls': related to locations.
+
+     Refer to the stacks thru separate pointers, to allow yyoverflow
+     to reallocate them elsewhere.  */
+
+  /* The state stack.  */
+  yytype_int16 yyssa[YYINITDEPTH];
+  yytype_int16 *yyss = yyssa;
+  yytype_int16 *yyssp;
+
+  /* The semantic value stack.  */
+  YYSTYPE yyvsa[YYINITDEPTH];
+  YYSTYPE *yyvs = yyvsa;
+  YYSTYPE *yyvsp;
+
+
+
+#define YYPOPSTACK(N)   (yyvsp -= (N), yyssp -= (N))
+
+  YYSIZE_T yystacksize = YYINITDEPTH;
+
+  /* The variables used to return semantic value and location from the
+     action routines.  */
+  YYSTYPE yyval;
+
+
+  /* The number of symbols on the RHS of the reduced rule.
+     Keep to zero when no symbol should be popped.  */
+  int yylen = 0;
+
+  YYDPRINTF ((stderr, "Starting parse\n"));
+
+  yystate = 0;
+  yyerrstatus = 0;
+  yynerrs = 0;
+  yychar = YYEMPTY;            /* Cause a token to be read.  */
+
+  /* Initialize stack pointers.
+     Waste one element of value and location stack
+     so that they stay on the same level as the state stack.
+     The wasted elements are never initialized.  */
+
+  yyssp = yyss;
+  yyvsp = yyvs;
+
+  goto yysetstate;
+
+/*------------------------------------------------------------.
+| yynewstate -- Push a new state, which is found in yystate.  |
+`------------------------------------------------------------*/
+ yynewstate:
+  /* In all cases, when you get here, the value and location stacks
+     have just been pushed.  So pushing a state here evens the stacks.  */
+  yyssp++;
+
+ yysetstate:
+  *yyssp = yystate;
+
+  if (yyss + yystacksize - 1 <= yyssp)
+    {
+      /* Get the current used size of the three stacks, in elements.  */
+      YYSIZE_T yysize = yyssp - yyss + 1;
+
+#ifdef yyoverflow
+      {
+       /* Give user a chance to reallocate the stack.  Use copies of
+          these so that the &'s don't force the real ones into
+          memory.  */
+       YYSTYPE *yyvs1 = yyvs;
+       yytype_int16 *yyss1 = yyss;
+
+
+       /* Each stack pointer address is followed by the size of the
+          data in use in that stack, in bytes.  This used to be a
+          conditional around just the two extra args, but that might
+          be undefined if yyoverflow is a macro.  */
+       yyoverflow (YY_("memory exhausted"),
+                   &yyss1, yysize * sizeof (*yyssp),
+                   &yyvs1, yysize * sizeof (*yyvsp),
+
+                   &yystacksize);
+
+       yyss = yyss1;
+       yyvs = yyvs1;
+      }
+#else /* no yyoverflow */
+# ifndef YYSTACK_RELOCATE
+      goto yyexhaustedlab;
+# else
+      /* Extend the stack our own way.  */
+      if (YYMAXDEPTH <= yystacksize)
+       goto yyexhaustedlab;
+      yystacksize *= 2;
+      if (YYMAXDEPTH < yystacksize)
+       yystacksize = YYMAXDEPTH;
+
+      {
+       yytype_int16 *yyss1 = yyss;
+       union yyalloc *yyptr =
+         (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
+       if (! yyptr)
+         goto yyexhaustedlab;
+       YYSTACK_RELOCATE (yyss);
+       YYSTACK_RELOCATE (yyvs);
+
+#  undef YYSTACK_RELOCATE
+       if (yyss1 != yyssa)
+         YYSTACK_FREE (yyss1);
+      }
+# endif
+#endif /* no yyoverflow */
+
+      yyssp = yyss + yysize - 1;
+      yyvsp = yyvs + yysize - 1;
+
+
+      YYDPRINTF ((stderr, "Stack size increased to %lu\n",
+                 (unsigned long int) yystacksize));
+
+      if (yyss + yystacksize - 1 <= yyssp)
+       YYABORT;
+    }
+
+  YYDPRINTF ((stderr, "Entering state %d\n", yystate));
+
+  goto yybackup;
+
+/*-----------.
+| yybackup.  |
+`-----------*/
+yybackup:
+
+  /* Do appropriate processing given the current state.  Read a
+     look-ahead token if we need one and don't already have one.  */
+
+  /* First try to decide what to do without reference to look-ahead token.  */
+  yyn = yypact[yystate];
+  if (yyn == YYPACT_NINF)
+    goto yydefault;
+
+  /* Not known => get a look-ahead token if don't already have one.  */
+
+  /* YYCHAR is either YYEMPTY or YYEOF or a valid look-ahead symbol.  */
+  if (yychar == YYEMPTY)
+    {
+      YYDPRINTF ((stderr, "Reading a token: "));
+      yychar = YYLEX;
+    }
+
+  if (yychar <= YYEOF)
+    {
+      yychar = yytoken = YYEOF;
+      YYDPRINTF ((stderr, "Now at end of input.\n"));
+    }
+  else
+    {
+      yytoken = YYTRANSLATE (yychar);
+      YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
+    }
+
+  /* If the proper action on seeing token YYTOKEN is to reduce or to
+     detect an error, take that action.  */
+  yyn += yytoken;
+  if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
+    goto yydefault;
+  yyn = yytable[yyn];
+  if (yyn <= 0)
+    {
+      if (yyn == 0 || yyn == YYTABLE_NINF)
+       goto yyerrlab;
+      yyn = -yyn;
+      goto yyreduce;
+    }
+
+  if (yyn == YYFINAL)
+    YYACCEPT;
+
+  /* Count tokens shifted since error; after three, turn off error
+     status.  */
+  if (yyerrstatus)
+    yyerrstatus--;
+
+  /* Shift the look-ahead token.  */
+  YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
+
+  /* Discard the shifted token unless it is eof.  */
+  if (yychar != YYEOF)
+    yychar = YYEMPTY;
+
+  yystate = yyn;
+  *++yyvsp = yylval;
+
+  goto yynewstate;
+
+
+/*-----------------------------------------------------------.
+| yydefault -- do the default action for the current state.  |
+`-----------------------------------------------------------*/
+yydefault:
+  yyn = yydefact[yystate];
+  if (yyn == 0)
+    goto yyerrlab;
+  goto yyreduce;
+
+
+/*-----------------------------.
+| yyreduce -- Do a reduction.  |
+`-----------------------------*/
+yyreduce:
+  /* yyn is the number of a rule to reduce with.  */
+  yylen = yyr2[yyn];
+
+  /* If YYLEN is nonzero, implement the default value of the action:
+     `$$ = $1'.
+
+     Otherwise, the following line sets YYVAL to garbage.
+     This behavior is undocumented and Bison
+     users should not rely upon it.  Assigning to YYVAL
+     unconditionally makes the parser a bit smaller, and it avoids a
+     GCC warning that YYVAL may be used uninitialized.  */
+  yyval = yyvsp[1-yylen];
+
+
+  YY_REDUCE_PRINT (yyn);
+  switch (yyn)
+    {
+        case 4:
+#line 129 "gram.y"
+    {
+                       struct Interface *iface2;
+
+                       iface2 = IfaceList;
+                       while (iface2)
+                       {
+                               if (!strcmp(iface2->Name, iface->Name))
+                               {
+                                       flog(LOG_ERR, "duplicate interface "
+                                               "definition for %s", iface->Name);
+                                       ABORT;
+                               }
+                               iface2 = iface2->next;
+                       }                       
+
+                       if (check_device(sock, iface) < 0) {
+                               if (iface->IgnoreIfMissing) {
+                                       dlog(LOG_DEBUG, 4, "interface %s did not exist, ignoring the interface", iface->Name);
+                                       goto skip_interface;
+                               }
+                               else {
+                                       flog(LOG_ERR, "interface %s does not exist", iface->Name);
+                                       ABORT;
+                               }
+                       }
+                       if (setup_deviceinfo(sock, iface) < 0)
+                               ABORT;
+                       if (check_iface(iface) < 0)
+                               ABORT;
+                       if (setup_linklocal_addr(sock, iface) < 0)
+                               ABORT;
+                       if (setup_allrouters_membership(sock, iface) < 0)
+                               ABORT;
+
+                       iface->next = IfaceList;
+                       IfaceList = iface;
+
+                       dlog(LOG_DEBUG, 4, "interface definition for %s is ok", iface->Name);
+
+skip_interface:
+                       iface = NULL;
+               }
+    break;
+
+  case 5:
+#line 173 "gram.y"
+    {
+                       iface = malloc(sizeof(struct Interface));
+
+                       if (iface == NULL) {
+                               flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+                               ABORT;
+                       }
+
+                       iface_init_defaults(iface);
+                       strncpy(iface->Name, (yyvsp[(2) - (2)].str), IFNAMSIZ-1);
+                       iface->Name[IFNAMSIZ-1] = '\0';
+               }
+    break;
+
+  case 6:
+#line 188 "gram.y"
+    {
+                       /* check vality */
+                       (yyval.str) = (yyvsp[(1) - (1)].str);
+               }
+    break;
+
+  case 7:
+#line 195 "gram.y"
+    {
+                       iface->AdvPrefixList = (yyvsp[(2) - (4)].pinfo);
+                       iface->AdvRouteList = (yyvsp[(3) - (4)].rinfo);
+                       iface->AdvRDNSSList = (yyvsp[(4) - (4)].rdnssinfo);
+               }
+    break;
+
+  case 10:
+#line 207 "gram.y"
+    {
+                       (yyval.pinfo) = NULL;
+               }
+    break;
+
+  case 12:
+#line 214 "gram.y"
+    {
+                       (yyval.rinfo) = NULL;
+               }
+    break;
+
+  case 14:
+#line 221 "gram.y"
+    {
+                       (yyval.rdnssinfo) = NULL;
+               }
+    break;
+
+  case 18:
+#line 232 "gram.y"
+    {
+                       iface->MinRtrAdvInterval = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 19:
+#line 236 "gram.y"
+    {
+                       iface->MaxRtrAdvInterval = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 20:
+#line 240 "gram.y"
+    {
+                       iface->MinDelayBetweenRAs = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 21:
+#line 244 "gram.y"
+    {
+                       iface->MinRtrAdvInterval = (yyvsp[(2) - (3)].dec);
+               }
+    break;
+
+  case 22:
+#line 248 "gram.y"
+    {
+                       iface->MaxRtrAdvInterval = (yyvsp[(2) - (3)].dec);
+               }
+    break;
+
+  case 23:
+#line 252 "gram.y"
+    {
+                       iface->MinDelayBetweenRAs = (yyvsp[(2) - (3)].dec);
+               }
+    break;
+
+  case 24:
+#line 256 "gram.y"
+    {
+                       iface->IgnoreIfMissing = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 25:
+#line 260 "gram.y"
+    {
+                       iface->AdvSendAdvert = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 26:
+#line 264 "gram.y"
+    {
+                       iface->AdvManagedFlag = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 27:
+#line 268 "gram.y"
+    {
+                       iface->AdvOtherConfigFlag = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 28:
+#line 272 "gram.y"
+    {
+                       iface->AdvLinkMTU = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 29:
+#line 276 "gram.y"
+    {
+                       iface->AdvReachableTime = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 30:
+#line 280 "gram.y"
+    {
+                       iface->AdvRetransTimer = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 31:
+#line 284 "gram.y"
+    {
+                       iface->AdvDefaultLifetime = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 32:
+#line 288 "gram.y"
+    {
+                       iface->AdvDefaultPreference = (yyvsp[(2) - (3)].snum);
+               }
+    break;
+
+  case 33:
+#line 292 "gram.y"
+    {
+                       iface->AdvCurHopLimit = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 34:
+#line 296 "gram.y"
+    {
+                       iface->AdvSourceLLAddress = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 35:
+#line 300 "gram.y"
+    {
+                       iface->AdvIntervalOpt = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 36:
+#line 304 "gram.y"
+    {
+                       iface->AdvHomeAgentInfo = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 37:
+#line 308 "gram.y"
+    {
+                       iface->AdvHomeAgentFlag = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 38:
+#line 312 "gram.y"
+    {
+                       iface->HomeAgentPreference = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 39:
+#line 316 "gram.y"
+    {
+                       iface->HomeAgentLifetime = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 40:
+#line 320 "gram.y"
+    {
+                       iface->UnicastOnly = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 41:
+#line 324 "gram.y"
+    {
+                       iface->AdvMobRtrSupportFlag = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 42:
+#line 330 "gram.y"
+    {
+                       (yyval.pinfo) = (yyvsp[(1) - (1)].pinfo);
+               }
+    break;
+
+  case 43:
+#line 334 "gram.y"
+    {
+                       (yyvsp[(2) - (2)].pinfo)->next = (yyvsp[(1) - (2)].pinfo);
+                       (yyval.pinfo) = (yyvsp[(2) - (2)].pinfo);
+               }
+    break;
+
+  case 44:
+#line 341 "gram.y"
+    {
+                       unsigned int dst;
+
+                       if (prefix->AdvPreferredLifetime >
+                           prefix->AdvValidLifetime)
+                       {
+                               flog(LOG_ERR, "AdvValidLifeTime must be "
+                                       "greater than AdvPreferredLifetime in %s, line %d", 
+                                       conf_file, num_lines);
+                               ABORT;
+                       }
+
+                       if( prefix->if6to4[0] )
+                       {
+                               if (get_v4addr(prefix->if6to4, &dst) < 0)
+                               {
+                                       flog(LOG_ERR, "interface %s has no IPv4 addresses, disabling 6to4 prefix", prefix->if6to4 );
+                                       prefix->enabled = 0;
+                               } else
+                               {
+                                       *((uint16_t *)(prefix->Prefix.s6_addr)) = htons(0x2002);
+                                       memcpy( prefix->Prefix.s6_addr + 2, &dst, sizeof( dst ) );
+                               }
+                       }
+
+                       (yyval.pinfo) = prefix;
+                       prefix = NULL;
+               }
+    break;
+
+  case 45:
+#line 372 "gram.y"
+    {
+                       prefix = malloc(sizeof(struct AdvPrefix));
+                       
+                       if (prefix == NULL) {
+                               flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+                               ABORT;
+                       }
+
+                       prefix_init_defaults(prefix);
+
+                       if ((yyvsp[(4) - (4)].num) > MAX_PrefixLen)
+                       {
+                               flog(LOG_ERR, "invalid prefix length in %s, line %d", conf_file, num_lines);
+                               ABORT;
+                       }
+
+                       prefix->PrefixLen = (yyvsp[(4) - (4)].num);
+
+                       memcpy(&prefix->Prefix, (yyvsp[(2) - (4)].addr), sizeof(struct in6_addr));
+               }
+    break;
+
+  case 50:
+#line 403 "gram.y"
+    {
+                       prefix->AdvOnLinkFlag = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 51:
+#line 407 "gram.y"
+    {
+                       prefix->AdvAutonomousFlag = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 52:
+#line 411 "gram.y"
+    {
+                       prefix->AdvRouterAddr = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 53:
+#line 415 "gram.y"
+    {
+                       prefix->AdvValidLifetime = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 54:
+#line 419 "gram.y"
+    {
+                       prefix->AdvPreferredLifetime = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 55:
+#line 423 "gram.y"
+    {
+                       dlog(LOG_DEBUG, 4, "using interface %s for 6to4", (yyvsp[(2) - (3)].str));
+                       strncpy(prefix->if6to4, (yyvsp[(2) - (3)].str), IFNAMSIZ-1);
+                       prefix->if6to4[IFNAMSIZ-1] = '\0';
+               }
+    break;
+
+  case 56:
+#line 431 "gram.y"
+    {
+                       (yyval.rinfo) = (yyvsp[(1) - (1)].rinfo);
+               }
+    break;
+
+  case 57:
+#line 435 "gram.y"
+    {
+                       (yyvsp[(2) - (2)].rinfo)->next = (yyvsp[(1) - (2)].rinfo);
+                       (yyval.rinfo) = (yyvsp[(2) - (2)].rinfo);
+               }
+    break;
+
+  case 58:
+#line 442 "gram.y"
+    {
+                       (yyval.rinfo) = route;
+                       route = NULL;
+               }
+    break;
+
+  case 59:
+#line 450 "gram.y"
+    {
+                       route = malloc(sizeof(struct AdvRoute));
+                       
+                       if (route == NULL) {
+                               flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+                               ABORT;
+                       }
+
+                       route_init_defaults(route, iface);
+
+                       if ((yyvsp[(4) - (4)].num) > MAX_PrefixLen)
+                       {
+                               flog(LOG_ERR, "invalid route prefix length in %s, line %d", conf_file, num_lines);
+                               ABORT;
+                       }
+
+                       route->PrefixLen = (yyvsp[(4) - (4)].num);
+
+                       memcpy(&route->Prefix, (yyvsp[(2) - (4)].addr), sizeof(struct in6_addr));
+               }
+    break;
+
+  case 64:
+#line 483 "gram.y"
+    {
+                       route->AdvRoutePreference = (yyvsp[(2) - (3)].snum);
+               }
+    break;
+
+  case 65:
+#line 487 "gram.y"
+    {
+                       route->AdvRouteLifetime = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 66:
+#line 493 "gram.y"
+    {
+                       (yyval.rdnssinfo) = (yyvsp[(1) - (1)].rdnssinfo);
+               }
+    break;
+
+  case 67:
+#line 497 "gram.y"
+    {
+                       (yyvsp[(2) - (2)].rdnssinfo)->next = (yyvsp[(1) - (2)].rdnssinfo);
+                       (yyval.rdnssinfo) = (yyvsp[(2) - (2)].rdnssinfo);
+               }
+    break;
+
+  case 68:
+#line 504 "gram.y"
+    {
+                       (yyval.rdnssinfo) = rdnss;
+                       rdnss = NULL;
+               }
+    break;
+
+  case 71:
+#line 515 "gram.y"
+    {
+                       if (!rdnss) {
+                               /* first IP found */
+                               rdnss = malloc(sizeof(struct AdvRDNSS));
+                               
+                               if (rdnss == NULL) {
+                                       flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+                                       ABORT;
+                               }
+
+                               rdnss_init_defaults(rdnss, iface);
+                       }
+                       
+                       switch (rdnss->AdvRDNSSNumber) {
+                               case 0:
+                                       memcpy(&rdnss->AdvRDNSSAddr1, (yyvsp[(1) - (1)].addr), sizeof(struct in6_addr));
+                                       rdnss->AdvRDNSSNumber++;
+                                       break;
+                               case 1:
+                                       memcpy(&rdnss->AdvRDNSSAddr2, (yyvsp[(1) - (1)].addr), sizeof(struct in6_addr));
+                                       rdnss->AdvRDNSSNumber++;
+                                       break;
+                               case 2:
+                                       memcpy(&rdnss->AdvRDNSSAddr3, (yyvsp[(1) - (1)].addr), sizeof(struct in6_addr));
+                                       rdnss->AdvRDNSSNumber++;
+                                       break;
+                               default:
+                                       flog(LOG_CRIT, "Too many addresses in RDNSS section");
+                                       ABORT;
+                       }
+                       
+               }
+    break;
+
+  case 72:
+#line 550 "gram.y"
+    {
+                       if (!rdnss) {
+                               flog(LOG_CRIT, "No address specified in RDNSS section");
+                               ABORT;
+                       }
+               }
+    break;
+
+  case 77:
+#line 568 "gram.y"
+    {
+                       rdnss->AdvRDNSSPreference = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 78:
+#line 572 "gram.y"
+    {
+                       rdnss->AdvRDNSSOpenFlag = (yyvsp[(2) - (3)].bool);
+               }
+    break;
+
+  case 79:
+#line 576 "gram.y"
+    {
+                       if ((yyvsp[(2) - (3)].num) < iface->MaxRtrAdvInterval && (yyvsp[(2) - (3)].num) != 0) {
+                               flog(LOG_ERR, "AdvRDNSSLifetime must be at least MaxRtrAdvInterval");
+                               ABORT;
+                       }
+                       if ((yyvsp[(2) - (3)].num) > 2*(iface->MaxRtrAdvInterval))
+                               flog(LOG_WARNING, "Warning: AdvRDNSSLifetime <= 2*MaxRtrAdvInterval would allow stale DNS servers to be deleted faster");
+
+                       rdnss->AdvRDNSSLifetime = (yyvsp[(2) - (3)].num);
+               }
+    break;
+
+  case 80:
+#line 589 "gram.y"
+    {
+                                (yyval.num) = (yyvsp[(1) - (1)].num); 
+                        }
+    break;
+
+  case 81:
+#line 593 "gram.y"
+    {
+                                (yyval.num) = (uint32_t)~0;
+                        }
+    break;
+
+
+/* Line 1267 of yacc.c.  */
+#line 2152 "gram.c"
+      default: break;
+    }
+  YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
+
+  YYPOPSTACK (yylen);
+  yylen = 0;
+  YY_STACK_PRINT (yyss, yyssp);
+
+  *++yyvsp = yyval;
+
+
+  /* Now `shift' the result of the reduction.  Determine what state
+     that goes to, based on the state we popped back to and the rule
+     number reduced by.  */
+
+  yyn = yyr1[yyn];
+
+  yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
+  if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
+    yystate = yytable[yystate];
+  else
+    yystate = yydefgoto[yyn - YYNTOKENS];
+
+  goto yynewstate;
+
+
+/*------------------------------------.
+| yyerrlab -- here on detecting error |
+`------------------------------------*/
+yyerrlab:
+  /* If not already recovering from an error, report this error.  */
+  if (!yyerrstatus)
+    {
+      ++yynerrs;
+#if ! YYERROR_VERBOSE
+      yyerror (YY_("syntax error"));
+#else
+      {
+       YYSIZE_T yysize = yysyntax_error (0, yystate, yychar);
+       if (yymsg_alloc < yysize && yymsg_alloc < YYSTACK_ALLOC_MAXIMUM)
+         {
+           YYSIZE_T yyalloc = 2 * yysize;
+           if (! (yysize <= yyalloc && yyalloc <= YYSTACK_ALLOC_MAXIMUM))
+             yyalloc = YYSTACK_ALLOC_MAXIMUM;
+           if (yymsg != yymsgbuf)
+             YYSTACK_FREE (yymsg);
+           yymsg = (char *) YYSTACK_ALLOC (yyalloc);
+           if (yymsg)
+             yymsg_alloc = yyalloc;
+           else
+             {
+               yymsg = yymsgbuf;
+               yymsg_alloc = sizeof yymsgbuf;
+             }
+         }
+
+       if (0 < yysize && yysize <= yymsg_alloc)
+         {
+           (void) yysyntax_error (yymsg, yystate, yychar);
+           yyerror (yymsg);
+         }
+       else
+         {
+           yyerror (YY_("syntax error"));
+           if (yysize != 0)
+             goto yyexhaustedlab;
+         }
+      }
+#endif
+    }
+
+
+
+  if (yyerrstatus == 3)
+    {
+      /* If just tried and failed to reuse look-ahead token after an
+        error, discard it.  */
+
+      if (yychar <= YYEOF)
+       {
+         /* Return failure if at end of input.  */
+         if (yychar == YYEOF)
+           YYABORT;
+       }
+      else
+       {
+         yydestruct ("Error: discarding",
+                     yytoken, &yylval);
+         yychar = YYEMPTY;
+       }
+    }
+
+  /* Else will try to reuse look-ahead token after shifting the error
+     token.  */
+  goto yyerrlab1;
+
+
+/*---------------------------------------------------.
+| yyerrorlab -- error raised explicitly by YYERROR.  |
+`---------------------------------------------------*/
+yyerrorlab:
+
+  /* Pacify compilers like GCC when the user code never invokes
+     YYERROR and the label yyerrorlab therefore never appears in user
+     code.  */
+  if (/*CONSTCOND*/ 0)
+     goto yyerrorlab;
+
+  /* Do not reclaim the symbols of the rule which action triggered
+     this YYERROR.  */
+  YYPOPSTACK (yylen);
+  yylen = 0;
+  YY_STACK_PRINT (yyss, yyssp);
+  yystate = *yyssp;
+  goto yyerrlab1;
+
+
+/*-------------------------------------------------------------.
+| yyerrlab1 -- common code for both syntax error and YYERROR.  |
+`-------------------------------------------------------------*/
+yyerrlab1:
+  yyerrstatus = 3;     /* Each real token shifted decrements this.  */
+
+  for (;;)
+    {
+      yyn = yypact[yystate];
+      if (yyn != YYPACT_NINF)
+       {
+         yyn += YYTERROR;
+         if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
+           {
+             yyn = yytable[yyn];
+             if (0 < yyn)
+               break;
+           }
+       }
+
+      /* Pop the current state because it cannot handle the error token.  */
+      if (yyssp == yyss)
+       YYABORT;
+
+
+      yydestruct ("Error: popping",
+                 yystos[yystate], yyvsp);
+      YYPOPSTACK (1);
+      yystate = *yyssp;
+      YY_STACK_PRINT (yyss, yyssp);
+    }
+
+  if (yyn == YYFINAL)
+    YYACCEPT;
+
+  *++yyvsp = yylval;
+
+
+  /* Shift the error token.  */
+  YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
+
+  yystate = yyn;
+  goto yynewstate;
+
+
+/*-------------------------------------.
+| yyacceptlab -- YYACCEPT comes here.  |
+`-------------------------------------*/
+yyacceptlab:
+  yyresult = 0;
+  goto yyreturn;
+
+/*-----------------------------------.
+| yyabortlab -- YYABORT comes here.  |
+`-----------------------------------*/
+yyabortlab:
+  yyresult = 1;
+  goto yyreturn;
+
+#ifndef yyoverflow
+/*-------------------------------------------------.
+| yyexhaustedlab -- memory exhaustion comes here.  |
+`-------------------------------------------------*/
+yyexhaustedlab:
+  yyerror (YY_("memory exhausted"));
+  yyresult = 2;
+  /* Fall through.  */
+#endif
+
+yyreturn:
+  if (yychar != YYEOF && yychar != YYEMPTY)
+     yydestruct ("Cleanup: discarding lookahead",
+                yytoken, &yylval);
+  /* Do not reclaim the symbols of the rule which action triggered
+     this YYABORT or YYACCEPT.  */
+  YYPOPSTACK (yylen);
+  YY_STACK_PRINT (yyss, yyssp);
+  while (yyssp != yyss)
+    {
+      yydestruct ("Cleanup: popping",
+                 yystos[*yyssp], yyvsp);
+      YYPOPSTACK (1);
+    }
+#ifndef yyoverflow
+  if (yyss != yyssa)
+    YYSTACK_FREE (yyss);
+#endif
+#if YYERROR_VERBOSE
+  if (yymsg != yymsgbuf)
+    YYSTACK_FREE (yymsg);
+#endif
+  /* Make sure YYID is used.  */
+  return YYID (yyresult);
+}
+
+
+#line 598 "gram.y"
+
+
+static
+void cleanup(void)
+{
+       if (iface)
+               free(iface);
+       
+       if (prefix)
+               free(prefix);
+
+       if (route)
+               free(route);
+
+       if (rdnss)
+               free(rdnss);
+}
+
+static void
+yyerror(char *msg)
+{
+       cleanup();
+       flog(LOG_ERR, "%s in %s, line %d: %s", msg, conf_file, num_lines, yytext);
+}
+
diff --git a/support/sdk/c/blip/driver/radvd-1.0/gram.h b/support/sdk/c/blip/driver/radvd-1.0/gram.h
new file mode 100644 (file)
index 0000000..a9d24a9
--- /dev/null
@@ -0,0 +1,160 @@
+/* A Bison parser, made by GNU Bison 2.3.  */
+
+/* Skeleton interface for Bison's Yacc-like parsers in C
+
+   Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004, 2005, 2006
+   Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 51 Franklin Street, Fifth Floor,
+   Boston, MA 02110-1301, USA.  */
+
+/* As a special exception, you may create a larger work that contains
+   part or all of the Bison parser skeleton and distribute that work
+   under terms of your choice, so long as that work isn't itself a
+   parser generator using the skeleton or a modified version thereof
+   as a parser skeleton.  Alternatively, if you modify or redistribute
+   the parser skeleton itself, you may (at your option) remove this
+   special exception, which will cause the skeleton and the resulting
+   Bison output files to be licensed under the GNU General Public
+   License without this special exception.
+
+   This special exception was added by the Free Software Foundation in
+   version 2.2 of Bison.  */
+
+/* Tokens.  */
+#ifndef YYTOKENTYPE
+# define YYTOKENTYPE
+   /* Put the tokens into the symbol table, so that GDB and other debuggers
+      know about them.  */
+   enum yytokentype {
+     T_INTERFACE = 258,
+     T_PREFIX = 259,
+     T_ROUTE = 260,
+     T_RDNSS = 261,
+     STRING = 262,
+     NUMBER = 263,
+     SIGNEDNUMBER = 264,
+     DECIMAL = 265,
+     SWITCH = 266,
+     IPV6ADDR = 267,
+     INFINITY = 268,
+     T_IgnoreIfMissing = 269,
+     T_AdvSendAdvert = 270,
+     T_MaxRtrAdvInterval = 271,
+     T_MinRtrAdvInterval = 272,
+     T_MinDelayBetweenRAs = 273,
+     T_AdvManagedFlag = 274,
+     T_AdvOtherConfigFlag = 275,
+     T_AdvLinkMTU = 276,
+     T_AdvReachableTime = 277,
+     T_AdvRetransTimer = 278,
+     T_AdvCurHopLimit = 279,
+     T_AdvDefaultLifetime = 280,
+     T_AdvDefaultPreference = 281,
+     T_AdvSourceLLAddress = 282,
+     T_AdvOnLink = 283,
+     T_AdvAutonomous = 284,
+     T_AdvValidLifetime = 285,
+     T_AdvPreferredLifetime = 286,
+     T_AdvRouterAddr = 287,
+     T_AdvHomeAgentFlag = 288,
+     T_AdvIntervalOpt = 289,
+     T_AdvHomeAgentInfo = 290,
+     T_Base6to4Interface = 291,
+     T_UnicastOnly = 292,
+     T_HomeAgentPreference = 293,
+     T_HomeAgentLifetime = 294,
+     T_AdvRoutePreference = 295,
+     T_AdvRouteLifetime = 296,
+     T_AdvRDNSSPreference = 297,
+     T_AdvRDNSSOpenFlag = 298,
+     T_AdvRDNSSLifetime = 299,
+     T_AdvMobRtrSupportFlag = 300,
+     T_BAD_TOKEN = 301
+   };
+#endif
+/* Tokens.  */
+#define T_INTERFACE 258
+#define T_PREFIX 259
+#define T_ROUTE 260
+#define T_RDNSS 261
+#define STRING 262
+#define NUMBER 263
+#define SIGNEDNUMBER 264
+#define DECIMAL 265
+#define SWITCH 266
+#define IPV6ADDR 267
+#define INFINITY 268
+#define T_IgnoreIfMissing 269
+#define T_AdvSendAdvert 270
+#define T_MaxRtrAdvInterval 271
+#define T_MinRtrAdvInterval 272
+#define T_MinDelayBetweenRAs 273
+#define T_AdvManagedFlag 274
+#define T_AdvOtherConfigFlag 275
+#define T_AdvLinkMTU 276
+#define T_AdvReachableTime 277
+#define T_AdvRetransTimer 278
+#define T_AdvCurHopLimit 279
+#define T_AdvDefaultLifetime 280
+#define T_AdvDefaultPreference 281
+#define T_AdvSourceLLAddress 282
+#define T_AdvOnLink 283
+#define T_AdvAutonomous 284
+#define T_AdvValidLifetime 285
+#define T_AdvPreferredLifetime 286
+#define T_AdvRouterAddr 287
+#define T_AdvHomeAgentFlag 288
+#define T_AdvIntervalOpt 289
+#define T_AdvHomeAgentInfo 290
+#define T_Base6to4Interface 291
+#define T_UnicastOnly 292
+#define T_HomeAgentPreference 293
+#define T_HomeAgentLifetime 294
+#define T_AdvRoutePreference 295
+#define T_AdvRouteLifetime 296
+#define T_AdvRDNSSPreference 297
+#define T_AdvRDNSSOpenFlag 298
+#define T_AdvRDNSSLifetime 299
+#define T_AdvMobRtrSupportFlag 300
+#define T_BAD_TOKEN 301
+
+
+
+
+#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
+typedef union YYSTYPE
+#line 110 "gram.y"
+{
+       unsigned int            num;
+       int                     snum;
+       double                  dec;
+       int                     bool;
+       struct in6_addr         *addr;
+       char                    *str;
+       struct AdvPrefix        *pinfo;
+       struct AdvRoute         *rinfo;
+       struct AdvRDNSS         *rdnssinfo;
+}
+/* Line 1489 of yacc.c.  */
+#line 153 "gram.h"
+       YYSTYPE;
+# define yystype YYSTYPE /* obsolescent; will be withdrawn */
+# define YYSTYPE_IS_DECLARED 1
+# define YYSTYPE_IS_TRIVIAL 1
+#endif
+
+extern YYSTYPE yylval;
+
diff --git a/support/sdk/c/blip/driver/radvd-1.0/gram.y b/support/sdk/c/blip/driver/radvd-1.0/gram.y
new file mode 100644 (file)
index 0000000..06b7acf
--- /dev/null
@@ -0,0 +1,621 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996-2000 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+%{
+#include <config.h>
+#include <includes.h>
+#include <radvd.h>
+#include <defaults.h>
+
+extern struct Interface *IfaceList;
+struct Interface *iface = NULL;
+struct AdvPrefix *prefix = NULL;
+struct AdvRoute *route = NULL;
+struct AdvRDNSS *rdnss = NULL;
+
+extern char *conf_file;
+extern int num_lines;
+extern char *yytext;
+extern int sock;
+
+static void cleanup(void);
+static void yyerror(char *msg);
+
+#if 0 /* no longer necessary? */
+#ifndef HAVE_IN6_ADDR_S6_ADDR
+# ifdef __FreeBSD__
+#  define s6_addr32 __u6_addr.__u6_addr32
+#  define s6_addr16 __u6_addr.__u6_addr16
+# endif
+#endif
+#endif
+
+#define ABORT  do { cleanup(); YYABORT; } while (0);
+
+%}
+
+%token         T_INTERFACE
+%token         T_PREFIX
+%token         T_ROUTE
+%token         T_RDNSS
+
+%token <str>   STRING
+%token <num>   NUMBER
+%token <snum>  SIGNEDNUMBER
+%token <dec>   DECIMAL
+%token <bool>  SWITCH
+%token <addr>  IPV6ADDR
+%token                 INFINITY
+
+%token         T_IgnoreIfMissing
+%token         T_AdvSendAdvert
+%token         T_MaxRtrAdvInterval
+%token         T_MinRtrAdvInterval
+%token         T_MinDelayBetweenRAs
+%token         T_AdvManagedFlag
+%token         T_AdvOtherConfigFlag
+%token         T_AdvLinkMTU
+%token         T_AdvReachableTime
+%token         T_AdvRetransTimer
+%token         T_AdvCurHopLimit
+%token         T_AdvDefaultLifetime
+%token         T_AdvDefaultPreference
+%token         T_AdvSourceLLAddress
+
+%token         T_AdvOnLink
+%token         T_AdvAutonomous
+%token         T_AdvValidLifetime
+%token         T_AdvPreferredLifetime
+
+%token         T_AdvRouterAddr
+%token         T_AdvHomeAgentFlag
+%token         T_AdvIntervalOpt
+%token         T_AdvHomeAgentInfo
+
+%token         T_Base6to4Interface
+%token         T_UnicastOnly
+
+%token         T_HomeAgentPreference
+%token         T_HomeAgentLifetime
+
+%token         T_AdvRoutePreference
+%token         T_AdvRouteLifetime
+
+%token         T_AdvRDNSSPreference
+%token         T_AdvRDNSSOpenFlag
+%token         T_AdvRDNSSLifetime
+
+%token         T_AdvMobRtrSupportFlag
+
+%token         T_BAD_TOKEN
+
+%type  <str>   name
+%type  <pinfo> optional_prefixlist prefixdef prefixlist
+%type  <rinfo> optional_routelist routedef routelist
+%type  <rdnssinfo> optional_rdnsslist rdnssdef rdnsslist
+%type   <num>  number_or_infinity
+
+%union {
+       unsigned int            num;
+       int                     snum;
+       double                  dec;
+       int                     bool;
+       struct in6_addr         *addr;
+       char                    *str;
+       struct AdvPrefix        *pinfo;
+       struct AdvRoute         *rinfo;
+       struct AdvRDNSS         *rdnssinfo;
+};
+
+%%
+
+grammar                : grammar ifacedef
+               | ifacedef
+               ;
+
+ifacedef       : ifacehead '{' ifaceparams  '}' ';'
+               {
+                       struct Interface *iface2;
+
+                       iface2 = IfaceList;
+                       while (iface2)
+                       {
+                               if (!strcmp(iface2->Name, iface->Name))
+                               {
+                                       flog(LOG_ERR, "duplicate interface "
+                                               "definition for %s", iface->Name);
+                                       ABORT;
+                               }
+                               iface2 = iface2->next;
+                       }                       
+
+                       if (check_device(sock, iface) < 0) {
+                               if (iface->IgnoreIfMissing) {
+                                       dlog(LOG_DEBUG, 4, "interface %s did not exist, ignoring the interface", iface->Name);
+                                       goto skip_interface;
+                               }
+                               else {
+                                       flog(LOG_ERR, "interface %s does not exist", iface->Name);
+                                       ABORT;
+                               }
+                       }
+                       if (setup_deviceinfo(sock, iface) < 0)
+                               ABORT;
+                       if (check_iface(iface) < 0)
+                               ABORT;
+                       if (setup_linklocal_addr(sock, iface) < 0)
+                               ABORT;
+                       if (setup_allrouters_membership(sock, iface) < 0)
+                               ABORT;
+
+                       iface->next = IfaceList;
+                       IfaceList = iface;
+
+                       dlog(LOG_DEBUG, 4, "interface definition for %s is ok", iface->Name);
+
+skip_interface:
+                       iface = NULL;
+               };
+
+ifacehead      : T_INTERFACE name
+               {
+                       iface = malloc(sizeof(struct Interface));
+
+                       if (iface == NULL) {
+                               flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+                               ABORT;
+                       }
+
+                       iface_init_defaults(iface);
+                       strncpy(iface->Name, $2, IFNAMSIZ-1);
+                       iface->Name[IFNAMSIZ-1] = '\0';
+               }
+               ;
+       
+name           : STRING
+               {
+                       /* check vality */
+                       $$ = $1;
+               }
+               ;
+
+ifaceparams    : optional_ifacevlist optional_prefixlist optional_routelist optional_rdnsslist
+               {
+                       iface->AdvPrefixList = $2;
+                       iface->AdvRouteList = $3;
+                       iface->AdvRDNSSList = $4;
+               }
+               ;
+
+optional_ifacevlist: /* empty */
+                  | ifacevlist
+                  ;
+
+optional_prefixlist: /* empty */
+               {
+                       $$ = NULL;
+               }
+               | prefixlist
+               ;
+
+optional_routelist: /* empty */
+               {
+                       $$ = NULL;
+               }
+               | routelist
+               ;
+               
+optional_rdnsslist: /* empty */
+               {
+                       $$ = NULL;
+               }
+               | rdnsslist
+               ;
+
+ifacevlist     : ifacevlist ifaceval
+               | ifaceval
+               ;
+
+ifaceval       : T_MinRtrAdvInterval NUMBER ';'
+               {
+                       iface->MinRtrAdvInterval = $2;
+               }
+               | T_MaxRtrAdvInterval NUMBER ';'
+               {
+                       iface->MaxRtrAdvInterval = $2;
+               }
+               | T_MinDelayBetweenRAs NUMBER ';'
+               {
+                       iface->MinDelayBetweenRAs = $2;
+               }
+               | T_MinRtrAdvInterval DECIMAL ';'
+               {
+                       iface->MinRtrAdvInterval = $2;
+               }
+               | T_MaxRtrAdvInterval DECIMAL ';'
+               {
+                       iface->MaxRtrAdvInterval = $2;
+               }
+               | T_MinDelayBetweenRAs DECIMAL ';'
+               {
+                       iface->MinDelayBetweenRAs = $2;
+               }
+               | T_IgnoreIfMissing SWITCH ';'
+               {
+                       iface->IgnoreIfMissing = $2;
+               }
+               | T_AdvSendAdvert SWITCH ';'
+               {
+                       iface->AdvSendAdvert = $2;
+               }
+               | T_AdvManagedFlag SWITCH ';'
+               {
+                       iface->AdvManagedFlag = $2;
+               }
+               | T_AdvOtherConfigFlag SWITCH ';'
+               {
+                       iface->AdvOtherConfigFlag = $2;
+               }
+               | T_AdvLinkMTU NUMBER ';'
+               {
+                       iface->AdvLinkMTU = $2;
+               }
+               | T_AdvReachableTime NUMBER ';'
+               {
+                       iface->AdvReachableTime = $2;
+               }
+               | T_AdvRetransTimer NUMBER ';'
+               {
+                       iface->AdvRetransTimer = $2;
+               }
+               | T_AdvDefaultLifetime NUMBER ';'
+               {
+                       iface->AdvDefaultLifetime = $2;
+               }
+               | T_AdvDefaultPreference SIGNEDNUMBER ';'
+               {
+                       iface->AdvDefaultPreference = $2;
+               }
+               | T_AdvCurHopLimit NUMBER ';'
+               {
+                       iface->AdvCurHopLimit = $2;
+               }
+               | T_AdvSourceLLAddress SWITCH ';'
+               {
+                       iface->AdvSourceLLAddress = $2;
+               }
+               | T_AdvIntervalOpt SWITCH ';'
+               {
+                       iface->AdvIntervalOpt = $2;
+               }
+               | T_AdvHomeAgentInfo SWITCH ';'
+               {
+                       iface->AdvHomeAgentInfo = $2;
+               }
+               | T_AdvHomeAgentFlag SWITCH ';'
+               {
+                       iface->AdvHomeAgentFlag = $2;
+               }
+               | T_HomeAgentPreference NUMBER ';'
+               {
+                       iface->HomeAgentPreference = $2;
+               }
+               | T_HomeAgentLifetime NUMBER ';'
+               {
+                       iface->HomeAgentLifetime = $2;
+               }
+               | T_UnicastOnly SWITCH ';'
+               {
+                       iface->UnicastOnly = $2;
+               }
+               | T_AdvMobRtrSupportFlag SWITCH ';'
+               {
+                       iface->AdvMobRtrSupportFlag = $2;
+               }
+               ;
+               
+prefixlist     : prefixdef
+               {
+                       $$ = $1;
+               }
+               | prefixlist prefixdef
+               {
+                       $2->next = $1;
+                       $$ = $2;
+               }
+               ;
+
+prefixdef      : prefixhead '{' optional_prefixplist '}' ';'
+               {
+                       unsigned int dst;
+
+                       if (prefix->AdvPreferredLifetime >
+                           prefix->AdvValidLifetime)
+                       {
+                               flog(LOG_ERR, "AdvValidLifeTime must be "
+                                       "greater than AdvPreferredLifetime in %s, line %d", 
+                                       conf_file, num_lines);
+                               ABORT;
+                       }
+
+                       if( prefix->if6to4[0] )
+                       {
+                               if (get_v4addr(prefix->if6to4, &dst) < 0)
+                               {
+                                       flog(LOG_ERR, "interface %s has no IPv4 addresses, disabling 6to4 prefix", prefix->if6to4 );
+                                       prefix->enabled = 0;
+                               } else
+                               {
+                                       *((uint16_t *)(prefix->Prefix.s6_addr)) = htons(0x2002);
+                                       memcpy( prefix->Prefix.s6_addr + 2, &dst, sizeof( dst ) );
+                               }
+                       }
+
+                       $$ = prefix;
+                       prefix = NULL;
+               }
+               ;
+
+prefixhead     : T_PREFIX IPV6ADDR '/' NUMBER
+               {
+                       prefix = malloc(sizeof(struct AdvPrefix));
+                       
+                       if (prefix == NULL) {
+                               flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+                               ABORT;
+                       }
+
+                       prefix_init_defaults(prefix);
+
+                       if ($4 > MAX_PrefixLen)
+                       {
+                               flog(LOG_ERR, "invalid prefix length in %s, line %d", conf_file, num_lines);
+                               ABORT;
+                       }
+
+                       prefix->PrefixLen = $4;
+
+                       memcpy(&prefix->Prefix, $2, sizeof(struct in6_addr));
+               }
+               ;
+
+optional_prefixplist: /* empty */
+               | prefixplist 
+               ;
+
+prefixplist    : prefixplist prefixparms
+               | prefixparms
+               ;
+
+prefixparms    : T_AdvOnLink SWITCH ';'
+               {
+                       prefix->AdvOnLinkFlag = $2;
+               }
+               | T_AdvAutonomous SWITCH ';'
+               {
+                       prefix->AdvAutonomousFlag = $2;
+               }
+               | T_AdvRouterAddr SWITCH ';'
+               {
+                       prefix->AdvRouterAddr = $2;
+               }
+               | T_AdvValidLifetime number_or_infinity ';'
+               {
+                       prefix->AdvValidLifetime = $2;
+               }
+               | T_AdvPreferredLifetime number_or_infinity ';'
+               {
+                       prefix->AdvPreferredLifetime = $2;
+               }
+               | T_Base6to4Interface name ';'
+               {
+                       dlog(LOG_DEBUG, 4, "using interface %s for 6to4", $2);
+                       strncpy(prefix->if6to4, $2, IFNAMSIZ-1);
+                       prefix->if6to4[IFNAMSIZ-1] = '\0';
+               }
+               ;
+
+routelist      : routedef
+               {
+                       $$ = $1;
+               }
+               | routelist routedef
+               {
+                       $2->next = $1;
+                       $$ = $2;
+               }
+               ;
+
+routedef       : routehead '{' optional_routeplist '}' ';'
+               {
+                       $$ = route;
+                       route = NULL;
+               }
+               ;
+
+
+routehead      : T_ROUTE IPV6ADDR '/' NUMBER
+               {
+                       route = malloc(sizeof(struct AdvRoute));
+                       
+                       if (route == NULL) {
+                               flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+                               ABORT;
+                       }
+
+                       route_init_defaults(route, iface);
+
+                       if ($4 > MAX_PrefixLen)
+                       {
+                               flog(LOG_ERR, "invalid route prefix length in %s, line %d", conf_file, num_lines);
+                               ABORT;
+                       }
+
+                       route->PrefixLen = $4;
+
+                       memcpy(&route->Prefix, $2, sizeof(struct in6_addr));
+               }
+               ;
+
+
+optional_routeplist: /* empty */
+               | routeplist 
+               ;
+
+routeplist     : routeplist routeparms
+               | routeparms
+               ;
+
+
+routeparms     : T_AdvRoutePreference SIGNEDNUMBER ';'
+               {
+                       route->AdvRoutePreference = $2;
+               }
+               | T_AdvRouteLifetime number_or_infinity ';'
+               {
+                       route->AdvRouteLifetime = $2;
+               }
+               ;
+               
+rdnsslist      : rdnssdef
+               {
+                       $$ = $1;
+               }
+               | rdnsslist rdnssdef
+               {
+                       $2->next = $1;
+                       $$ = $2;
+               }
+               ;
+               
+rdnssdef       : rdnsshead '{' optional_rdnssplist '}' ';'
+               {
+                       $$ = rdnss;
+                       rdnss = NULL;
+               }
+               ;
+
+rdnssaddrs     : rdnssaddrs rdnssaddr
+               | rdnssaddr
+               ;
+
+rdnssaddr      : IPV6ADDR
+               {
+                       if (!rdnss) {
+                               /* first IP found */
+                               rdnss = malloc(sizeof(struct AdvRDNSS));
+                               
+                               if (rdnss == NULL) {
+                                       flog(LOG_CRIT, "malloc failed: %s", strerror(errno));
+                                       ABORT;
+                               }
+
+                               rdnss_init_defaults(rdnss, iface);
+                       }
+                       
+                       switch (rdnss->AdvRDNSSNumber) {
+                               case 0:
+                                       memcpy(&rdnss->AdvRDNSSAddr1, $1, sizeof(struct in6_addr));
+                                       rdnss->AdvRDNSSNumber++;
+                                       break;
+                               case 1:
+                                       memcpy(&rdnss->AdvRDNSSAddr2, $1, sizeof(struct in6_addr));
+                                       rdnss->AdvRDNSSNumber++;
+                                       break;
+                               case 2:
+                                       memcpy(&rdnss->AdvRDNSSAddr3, $1, sizeof(struct in6_addr));
+                                       rdnss->AdvRDNSSNumber++;
+                                       break;
+                               default:
+                                       flog(LOG_CRIT, "Too many addresses in RDNSS section");
+                                       ABORT;
+                       }
+                       
+               }
+               ;
+               
+rdnsshead      : T_RDNSS rdnssaddrs
+               {
+                       if (!rdnss) {
+                               flog(LOG_CRIT, "No address specified in RDNSS section");
+                               ABORT;
+                       }
+               }
+               ;
+               
+optional_rdnssplist: /* empty */
+               | rdnssplist 
+               ;
+               
+rdnssplist     : rdnssplist rdnssparms
+               | rdnssparms
+               ;
+
+
+rdnssparms     : T_AdvRDNSSPreference NUMBER ';'
+               {
+                       rdnss->AdvRDNSSPreference = $2;
+               }
+               | T_AdvRDNSSOpenFlag SWITCH ';'
+               {
+                       rdnss->AdvRDNSSOpenFlag = $2;
+               }
+               | T_AdvRDNSSLifetime number_or_infinity ';'
+               {
+                       if ($2 < iface->MaxRtrAdvInterval && $2 != 0) {
+                               flog(LOG_ERR, "AdvRDNSSLifetime must be at least MaxRtrAdvInterval");
+                               ABORT;
+                       }
+                       if ($2 > 2*(iface->MaxRtrAdvInterval))
+                               flog(LOG_WARNING, "Warning: AdvRDNSSLifetime <= 2*MaxRtrAdvInterval would allow stale DNS servers to be deleted faster");
+
+                       rdnss->AdvRDNSSLifetime = $2;
+               }
+               ;
+
+number_or_infinity      : NUMBER
+                        {
+                                $$ = $1; 
+                        }
+                        | INFINITY
+                        {
+                                $$ = (uint32_t)~0;
+                        }
+                        ;
+
+%%
+
+static
+void cleanup(void)
+{
+       if (iface)
+               free(iface);
+       
+       if (prefix)
+               free(prefix);
+
+       if (route)
+               free(route);
+
+       if (rdnss)
+               free(rdnss);
+}
+
+static void
+yyerror(char *msg)
+{
+       cleanup();
+       flog(LOG_ERR, "%s in %s, line %d: %s", msg, conf_file, num_lines, yytext);
+}
diff --git a/support/sdk/c/blip/driver/radvd-1.0/includes.h b/support/sdk/c/blip/driver/radvd-1.0/includes.h
new file mode 100644 (file)
index 0000000..0bfaa32
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#ifndef INCLUDES_H
+#define INCLUDES_H
+
+#include <config.h>
+
+#include <string.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+#include <time.h>
+#include <syslog.h>
+#include <unistd.h>
+#include <errno.h>
+#include <signal.h>
+#include <netdb.h>
+#include <pwd.h>
+#include <grp.h>
+
+#include <sys/types.h>
+#ifdef HAVE_INTTYPES_H
+# include <inttypes.h>
+#endif
+
+#ifdef HAVE_SYS_PARAM_H
+# include <sys/param.h>
+#else
+# ifdef HAVE_MACHINE_PARAM_H
+#  include <machine/param.h>
+# endif
+# ifdef HAVE_MACHINE_LIMITS_H
+#  include <machine/limits.h>
+# endif
+#endif
+
+#if TIME_WITH_SYS_TIME
+# include <sys/time.h>
+# include <time.h>
+#else
+# if HAVE_SYS_TIME_H
+#  include <sys/time.h>
+# else
+#  include <time.h>
+# endif
+#endif
+
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <sys/uio.h>
+
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#include <netinet/in.h>
+
+#include <netinet/ip6.h>
+#include <netinet/icmp6.h>
+
+#include <arpa/inet.h>
+
+#include <sys/sysctl.h>
+
+#include <net/if.h>
+
+#ifdef HAVE_NET_IF_DL_H
+# include <net/if_dl.h>
+#endif
+#ifdef HAVE_NET_IF_TYPES_H
+# include <net/if_types.h>
+#endif
+#if defined(HAVE_NET_IF_ARP_H) && !defined(ARPHRD_ETHER)
+# include <net/if_arp.h>
+#endif /* defined(HAVE_NET_IF_ARP_H) && !defined(ARPHRD_ETHER) */
+
+#ifdef HAVE_SYS_SOCKIO_H
+# include <sys/sockio.h>
+#endif
+
+#ifdef HAVE_GETOPT_H
+# include <getopt.h>
+#endif
+
+
+#endif /* INCLUDES_H */
diff --git a/support/sdk/c/blip/driver/radvd-1.0/install-sh b/support/sdk/c/blip/driver/radvd-1.0/install-sh
new file mode 100755 (executable)
index 0000000..e9de238
--- /dev/null
@@ -0,0 +1,251 @@
+#!/bin/sh
+#
+# install - install a program, script, or datafile
+# This comes from X11R5 (mit/util/scripts/install.sh).
+#
+# Copyright 1991 by the Massachusetts Institute of Technology
+#
+# Permission to use, copy, modify, distribute, and sell this software and its
+# documentation for any purpose is hereby granted without fee, provided that
+# the above copyright notice appear in all copies and that both that
+# copyright notice and this permission notice appear in supporting
+# documentation, and that the name of M.I.T. not be used in advertising or
+# publicity pertaining to distribution of the software without specific,
+# written prior permission.  M.I.T. makes no representations about the
+# suitability of this software for any purpose.  It is provided "as is"
+# without express or implied warranty.
+#
+# Calling this script install-sh is preferred over install.sh, to prevent
+# `make' implicit rules from creating a file called install from it
+# when there is no Makefile.
+#
+# This script is compatible with the BSD install script, but was written
+# from scratch.  It can only install one file at a time, a restriction
+# shared with many OS's install programs.
+
+
+# set DOITPROG to echo to test this script
+
+# Don't use :- since 4.3BSD and earlier shells don't like it.
+doit="${DOITPROG-}"
+
+
+# put in absolute paths if you don't have them in your path; or use env. vars.
+
+mvprog="${MVPROG-mv}"
+cpprog="${CPPROG-cp}"
+chmodprog="${CHMODPROG-chmod}"
+chownprog="${CHOWNPROG-chown}"
+chgrpprog="${CHGRPPROG-chgrp}"
+stripprog="${STRIPPROG-strip}"
+rmprog="${RMPROG-rm}"
+mkdirprog="${MKDIRPROG-mkdir}"
+
+transformbasename=""
+transform_arg=""
+instcmd="$mvprog"
+chmodcmd="$chmodprog 0755"
+chowncmd=""
+chgrpcmd=""
+stripcmd=""
+rmcmd="$rmprog -f"
+mvcmd="$mvprog"
+src=""
+dst=""
+dir_arg=""
+
+while [ x"$1" != x ]; do
+    case $1 in
+       -c) instcmd="$cpprog"
+           shift
+           continue;;
+
+       -d) dir_arg=true
+           shift
+           continue;;
+
+       -m) chmodcmd="$chmodprog $2"
+           shift
+           shift
+           continue;;
+
+       -o) chowncmd="$chownprog $2"
+           shift
+           shift
+           continue;;
+
+       -g) chgrpcmd="$chgrpprog $2"
+           shift
+           shift
+           continue;;
+
+       -s) stripcmd="$stripprog"
+           shift
+           continue;;
+
+       -t=*) transformarg=`echo $1 | sed 's/-t=//'`
+           shift
+           continue;;
+
+       -b=*) transformbasename=`echo $1 | sed 's/-b=//'`
+           shift
+           continue;;
+
+       *)  if [ x"$src" = x ]
+           then
+               src=$1
+           else
+               # this colon is to work around a 386BSD /bin/sh bug
+               :
+               dst=$1
+           fi
+           shift
+           continue;;
+    esac
+done
+
+if [ x"$src" = x ]
+then
+       echo "install:  no input file specified"
+       exit 1
+else
+       true
+fi
+
+if [ x"$dir_arg" != x ]; then
+       dst=$src
+       src=""
+       
+       if [ -d $dst ]; then
+               instcmd=:
+               chmodcmd=""
+       else
+               instcmd=mkdir
+       fi
+else
+
+# Waiting for this to be detected by the "$instcmd $src $dsttmp" command
+# might cause directories to be created, which would be especially bad 
+# if $src (and thus $dsttmp) contains '*'.
+
+       if [ -f $src -o -d $src ]
+       then
+               true
+       else
+               echo "install:  $src does not exist"
+               exit 1
+       fi
+       
+       if [ x"$dst" = x ]
+       then
+               echo "install:  no destination specified"
+               exit 1
+       else
+               true
+       fi
+
+# If destination is a directory, append the input filename; if your system
+# does not like double slashes in filenames, you may need to add some logic
+
+       if [ -d $dst ]
+       then
+               dst="$dst"/`basename $src`
+       else
+               true
+       fi
+fi
+
+## this sed command emulates the dirname command
+dstdir=`echo $dst | sed -e 's,[^/]*$,,;s,/$,,;s,^$,.,'`
+
+# Make sure that the destination directory exists.
+#  this part is taken from Noah Friedman's mkinstalldirs script
+
+# Skip lots of stat calls in the usual case.
+if [ ! -d "$dstdir" ]; then
+defaultIFS='   
+'
+IFS="${IFS-${defaultIFS}}"
+
+oIFS="${IFS}"
+# Some sh's can't handle IFS=/ for some reason.
+IFS='%'
+set - `echo ${dstdir} | sed -e 's@/@%@g' -e 's@^%@/@'`
+IFS="${oIFS}"
+
+pathcomp=''
+
+while [ $# -ne 0 ] ; do
+       pathcomp="${pathcomp}${1}"
+       shift
+
+       if [ ! -d "${pathcomp}" ] ;
+        then
+               $mkdirprog "${pathcomp}"
+       else
+               true
+       fi
+
+       pathcomp="${pathcomp}/"
+done
+fi
+
+if [ x"$dir_arg" != x ]
+then
+       $doit $instcmd $dst &&
+
+       if [ x"$chowncmd" != x ]; then $doit $chowncmd $dst; else true ; fi &&
+       if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dst; else true ; fi &&
+       if [ x"$stripcmd" != x ]; then $doit $stripcmd $dst; else true ; fi &&
+       if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dst; else true ; fi
+else
+
+# If we're going to rename the final executable, determine the name now.
+
+       if [ x"$transformarg" = x ] 
+       then
+               dstfile=`basename $dst`
+       else
+               dstfile=`basename $dst $transformbasename | 
+                       sed $transformarg`$transformbasename
+       fi
+
+# don't allow the sed command to completely eliminate the filename
+
+       if [ x"$dstfile" = x ] 
+       then
+               dstfile=`basename $dst`
+       else
+               true
+       fi
+
+# Make a temp file name in the proper directory.
+
+       dsttmp=$dstdir/#inst.$$#
+
+# Move or copy the file name to the temp name
+
+       $doit $instcmd $src $dsttmp &&
+
+       trap "rm -f ${dsttmp}" 0 &&
+
+# and set any options; do chmod last to preserve setuid bits
+
+# If any of these fail, we abort the whole thing.  If we want to
+# ignore errors from any of these, just make sure not to ignore
+# errors from the above "$doit $instcmd $src $dsttmp" command.
+
+       if [ x"$chowncmd" != x ]; then $doit $chowncmd $dsttmp; else true;fi &&
+       if [ x"$chgrpcmd" != x ]; then $doit $chgrpcmd $dsttmp; else true;fi &&
+       if [ x"$stripcmd" != x ]; then $doit $stripcmd $dsttmp; else true;fi &&
+       if [ x"$chmodcmd" != x ]; then $doit $chmodcmd $dsttmp; else true;fi &&
+
+# Now rename the file to the real destination.
+
+       $doit $rmcmd -f $dstdir/$dstfile &&
+       $doit $mvcmd $dsttmp $dstdir/$dstfile 
+
+fi &&
+
+
+exit 0
diff --git a/support/sdk/c/blip/driver/radvd-1.0/interface.c b/support/sdk/c/blip/driver/radvd-1.0/interface.c
new file mode 100644 (file)
index 0000000..f1fa79e
--- /dev/null
@@ -0,0 +1,248 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+#include "defaults.h"
+
+void
+iface_init_defaults(struct Interface *iface)
+{
+       memset(iface, 0, sizeof(struct Interface));
+
+       iface->HasFailed          = 0;
+       iface->IgnoreIfMissing    = DFLT_IgnoreIfMissing;
+       iface->AdvSendAdvert      = DFLT_AdvSendAdv;
+       iface->MaxRtrAdvInterval  = DFLT_MaxRtrAdvInterval;
+       iface->AdvSourceLLAddress = DFLT_AdvSourceLLAddress;
+       iface->AdvReachableTime   = DFLT_AdvReachableTime;
+       iface->AdvRetransTimer    = DFLT_AdvRetransTimer;
+       iface->AdvLinkMTU         = DFLT_AdvLinkMTU;
+       iface->AdvCurHopLimit     = DFLT_AdvCurHopLimit;
+       iface->AdvIntervalOpt     = DFLT_AdvIntervalOpt;
+       iface->AdvHomeAgentInfo   = DFLT_AdvHomeAgentInfo;
+       iface->AdvHomeAgentFlag   = DFLT_AdvHomeAgentFlag;
+       iface->HomeAgentPreference = DFLT_HomeAgentPreference;
+       iface->MinDelayBetweenRAs   = DFLT_MinDelayBetweenRAs;
+       iface->AdvMobRtrSupportFlag = DFLT_AdvMobRtrSupportFlag;
+
+       iface->MinRtrAdvInterval = -1;
+       iface->AdvDefaultLifetime = -1;
+       iface->AdvDefaultPreference = DFLT_AdvDefaultPreference;
+       iface->HomeAgentLifetime = -1;
+}
+
+void
+prefix_init_defaults(struct AdvPrefix *prefix)
+{
+       memset(prefix, 0, sizeof(struct AdvPrefix));
+               
+       prefix->AdvOnLinkFlag = DFLT_AdvOnLinkFlag;
+       prefix->AdvAutonomousFlag = DFLT_AdvAutonomousFlag;
+       prefix->AdvRouterAddr = DFLT_AdvRouterAddr;
+       prefix->AdvValidLifetime = DFLT_AdvValidLifetime;
+       prefix->AdvPreferredLifetime = DFLT_AdvPreferredLifetime;
+       prefix->if6to4[0] = 0;
+       prefix->enabled = 1;
+}
+
+void
+route_init_defaults(struct AdvRoute *route, struct Interface *iface)
+{
+       memset(route, 0, sizeof(struct AdvRoute));
+               
+       route->AdvRouteLifetime = DFLT_AdvRouteLifetime(iface);
+       route->AdvRoutePreference = DFLT_AdvRoutePreference;
+}
+
+void
+rdnss_init_defaults(struct AdvRDNSS *rdnss, struct Interface *iface)
+{
+       memset(rdnss, 0, sizeof(struct AdvRDNSS));
+               
+       rdnss->AdvRDNSSPreference = DFLT_AdvRDNSSPreference;
+       rdnss->AdvRDNSSOpenFlag = DFLT_AdvRDNSSOpenFlag;
+       rdnss->AdvRDNSSLifetime = DFLT_AdvRDNSSLifetime(iface);
+       rdnss->AdvRDNSSNumber = 0;
+}
+
+int
+check_iface(struct Interface *iface)
+{
+       struct AdvPrefix *prefix;
+       struct AdvRoute *route;
+       int res = 0;
+       int MIPv6 = 0;
+
+       /* Check if we use Mobile IPv6 extensions */
+       if (iface->AdvHomeAgentFlag || iface->AdvHomeAgentInfo ||
+               iface->AdvIntervalOpt)
+       {
+               MIPv6 = 1;
+               flog(LOG_INFO, "using Mobile IPv6 extensions");
+       }
+
+       prefix = iface->AdvPrefixList;  
+       while (!MIPv6 && prefix)
+       {
+               if (prefix->AdvRouterAddr)
+               {
+                       MIPv6 = 1;
+               }
+               prefix = prefix->next;
+       }
+
+       if (iface->MinRtrAdvInterval < 0)
+               iface->MinRtrAdvInterval = DFLT_MinRtrAdvInterval(iface);
+
+       if ((iface->MinRtrAdvInterval < (MIPv6 ? MIN_MinRtrAdvInterval_MIPv6 : MIN_MinRtrAdvInterval)) || 
+                   (iface->MinRtrAdvInterval > MAX_MinRtrAdvInterval(iface)))
+       {
+               flog(LOG_ERR, 
+                       "MinRtrAdvInterval for %s (%.2f) must be at least %.2f but no more than 3/4 of MaxRtrAdvInterval (%.2f)",
+                       iface->Name, iface->MinRtrAdvInterval,
+                       MIPv6 ? MIN_MinRtrAdvInterval_MIPv6 : (int)MIN_MinRtrAdvInterval,
+                       MAX_MinRtrAdvInterval(iface));
+               res = -1;
+       }
+
+       if ((iface->MaxRtrAdvInterval < (MIPv6 ? MIN_MaxRtrAdvInterval_MIPv6 : MIN_MaxRtrAdvInterval)) 
+                       || (iface->MaxRtrAdvInterval > MAX_MaxRtrAdvInterval))
+       {
+               flog(LOG_ERR, 
+                       "MaxRtrAdvInterval for %s (%.2f) must be between %.2f and %d",
+                       iface->Name, iface->MaxRtrAdvInterval,
+                       MIPv6 ? MIN_MaxRtrAdvInterval_MIPv6 : (int)MIN_MaxRtrAdvInterval,
+                       MAX_MaxRtrAdvInterval);
+               res = -1;
+       }
+
+       if (iface->MinDelayBetweenRAs < (MIPv6 ? MIN_DELAY_BETWEEN_RAS_MIPv6 : MIN_DELAY_BETWEEN_RAS)) 
+       {
+               flog(LOG_ERR, 
+                       "MinDelayBetweenRAs for %s (%.2f) must be at least %.2f",
+                       iface->Name, iface->MinDelayBetweenRAs,
+                       MIPv6 ? MIN_DELAY_BETWEEN_RAS_MIPv6 : MIN_DELAY_BETWEEN_RAS);
+               res = -1;
+       }
+
+       if ((iface->AdvLinkMTU != 0) &&
+          ((iface->AdvLinkMTU < MIN_AdvLinkMTU) || 
+          (iface->if_maxmtu != -1 && (iface->AdvLinkMTU > iface->if_maxmtu))))
+       {
+               flog(LOG_ERR,  "AdvLinkMTU for %s (%u) must be zero or between %u and %u",
+               iface->Name, iface->AdvLinkMTU, MIN_AdvLinkMTU, iface->if_maxmtu);
+               res = -1;
+       }
+
+       if (iface->AdvReachableTime >  MAX_AdvReachableTime)
+       {
+               flog(LOG_ERR, 
+                       "AdvReachableTime for %s (%u) must not be greater than %u",
+                       iface->Name, iface->AdvReachableTime, MAX_AdvReachableTime);
+               res = -1;
+       }
+
+       if (iface->AdvCurHopLimit > MAX_AdvCurHopLimit)
+       {
+               flog(LOG_ERR, "AdvCurHopLimit for %s (%u) must not be greater than %u",
+                       iface->Name, iface->AdvCurHopLimit, MAX_AdvCurHopLimit);
+               res = -1;
+       }
+
+       if (iface->AdvDefaultLifetime < 0)
+               iface->AdvDefaultLifetime = DFLT_AdvDefaultLifetime(iface);
+
+       if ((iface->AdvDefaultLifetime != 0) &&
+          ((iface->AdvDefaultLifetime > MAX_AdvDefaultLifetime) ||
+           (iface->AdvDefaultLifetime < MIN_AdvDefaultLifetime(iface))))
+       {
+               flog(LOG_ERR, 
+                       "AdvDefaultLifetime for %s (%u) must be zero or between %u and %u",
+                       iface->Name, iface->AdvDefaultLifetime, (int)MIN_AdvDefaultLifetime(iface),
+                       MAX_AdvDefaultLifetime);
+               res = -1;
+       }
+
+       /* Mobile IPv6 ext */
+       if (iface->HomeAgentLifetime < 0)
+               iface->HomeAgentLifetime = DFLT_HomeAgentLifetime(iface);
+
+       /* Mobile IPv6 ext */
+       if (iface->AdvHomeAgentInfo)
+       {
+               if ((iface->HomeAgentLifetime > MAX_HomeAgentLifetime) ||
+                       (iface->HomeAgentLifetime < MIN_HomeAgentLifetime))
+               {
+                       flog(LOG_ERR, 
+                               "HomeAgentLifetime for %s (%u) must be between %u and %u",
+                               iface->Name, iface->HomeAgentLifetime,
+                               MIN_HomeAgentLifetime, MAX_HomeAgentLifetime);
+                       res = -1;
+               }
+       }
+
+       /* Mobile IPv6 ext */
+       if (iface->AdvHomeAgentInfo && !(iface->AdvHomeAgentFlag))
+       {
+               flog(LOG_ERR, 
+                       "AdvHomeAgentFlag for %s must be set with HomeAgentInfo", iface->Name);
+               res = -1;
+       }
+       if (iface->AdvMobRtrSupportFlag && !(iface->AdvHomeAgentInfo))
+       {
+               flog(LOG_ERR, 
+                       "AdvHomeAgentInfo for %s must be set with AdvMobRtrSupportFlag", iface->Name);
+               res = -1;
+       }
+
+       /* XXX: need this? prefix = iface->AdvPrefixList; */
+
+       while (prefix)
+       {
+               if (prefix->PrefixLen > MAX_PrefixLen)
+               {
+                       flog(LOG_ERR, "invalid prefix length (%u) for %s", prefix->PrefixLen, iface->Name);
+                       res = -1;
+               }
+
+               if (prefix->AdvPreferredLifetime > prefix->AdvValidLifetime)
+               {
+                       flog(LOG_ERR, "AdvValidLifetime for %s (%u) must be "
+                               "greater than AdvPreferredLifetime for", 
+                               iface->Name, prefix->AdvValidLifetime);
+                       res = -1;
+               }
+
+               prefix = prefix->next;
+       }
+
+
+       route = iface->AdvRouteList;
+
+       while(route)
+       {
+               if (route->PrefixLen > MAX_PrefixLen)
+               {
+                       flog(LOG_ERR, "invalid route prefix length (%u) for %s", route->PrefixLen, iface->Name);
+                       res = -1;
+               }
+
+               route = route->next;
+       }
+
+       return res;
+}
diff --git a/support/sdk/c/blip/driver/radvd-1.0/log.c b/support/sdk/c/blip/driver/radvd-1.0/log.c
new file mode 100644 (file)
index 0000000..9f33013
--- /dev/null
@@ -0,0 +1,182 @@
+/*
+ *     $Id$
+ *
+ *     Authors:
+ *      Lars Fenneberg         <lf@elemental.net>       
+ *
+ *     This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *     All Rights Reserved.
+ *
+ *     The license which is distributed with this software in the file
+ *     COPYRIGHT applies to this software. If your distribution is missing 
+ *     this file, you may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+
+static int     log_method = L_NONE;
+static char *log_ident;
+static char *log_file;
+static FILE *log_file_fd;
+static int log_facility;
+static int debug_level = 0;
+
+int
+log_open(int method, char *ident, char *log, int facility)
+{
+       log_method = method;
+       log_ident = ident;
+       
+       switch (log_method) {
+               case L_NONE:
+               case L_STDERR:
+                       break;
+               case L_STDERR_SYSLOG:
+                       /* fallthrough */
+               case L_SYSLOG:
+                       if (facility == -1)
+                               log_facility = LOG_DAEMON;
+                       else 
+                               log_facility = facility;
+                               
+                       openlog(log_ident, LOG_PID, log_facility);
+                       break;
+               case L_LOGFILE:
+                       if (!log)
+                       {
+                               fprintf(stderr, "%s: no logfile specified\n", log_ident);
+                               return (-1);                            
+                       }
+                       log_file = log;
+                       if ((log_file_fd = fopen(log_file, "a")) == NULL)
+                       {
+                               fprintf(stderr, "%s: can't open %s: %s\n", log_ident, log_file, strerror(errno));
+                               return (-1);                            
+                       }
+                       break;
+               default:
+                       fprintf(stderr, "%s: unknown logging method: %d\n", log_ident, log_method);
+                       log_method = L_NONE;
+                       return (-1);                            
+       }
+       return 0;
+}
+
+static int
+vlog(int prio, char *format, va_list ap)
+{
+       char tstamp[64], buff[1024];
+       struct tm *tm;
+       time_t current;
+                  
+       switch (log_method) {
+               case L_NONE:
+                       break;
+               case L_SYSLOG:
+                       vsnprintf(buff, sizeof(buff), format, ap);
+                       syslog(prio, "%s", buff);
+                       break;
+               case L_STDERR_SYSLOG:
+                       vsnprintf(buff, sizeof(buff), format, ap);
+                       syslog(prio, "%s", buff);
+                       if (prio > LOG_ERR) /* fall through for messages with high priority */
+                               break;
+               case L_STDERR:
+                       current = time(NULL);
+                       tm = localtime(&current);
+                       (void) strftime(tstamp, sizeof(tstamp), LOG_TIME_FORMAT, tm);
+
+                       fprintf(stderr, "[%s] %s: ", tstamp, log_ident);
+                       vfprintf(stderr, format, ap);
+                       fputs("\n", stderr);
+                       fflush(stderr);
+                       break;
+               case L_LOGFILE:
+                       current = time(NULL);
+                       tm = localtime(&current);
+                       (void) strftime(tstamp, sizeof(tstamp), LOG_TIME_FORMAT, tm);
+
+                       fprintf(log_file_fd, "[%s] %s: ", tstamp, log_ident);
+                       vfprintf(log_file_fd, format, ap);
+                       fputs("\n", log_file_fd);
+                       fflush(log_file_fd);
+                       break;
+               default:
+                       fprintf(stderr, "%s: unknown logging method: %d\n", log_ident, log_method);
+                       log_method = L_NONE;
+                       return (-1);                            
+       }
+       return 0;
+}
+
+void
+dlog(int prio, int level, char *format, ...)
+{
+       va_list ap;
+       int res;
+
+       if (debug_level < level)
+               return;
+       
+       va_start(ap, format);
+       res = vlog(prio, format, ap);
+       va_end(ap);             
+
+       /* XXX: should we do something if res < 0.. */
+}
+
+void
+flog(int prio, char *format, ...)
+{
+       va_list ap;
+       int res;
+
+       va_start(ap, format);
+       res = vlog(prio, format, ap);
+       va_end(ap);             
+
+       /* XXX: should we do something if res < 0.. */
+}
+
+int
+log_close(void)
+{
+       switch (log_method) {
+               case L_NONE:
+               case L_STDERR:
+                       break;
+               case L_SYSLOG:
+                       closelog();
+                       break;
+               case L_LOGFILE:
+                       fclose(log_file_fd);
+                       break;
+               default:
+                       fprintf(stderr, "%s: unknown logging method: %d\n", log_ident, log_method);
+                       log_method = L_NONE;
+                       return (-1);                            
+       }
+       return 0;
+}
+
+int
+log_reopen(void)
+{
+       log_close();
+       return log_open(log_method, log_ident, log_file, log_facility);
+}
+
+void
+set_debuglevel(int level) 
+{
+       debug_level = level;
+}
+
+int
+get_debuglevel(void) 
+{
+       return debug_level;
+}
diff --git a/support/sdk/c/blip/driver/radvd-1.0/missing b/support/sdk/c/blip/driver/radvd-1.0/missing
new file mode 100755 (executable)
index 0000000..fc54c64
--- /dev/null
@@ -0,0 +1,336 @@
+#! /bin/sh
+# Common stub for a few missing GNU programs while installing.
+# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003 Free Software Foundation, Inc.
+# Originally by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2, or (at your option)
+# any later version.
+
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+# 02111-1307, USA.
+
+# As a special exception to the GNU General Public License, if you
+# distribute this file as part of a program that contains a
+# configuration script generated by Autoconf, you may include it under
+# the same distribution terms that you use for the rest of that program.
+
+if test $# -eq 0; then
+  echo 1>&2 "Try \`$0 --help' for more information"
+  exit 1
+fi
+
+run=:
+
+# In the cases where this matters, `missing' is being run in the
+# srcdir already.
+if test -f configure.ac; then
+  configure_ac=configure.ac
+else
+  configure_ac=configure.in
+fi
+
+case "$1" in
+--run)
+  # Try to run requested program, and just exit if it succeeds.
+  run=
+  shift
+  "$@" && exit 0
+  ;;
+esac
+
+# If it does not exist, or fails to run (possibly an outdated version),
+# try to emulate it.
+case "$1" in
+
+  -h|--h|--he|--hel|--help)
+    echo "\
+$0 [OPTION]... PROGRAM [ARGUMENT]...
+
+Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an
+error status if there is no known handling for PROGRAM.
+
+Options:
+  -h, --help      display this help and exit
+  -v, --version   output version information and exit
+  --run           try to run the given command, and emulate it if it fails
+
+Supported PROGRAM values:
+  aclocal      touch file \`aclocal.m4'
+  autoconf     touch file \`configure'
+  autoheader   touch file \`config.h.in'
+  automake     touch all \`Makefile.in' files
+  bison        create \`y.tab.[ch]', if possible, from existing .[ch]
+  flex         create \`lex.yy.c', if possible, from existing .c
+  help2man     touch the output file
+  lex          create \`lex.yy.c', if possible, from existing .c
+  makeinfo     touch the output file
+  tar          try tar, gnutar, gtar, then tar without non-portable flags
+  yacc         create \`y.tab.[ch]', if possible, from existing .[ch]"
+    ;;
+
+  -v|--v|--ve|--ver|--vers|--versi|--versio|--version)
+    echo "missing 0.4 - GNU automake"
+    ;;
+
+  -*)
+    echo 1>&2 "$0: Unknown \`$1' option"
+    echo 1>&2 "Try \`$0 --help' for more information"
+    exit 1
+    ;;
+
+  aclocal*)
+    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+       # We have it, but it failed.
+       exit 1
+    fi
+
+    echo 1>&2 "\
+WARNING: \`$1' is missing on your system.  You should only need it if
+         you modified \`acinclude.m4' or \`${configure_ac}'.  You might want
+         to install the \`Automake' and \`Perl' packages.  Grab them from
+         any GNU archive site."
+    touch aclocal.m4
+    ;;
+
+  autoconf)
+    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+       # We have it, but it failed.
+       exit 1
+    fi
+
+    echo 1>&2 "\
+WARNING: \`$1' is missing on your system.  You should only need it if
+         you modified \`${configure_ac}'.  You might want to install the
+         \`Autoconf' and \`GNU m4' packages.  Grab them from any GNU
+         archive site."
+    touch configure
+    ;;
+
+  autoheader)
+    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+       # We have it, but it failed.
+       exit 1
+    fi
+
+    echo 1>&2 "\
+WARNING: \`$1' is missing on your system.  You should only need it if
+         you modified \`acconfig.h' or \`${configure_ac}'.  You might want
+         to install the \`Autoconf' and \`GNU m4' packages.  Grab them
+         from any GNU archive site."
+    files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}`
+    test -z "$files" && files="config.h"
+    touch_files=
+    for f in $files; do
+      case "$f" in
+      *:*) touch_files="$touch_files "`echo "$f" |
+                                      sed -e 's/^[^:]*://' -e 's/:.*//'`;;
+      *) touch_files="$touch_files $f.in";;
+      esac
+    done
+    touch $touch_files
+    ;;
+
+  automake*)
+    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+       # We have it, but it failed.
+       exit 1
+    fi
+
+    echo 1>&2 "\
+WARNING: \`$1' is missing on your system.  You should only need it if
+         you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'.
+         You might want to install the \`Automake' and \`Perl' packages.
+         Grab them from any GNU archive site."
+    find . -type f -name Makefile.am -print |
+          sed 's/\.am$/.in/' |
+          while read f; do touch "$f"; done
+    ;;
+
+  autom4te)
+    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+       # We have it, but it failed.
+       exit 1
+    fi
+
+    echo 1>&2 "\
+WARNING: \`$1' is needed, and you do not seem to have it handy on your
+         system.  You might have modified some files without having the
+         proper tools for further handling them.
+         You can get \`$1' as part of \`Autoconf' from any GNU
+         archive site."
+
+    file=`echo "$*" | sed -n 's/.*--output[ =]*\([^ ]*\).*/\1/p'`
+    test -z "$file" && file=`echo "$*" | sed -n 's/.*-o[ ]*\([^ ]*\).*/\1/p'`
+    if test -f "$file"; then
+       touch $file
+    else
+       test -z "$file" || exec >$file
+       echo "#! /bin/sh"
+       echo "# Created by GNU Automake missing as a replacement of"
+       echo "#  $ $@"
+       echo "exit 0"
+       chmod +x $file
+       exit 1
+    fi
+    ;;
+
+  bison|yacc)
+    echo 1>&2 "\
+WARNING: \`$1' is missing on your system.  You should only need it if
+         you modified a \`.y' file.  You may need the \`Bison' package
+         in order for those modifications to take effect.  You can get
+         \`Bison' from any GNU archive site."
+    rm -f y.tab.c y.tab.h
+    if [ $# -ne 1 ]; then
+        eval LASTARG="\${$#}"
+       case "$LASTARG" in
+       *.y)
+           SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'`
+           if [ -f "$SRCFILE" ]; then
+                cp "$SRCFILE" y.tab.c
+           fi
+           SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'`
+           if [ -f "$SRCFILE" ]; then
+                cp "$SRCFILE" y.tab.h
+           fi
+         ;;
+       esac
+    fi
+    if [ ! -f y.tab.h ]; then
+       echo >y.tab.h
+    fi
+    if [ ! -f y.tab.c ]; then
+       echo 'main() { return 0; }' >y.tab.c
+    fi
+    ;;
+
+  lex|flex)
+    echo 1>&2 "\
+WARNING: \`$1' is missing on your system.  You should only need it if
+         you modified a \`.l' file.  You may need the \`Flex' package
+         in order for those modifications to take effect.  You can get
+         \`Flex' from any GNU archive site."
+    rm -f lex.yy.c
+    if [ $# -ne 1 ]; then
+        eval LASTARG="\${$#}"
+       case "$LASTARG" in
+       *.l)
+           SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'`
+           if [ -f "$SRCFILE" ]; then
+                cp "$SRCFILE" lex.yy.c
+           fi
+         ;;
+       esac
+    fi
+    if [ ! -f lex.yy.c ]; then
+       echo 'main() { return 0; }' >lex.yy.c
+    fi
+    ;;
+
+  help2man)
+    if test -z "$run" && ($1 --version) > /dev/null 2>&1; then
+       # We have it, but it failed.
+       exit 1
+    fi
+
+    echo 1>&2 "\
+WARNING: \`$1' is missing on your system.  You should only need it if
+        you modified a dependency of a manual page.  You may need the
+        \`Help2man' package in order for those modifications to take
+        effect.  You can get \`Help2man' from any GNU archive site."
+
+    file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
+    if test -z "$file"; then
+       file=`echo "$*" | sed -n 's/.*--output=\([^ ]*\).*/\1/p'`
+    fi
+    if [ -f "$file" ]; then
+       touch $file
+    else
+       test -z "$file" || exec >$file
+       echo ".ab help2man is required to generate this page"
+       exit 1
+    fi
+    ;;
+
+  makeinfo)
+    if test -z "$run" && (makeinfo --version) > /dev/null 2>&1; then
+       # We have makeinfo, but it failed.
+       exit 1
+    fi
+
+    echo 1>&2 "\
+WARNING: \`$1' is missing on your system.  You should only need it if
+         you modified a \`.texi' or \`.texinfo' file, or any other file
+         indirectly affecting the aspect of the manual.  The spurious
+         call might also be the consequence of using a buggy \`make' (AIX,
+         DU, IRIX).  You might want to install the \`Texinfo' package or
+         the \`GNU make' package.  Grab either from any GNU archive site."
+    file=`echo "$*" | sed -n 's/.*-o \([^ ]*\).*/\1/p'`
+    if test -z "$file"; then
+      file=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'`
+      file=`sed -n '/^@setfilename/ { s/.* \([^ ]*\) *$/\1/; p; q; }' $file`
+    fi
+    touch $file
+    ;;
+
+  tar)
+    shift
+    if test -n "$run"; then
+      echo 1>&2 "ERROR: \`tar' requires --run"
+      exit 1
+    fi
+
+    # We have already tried tar in the generic part.
+    # Look for gnutar/gtar before invocation to avoid ugly error
+    # messages.
+    if (gnutar --version > /dev/null 2>&1); then
+       gnutar "$@" && exit 0
+    fi
+    if (gtar --version > /dev/null 2>&1); then
+       gtar "$@" && exit 0
+    fi
+    firstarg="$1"
+    if shift; then
+       case "$firstarg" in
+       *o*)
+           firstarg=`echo "$firstarg" | sed s/o//`
+           tar "$firstarg" "$@" && exit 0
+           ;;
+       esac
+       case "$firstarg" in
+       *h*)
+           firstarg=`echo "$firstarg" | sed s/h//`
+           tar "$firstarg" "$@" && exit 0
+           ;;
+       esac
+    fi
+
+    echo 1>&2 "\
+WARNING: I can't seem to be able to run \`tar' with the given arguments.
+         You may want to install GNU tar or Free paxutils, or check the
+         command line arguments."
+    exit 1
+    ;;
+
+  *)
+    echo 1>&2 "\
+WARNING: \`$1' is needed, and you do not seem to have it handy on your
+         system.  You might have modified some files without having the
+         proper tools for further handling them.  Check the \`README' file,
+         it often tells you about the needed prerequisites for installing
+         this package.  You may also peek at any GNU archive site, in case
+         some other package would contain this missing \`$1' program."
+    exit 1
+    ;;
+esac
+
+exit 0
diff --git a/support/sdk/c/blip/driver/radvd-1.0/mkinstalldirs b/support/sdk/c/blip/driver/radvd-1.0/mkinstalldirs
new file mode 100755 (executable)
index 0000000..6b3b5fc
--- /dev/null
@@ -0,0 +1,40 @@
+#! /bin/sh
+# mkinstalldirs --- make directory hierarchy
+# Author: Noah Friedman <friedman@prep.ai.mit.edu>
+# Created: 1993-05-16
+# Public domain
+
+# $Id$
+
+errstatus=0
+
+for file
+do
+   set fnord `echo ":$file" | sed -ne 's/^:\//#/;s/^://;s/\// /g;s/^#/\//;p'`
+   shift
+
+   pathcomp=
+   for d
+   do
+     pathcomp="$pathcomp$d"
+     case "$pathcomp" in
+       -* ) pathcomp=./$pathcomp ;;
+     esac
+
+     if test ! -d "$pathcomp"; then
+        echo "mkdir $pathcomp"
+
+        mkdir "$pathcomp" || lasterr=$?
+
+        if test ! -d "$pathcomp"; then
+         errstatus=$lasterr
+        fi
+     fi
+
+     pathcomp="$pathcomp/"
+   done
+done
+
+exit $errstatus
+
+# mkinstalldirs ends here
diff --git a/support/sdk/c/blip/driver/radvd-1.0/pathnames.h b/support/sdk/c/blip/driver/radvd-1.0/pathnames.h
new file mode 100644 (file)
index 0000000..c061455
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#ifndef PATHNAMES_H
+#define PATHNAMES_H
+
+#ifndef PATH_RADVD_CONF
+#define PATH_RADVD_CONF "/etc/radvd.conf"
+#endif
+
+#ifndef PATH_RADVD_PID
+#define PATH_RADVD_PID "/var/run/radvd.pid"
+#endif
+
+#ifndef PATH_RADVD_LOG
+#define PATH_RADVD_LOG "/var/log/radvd.log"
+#endif
+
+#define PATH_PROC_NET_IF_INET6 "/proc/net/if_inet6"
+#define PATH_PROC_NET_IGMP6 "/proc/net/igmp6"
+
+#ifdef __linux__
+#define SYSCTL_IP6_FORWARDING CTL_NET, NET_IPV6, NET_IPV6_CONF, NET_PROTO_CONF_ALL, NET_IPV6_FORWARDING
+#define PROC_SYS_IP6_FORWARDING "/proc/sys/net/ipv6/conf/all/forwarding"
+#define PROC_SYS_IP6_LINKMTU "/proc/sys/net/ipv6/conf/%s/mtu"
+#define PROC_SYS_IP6_CURHLIM "/proc/sys/net/ipv6/conf/%s/hop_limit"
+#define PROC_SYS_IP6_BASEREACHTIME_MS "/proc/sys/net/ipv6/neigh/%s/base_reachable_time_ms"
+#define PROC_SYS_IP6_BASEREACHTIME "/proc/sys/net/ipv6/neigh/%s/base_reachable_time"
+#define PROC_SYS_IP6_RETRANSTIMER_MS "/proc/sys/net/ipv6/neigh/%s/retrans_time_ms"
+#define PROC_SYS_IP6_RETRANSTIMER "/proc/sys/net/ipv6/neigh/%s/retrans_time"
+#else /* BSD */
+#define SYSCTL_IP6_FORWARDING CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_FORWARDING
+#endif
+
+#endif
diff --git a/support/sdk/c/blip/driver/radvd-1.0/process.c b/support/sdk/c/blip/driver/radvd-1.0/process.c
new file mode 100644 (file)
index 0000000..d788ceb
--- /dev/null
@@ -0,0 +1,454 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+
+static void process_rs(int, struct Interface *, unsigned char *msg,
+                      int len, struct sockaddr_in6 *);
+static void process_ra(struct Interface *, unsigned char *msg, int len,
+       struct sockaddr_in6 *);
+static int  addr_match(struct in6_addr *a1, struct in6_addr *a2,
+       int prefixlen);
+
+void
+process(int sock, struct Interface *ifacel, unsigned char *msg, int len, 
+       struct sockaddr_in6 *addr, struct in6_pktinfo *pkt_info, int hoplimit)
+{
+       struct Interface *iface;
+       struct icmp6_hdr *icmph;
+       char addr_str[INET6_ADDRSTRLEN];
+
+       if ( ! pkt_info )
+       {
+               flog(LOG_WARNING, "received packet with no pkt_info!" );
+               return;
+       }
+
+       /*
+        * can this happen?
+        */
+
+       if (len < sizeof(struct icmp6_hdr))
+       {
+               flog(LOG_WARNING, "received icmpv6 packet with invalid length: %d",
+                       len);
+               return;
+       }
+
+       icmph = (struct icmp6_hdr *) msg;
+
+       if (icmph->icmp6_type != ND_ROUTER_SOLICIT &&
+           icmph->icmp6_type != ND_ROUTER_ADVERT)
+       {
+               /*
+                *      We just want to listen to RSs and RAs
+                */
+               
+               flog(LOG_ERR, "icmpv6 filter failed");
+               return;
+       }
+
+       if (icmph->icmp6_type == ND_ROUTER_ADVERT)
+       {
+               if (len < sizeof(struct nd_router_advert)) {
+                       flog(LOG_WARNING, "received icmpv6 RA packet with invalid length: %d",
+                               len);
+                       return;
+               }
+
+               if (!IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
+                       flog(LOG_WARNING, "received icmpv6 RA packet with non-linklocal source address");
+                       return;
+               }
+       }                       
+       
+       if (icmph->icmp6_type == ND_ROUTER_SOLICIT)
+       {
+               if (len < sizeof(struct nd_router_solicit)) {
+                       flog(LOG_WARNING, "received icmpv6 RS packet with invalid length: %d",
+                               len);
+                       return;
+               }
+       }                       
+
+       if (icmph->icmp6_code != 0)
+       {
+               flog(LOG_WARNING, "received icmpv6 RS/RA packet with invalid code: %d",
+                       icmph->icmp6_code);
+               return;
+       }
+       
+       dlog(LOG_DEBUG, 4, "if_index %u", pkt_info->ipi6_ifindex);
+
+       /* get iface by received if_index */
+
+       for (iface = ifacel; iface; iface=iface->next)
+       {
+               if (iface->if_index == pkt_info->ipi6_ifindex)
+               {
+                       break;
+               }
+       }
+
+       if (iface == NULL)
+       {
+               dlog(LOG_DEBUG, 2, "received packet from unknown interface: %d",
+                       pkt_info->ipi6_ifindex);
+               return;
+       }
+       
+       if (hoplimit != 255)
+       {
+               print_addr(&addr->sin6_addr, addr_str);
+               flog(LOG_WARNING, "received RS or RA with invalid hoplimit %d from %s",
+                       hoplimit, addr_str);
+               return;
+       }
+       
+       if (!iface->AdvSendAdvert)
+       {
+               dlog(LOG_DEBUG, 2, "AdvSendAdvert is off for %s", iface->Name);
+               return;
+       }
+
+       dlog(LOG_DEBUG, 4, "found Interface: %s", iface->Name);
+
+       if (icmph->icmp6_type == ND_ROUTER_SOLICIT)
+       {
+               process_rs(sock, iface, msg, len, addr);
+       }
+       else if (icmph->icmp6_type == ND_ROUTER_ADVERT)
+       {
+               process_ra(iface, msg, len, addr);
+       }
+}
+
+static void
+process_rs(int sock, struct Interface *iface, unsigned char *msg, int len,
+       struct sockaddr_in6 *addr)
+{
+       double delay;
+       double next;
+       struct timeval tv;
+       uint8_t *opt_str;
+
+       /* validation */
+       len -= sizeof(struct nd_router_solicit);
+
+       opt_str = (uint8_t *)(msg + sizeof(struct nd_router_solicit));
+
+       while (len > 0)
+       {
+               int optlen;
+
+               if (len < 2)
+               {
+                       flog(LOG_WARNING, "trailing garbage in RS");
+                       return;
+               }
+
+               optlen = (opt_str[1] << 3);
+
+               if (optlen == 0)
+               {
+                       flog(LOG_WARNING, "zero length option in RS");
+                       return;
+               }
+               else if (optlen > len)
+               {
+                       flog(LOG_WARNING, "option length greater than total length in RS");
+                       return;
+               }
+
+               if (*opt_str == ND_OPT_SOURCE_LINKADDR &&
+                   IN6_IS_ADDR_UNSPECIFIED(&addr->sin6_addr)) {
+                       flog(LOG_WARNING, "received icmpv6 RS packet with unspecified source address and there is a lladdr option"); 
+                       return;
+               }
+
+               len -= optlen;
+               opt_str += optlen;
+       }
+
+       gettimeofday(&tv, NULL);
+
+       delay = MAX_RA_DELAY_TIME*rand()/(RAND_MAX+1.0);
+       dlog(LOG_DEBUG, 3, "random mdelay for %s: %.2f", iface->Name, delay);
+       
+       if (iface->UnicastOnly) {
+               mdelay(delay);
+               send_ra(sock, iface, &addr->sin6_addr);
+       }
+       else if ((tv.tv_sec + tv.tv_usec / 1000000.0) - (iface->last_multicast_sec +
+                 iface->last_multicast_usec / 1000000.0) < iface->MinDelayBetweenRAs) {
+               /* last RA was sent only a few moments ago, don't send another immediately */
+               clear_timer(&iface->tm);
+               next = iface->MinDelayBetweenRAs - (tv.tv_sec + tv.tv_usec / 1000000.0) +
+                      (iface->last_multicast_sec + iface->last_multicast_usec / 1000000.0) + delay/1000.0;
+               set_timer(&iface->tm, next);
+       }
+       else {
+               /* no RA sent in a while, send an immediate multicast reply */
+               clear_timer(&iface->tm);
+               send_ra(sock, iface, NULL);
+               
+               next = rand_between(iface->MinRtrAdvInterval, iface->MaxRtrAdvInterval); 
+               set_timer(&iface->tm, next);
+       }
+}
+
+/*
+ * check router advertisements according to RFC 2461, 6.2.7
+ */
+static void
+process_ra(struct Interface *iface, unsigned char *msg, int len, 
+       struct sockaddr_in6 *addr)
+{
+       struct nd_router_advert *radvert;
+       char addr_str[INET6_ADDRSTRLEN];
+       uint8_t *opt_str;
+
+       print_addr(&addr->sin6_addr, addr_str);
+
+       radvert = (struct nd_router_advert *) msg;
+
+       if ((radvert->nd_ra_curhoplimit && iface->AdvCurHopLimit) && 
+          (radvert->nd_ra_curhoplimit != iface->AdvCurHopLimit))
+       {
+               dlog(LOG_WARNING, LOG_INFO, "our AdvCurHopLimit on %s doesn't agree with %s",
+                       iface->Name, addr_str);
+       }
+
+       if ((radvert->nd_ra_flags_reserved & ND_RA_FLAG_MANAGED) && !iface->AdvManagedFlag)
+       {
+               dlog(LOG_WARNING, LOG_INFO, "our AdvManagedFlag on %s doesn't agree with %s",
+                       iface->Name, addr_str);
+       }
+       
+       if ((radvert->nd_ra_flags_reserved & ND_RA_FLAG_OTHER) && !iface->AdvOtherConfigFlag)
+       {
+               dlog(LOG_WARNING, LOG_INFO, "our AdvOtherConfigFlag on %s doesn't agree with %s",
+                       iface->Name, addr_str);
+       }
+
+       /* note: we don't check the default router preference here, because they're likely different */
+
+       if ((radvert->nd_ra_reachable && iface->AdvReachableTime) &&
+          (ntohl(radvert->nd_ra_reachable) != iface->AdvReachableTime))
+       {
+               dlog(LOG_WARNING, LOG_INFO, "our AdvReachableTime on %s doesn't agree with %s",
+                       iface->Name, addr_str);
+       }
+       
+       if ((radvert->nd_ra_retransmit && iface->AdvRetransTimer) &&
+          (ntohl(radvert->nd_ra_retransmit) != iface->AdvRetransTimer))
+       {
+               dlog(LOG_WARNING, LOG_INFO, "our AdvRetransTimer on %s doesn't agree with %s",
+                       iface->Name, addr_str);
+       }
+
+       len -= sizeof(struct nd_router_advert);
+
+       if (len == 0)
+               return;
+               
+       opt_str = (uint8_t *)(msg + sizeof(struct nd_router_advert));
+               
+       while (len > 0)
+       {
+               int optlen;
+               struct nd_opt_prefix_info *pinfo;
+               struct nd_opt_rdnss_info_local *rdnssinfo;
+               struct nd_opt_mtu *mtu;
+               struct AdvPrefix *prefix;
+               struct AdvRDNSS *rdnss;
+               char prefix_str[INET6_ADDRSTRLEN];
+               char rdnss_str[INET6_ADDRSTRLEN];
+               uint32_t preferred, valid, count;
+
+               if (len < 2)
+               {
+                       flog(LOG_ERR, "trailing garbage in RA on %s from %s", 
+                               iface->Name, addr_str);
+                       break;
+               }
+               
+               optlen = (opt_str[1] << 3);
+
+               if (optlen == 0) 
+               {
+                       flog(LOG_ERR, "zero length option in RA on %s from %s",
+                               iface->Name, addr_str);
+                       break;
+               } 
+               else if (optlen > len)
+               {
+                       flog(LOG_ERR, "option length greater than total"
+                               " length in RA on %s from %s",
+                               iface->Name, addr_str);
+                       break;
+               }               
+
+               switch (*opt_str)
+               {
+               case ND_OPT_MTU:
+                       mtu = (struct nd_opt_mtu *)opt_str;
+
+                       if (iface->AdvLinkMTU && (ntohl(mtu->nd_opt_mtu_mtu) != iface->AdvLinkMTU))
+                       {
+                               flog(LOG_WARNING, "our AdvLinkMTU on %s doesn't agree with %s",
+                                       iface->Name, addr_str);
+                       }
+                       break;
+               case ND_OPT_PREFIX_INFORMATION:
+                       pinfo = (struct nd_opt_prefix_info *) opt_str;
+                       preferred = ntohl(pinfo->nd_opt_pi_preferred_time);
+                       valid = ntohl(pinfo->nd_opt_pi_valid_time);
+                       
+                       prefix = iface->AdvPrefixList;
+                       while (prefix)
+                       {
+                               if (prefix->enabled &&
+                                   (prefix->PrefixLen == pinfo->nd_opt_pi_prefix_len) &&
+                                   addr_match(&prefix->Prefix, &pinfo->nd_opt_pi_prefix,
+                                        prefix->PrefixLen))
+                               {
+                                       print_addr(&prefix->Prefix, prefix_str);
+
+                                       if (valid != prefix->AdvValidLifetime)
+                                       {
+                                          dlog(LOG_WARNING, LOG_INFO, "our AdvValidLifetime on"
+                                                " %s for %s doesn't agree with %s",
+                                                iface->Name,
+                                                prefix_str,
+                                                addr_str
+                                                );
+                                       }
+                                       if (preferred != prefix->AdvPreferredLifetime)
+                                       {
+                                          dlog(LOG_WARNING, LOG_INFO, "our AdvPreferredLifetime on"
+                                                " %s for %s doesn't agree with %s",
+                                                iface->Name,
+                                                prefix_str,
+                                                addr_str
+                                                );
+                                       }
+                               }
+
+                               prefix = prefix->next;
+                       }                       
+                       break;
+               case ND_OPT_ROUTE_INFORMATION:
+                       /* not checked: these will very likely vary a lot */
+                       break;
+               case ND_OPT_SOURCE_LINKADDR:
+                       /* not checked */
+                       break;
+               case ND_OPT_TARGET_LINKADDR:
+               case ND_OPT_REDIRECTED_HEADER:
+                       flog(LOG_ERR, "invalid option %d in RA on %s from %s",
+                               (int)*opt_str, iface->Name, addr_str);
+                       break;
+               /* Mobile IPv6 extensions */
+               case ND_OPT_RTR_ADV_INTERVAL:
+               case ND_OPT_HOME_AGENT_INFO:
+                       /* not checked */
+                       break;
+               case ND_OPT_RDNSS_INFORMATION:
+                       rdnssinfo = (struct nd_opt_rdnss_info_local *) opt_str;
+                       count = rdnssinfo->nd_opt_rdnssi_len;
+                       
+                       /* Check the RNDSS addresses received */
+                       switch (count) {
+                               case 7:
+                                       rdnss = iface->AdvRDNSSList;
+                                       if (!check_rdnss_presence(rdnss, &rdnssinfo->nd_opt_rdnssi_addr3 )) {
+                                               /* no match found in iface->AdvRDNSSList */
+                                               print_addr(&rdnssinfo->nd_opt_rdnssi_addr3, rdnss_str);
+                                               flog(LOG_WARNING, "RDNSS address %s received on %s from %s is not advertised by us",
+                                                       rdnss_str, iface->Name, addr_str);
+                                       }
+                                       /* FALLTHROUGH */
+                               case 5:
+                                       rdnss = iface->AdvRDNSSList;
+                                       if (!check_rdnss_presence(rdnss, &rdnssinfo->nd_opt_rdnssi_addr2 )) {
+                                               /* no match found in iface->AdvRDNSSList */
+                                               print_addr(&rdnssinfo->nd_opt_rdnssi_addr2, rdnss_str);
+                                               flog(LOG_WARNING, "RDNSS address %s received on %s from %s is not advertised by us",
+                                                       rdnss_str, iface->Name, addr_str);
+                                       }
+                                       /* FALLTHROUGH */
+                               case 3:
+                                       rdnss = iface->AdvRDNSSList;
+                                       if (!check_rdnss_presence(rdnss, &rdnssinfo->nd_opt_rdnssi_addr1 )) {
+                                               /* no match found in iface->AdvRDNSSList */
+                                               print_addr(&rdnssinfo->nd_opt_rdnssi_addr1, rdnss_str);
+                                               flog(LOG_WARNING, "RDNSS address %s received on %s from %s is not advertised by us",
+                                                       rdnss_str, iface->Name, addr_str);
+                                       }
+                                       
+                                       break;
+                               default:
+                                       flog(LOG_ERR, "invalid len %i in RDNSS option on %s from %s",
+                                                       count, iface->Name, addr_str);
+                       }
+                       
+                       break;  
+               default:
+                       dlog(LOG_DEBUG, 1, "unknown option %d in RA on %s from %s",
+                               (int)*opt_str, iface->Name, addr_str);
+                       break;
+               }
+               
+               len -= optlen;
+               opt_str += optlen;
+       }
+}
+
+static int 
+addr_match(struct in6_addr *a1, struct in6_addr *a2, int prefixlen)
+{
+       unsigned int pdw;
+       unsigned int pbi;
+
+       pdw = prefixlen >> 0x05;  /* num of whole uint32_t in prefix */
+       pbi = prefixlen &  0x1f;  /* num of bits in incomplete uint32_t in prefix */
+
+       if (pdw) 
+       {
+               if (memcmp(a1, a2, pdw << 2))
+                       return 0;
+       }
+
+       if (pbi) 
+       {
+               uint32_t w1, w2;
+               uint32_t mask;
+
+               w1 = *((uint32_t *)a1 + pdw);
+               w2 = *((uint32_t *)a2 + pdw);
+
+               mask = htonl(((uint32_t) 0xffffffff) << (0x20 - pbi));
+
+               if ((w1 ^ w2) & mask)
+                       return 0;
+       }
+
+       return 1;
+}
+
diff --git a/support/sdk/c/blip/driver/radvd-1.0/radvd.8.man b/support/sdk/c/blip/driver/radvd-1.0/radvd.8.man
new file mode 100644 (file)
index 0000000..5fe0e94
--- /dev/null
@@ -0,0 +1,173 @@
+.\"
+.\"   $Id$
+.\"
+.\"   Authors:
+.\"    Lars Fenneberg          <lf@elemental.net>       
+.\"
+.\"   This software is Copyright 1996-2000 by the above mentioned author(s), 
+.\"   All Rights Reserved.
+.\"
+.\"   The license which is distributed with this software in the file COPYRIGHT
+.\"   applies to this software. If your distribution is missing this file, you
+.\"   may request it from <pekkas@netcore.fi>.
+.\"
+.\"
+.\"
+.TH RADVD 8 "29 Mar 2001" "radvd @VERSION@" ""
+.SH NAME
+radvd \- router advertisement daemon for IPv6
+.SH SYNOPSIS
+.B radvd
+.B "[ \-vh ]"
+.BI "[ \-d " debuglevel " ]"
+.BI "[ \-C " configfile " ]"
+.BI "[ \-p " pidfile " ]"
+.BI "[ \-m " logmethod " ]"
+.BI "[ \-l " logfile " ]"
+.BI "[ \-f " facility " ]"
+.BI "[ \-t " chrootdir " ]"
+.BI "[ \-u " username " ]"
+
+.SH DESCRIPTION
+.B radvd
+is the router advertisement daemon for IPv6. It listens to router
+solicitations and sends router advertisements as described in
+"Neighbor Discovery for IP Version 6 (IPv6)" (RFC 2461).
+With these advertisements hosts can automatically configure their
+addresses and some other parameters. They also can choose a default
+router based on these advertisements.
+
+Note that if debugging is not enabled,
+.B radvd
+will not start if IPv6 forwarding is disabled.  IPv6 forwarding can be
+controlled via sysctl(8),
+.B net.ipv6.conf.all.forwarding
+on Linux or
+.B net.inet6.ip6.forwarding
+on BSD.
+
+Similarly, the configuration file must not be writable by others, and if
+non-root operation is requested, not even by self/own group.
+
+.SH OPTIONS
+
+For every one character option there is also a long option, which
+is listed right next to the "short" option name:
+
+.TP
+.BR "\-v" , " \-\-version"
+Displays the version of
+.I radvd
+and then aborts.
+.TP
+.BR "\-h" , " \-\-help"
+Displays a short usage description and then aborts.
+.TP
+.BR "\-d " debuglevel, " \-\-debug " debuglevel
+With this option you turn on debugging information. The debugging level is
+an integer in the range from 1 to 5, from  quiet to very verbose. A
+debugging level of 0 completely turns off debugging. If a debugging level 
+greater than 0 is used,
+.I radvd
+doesn't background itself on start. The default debugging level is 0.
+.TP
+.BR "\-C " configfile, " \-\-config " configfile
+Specifies an alternate config file. Normally the compiled in default
+.I @PATH_RADVD_CONF@
+is used.
+.TP
+.BR "\-p " pidfile, " \-\-pidfile " pidfile
+Specifies an alternate pidfile. Normally the compiled in default
+.I @PATH_RADVD_PID@
+is used.
+.TP
+.BR "\-m " method, " \-\-logmethod " method
+Specifies the logging method to use. Possibly values are:
+.RS
+.TP
+.B none
+Completely disables any logging.
+.TP
+.B logfile
+Logs to the logfile which is specified by the
+.I \-l
+option. If no logfile is specified on the command line, then
+a compiled in default is used (see next option).
+.TP
+.B stderr
+Logs to standard error.
+.TP
+.B stderr_syslog
+Logs only the high messages (of at least LOG_ERR priority) to standard
+error, and everything to syslog (default method).
+.TP
+.B syslog
+Logs to syslog.
+.RE
+.PP
+.TP
+.BR "\-l " logfile, " \-\-logfile " logfile
+Specifies the logfile to use when using the logging method
+.IR logfile .
+The default logfile is
+.IR @PATH_RADVD_LOG@ .
+.TP
+.BR "\-f " facility, " \-\-facility " facility
+Specifies the facility (as an integer) when using syslog logging. Default
+is @LOG_FACILITY@.
+.TP
+.BR "\-t " chrootdir, " \-\-chrootdir " chrootdir
+If specified, switches to 
+.I chrootdir
+before doing anything else.  This directory and its
+subdirectories must have been populated first.
+For security reasons,
+.I \-u 
+must always be used when using
+.IR chrootdir .
+
+Note that on Linux
+.I radvd
+requires access to the
+.I /proc
+filesystem,
+so it is more challenging to set up the chroot environment.
+.TP
+.BR "\-u " username, " \-\-username " username
+If specified, drops root privileges and changes user ID to
+.I username
+and group ID to the primary group of
+.IR username .
+This is recommended for security reasons.
+You might also need to use
+.I \-p
+to point to a file in a
+.I username
+-writable directory (e.g. /var/run/radvd/radvd.pid).
+.SH FILES
+
+.nf
+@sbindir@/radvd
+@PATH_RADVD_CONF@
+@PATH_RADVD_PID@
+@PATH_RADVD_LOG@
+.fi
+.SH BUGS
+
+There certainly are some bugs. If you find them or have other
+suggestions please contact Pekka Savola <pekkas@netcore.fi>.
+
+.SH "SEE ALSO"
+
+.BR radvd.conf (5),
+.BR radvdump (8)
+.SH AUTHORS
+
+.nf
+Pedro Roque    <roque@di.fc.ul.pt>     - wrote first version for Linux
+Lars Fenneberg <lf@elemental.net>      - previous maintainer
+Nathan Lutchansky      <lutchann@litech.org>   - previous maintainer
+Pekka Savola   <pekkas@netcore.fi>     - current maintainer
+Craig Metz     <cmetz@inner.net>       - port to NRL's IPv6 code for BSD4.4
+Marko Myllynen <myllynen@lut.fi>       - RFC 2461 update, Mobile IPv6 support
+.fi
diff --git a/support/sdk/c/blip/driver/radvd-1.0/radvd.c b/support/sdk/c/blip/driver/radvd-1.0/radvd.c
new file mode 100644 (file)
index 0000000..9125850
--- /dev/null
@@ -0,0 +1,638 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996-2000 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include <config.h>
+#include <includes.h>
+#include <radvd.h>
+#include <pathnames.h>
+
+struct Interface *IfaceList = NULL;
+
+char usage_str[] =
+       "[-vh] [-d level] [-C config_file] [-m log_method] [-l log_file]\n"
+       "\t[-f facility] [-p pid_file] [-u username] [-t chrootdir]";
+
+#ifdef HAVE_GETOPT_LONG
+struct option prog_opt[] = {
+       {"debug", 1, 0, 'd'},
+       {"config", 1, 0, 'C'},
+       {"pidfile", 1, 0, 'p'},
+       {"logfile", 1, 0, 'l'},
+       {"logmethod", 1, 0, 'm'},
+       {"facility", 1, 0, 'f'},
+       {"username", 1, 0, 'u'},
+       {"chrootdir", 1, 0, 't'},
+       {"version", 0, 0, 'v'},
+       {"help", 0, 0, 'h'},
+       {NULL, 0, 0, 0}
+};
+#endif
+
+extern FILE *yyin;
+
+char *conf_file = NULL;
+char *pname;
+int sock = -1;
+
+volatile int sighup_received = 0;
+volatile int sigterm_received = 0;
+volatile int sigint_received = 0;
+
+void sighup_handler(int sig);
+void sigterm_handler(int sig);
+void sigint_handler(int sig);
+void timer_handler(void *data);
+void config_interface(void);
+void kickoff_adverts(void);
+void stop_adverts(void);
+void version(void);
+void usage(void);
+int drop_root_privileges(const char *);
+int readin_config(char *);
+int check_conffile_perm(const char *, const char *);
+
+int
+main(int argc, char *argv[])
+{
+       unsigned char msg[MSG_SIZE];
+       char pidstr[16];
+       int c, log_method;
+       char *logfile, *pidfile;
+        sigset_t oset, nset;
+       int facility, fd;
+       char *username = NULL;
+       char *chrootdir = NULL;
+#ifdef HAVE_GETOPT_LONG
+       int opt_idx;
+#endif
+
+       pname = ((pname=strrchr(argv[0],'/')) != NULL)?pname+1:argv[0];
+
+       srand((unsigned int)time(NULL));
+
+       log_method = L_STDERR_SYSLOG;
+       logfile = PATH_RADVD_LOG;
+       conf_file = PATH_RADVD_CONF;
+       facility = LOG_FACILITY;
+       pidfile = PATH_RADVD_PID;
+
+       /* parse args */
+#ifdef HAVE_GETOPT_LONG
+       while ((c = getopt_long(argc, argv, "d:C:l:m:p:t:u:vh", prog_opt, &opt_idx)) > 0)
+#else
+       while ((c = getopt(argc, argv, "d:C:l:m:p:t:u:vh")) > 0)
+#endif
+       {
+               switch (c) {
+               case 'C':
+                       conf_file = optarg;
+                       break;
+               case 'd':
+                       set_debuglevel(atoi(optarg));
+                       break;
+               case 'f':
+                       facility = atoi(optarg);
+                       break;
+               case 'l':
+                       logfile = optarg;
+                       break;
+               case 'p':
+                       pidfile = optarg;
+                       break;
+               case 'm':
+                       if (!strcmp(optarg, "syslog"))
+                       {
+                               log_method = L_SYSLOG;
+                       }
+                       else if (!strcmp(optarg, "stderr_syslog"))
+                       {
+                               log_method = L_STDERR_SYSLOG;
+                       }
+                       else if (!strcmp(optarg, "stderr"))
+                       {
+                               log_method = L_STDERR;
+                       }
+                       else if (!strcmp(optarg, "logfile"))
+                       {
+                               log_method = L_LOGFILE;
+                       }
+                       else if (!strcmp(optarg, "none"))
+                       {
+                               log_method = L_NONE;
+                       }
+                       else
+                       {
+                               fprintf(stderr, "%s: unknown log method: %s\n", pname, optarg);
+                               exit(1);
+                       }
+                       break;
+               case 't':
+                       chrootdir = strdup(optarg);
+                       break;
+               case 'u':
+                       username = strdup(optarg);
+                       break;
+               case 'v':
+                       version();
+                       break;
+               case 'h':
+                       usage();
+#ifdef HAVE_GETOPT_LONG
+               case ':':
+                       fprintf(stderr, "%s: option %s: parameter expected\n", pname,
+                               prog_opt[opt_idx].name);
+                       exit(1);
+#endif
+               case '?':
+                       exit(1);
+               }
+       }
+
+       if (chrootdir) {
+               if (!username) {
+                       fprintf(stderr, "Chroot as root is not safe, exiting\n");
+                       exit(1);
+               }
+               
+               if (chroot(chrootdir) == -1) {
+                       perror("chroot");
+                       exit (1);
+               }
+               
+               if (chdir("/") == -1) {
+                       perror("chdir");
+                       exit (1);
+               }
+               /* username will be switched later */
+       }
+       
+       if (log_open(log_method, pname, logfile, facility) < 0)
+               exit(1);
+
+       flog(LOG_INFO, "version %s started", VERSION);
+
+       /* get a raw socket for sending and receiving ICMPv6 messages */
+       sock = open_icmpv6_socket();
+       if (sock < 0)
+               exit(1);
+
+       /* drop root privileges if requested. */
+       if (username) {
+               if (drop_root_privileges(username) < 0)
+                       exit(1);
+       }
+
+       /* check that 'other' cannot write the file
+         * for non-root, also that self/own group can't either
+         */
+       if (check_conffile_perm(username, conf_file) < 0) {
+               if (get_debuglevel() == 0)
+                       exit(1);
+               else
+                       flog(LOG_WARNING, "Insecure file permissions, but continuing anyway");
+       }
+       
+       /* if we know how to do it, check whether forwarding is enabled */
+       if (check_ip6_forwarding()) {
+               if (get_debuglevel() == 0) {
+                       flog(LOG_ERR, "IPv6 forwarding seems to be disabled, exiting");
+                       exit(1);
+               }
+               else
+                       flog(LOG_WARNING, "IPv6 forwarding seems to be disabled, but continuing anyway.");
+       }
+
+       /* parse config file */
+       if (readin_config(conf_file) < 0)
+               exit(1);
+
+       /* FIXME: not atomic if pidfile is on an NFS mounted volume */  
+       if ((fd = open(pidfile, O_CREAT|O_EXCL|O_WRONLY, 0644)) < 0)
+       {
+               flog(LOG_ERR, "another radvd seems to be already running, terminating");
+               exit(1);
+       }
+       
+       /*
+        * okay, config file is read in, socket and stuff is setup, so
+        * lets fork now...
+        */
+
+       if (get_debuglevel() == 0) {
+
+               /* Detach from controlling terminal */
+               if (daemon(0, 0) < 0)
+                       perror("daemon");
+
+               /* close old logfiles, including stderr */
+               log_close();
+               
+               /* reopen logfiles, but don't log to stderr unless explicitly requested */
+               if (log_method == L_STDERR_SYSLOG)
+                       log_method = L_SYSLOG;
+               if (log_open(log_method, pname, logfile, facility) < 0)
+                       exit(1);
+
+       }
+
+       /*
+        *      config signal handlers, also make sure ALRM isn't blocked and raise a warning if so
+        *      (some stupid scripts/pppd appears to do this...)
+        */
+       sigemptyset(&nset);
+       sigaddset(&nset, SIGALRM);
+       sigprocmask(SIG_UNBLOCK, &nset, &oset);
+       if (sigismember(&oset, SIGALRM))
+               flog(LOG_WARNING, "SIGALRM has been unblocked. Your startup environment might be wrong.");
+
+       signal(SIGHUP, sighup_handler);
+       signal(SIGTERM, sigterm_handler);
+       signal(SIGINT, sigint_handler);
+
+       snprintf(pidstr, sizeof(pidstr), "%d\n", getpid());
+       
+       write(fd, pidstr, strlen(pidstr));
+       
+       close(fd);
+
+       config_interface();
+       kickoff_adverts();
+
+       /* enter loop */
+
+       for (;;)
+       {
+               int len, hoplimit;
+               struct sockaddr_in6 rcv_addr;
+               struct in6_pktinfo *pkt_info = NULL;
+               
+               len = recv_rs_ra(sock, msg, &rcv_addr, &pkt_info, &hoplimit);
+               if (len > 0)
+                       process(sock, IfaceList, msg, len, 
+                               &rcv_addr, pkt_info, hoplimit);
+
+               if (sigterm_received || sigint_received) {
+                       stop_adverts();
+                       break;
+               }
+
+               if (sighup_received)
+               {
+                       reload_config();                
+                       sighup_received = 0;
+               }
+       }
+       
+       unlink(pidfile);
+       exit(0);
+}
+
+void
+timer_handler(void *data)
+{
+       struct Interface *iface = (struct Interface *) data;
+       double next;
+
+       dlog(LOG_DEBUG, 4, "timer_handler called for %s", iface->Name);
+
+       send_ra(sock, iface, NULL);
+
+       next = rand_between(iface->MinRtrAdvInterval, iface->MaxRtrAdvInterval); 
+
+       if (iface->init_racount < MAX_INITIAL_RTR_ADVERTISEMENTS)
+       {
+               iface->init_racount++;
+               next = min(MAX_INITIAL_RTR_ADVERT_INTERVAL, next);
+       }
+
+       set_timer(&iface->tm, next);
+}
+
+void
+config_interface(void)
+{
+       struct Interface *iface;
+       for(iface=IfaceList; iface; iface=iface->next)
+       {
+               if (iface->AdvLinkMTU)
+                       set_interface_linkmtu(iface->Name, iface->AdvLinkMTU);
+               if (iface->AdvCurHopLimit)
+                       set_interface_curhlim(iface->Name, iface->AdvCurHopLimit);
+               if (iface->AdvReachableTime)
+                       set_interface_reachtime(iface->Name, iface->AdvReachableTime);
+               if (iface->AdvRetransTimer)
+                       set_interface_retranstimer(iface->Name, iface->AdvRetransTimer);
+       }
+}
+
+void
+kickoff_adverts(void)
+{
+       struct Interface *iface;
+
+       /*
+        *      send initial advertisement and set timers
+        */
+
+       for(iface=IfaceList; iface; iface=iface->next)
+       {
+               if( ! iface->UnicastOnly )
+               {
+                       init_timer(&iface->tm, timer_handler, (void *) iface);
+                       if (iface->AdvSendAdvert)
+                       {
+                               /* send an initial advertisement */
+                               send_ra(sock, iface, NULL);
+
+                               iface->init_racount++;
+
+                               set_timer(&iface->tm,
+                                         min(MAX_INITIAL_RTR_ADVERT_INTERVAL,
+                                             iface->MaxRtrAdvInterval));
+                       }
+               }
+       }
+}
+
+void
+stop_adverts(void)
+{
+       struct Interface *iface;
+
+       /*
+        *      send final RA (a SHOULD in RFC2461 section 6.2.5)
+        */
+
+       for (iface=IfaceList; iface; iface=iface->next) {
+               if( ! iface->UnicastOnly ) {
+                       if (iface->AdvSendAdvert) {
+                               /* send a final advertisement with zero Router Lifetime */
+                               iface->AdvDefaultLifetime = 0;
+                               send_ra(sock, iface, NULL);
+                       }
+               }
+       }
+}
+
+void reload_config(void)
+{
+       struct Interface *iface;
+
+       flog(LOG_INFO, "attempting to reread config file");
+
+       dlog(LOG_DEBUG, 4, "reopening log");
+       if (log_reopen() < 0)
+               exit(1);
+
+       /* disable timers, free interface and prefix structures */
+       for(iface=IfaceList; iface; iface=iface->next)
+       {
+               /* check that iface->tm was set in the first place */
+               if (iface->tm.next && iface->tm.prev)
+               {
+                       dlog(LOG_DEBUG, 4, "disabling timer for %s", iface->Name);
+                       clear_timer(&iface->tm);
+               }
+       }
+
+       iface=IfaceList; 
+       while(iface)
+       {
+               struct Interface *next_iface = iface->next;
+               struct AdvPrefix *prefix;
+               struct AdvRoute *route;
+               struct AdvRDNSS *rdnss;
+
+               dlog(LOG_DEBUG, 4, "freeing interface %s", iface->Name);
+               
+               prefix = iface->AdvPrefixList;
+               while (prefix)
+               {
+                       struct AdvPrefix *next_prefix = prefix->next;
+                       
+                       free(prefix);
+                       prefix = next_prefix;
+               }
+               
+               route = iface->AdvRouteList;
+               while (route)
+               {
+                       struct AdvRoute *next_route = route->next;
+
+                       free(route);
+                       route = next_route;
+               }
+               
+               rdnss = iface->AdvRDNSSList;
+               while (rdnss) 
+               {
+                       struct AdvRDNSS *next_rdnss = rdnss->next;
+                       
+                       free(rdnss);
+                       rdnss = next_rdnss;
+               }        
+
+               free(iface);
+               iface = next_iface;
+       }
+
+       IfaceList = NULL;
+
+       /* reread config file */
+       if (readin_config(conf_file) < 0)
+               exit(1);
+
+       config_interface();
+       kickoff_adverts();
+
+       flog(LOG_INFO, "resuming normal operation");
+}
+
+void
+sighup_handler(int sig)
+{
+       /* Linux has "one-shot" signals, reinstall the signal handler */
+       signal(SIGHUP, sighup_handler);
+
+       dlog(LOG_DEBUG, 4, "sighup_handler called");
+
+       sighup_received = 1;
+}
+
+void
+sigterm_handler(int sig)
+{
+       /* Linux has "one-shot" signals, reinstall the signal handler */
+       signal(SIGTERM, sigterm_handler);
+
+       dlog(LOG_DEBUG, 4, "sigterm_handler called");
+
+       sigterm_received = 1;
+}
+
+void
+sigint_handler(int sig)
+{
+       /* Linux has "one-shot" signals, reinstall the signal handler */
+       signal(SIGINT, sigint_handler);
+
+       dlog(LOG_DEBUG, 4, "sigint_handler called");
+
+       sigint_received = 1;
+}
+
+int
+drop_root_privileges(const char *username)
+{
+       struct passwd *pw = NULL;
+       pw = getpwnam(username);
+       if (pw) {
+               if (initgroups(username, pw->pw_gid) != 0 || setgid(pw->pw_gid) != 0 || setuid(pw->pw_uid) != 0) {
+                       flog(LOG_ERR, "Couldn't change to '%.32s' uid=%d gid=%d\n", 
+                                       username, pw->pw_uid, pw->pw_gid);
+                       return (-1);
+               }
+       }
+       else {
+               flog(LOG_ERR, "Couldn't find user '%.32s'\n", username);
+               return (-1);
+       }
+       return 0;
+}
+
+int
+check_conffile_perm(const char *username, const char *conf_file)
+{
+       struct stat *st = NULL;
+       struct passwd *pw = NULL;
+       FILE *fp = fopen(conf_file, "r");
+
+       if (fp == NULL) {
+               flog(LOG_ERR, "can't open %s: %s", conf_file, strerror(errno));
+               return (-1);
+       }
+       fclose(fp);
+
+       st = malloc(sizeof(struct stat));
+       if (st == NULL)
+               goto errorout;
+
+       if (!username)
+               username = "root";
+       
+       pw = getpwnam(username);
+
+       if (stat(conf_file, st) || pw == NULL)
+               goto errorout;
+
+       if (st->st_mode & S_IWOTH) {
+                flog(LOG_ERR, "Insecure file permissions (writable by others): %s", conf_file);
+               goto errorout;
+        }
+
+       /* for non-root: must not be writable by self/own group */
+       if (strncmp(username, "root", 5) != 0 &&
+           ((st->st_mode & S_IWGRP && pw->pw_gid == st->st_gid) ||
+            (st->st_mode & S_IWUSR && pw->pw_uid == st->st_uid))) {
+                flog(LOG_ERR, "Insecure file permissions (writable by self/group): %s", conf_file);
+               goto errorout;
+        }
+
+       free(st);
+        return 0;
+
+errorout:
+       if (st)
+               free(st);
+       return(-1);
+}
+
+int
+check_ip6_forwarding(void)
+{
+       int forw_sysctl[] = { SYSCTL_IP6_FORWARDING };
+       int value;
+       size_t size = sizeof(value);
+       FILE *fp = NULL;
+
+#ifdef __linux__
+       fp = fopen(PROC_SYS_IP6_FORWARDING, "r");
+       if (fp) {
+               fscanf(fp, "%d", &value);
+               fclose(fp);
+       }
+       else
+               flog(LOG_DEBUG, "Correct IPv6 forwarding procfs entry not found, "
+                              "perhaps the procfs is disabled, "
+                               "or the kernel interface has changed?");
+#endif /* __linux__ */
+
+       if (!fp && sysctl(forw_sysctl, sizeof(forw_sysctl)/sizeof(forw_sysctl[0]),
+           &value, &size, NULL, 0) < 0) {
+               flog(LOG_DEBUG, "Correct IPv6 forwarding sysctl branch not found, "
+                       "perhaps the kernel interface has changed?");
+               return(0);      /* this is of advisory value only */
+       }
+       
+       if (value != 1) {
+               flog(LOG_DEBUG, "IPv6 forwarding setting is: %u, should be 1", value);
+               return(-1);
+       }
+               
+       return(0);
+}
+
+int
+readin_config(char *fname)
+{
+       if ((yyin = fopen(fname, "r")) == NULL)
+       {
+               flog(LOG_ERR, "can't open %s: %s", fname, strerror(errno));
+               return (-1);
+       }
+
+       if (yyparse() != 0)
+       {
+               flog(LOG_ERR, "error parsing or activating the config file: %s", fname);
+               return (-1);
+       }
+       
+       fclose(yyin);
+       return 0;
+}
+
+void
+version(void)
+{
+       fprintf(stderr, "Version: %s\n\n", VERSION);
+       fprintf(stderr, "Compiled in settings:\n");
+       fprintf(stderr, "  default config file          \"%s\"\n", PATH_RADVD_CONF);
+       fprintf(stderr, "  default pidfile              \"%s\"\n", PATH_RADVD_PID);
+       fprintf(stderr, "  default logfile              \"%s\"\n", PATH_RADVD_LOG);
+       fprintf(stderr, "  default syslog facililty     %d\n", LOG_FACILITY);
+       fprintf(stderr, "Please send bug reports or suggestions to %s.\n",
+               CONTACT_EMAIL);
+
+       exit(1);        
+}
+
+void
+usage(void)
+{
+       fprintf(stderr, "usage: %s %s\n", pname, usage_str);
+       exit(1);        
+}
+
diff --git a/support/sdk/c/blip/driver/radvd-1.0/radvd.conf.5.man b/support/sdk/c/blip/driver/radvd-1.0/radvd.conf.5.man
new file mode 100644 (file)
index 0000000..8e06194
--- /dev/null
@@ -0,0 +1,591 @@
+.\"
+.\"   $Id$
+.\"
+.\"   Authors:
+.\"    Lars Fenneberg          <lf@elemental.net>
+.\"    Marko Myllynen           <myllynen@lut.fi>       
+.\"
+.\"   This software is Copyright 1996-2000 by the above mentioned author(s), 
+.\"   All Rights Reserved.
+.\"
+.\"   The license which is distributed with this software in the file COPYRIGHT
+.\"   applies to this software. If your distribution is missing this file, you
+.\"   may request it from <pekkas@netcore.fi>.
+.\"
+.\"
+.\"
+.TH RADVD.CONF 5 "20 Aug 2004" "radvd @VERSION@" ""
+.SH NAME
+radvd.conf \- configuration file of the router advertisement daemon
+.B radvd
+.SH DESCRIPTION
+This file describes the information which is included in the router
+advertisement (RA) of a specific interface.
+.P
+The file contains one or more interface definitions of the form:
+
+.nf
+.BR "interface " "name " {
+       list of interface specific options
+       list of prefix definitions
+       list of route definitions
+       list of RDNSS definitions
+.B };
+.fi
+
+All the possible interface specific options are detailed below.  Each
+option has to be terminated by a semicolon.
+
+Prefix definitions are of the form:
+
+.nf
+.BR "prefix " prefix / "length " {
+       list of prefix specific options
+.B };
+.fi
+
+Prefix can be network prefix or the address of the inferface.
+The address of interface should be used when using Mobile IPv6
+extensions.
+
+All the possible prefix specific options are described below.  Each
+option has to be terminated by a semicolon.
+
+Decimal values are allowed only for MinDelayBetweenRAs,
+MaxRtrAdvInterval and MinRtrAdvInterval.  Decimal values should
+be used only when using Mobile IPv6 extensions.
+
+Route definitions are of the form:
+
+.nf
+.BR "route " prefix / "length " {
+       list of route specific options
+.B };
+.fi
+
+The prefix of a route definition should be network prefix; it can be used to
+advertise more specific routes to the hosts.
+
+RDNSS (Recursive DNS server) definitions are of the form:
+
+.nf
+.BR "RDNSS " "ip [ip] [ip] " {
+       list of rdnss specific options
+.B };
+.fi
+
+.SH INTERFACE SPECIFIC OPTIONS
+
+.TP
+.BR IgnoreIfMissing " " on | off
+
+A flag indicating whether or not the interface is ignored
+if it does not exist at start-up.  By default, radvd exits.
+
+This is useful for dynamic interfaces which are not active when radvd
+starts or which are dynamically disabled and re-enabled during the time
+radvd runs.
+
+Current versions of radvd automatically try to re-enable interfaces.
+
+Enabling IgnoreIfMissing also quenches certain warnings in log messages
+relating to missing interfaces.
+
+Default: off
+
+.TP
+.BR AdvSendAdvert " " on | off
+
+A flag indicating whether or not the router sends
+periodic router advertisements and responds to
+router solicitations. 
+
+This option no longer has to be specified first, but it
+needs to be
+.B on
+to enable advertisement on this interface.
+
+Default: off
+
+.TP
+.BR UnicastOnly " " on | off
+
+Indicates that the interface link type only supports unicast.
+This will prevent unsolicited advertisements from being sent, and
+will cause solicited advertisements to be unicast to the
+soliciting node.  This option is necessary for non-broadcast,
+multiple-access links, such as ISATAP.
+
+Default: off
+
+.TP
+.BR "MaxRtrAdvInterval " seconds
+
+The maximum time allowed between sending unsolicited multicast
+router advertisements from the interface, in seconds.
+
+Must be no less than 4 seconds and no greater than 1800 seconds.
+
+Minimum when using Mobile IPv6 extensions: 0.07.
+
+For values less than 0.2 seconds, 0.02 seconds is added to account for
+scheduling granularities as specified in RFC3775.
+
+Default: 600 seconds   
+
+.TP
+.BR "MinRtrAdvInterval " seconds
+
+The minimum time allowed between sending unsolicited multicast
+router advertisements from the interface, in seconds.
+
+Must be no less than 3 seconds and no greater than 0.75 *
+MaxRtrAdvInterval.
+
+Minimum when using Mobile IPv6 extensions: 0.03.
+
+Default: 0.33 * MaxRtrAdvInterval
+
+.TP
+.BR "MinDelayBetweenRAs " seconds
+
+The minimum time allowed between sending multicast
+router advertisements from the interface, in seconds.
+
+This applies to solicited multicast RAs.
+This is defined as the protocol constant MIN_DELAY_BETWEEN_RAS in RFC2461.
+MIPv6 redefines this parameter to have a minimum of 0.03 seconds.
+
+Minimum when using Mobile IPv6 extensions: 0.03.
+
+Default: 3 
+
+.TP
+.BR AdvManagedFlag " " on | off
+
+When set, hosts use the administered (stateful) protocol for address
+autoconfiguration in addition to any addresses autoconfigured using
+stateless address autoconfiguration.  The use of this flag is
+described in RFC 2462.
+
+Default: off
+
+.TP
+.BR AdvOtherConfigFlag " " on | off
+
+When set, hosts use the administered (stateful) protocol for
+autoconfiguration of other (non-address) information.  The use of
+this flag is described in RFC 2462.
+
+Default: off
+
+.TP
+.BR "AdvLinkMTU " integer
+
+The MTU option is used in  router advertisement messages to insure
+that all nodes on a link use the same MTU value in those cases where
+the link MTU is not well known.
+
+If specified, i.e. not 0, must not be smaller than 1280 and not greater
+than the maximum MTU allowed for this link (e.g. ethernet has
+a maximum MTU of 1500. See RFC 2464).
+
+Default: 0
+
+.TP
+.BR "AdvReachableTime " milliseconds
+
+The time, in milliseconds, that a node assumes a neighbor is
+reachable after having received a reachability confirmation.  Used
+by the Neighbor Unreachability Detection algorithm (see Section
+7.3 of RFC 2461).  A value of zero means unspecified (by this router).
+
+Must be no greater than 3,600,000 milliseconds (1 hour).
+
+Default: 0
+
+.TP
+.BR "AdvRetransTimer " milliseconds
+
+The time, in milliseconds, between retransmitted Neighbor
+Solicitation messages.  Used by address resolution and the Neighbor
+Unreachability Detection algorithm (see Sections 7.2 and 7.3 of RFC 2461).
+A value of zero means unspecified (by this router).
+
+Default: 0
+
+.TP
+.BR "AdvCurHopLimit " integer
+
+The default value that should be placed in the Hop Count field of
+the IP header for outgoing (unicast) IP packets.  The value should
+be set to the current diameter of the Internet.  The value zero
+means unspecified (by this router).
+
+Default: 64
+
+.TP
+.BR "AdvDefaultLifetime " seconds
+
+The lifetime associated with the default router in units of seconds. 
+The maximum value corresponds to 18.2 hours.  A lifetime of 0
+indicates that the router is not a default router and should not
+appear on the default router list.  The router lifetime applies only
+to the router's usefulness as a default router; it does not apply to
+information contained in other message fields or options.  Options
+that need time limits for their information include their own
+lifetime fields.
+
+Must be either zero or between MaxRtrAdvInterval and 9000 seconds.
+
+Default: 3 * MaxRtrAdvInterval (Minimum 1 second).
+
+.TP
+.BR AdvDefaultPreference " " low | medium | high
+
+The preference associated with the default router, as either "low",
+"medium", or "high".
+
+Default: medium
+
+.TP
+.BR AdvSourceLLAddress " " on | off
+
+When set, the link-layer address of the outgoing interface is
+included in the RA.
+
+Default: on
+
+.TP
+.BR AdvHomeAgentFlag " " on | off
+
+When set, indicates that sending router is able to serve as Mobile
+IPv6 Home Agent.  When set, minimum limits specified by Mobile IPv6
+are used for MinRtrAdvInterval and MaxRtrAdvInterval.
+
+Default: off
+
+.TP
+.BR AdvHomeAgentInfo " " on | off
+
+When set, Home Agent Information Option (specified by Mobile IPv6)
+is included in Router Advertisements.  AdvHomeAgentFlag must also
+be set when using this option.
+
+Default: off
+
+.TP
+.BR "HomeAgentLifetime " seconds
+
+The length of time in seconds (relative to the time the packet is
+sent) that the router is offering Mobile IPv6 Home Agent services.  
+A value 0 must not be used.  The maximum lifetime is 65520 seconds 
+(18.2 hours).  This option is ignored, if AdvHomeAgentInfo is not
+set.
+
+If both HomeAgentLifetime and HomeAgentPreference are set to their
+default values, Home Agent Information Option will not be sent.
+
+Default: AdvDefaultLifetime
+
+.TP
+.BR "HomeAgentPreference " integer
+
+The preference for the Home Agent sending this Router Advertisement.  
+Values greater than 0 indicate more preferable Home Agent, values
+less than 0 indicate less preferable Home Agent.  This option is
+ignored, if AdvHomeAgentInfo is not set.
+
+If both HomeAgentLifetime and HomeAgentPreference are set to their
+default values, Home Agent Information Option will not be sent.
+
+Default: 0
+
+.TP
+.BR AdvMobRtrSupportFlag " " on | off
+
+When set, the Home Agent signals it supports Mobile Router
+registrations (specified by NEMO Basic).  AdvHomeAgentInfo must also
+be set when using this option.
+
+Default: off
+
+.TP
+.BR AdvIntervalOpt " " on | off
+
+When set, Advertisement Interval Option (specified by Mobile IPv6)
+is included in Router Advertisements.  When set, minimum limits
+specified by Mobile IPv6 are used for MinRtrAdvInterval and
+MaxRtrAdvInterval.
+
+The advertisement interval is based on the configured MaxRtrAdvInterval
+parameter except where this is less than 200ms.  In this case,
+the advertised interval is ( MaxRtrAdvInterval + 20ms ).
+
+Default: off
+
+.SH PREFIX SPECIFIC OPTIONS
+
+.TP
+.BR AdvOnLink " " on | off
+
+When set, indicates that this prefix can be used for on-link
+determination.  When not set the advertisement makes no statement
+about on-link or off-link properties of the prefix.  For instance,
+the prefix might be used for address configuration with some of the
+addresses belonging to the prefix being on-link and others being
+off-link.
+
+Default: on
+
+.TP
+.BR AdvAutonomous " " on | off
+
+When set, indicates that this prefix can be used for autonomous
+address configuration as specified in RFC 2462.
+
+Default: on
+
+.TP
+.BR AdvRouterAddr " " on | off
+
+When set, indicates that the address of interface is sent instead of
+network prefix, as is required by Mobile IPv6.  When set, minimum
+limits specified by Mobile IPv6 are used for MinRtrAdvInterval and
+MaxRtrAdvInterval.
+
+Default: off
+
+.TP
+.BR "AdvValidLifetime " seconds "" | infinity
+
+The length of time in seconds (relative to the time the packet is
+sent) that the prefix is valid for the purpose of on-link
+determination.  The symbolic value
+.B infinity
+represents infinity (i.e. a value of all one bits (0xffffffff)).
+The valid lifetime is also used by RFC 2462.
+
+Default: 2592000 seconds (30 days)
+
+.TP
+.BR "AdvPreferredLifetime " seconds "" | infinity
+
+The length of time in seconds (relative to the time the packet is
+sent) that addresses generated from the prefix via stateless address
+autoconfiguration remain preferred. 
+The symbolic value
+.B infinity
+represents infinity (i.e. a value of all one bits (0xffffffff)).
+See RFC 2462.
+
+Default: 604800 seconds (7 days)
+
+.TP
+.BR "Base6to4Interface " name 
+
+If this option is specified, this prefix will be combined with the
+IPv4 address of interface
+.B name
+to produce a valid 6to4 prefix. The first 16 bits of this prefix
+will be replaced by
+.B 2002
+and the next 32 bits of this prefix will be replaced by the IPv4
+address assigned to interface
+.B name
+at configuration time. The remaining 80 bits of the prefix (including
+the SLA ID) will be advertised as specified in the configuration file.
+See the next section for an example.
+
+If interface
+.B name
+is not available at configuration time, a warning will be written to
+the log and this prefix will be disabled until radvd is reconfigured.
+
+This option enables systems with dynamic IPv4 addresses to update their
+advertised 6to4 prefixes simply by restarting radvd or sending a SIGHUP
+signal to cause radvd to reconfigure itself.
+
+Note that 6to4 prefixes derived from dynamically-assigned IPv4 addresses
+should be advertised with a significantly shorter lifetime (see the
+.B AdvValidLifetime
+and
+.B AdvPreferredLifetime
+options).
+
+For more information on 6to4, see RFC 3056.
+
+Default: 6to4 is not used
+
+.SH ROUTE SPECIFIC OPTIONS
+
+.TP
+.BR "AdvRouteLifetime " seconds "" | infinity
+
+The lifetime associated with the route in units of seconds.
+The symbolic value
+.B infinity
+represents infinity (i.e. a value of all one bits (0xffffffff)).
+
+Default: 3 * MaxRtrAdvInterval
+
+.TP
+.BR AdvRoutePreference " " low | medium | high
+
+The preference associated with the default router, as either "low",
+"medium", or "high".
+
+Default: medium
+
+.SH RDNSS SPECIFIC OPTIONS
+
+.TP
+.BR "AdvRDNSSPreference " integer;
+
+The preference of the DNS server, compared to other DNS servers advertised and used.
+0 to 7 means less important than manually configured nameservers in resolv.conf, while 12 to 15 means more important.
+
+Default: 8
+
+.TP
+.BR "AdvRDNSSOpen " on | off;
+
+"Service Open" flag. When set, indicates that RDNSS continues to be available to hosts even if they moved to a different subnet.
+
+Default: off
+
+.TP
+.BR "AdvRDNSSLifetime " seconds | infinity;
+The maximum duration how long the RDNSS entries are used for name resolution. A value of 0 means the nameserver should no longer be used.
+The maximum duration how long the RDNSS entries are used for name resolution. A value of 0 means the nameserver should no longer be used.
+The value, if not 0, must be at least MaxRtrAdvInterval.  To ensure stale
+RDNSS info gets removed in a timely fashion, this should not be greater than
+2*MaxRtrAdvInterval.
+
+Default: 2*MaxRtrAdvInterval
+
+.SH EXAMPLES
+
+.nf
+interface eth0
+{
+        AdvSendAdvert on;
+        prefix 2001:db8:0:1::/64
+        {
+                AdvOnLink on;
+                AdvAutonomous on;
+        };
+};
+.fi
+
+It says that router advertisement daemon should advertise
+(AdvSendAdvert on;) the prefix 2001:db8:0:1:: which has a lenght of 64
+on the interface eth0.  Also the prefix should be marked as autonomous
+(AdvAutonomous on;) and as on-link (AdvOnLink on;).  All the other
+options are left on their default values.
+
+To support movement detection of Mobile IPv6 Mobile Nodes, the
+address of interface should be used instead of network prefix:
+
+.nf
+interface eth0
+{
+        AdvSendAdvert on;
+        prefix 2001:db8:0:1::4/64
+        {
+                AdvOnLink on;
+                AdvAutonomous on;
+                AdvRouterAddr on;
+        };
+};
+.fi
+
+For 6to4 support, include the
+.B Base6to4Interface
+option in each prefix section. When using a dynamic IPv4 address, set
+small prefix lifetimes to prevent hosts from retaining unreachable
+prefixes after a new IPv4 address has been assigned.  When advertising to on
+a dynamic interface (e.g., Bluetooth), skip the interface if it is not
+active yet.
+
+.nf
+interface bnep0
+{
+        IgnoreIfMissing on;
+        AdvSendAdvert on;
+
+        # Advertise at least every 30 seconds
+        MaxRtrAdvInterval 30;
+
+        prefix 0:0:0:5678::/64
+        {
+                AdvOnLink on;
+                AdvAutonomous on;
+                Base6to4Interface ppp0;
+
+                # Very short lifetimes for dynamic addresses
+                AdvValidLifetime 300;
+                AdvPreferredLifetime 120;
+        };
+};
+.fi
+
+Since 6to4 is enabled, the prefix will be advertised as
+2002:WWXX:YYZZ:5678::/64, where WW.XX.YY.ZZ is the IPv4 address of
+ppp0 at configuration time. (IPv6 addresses are written in hexadecimal
+whereas IPv4 addresses are written in decimal, so the IPv4 address
+WW.XX.YY.ZZ in the 6to4 prefix will be represented in hex.)
+
+In this specific case, the configuration scripts may send HUP signal to
+radvd when taking bnep0 up or down to notify about the status; in the
+current radvd releases, sending HUP is no longer mandatory when the link
+comes back up.
+
+.SH FILES
+
+.nf
+@sbindir@/radvd
+@PATH_RADVD_CONF@
+@PATH_RADVD_PID@
+@PATH_RADVD_LOG@
+.fi
+
+.SH CREDIT
+The description of the different flags and variables is in large
+parts taken from RFC 2461.
+
+.SH RFCS
+Narten, T., E. Nordmark, W. Simpson, "Neighbor Discovery for IP
+Version 6 (IPv6)", RFC 2461, December 1998
+.PP
+Thomson, S., and T. Narten, "IPv6 Stateless Address Autoconfiguration", 
+RFC 2462, December 1998.
+.PP
+Deering, S., and R. Hinden, "IP Version 6 Addressing
+Architecture", RFC 3513, April 2003.
+.PP    
+Conta, A., and S. Deering, "Internet Control Message Protocol (ICMPv6)
+for the Internet Protocol Version 6 (IPv6)", RFC 2463, December 1998.
+.PP
+Crawford, M., "Transmission of IPv6 Packets over Ethernet Networks",
+RFC 2464, December 1998.       
+.PP
+Carpenter B., K. Moore, "Connection of IPv6 Domains via IPv4 Clouds",
+RFC 3056, February 2001. (6to4 specification)
+.PP
+Draves, R., D. Thaler, "Default Router Preferences and More-Specific Routes",
+RFC 4191, November 2005.
+.PP
+Johnson, D., Perkins, C., and J. Arkko, "Mobility Support in IPv6",
+RFC 3775, June 2004.
+.PP
+Devarapalli, V., Wakikawa, R., Petrescu, A., and P. Thubert "Network Mobility (NEMO) Basic Support Protocol",
+RFC 3963, January 2005.
+.PP
+J. Jeong, L. Beloeil, and S. Madanapalli, "IPv6 Router Advertisement Option for DNS Configuration",
+IETF Draft v08 (January 18, 2006).
+
+.SH "SEE ALSO"
+
+.BR radvd (8),
+.BR radvdump (8)
diff --git a/support/sdk/c/blip/driver/radvd-1.0/radvd.conf.example b/support/sdk/c/blip/driver/radvd-1.0/radvd.conf.example
new file mode 100644 (file)
index 0000000..b4bc5b9
--- /dev/null
@@ -0,0 +1,116 @@
+#
+# NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE 
+# NOTE                                                             NOTE
+# NOTE  This is an EXAMPLE, which serves only to demonstrate the   NOTE
+# NOTE  syntax of radvd.conf, and is not meant to be used for a    NOTE
+# NOTE  real radvd configuration.                                  NOTE
+# NOTE                                                             NOTE
+# NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE NOTE 
+#
+
+interface eth0
+{
+       AdvSendAdvert on;
+
+# This may be needed on some interfaces which are not active when
+# radvd starts, but becomoe available later on; see man page for details.
+
+       # IgnoreIfMissing on;
+
+#
+# These settings cause advertisements to be sent every 3-10 seconds.  This
+# range is good for 6to4 with a dynamic IPv4 address, but can be greatly
+# increased when not using 6to4 prefixes.
+#
+
+       MinRtrAdvInterval 3;
+       MaxRtrAdvInterval 10;
+
+#
+# You can use AdvDefaultPreference setting to advertise the preference of
+# the router for the purposes of default router determination.
+# NOTE: This feature is still being specified and is not widely supported!
+#
+       AdvDefaultPreference low;
+
+#
+# Disable Mobile IPv6 support
+#
+       AdvHomeAgentFlag off;
+
+#
+# example of a standard prefix
+#
+       prefix 2001:db8:1:0::/64
+       {
+               AdvOnLink on;
+               AdvAutonomous on;
+               AdvRouterAddr off;
+       };
+
+#
+# example of a 6to4 prefix
+#
+# Note that the first 48 bits are specified here as zeros.  These will be
+# replaced with the appropriate 6to4 address when radvd starts or is
+# reconfigured. Be sure that the SLA ID (1234 in this case) is specified
+# here!
+#
+       prefix 0:0:0:1234::/64
+       {
+               AdvOnLink on;
+               AdvAutonomous on;
+               AdvRouterAddr off;
+
+#
+# This setting causes radvd to replace the first 48 bits of the prefix
+# with the 6to4 address generated from the specified interface.  For example,
+# if the address of ppp0 is 192.0.2.25 when radvd configures itself, this
+# prefix will be advertised as 2002:C000:0219:1234::/64.
+#
+# If ppp0 is not available at configuration time, this prefix will not be
+# advertised, but other prefixes listed in the configuration will be
+# advertised as usual.
+#
+# When using the Base6to4Interface option, make sure radvd receives a
+# SIGHUP every time the ppp0 interface goes up, down, or is assigned a
+# new IPv4 address.  The SIGHUP will cause radvd to recognize that the
+# ppp0 interface has changed and will adjust the advertisements
+# accordingly.
+#
+
+               Base6to4Interface ppp0;
+
+#
+# If the IP address of ppp0 is assigned dynamically, be sure to set the
+# lifetimes for this prefix to be small.  Otherwise, hosts on your network
+# may continue to use a prefix that no longer corresponds to the address
+# on ppp0!
+#
+               AdvPreferredLifetime 120;
+               AdvValidLifetime 300;
+       };
+#
+# example of a more specific route
+# NOTE: This feature is still being specified and is not widely supported!
+#
+       route 2001:db0:fff::/48
+       {
+               AdvRoutePreference high;
+               AdvRouteLifetime 3600;
+       };
+
+#
+# RDNSS
+# NOTE: This feature is still a draft has no IANA number type for the moment
+#
+        RDNSS 2001:db8::1 2001:db8::2
+        {
+                AdvRDNSSPreference 8;
+                AdvRDNSSOpen off;
+                AdvRDNSSLifetime 30;
+        };
+
+
+};
+
diff --git a/support/sdk/c/blip/driver/radvd-1.0/radvd.h b/support/sdk/c/blip/driver/radvd-1.0/radvd.h
new file mode 100644 (file)
index 0000000..8276cef
--- /dev/null
@@ -0,0 +1,225 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#ifndef RADV_H
+#define RADV_H
+
+#include "config.h"
+#include "includes.h"
+#include "defaults.h"
+
+#define CONTACT_EMAIL  "Pekka Savola <pekkas@netcore.fi>"
+
+/* for log.c */
+#define        L_NONE          0
+#define L_SYSLOG       1
+#define L_STDERR       2
+#define L_STDERR_SYSLOG        3
+#define L_LOGFILE      4
+
+#define LOG_TIME_FORMAT "%b %d %H:%M:%S"
+
+struct timer_lst {
+       struct timeval          expires;
+       void                    (*handler)(void *);
+       void *                  data;
+       struct timer_lst        *next;
+       struct timer_lst        *prev;  
+};
+
+#define min(a,b)       (((a) < (b)) ? (a) : (b))
+
+struct AdvPrefix;
+
+#define HWADDR_MAX 16
+
+struct Interface {
+       char                    Name[IFNAMSIZ]; /* interface name */
+
+       struct in6_addr         if_addr;
+       unsigned int            if_index;
+
+       uint8_t                 init_racount;   /* Initial RAs */
+
+       uint8_t                 if_hwaddr[HWADDR_MAX];
+       int                     if_hwaddr_len;
+       int                     if_prefix_len;
+       int                     if_maxmtu;
+
+       int                     IgnoreIfMissing;
+       int                     AdvSendAdvert;
+       double                  MaxRtrAdvInterval;
+       double                  MinRtrAdvInterval;
+       double                  MinDelayBetweenRAs;
+       int                     AdvManagedFlag;
+       int                     AdvOtherConfigFlag;
+       uint32_t                AdvLinkMTU;
+       uint32_t                AdvReachableTime;
+       uint32_t                AdvRetransTimer;
+       uint8_t                 AdvCurHopLimit;
+       int32_t                 AdvDefaultLifetime;   /* XXX: really uint16_t but we need to use -1 */
+       int                     AdvDefaultPreference;
+       int                     AdvSourceLLAddress;
+       int                     UnicastOnly;
+
+       /* Mobile IPv6 extensions */
+       int                     AdvIntervalOpt;
+       int                     AdvHomeAgentInfo;
+       int                     AdvHomeAgentFlag;
+       uint16_t                HomeAgentPreference;
+       int32_t                 HomeAgentLifetime;    /* XXX: really uint16_t but we need to use -1 */
+
+       /* NEMO extensions */
+       int                     AdvMobRtrSupportFlag;
+
+       struct AdvPrefix        *AdvPrefixList;
+       struct AdvRoute         *AdvRouteList;
+       struct AdvRDNSS         *AdvRDNSSList;
+       struct timer_lst        tm;
+       time_t                  last_multicast_sec;
+       suseconds_t             last_multicast_usec;
+
+       /* Info whether this interface has failed in the past (and may need to be reinitialized) */
+       int                     HasFailed;
+
+       struct Interface        *next;
+};
+
+struct AdvPrefix {
+       struct in6_addr         Prefix;
+       uint8_t                 PrefixLen;
+       
+       int                     AdvOnLinkFlag;
+       int                     AdvAutonomousFlag;
+       uint32_t                AdvValidLifetime;
+       uint32_t                AdvPreferredLifetime;
+
+       /* Mobile IPv6 extensions */
+       int                     AdvRouterAddr;
+
+       /* 6to4 extensions */
+       char                    if6to4[IFNAMSIZ];
+       int                     enabled;
+
+       struct AdvPrefix        *next;
+};
+
+/* More-Specific Routes extensions */
+
+struct AdvRoute {
+       struct in6_addr         Prefix;
+       uint8_t                 PrefixLen;
+       
+       int                     AdvRoutePreference;
+       uint32_t                AdvRouteLifetime;
+
+       struct AdvRoute         *next;
+};
+
+/* Option for DNS configuration */
+struct AdvRDNSS {
+       int                     AdvRDNSSNumber;
+       uint8_t                 AdvRDNSSPreference;
+       int                     AdvRDNSSOpenFlag;
+       uint32_t                AdvRDNSSLifetime;
+       struct in6_addr         AdvRDNSSAddr1;
+       struct in6_addr         AdvRDNSSAddr2;
+       struct in6_addr         AdvRDNSSAddr3;
+       
+       struct AdvRDNSS         *next; 
+};
+
+/* Mobile IPv6 extensions */
+
+struct AdvInterval {
+       uint8_t                 type;
+       uint8_t                 length;
+       uint16_t                reserved;
+       uint32_t                adv_ival;
+};
+
+struct HomeAgentInfo {
+       uint8_t                 type;
+       uint8_t                 length;
+       uint16_t                flags_reserved;
+       uint16_t                preference;
+       uint16_t                lifetime;
+};     
+
+
+/* gram.y */
+int yyparse(void);
+
+/* scanner.l */
+int yylex(void);
+
+/* radvd.c */
+int check_ip6_forwarding(void);
+void reload_config(void);
+
+/* timer.c */
+void set_timer(struct timer_lst *tm, double);
+void clear_timer(struct timer_lst *tm);
+void init_timer(struct timer_lst *, void (*)(void *), void *); 
+
+/* log.c */
+int log_open(int, char *, char*, int);
+void flog(int, char *, ...);
+void dlog(int, int, char *, ...);
+int log_close(void);
+int log_reopen(void);
+void set_debuglevel(int);
+int get_debuglevel(void);
+
+/* device.c */
+int setup_deviceinfo(int, struct Interface *);
+int check_device(int, struct Interface *);
+int setup_linklocal_addr(int, struct Interface *);
+int setup_allrouters_membership(int, struct Interface *);
+int check_allrouters_membership(int, struct Interface *);
+int get_v4addr(const char *, unsigned int *);
+int set_interface_linkmtu(const char *, uint32_t);
+int set_interface_curhlim(const char *, uint8_t);
+int set_interface_reachtime(const char *, uint32_t);
+int set_interface_retranstimer(const char *, uint32_t);
+
+/* interface.c */
+void iface_init_defaults(struct Interface *);
+void prefix_init_defaults(struct AdvPrefix *);
+void route_init_defaults(struct AdvRoute *, struct Interface *);
+void rdnss_init_defaults(struct AdvRDNSS *, struct Interface *);
+int check_iface(struct Interface *);
+
+/* socket.c */
+int open_icmpv6_socket(void);
+
+/* send.c */
+void send_ra(int, struct Interface *iface, struct in6_addr *dest);
+
+/* process.c */
+void process(int sock, struct Interface *, unsigned char *, int,
+       struct sockaddr_in6 *, struct in6_pktinfo *, int);
+
+/* recv.c */
+int recv_rs_ra(int, unsigned char *, struct sockaddr_in6 *, struct in6_pktinfo **, int *);
+
+/* util.c */
+void mdelay(double);
+double rand_between(double, double);
+void print_addr(struct in6_addr *, char *);
+int check_rdnss_presence(struct AdvRDNSS *, struct in6_addr *);
+
+#endif
diff --git a/support/sdk/c/blip/driver/radvd-1.0/radvdump.8.man b/support/sdk/c/blip/driver/radvd-1.0/radvdump.8.man
new file mode 100644 (file)
index 0000000..98ee6b8
--- /dev/null
@@ -0,0 +1,87 @@
+.\"
+.\"   $Id$
+.\"
+.\"   Authors:
+.\"    Lars Fenneberg          <lf@elemental.net>       
+.\"    Marko Myllynen          <myllynen@lut.fi>       
+.\"
+.\"   This software is Copyright 1996 by the above mentioned author(s), 
+.\"   All Rights Reserved.
+.\"
+.\"   The license which is distributed with this software in the file COPYRIGHT
+.\"   applies to this software. If your distribution is missing this file, you
+.\"   may request it from <pekkas@netcore.fi>.
+.\"
+.\"
+.\"
+.TH RADVDUMP 8 "29 Dec 2001" "radvd @VERSION@" ""
+.SH NAME
+radvdump \- dump router advertisements
+.SH SYNOPSIS
+.B radvdump
+.B "[ \-vhfe ]"
+.BI "[ \-d " debuglevel " ]"
+
+.SH DESCRIPTION
+.B radvdump
+prints out the contents of incoming router advertisements sent by
+.B radvd
+or some other software implementing (parts of)
+"Neighbor Discovery for IP Version 6 (IPv6)" (RFC 2461).
+
+.SH OPTIONS
+
+For every one character option there is also a long option, which
+is listed right next to the "short" option name:
+
+.TP
+.BR "\-v" , " \-\-version"
+Displays the version of
+.I radvdump
+and then aborts.
+.TP
+.BR "\-h" , " \-\-help"
+Displays a short usage description and then aborts.
+.TP
+.BR "\-f" , " \-\-file\-format"
+Output received router advertisements in the format of the
+.B radvd
+configuration file.
+Since radvd 0.9, this is the default and the switch is provided
+for backward compatibility only.
+.TP
+.BR "\-e" , " \-\-exclude-defaults"
+Exclude default valued options from configuration file format.
+This option is ignored if option
+.B "\-f"
+is not set.
+.TP
+.BR "\-d " debuglevel, " \-\-debug " debuglevel
+With this option you turn on debugging information. The debugging level is
+an integer in the range from 1 to 4, from quiet to very verbose. A
+debugging level of 0 completely turns off debugging.
+
+The default debugging level is 0.
+
+.SH FILES
+
+.nf
+@sbindir@/radvdump
+.fi
+.SH BUGS
+
+There certainly are some bugs. If you find them or have other
+suggestions please contact Pekka Savola <pekkas@netcore.fi>.
+
+.SH "SEE ALSO"
+
+.BR radvd (8),
+.BR radvd.conf (5)
+.SH AUTHORS
+
+.nf
+Lars Fenneberg <lf@elemental.net>      - previous maintainer
+Nathan Lutchansky <lutchann@litech.org> - previous maintainer
+Pekka Savola   <pekkas@netcore.fi>     - current maintainer
+Marko Myllynen <myllynen@lut.fi>       - Mobile IPv6 support
+.fi
diff --git a/support/sdk/c/blip/driver/radvd-1.0/radvdump.c b/support/sdk/c/blip/driver/radvd-1.0/radvdump.c
new file mode 100644 (file)
index 0000000..e4beaf5
--- /dev/null
@@ -0,0 +1,477 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Lars Fenneberg           <lf@elemental.net>
+ *    Marko Myllynen           <myllynen@lut.fi>
+ *
+ *   This software is Copyright 1996-2000 by the above mentioned author(s),
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include <config.h>
+#include <includes.h>
+#include <radvd.h>
+
+char usage_str[] = "[-vhfe] [-d level]";
+
+#ifdef HAVE_GETOPT_LONG
+struct option prog_opt[] = {
+       {"debug", 1, 0, 'd'},
+       {"file-format", 0, 0, 'f'},
+       {"exclude-defaults", 0, 0, 'e'},
+       {"version", 0, 0, 'v'},
+       {"help", 0, 0, 'h'},
+       {NULL, 0, 0, 0}
+};
+#endif
+
+char *pname;
+int sock = -1;
+
+void version(void);
+void usage(void);
+void print_ff(unsigned char *, int, struct sockaddr_in6 *, int, unsigned int, int);
+void print_preferences(int);
+
+int
+main(int argc, char *argv[])
+{
+       unsigned char msg[MSG_SIZE];
+       int c, len, hoplimit;
+       int edefs = 0;
+       struct sockaddr_in6 rcv_addr;
+        struct in6_pktinfo *pkt_info = NULL;
+#ifdef HAVE_GETOPT_LONG
+       int opt_idx;
+#endif
+
+       pname = ((pname=strrchr(argv[0],'/')) != NULL)?pname+1:argv[0];
+
+       /* parse args */
+#ifdef HAVE_GETOPT_LONG
+       while ((c = getopt_long(argc, argv, "d:fehv", prog_opt, &opt_idx)) > 0)
+#else
+       while ((c = getopt(argc, argv, "d:fehv")) > 0)
+#endif
+       {
+               switch (c) {
+               case 'd':
+                       set_debuglevel(atoi(optarg));
+                       break;
+               case 'f':
+                       break;
+               case 'e':
+                       edefs = 1;
+                       break;
+               case 'v':
+                       version();
+                       break;
+               case 'h':
+                       usage();
+#ifdef HAVE_GETOPT_LONG
+               case ':':
+                       fprintf(stderr, "%s: option %s: parameter expected\n", pname,
+                               prog_opt[opt_idx].name);
+                       exit(1);
+#endif
+               case '?':
+                       exit(1);
+               }
+       }
+       
+       if (log_open(L_STDERR, pname, NULL, 0) < 0)
+               exit(1);
+
+       /* get a raw socket for sending and receiving ICMPv6 messages */
+       sock = open_icmpv6_socket();
+       if (sock < 0)
+               exit(1);
+               
+       for(;;)
+       {
+               len = recv_rs_ra(sock, msg, &rcv_addr, &pkt_info, &hoplimit);
+               if (len > 0)
+                       {
+                       struct icmp6_hdr *icmph;
+       
+                       /*
+                        * can this happen?
+                        */
+
+                       if (len < sizeof(struct icmp6_hdr))
+                       {
+                               flog(LOG_WARNING, "received icmpv6 packet with invalid length: %d",
+                                       len);
+                               exit(1);
+                       }
+
+                       icmph = (struct icmp6_hdr *) msg;
+
+                       if (icmph->icmp6_type != ND_ROUTER_SOLICIT &&
+                           icmph->icmp6_type != ND_ROUTER_ADVERT)
+                       {
+                               /*
+                                *      We just want to listen to RSs and RAs
+                                */
+                       
+                               flog(LOG_ERR, "icmpv6 filter failed");
+                               exit(1);
+                       }
+
+                       dlog(LOG_DEBUG, 4, "receiver if_index: %u", pkt_info->ipi6_ifindex);
+
+                       if (icmph->icmp6_type == ND_ROUTER_SOLICIT)
+                       {
+                               /* not yet */   
+                       }
+                       else if (icmph->icmp6_type == ND_ROUTER_ADVERT)
+                               print_ff(msg, len, &rcv_addr, hoplimit, (unsigned int)pkt_info->ipi6_ifindex, edefs);
+               }
+               else if (len == 0)
+                       {
+                               flog(LOG_ERR, "received zero lenght packet");
+                               exit(1);
+               }
+               else
+               {
+                       flog(LOG_ERR, "recv_rs_ra: %s", strerror(errno));
+                       exit(1);
+               }
+        }                                                                                            
+
+       exit(0);
+}
+
+void
+print_ff(unsigned char *msg, int len, struct sockaddr_in6 *addr, int hoplimit, unsigned int if_index, int edefs)
+{
+       /* XXX: hoplimit not being used for anything here.. */
+       struct nd_router_advert *radvert;
+       char addr_str[INET6_ADDRSTRLEN];
+       uint8_t *opt_str;
+       int orig_len = len;
+       char if_name[IFNAMSIZ] = "";
+
+       print_addr(&addr->sin6_addr, addr_str);
+       printf("#\n# radvd configuration generated by radvdump %s\n", VERSION);
+       printf("# based on Router Advertisement from %s\n", addr_str);
+       if_indextoname(if_index, if_name);
+       printf("# received by interface %s\n", if_name);
+       printf("#\n\ninterface %s\n{\n\tAdvSendAdvert on;\n", if_name);
+
+       printf("\t# Note: {Min,Max}RtrAdvInterval cannot be obtained with radvdump\n");
+
+       radvert = (struct nd_router_advert *) msg;
+
+       if (!edefs || DFLT_AdvManagedFlag != (ND_RA_FLAG_MANAGED == (radvert->nd_ra_flags_reserved & ND_RA_FLAG_MANAGED)))
+       printf("\tAdvManagedFlag %s;\n", 
+               (radvert->nd_ra_flags_reserved & ND_RA_FLAG_MANAGED)?"on":"off");
+
+       if (!edefs || DFLT_AdvOtherConfigFlag != (ND_RA_FLAG_OTHER == (radvert->nd_ra_flags_reserved & ND_RA_FLAG_OTHER)))
+       printf("\tAdvOtherConfigFlag %s;\n", 
+               (radvert->nd_ra_flags_reserved & ND_RA_FLAG_OTHER)?"on":"off");
+
+       if (!edefs || DFLT_AdvReachableTime != ntohl(radvert->nd_ra_reachable))
+       printf("\tAdvReachableTime %u;\n", ntohl(radvert->nd_ra_reachable));
+
+       if (!edefs || DFLT_AdvRetransTimer != ntohl(radvert->nd_ra_retransmit))
+       printf("\tAdvRetransTimer %u;\n", ntohl(radvert->nd_ra_retransmit));
+
+       if (!edefs || DFLT_AdvCurHopLimit != radvert->nd_ra_curhoplimit)
+       printf("\tAdvCurHopLimit %u;\n", radvert->nd_ra_curhoplimit);
+
+       /* Mobile IPv6 ext */
+       if (!edefs || DFLT_AdvHomeAgentFlag != (ND_RA_FLAG_HOME_AGENT == (radvert->nd_ra_flags_reserved & ND_RA_FLAG_HOME_AGENT)))
+       printf("\tAdvHomeAgentFlag %s;\n", 
+               (radvert->nd_ra_flags_reserved & ND_RA_FLAG_HOME_AGENT)?"on":"off");
+
+        /* Route Preferences and more specific routes */
+        /* XXX two middlemost bits from 8 bit field */
+       if (!edefs || (((radvert->nd_ra_flags_reserved & 0x18) >> 3) & 0xff) != DFLT_AdvDefaultPreference) {
+               printf("\tAdvDefaultPreference ");
+               print_preferences(((radvert->nd_ra_flags_reserved & 0x18) >> 3) & 0xff);
+               printf(";\n");
+       }
+
+       len -= sizeof(struct nd_router_advert);
+
+       if (len == 0)
+               return;
+               
+       opt_str = (uint8_t *)(msg + sizeof(struct nd_router_advert));
+               
+       while (len > 0)
+       {
+               int optlen;
+               struct nd_opt_mtu *mtu;
+               struct HomeAgentInfo *ha_info;
+
+               if (len < 2)
+               {
+                       flog(LOG_ERR, "trailing garbage in RA from %s", 
+                               addr_str);
+                       break;
+               }
+               
+               optlen = (opt_str[1] << 3);
+
+               if (optlen == 0) 
+               {
+                       flog(LOG_ERR, "zero length option in RA");
+                       break;
+               } 
+               else if (optlen > len)
+               {
+                       flog(LOG_ERR, "option length greater than total"
+                               " length in RA (type %d, optlen %d, len %d)", 
+                               (int)*opt_str, optlen, len);
+                       break;
+               }               
+
+               switch (*opt_str)
+               {
+               case ND_OPT_MTU:
+                       mtu = (struct nd_opt_mtu *)opt_str;
+
+                       if (!edefs || DFLT_AdvLinkMTU != ntohl(mtu->nd_opt_mtu_mtu))
+                       printf("\tAdvLinkMTU %u;\n", ntohl(mtu->nd_opt_mtu_mtu));
+                       break;
+               case ND_OPT_SOURCE_LINKADDR:
+                       /* XXX: !DFLT depends on current DFLT_ value */
+                       if (!edefs || !DFLT_AdvSourceLLAddress)
+                       printf("\tAdvSourceLLAddress on;\n");
+                       break;
+               /* Mobile IPv6 ext */
+               case ND_OPT_RTR_ADV_INTERVAL:
+                       /* XXX: !DFLT depends on current DFLT_ value */
+                       if (!edefs || !DFLT_AdvIntervalOpt)
+                       printf("\tAdvIntervalOpt on;\n");
+                       break;
+               /* Mobile IPv6 ext */
+               case ND_OPT_HOME_AGENT_INFO:
+                       ha_info = (struct HomeAgentInfo *)opt_str;
+
+                       /* XXX: we check DFLT_HomeAgentInfo by interface, and it's outside
+                          of context here, so we always need to print it out.. */
+                       printf("\tAdvHomeAgentInfo on;\n");
+
+                       /* NEMO ext */
+                       if (!edefs || DFLT_AdvMobRtrSupportFlag != (ha_info->flags_reserved & ND_OPT_HAI_FLAG_SUPPORT_MR))
+                               printf("\tAdvMobRtrSupportFlag %s;\n", (ha_info->flags_reserved & ND_OPT_HAI_FLAG_SUPPORT_MR)?"on":"off");
+
+                       if (!edefs || DFLT_HomeAgentPreference != ntohs(ha_info->preference))
+                       printf("\tHomeAgentPreference %hu;\n", ntohs(ha_info->preference));
+                       /* Hum.. */
+                       if (!edefs || (3*DFLT_MaxRtrAdvInterval) != ntohs(ha_info->lifetime))
+                       printf("\tHomeAgentLifetime %hu;\n", ntohs(ha_info->lifetime));
+                       break;
+               case ND_OPT_TARGET_LINKADDR:
+               case ND_OPT_REDIRECTED_HEADER:
+                       flog(LOG_ERR, "invalid option %d in RA", (int)*opt_str);
+                       break;
+               case ND_OPT_PREFIX_INFORMATION:
+                       break;
+               case ND_OPT_ROUTE_INFORMATION:
+                       break;
+               case ND_OPT_RDNSS_INFORMATION:
+                       break;
+               default:
+                       dlog(LOG_DEBUG, 1, "unknown option %d in RA",
+                               (int)*opt_str);
+                       break;
+               }
+               
+               len -= optlen;
+               opt_str += optlen;
+       }
+
+       orig_len -= sizeof(struct nd_router_advert);
+
+       if (orig_len == 0)
+               return;
+
+       opt_str = (uint8_t *)(msg + sizeof(struct nd_router_advert));
+               
+       while (orig_len > 0)
+       {
+               int optlen;
+               struct nd_opt_prefix_info *pinfo;
+               struct nd_opt_route_info_local *rinfo;
+               struct nd_opt_rdnss_info_local *rdnss_info;
+               char prefix_str[INET6_ADDRSTRLEN];
+
+               if (orig_len < 2)
+               {
+                       flog(LOG_ERR, "trailing garbage in RA from %s", 
+                               addr_str);
+                       break;
+               }
+               
+               optlen = (opt_str[1] << 3);
+
+               if (optlen == 0) 
+               {
+                       flog(LOG_ERR, "zero length option in RA");
+                       break;
+               } 
+               else if (optlen > orig_len)
+               {
+                       flog(LOG_ERR, "option length greater than total"
+                               " length in RA (type %d, optlen %d, len %d)", 
+                               (int)*opt_str, optlen, orig_len);
+                       break;
+               }               
+
+               switch (*opt_str)
+               {
+               case ND_OPT_PREFIX_INFORMATION:
+                       pinfo = (struct nd_opt_prefix_info *) opt_str;
+                       
+                       print_addr(&pinfo->nd_opt_pi_prefix, prefix_str);       
+                               
+                       printf("\n\tprefix %s/%d\n\t{\n", prefix_str, pinfo->nd_opt_pi_prefix_len);
+
+                       if (ntohl(pinfo->nd_opt_pi_valid_time) == 0xffffffff)
+                       {               
+                               if (!edefs || DFLT_AdvValidLifetime != 0xffffffff)
+                               printf("\t\tAdvValidLifetime infinity; # (0xffffffff)\n");
+                       }
+                       else
+                       {
+                               if (!edefs || DFLT_AdvValidLifetime != ntohl(pinfo->nd_opt_pi_valid_time))
+                               printf("\t\tAdvValidLifetime %u;\n", ntohl(pinfo->nd_opt_pi_valid_time));
+                       }
+                       if (ntohl(pinfo->nd_opt_pi_preferred_time) == 0xffffffff)
+                       {
+                               if (!edefs || DFLT_AdvPreferredLifetime != 0xffffffff)
+                               printf("\t\tAdvPreferredLifetime infinity; # (0xffffffff)\n");
+                       }
+                       else
+                       {
+                               if (!edefs || DFLT_AdvPreferredLifetime != ntohl(pinfo->nd_opt_pi_preferred_time))
+                               printf("\t\tAdvPreferredLifetime %u;\n", ntohl(pinfo->nd_opt_pi_preferred_time));
+                       }
+
+                       if (!edefs || DFLT_AdvOnLinkFlag != (ND_OPT_PI_FLAG_ONLINK == (pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_ONLINK)))
+                       printf("\t\tAdvOnLink %s;\n", 
+                               (pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_ONLINK)?"on":"off");
+
+                       if (!edefs || DFLT_AdvAutonomousFlag != (ND_OPT_PI_FLAG_AUTO == (pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_AUTO)))
+                       printf("\t\tAdvAutonomous %s;\n", 
+                               (pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_AUTO)?"on":"off");
+
+                       /* Mobile IPv6 ext */
+                       if (!edefs || DFLT_AdvRouterAddr != (ND_OPT_PI_FLAG_RADDR == (pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_RADDR)))
+                       printf("\t\tAdvRouterAddr %s;\n", 
+                               (pinfo->nd_opt_pi_flags_reserved & ND_OPT_PI_FLAG_RADDR)?"on":"off");
+
+                       printf("\t}; # End of prefix definition\n\n");
+                       break;
+               case ND_OPT_ROUTE_INFORMATION:
+                       rinfo = (struct nd_opt_route_info_local *) opt_str;
+                       
+                       print_addr(&rinfo->nd_opt_ri_prefix, prefix_str);       
+                               
+                       printf("\n\troute %s/%d\n\t{\n", prefix_str, rinfo->nd_opt_ri_prefix_len);
+
+                       if (!edefs || (((radvert->nd_ra_flags_reserved & 0x18) >> 3) & 0xff) != DFLT_AdvRoutePreference) {
+                               printf("\t\tAdvRoutePreference ");
+                               print_preferences(((rinfo->nd_opt_ri_flags_reserved & 0x18) >> 3) & 0xff);
+                               printf(";\n");
+                       }
+                       
+                       /* XXX: we check DFLT_AdvRouteLifetime by interface, and it's outside of context here */
+                       if (ntohl(rinfo->nd_opt_ri_lifetime) == 0xffffffff)
+                               printf("\t\tAdvRouteLifetime infinity; # (0xffffffff)\n");
+                       else
+                               printf("\t\tAdvRouteLifetime %u;\n", ntohl(rinfo->nd_opt_ri_lifetime));
+
+                       printf("\t}; # End of route definition\n\n");
+                       break;
+               case ND_OPT_RDNSS_INFORMATION:
+                       rdnss_info = (struct nd_opt_rdnss_info_local *) opt_str;
+
+                       printf("\n\tRDNSS");
+
+                       print_addr(&rdnss_info->nd_opt_rdnssi_addr1, prefix_str);
+                       printf(" %s", prefix_str);
+
+                       if (rdnss_info->nd_opt_rdnssi_len >= 5) {
+                               print_addr(&rdnss_info->nd_opt_rdnssi_addr2, prefix_str);
+                               printf(" %s", prefix_str);
+                       }
+                       if (rdnss_info->nd_opt_rdnssi_len >= 7) {
+                               print_addr(&rdnss_info->nd_opt_rdnssi_addr3, prefix_str);
+                               printf(" %s", prefix_str);
+                       }
+                       
+                       printf("\n\t{\n");
+                       if (!edefs 
+                           || ((rdnss_info->nd_opt_rdnssi_pref_flag_reserved & ND_OPT_RDNSSI_PREF_MASK) >> ND_OPT_RDNSSI_PREF_SHIFT) != DFLT_AdvRDNSSPreference)
+                               printf("\t\tAdvRDNSSPreference %d;\n", 
+                                 (rdnss_info->nd_opt_rdnssi_pref_flag_reserved & ND_OPT_RDNSSI_PREF_MASK) >> ND_OPT_RDNSSI_PREF_SHIFT);
+
+                       if (!edefs 
+                           || ((rdnss_info->nd_opt_rdnssi_pref_flag_reserved & ND_OPT_RDNSSI_FLAG_S) == 0 ) == DFLT_AdvRDNSSOpenFlag)
+                               printf("\t\tAdvRDNSSOpen %s;\n", rdnss_info->nd_opt_rdnssi_pref_flag_reserved & ND_OPT_RDNSSI_FLAG_S ? "on" : "off");
+
+                       /* as AdvRDNSSLifetime may depend on MaxRtrAdvInterval, it could change */
+                       if (ntohl(rdnss_info->nd_opt_rdnssi_lifetime) == 0xffffffff)
+                               printf("\t\tAdvRDNSSLifetime infinity; # (0xffffffff)\n");
+                       else
+                               printf("\t\tAdvRDNSSLifetime %u;\n", ntohl(rdnss_info->nd_opt_rdnssi_lifetime));
+                       
+                       printf("\t}; # End of RDNSS definition\n\n");
+                       break;
+               default:
+                       break;
+               }
+               orig_len -= optlen;
+               opt_str += optlen;
+       }
+
+       printf("}; # End of interface definition\n");
+
+       fflush(stdout);
+}
+
+void
+print_preferences(int p)
+{
+       switch (p) {
+               case 0:
+                       printf("medium");
+                       break;
+               case 1:
+                       printf("high");
+                       break;
+               case 2:
+                       /* reserved, ignore */
+                       break;
+               case 3:
+                       printf("low");
+                       break;
+       }               
+}
+
+void
+version(void)
+{
+       fprintf(stderr,"Version: %s\n\n", VERSION);
+       fprintf(stderr,"Please send bug reports and suggestions to %s\n",
+               CONTACT_EMAIL);
+       exit(1);        
+}
+
+void
+usage(void)
+{
+       fprintf(stderr,"usage: %s %s\n", pname, usage_str);
+       exit(1);        
+}
diff --git a/support/sdk/c/blip/driver/radvd-1.0/recv.c b/support/sdk/c/blip/driver/radvd-1.0/recv.c
new file mode 100644 (file)
index 0000000..18275c6
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+
+int
+recv_rs_ra(int sock, unsigned char *msg, struct sockaddr_in6 *addr,
+                 struct in6_pktinfo **pkt_info, int *hoplimit)
+{                 
+       struct msghdr mhdr;
+       struct cmsghdr *cmsg;
+       struct iovec iov;
+       static unsigned char *chdr = NULL;
+       static unsigned int chdrlen = 0;
+       int len;
+       fd_set rfds;
+
+       if( ! chdr )
+       {
+               chdrlen = CMSG_SPACE(sizeof(struct in6_pktinfo)) +
+                               CMSG_SPACE(sizeof(int));
+               if ((chdr = malloc(chdrlen)) == NULL) {
+                       flog(LOG_ERR, "recv_rs_ra: malloc: %s", strerror(errno));
+                       return -1;
+               }
+       }
+
+       FD_ZERO( &rfds );
+       FD_SET( sock, &rfds );
+
+       if( select( sock+1, &rfds, NULL, NULL, NULL ) < 0 )
+       {
+               if (errno != EINTR)
+                       flog(LOG_ERR, "select: %s", strerror(errno));
+                       
+               return -1;
+       }
+
+       iov.iov_len = MSG_SIZE;
+       iov.iov_base = (caddr_t) msg;
+
+       memset(&mhdr, 0, sizeof(mhdr));
+       mhdr.msg_name = (caddr_t)addr;
+       mhdr.msg_namelen = sizeof(*addr);
+       mhdr.msg_iov = &iov;
+       mhdr.msg_iovlen = 1;
+       mhdr.msg_control = (void *)chdr;
+       mhdr.msg_controllen = chdrlen;
+
+       len = recvmsg(sock, &mhdr, 0);
+
+       if (len < 0)
+       {
+               if (errno != EINTR)
+                       flog(LOG_ERR, "recvmsg: %s", strerror(errno));
+                       
+               return len;
+       }
+
+       *hoplimit = 255;
+
+        for (cmsg = CMSG_FIRSTHDR(&mhdr); cmsg != NULL; cmsg = CMSG_NXTHDR(&mhdr, cmsg))
+       {
+          if (cmsg->cmsg_level != IPPROTO_IPV6)
+               continue;
+          
+          switch(cmsg->cmsg_type)
+          {
+#ifdef IPV6_HOPLIMIT
+              case IPV6_HOPLIMIT:
+                if ((cmsg->cmsg_len == CMSG_LEN(sizeof(int))) && 
+                    (*(int *)CMSG_DATA(cmsg) >= 0) && 
+                    (*(int *)CMSG_DATA(cmsg) < 256))
+                {
+                  *hoplimit = *(int *)CMSG_DATA(cmsg);
+                }
+                else
+                {
+                  flog(LOG_ERR, "received a bogus IPV6_HOPLIMIT from the kernel! len=%d, data=%d",
+                       cmsg->cmsg_len, *(int *)CMSG_DATA(cmsg));
+                  return (-1); 
+                }  
+                break;
+#endif /* IPV6_HOPLIMIT */
+              case IPV6_PKTINFO:
+                if ((cmsg->cmsg_len == CMSG_LEN(sizeof(struct in6_pktinfo))) &&
+                    ((struct in6_pktinfo *)CMSG_DATA(cmsg))->ipi6_ifindex)
+                {
+                  *pkt_info = (struct in6_pktinfo *)CMSG_DATA(cmsg);
+                }
+                else
+                {
+                  flog(LOG_ERR, "received a bogus IPV6_PKTINFO from the kernel! len=%d, index=%d", 
+                       cmsg->cmsg_len, ((struct in6_pktinfo *)CMSG_DATA(cmsg))->ipi6_ifindex);
+                  return (-1);
+                } 
+                break;
+          }
+       }
+       
+       dlog(LOG_DEBUG, 4, "recvmsg len=%d", len);
+
+       return len;
+}
diff --git a/support/sdk/c/blip/driver/radvd-1.0/scanner.c b/support/sdk/c/blip/driver/radvd-1.0/scanner.c
new file mode 100644 (file)
index 0000000..47d6361
--- /dev/null
@@ -0,0 +1,2398 @@
+
+#line 3 "lex.yy.c"
+
+#define  YY_INT_ALIGNED short int
+
+/* A lexical scanner generated by flex */
+
+#define FLEX_SCANNER
+#define YY_FLEX_MAJOR_VERSION 2
+#define YY_FLEX_MINOR_VERSION 5
+#define YY_FLEX_SUBMINOR_VERSION 33
+#if YY_FLEX_SUBMINOR_VERSION > 0
+#define FLEX_BETA
+#endif
+
+/* First, we deal with  platform-specific or compiler-specific issues. */
+
+/* begin standard C headers. */
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <stdlib.h>
+
+/* end standard C headers. */
+
+/* flex integer type definitions */
+
+#ifndef FLEXINT_H
+#define FLEXINT_H
+
+/* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */
+
+#if __STDC_VERSION__ >= 199901L
+
+/* C99 says to define __STDC_LIMIT_MACROS before including stdint.h,
+ * if you want the limit (max/min) macros for int types. 
+ */
+#ifndef __STDC_LIMIT_MACROS
+#define __STDC_LIMIT_MACROS 1
+#endif
+
+#include <inttypes.h>
+typedef int8_t flex_int8_t;
+typedef uint8_t flex_uint8_t;
+typedef int16_t flex_int16_t;
+typedef uint16_t flex_uint16_t;
+typedef int32_t flex_int32_t;
+typedef uint32_t flex_uint32_t;
+#else
+typedef signed char flex_int8_t;
+typedef short int flex_int16_t;
+typedef int flex_int32_t;
+typedef unsigned char flex_uint8_t; 
+typedef unsigned short int flex_uint16_t;
+typedef unsigned int flex_uint32_t;
+#endif /* ! C99 */
+
+/* Limits of integral types. */
+#ifndef INT8_MIN
+#define INT8_MIN               (-128)
+#endif
+#ifndef INT16_MIN
+#define INT16_MIN              (-32767-1)
+#endif
+#ifndef INT32_MIN
+#define INT32_MIN              (-2147483647-1)
+#endif
+#ifndef INT8_MAX
+#define INT8_MAX               (127)
+#endif
+#ifndef INT16_MAX
+#define INT16_MAX              (32767)
+#endif
+#ifndef INT32_MAX
+#define INT32_MAX              (2147483647)
+#endif
+#ifndef UINT8_MAX
+#define UINT8_MAX              (255U)
+#endif
+#ifndef UINT16_MAX
+#define UINT16_MAX             (65535U)
+#endif
+#ifndef UINT32_MAX
+#define UINT32_MAX             (4294967295U)
+#endif
+
+#endif /* ! FLEXINT_H */
+
+#ifdef __cplusplus
+
+/* The "const" storage-class-modifier is valid. */
+#define YY_USE_CONST
+
+#else  /* ! __cplusplus */
+
+#if __STDC__
+
+#define YY_USE_CONST
+
+#endif /* __STDC__ */
+#endif /* ! __cplusplus */
+
+#ifdef YY_USE_CONST
+#define yyconst const
+#else
+#define yyconst
+#endif
+
+/* Returned upon end-of-file. */
+#define YY_NULL 0
+
+/* Promotes a possibly negative, possibly signed char to an unsigned
+ * integer for use as an array index.  If the signed char is negative,
+ * we want to instead treat it as an 8-bit unsigned char, hence the
+ * double cast.
+ */
+#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)
+
+/* Enter a start condition.  This macro really ought to take a parameter,
+ * but we do it the disgusting crufty way forced on us by the ()-less
+ * definition of BEGIN.
+ */
+#define BEGIN (yy_start) = 1 + 2 *
+
+/* Translate the current start state into a value that can be later handed
+ * to BEGIN to return to the state.  The YYSTATE alias is for lex
+ * compatibility.
+ */
+#define YY_START (((yy_start) - 1) / 2)
+#define YYSTATE YY_START
+
+/* Action number for EOF rule of a given start state. */
+#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1)
+
+/* Special action meaning "start processing a new file". */
+#define YY_NEW_FILE yyrestart(yyin  )
+
+#define YY_END_OF_BUFFER_CHAR 0
+
+/* Size of default input buffer. */
+#ifndef YY_BUF_SIZE
+#define YY_BUF_SIZE 16384
+#endif
+
+/* The state buf must be large enough to hold one state per character in the main buffer.
+ */
+#define YY_STATE_BUF_SIZE   ((YY_BUF_SIZE + 2) * sizeof(yy_state_type))
+
+#ifndef YY_TYPEDEF_YY_BUFFER_STATE
+#define YY_TYPEDEF_YY_BUFFER_STATE
+typedef struct yy_buffer_state *YY_BUFFER_STATE;
+#endif
+
+extern int yyleng;
+
+extern FILE *yyin, *yyout;
+
+#define EOB_ACT_CONTINUE_SCAN 0
+#define EOB_ACT_END_OF_FILE 1
+#define EOB_ACT_LAST_MATCH 2
+
+    #define YY_LESS_LINENO(n)
+    
+/* Return all but the first "n" matched characters back to the input stream. */
+#define yyless(n) \
+       do \
+               { \
+               /* Undo effects of setting up yytext. */ \
+        int yyless_macro_arg = (n); \
+        YY_LESS_LINENO(yyless_macro_arg);\
+               *yy_cp = (yy_hold_char); \
+               YY_RESTORE_YY_MORE_OFFSET \
+               (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \
+               YY_DO_BEFORE_ACTION; /* set up yytext again */ \
+               } \
+       while ( 0 )
+
+#define unput(c) yyunput( c, (yytext_ptr)  )
+
+/* The following is because we cannot portably get our hands on size_t
+ * (without autoconf's help, which isn't available because we want
+ * flex-generated scanners to compile on their own).
+ */
+
+#ifndef YY_TYPEDEF_YY_SIZE_T
+#define YY_TYPEDEF_YY_SIZE_T
+typedef unsigned int yy_size_t;
+#endif
+
+#ifndef YY_STRUCT_YY_BUFFER_STATE
+#define YY_STRUCT_YY_BUFFER_STATE
+struct yy_buffer_state
+       {
+       FILE *yy_input_file;
+
+       char *yy_ch_buf;                /* input buffer */
+       char *yy_buf_pos;               /* current position in input buffer */
+
+       /* Size of input buffer in bytes, not including room for EOB
+        * characters.
+        */
+       yy_size_t yy_buf_size;
+
+       /* Number of characters read into yy_ch_buf, not including EOB
+        * characters.
+        */
+       int yy_n_chars;
+
+       /* Whether we "own" the buffer - i.e., we know we created it,
+        * and can realloc() it to grow it, and should free() it to
+        * delete it.
+        */
+       int yy_is_our_buffer;
+
+       /* Whether this is an "interactive" input source; if so, and
+        * if we're using stdio for input, then we want to use getc()
+        * instead of fread(), to make sure we stop fetching input after
+        * each newline.
+        */
+       int yy_is_interactive;
+
+       /* Whether we're considered to be at the beginning of a line.
+        * If so, '^' rules will be active on the next match, otherwise
+        * not.
+        */
+       int yy_at_bol;
+
+    int yy_bs_lineno; /**< The line count. */
+    int yy_bs_column; /**< The column count. */
+    
+       /* Whether to try to fill the input buffer when we reach the
+        * end of it.
+        */
+       int yy_fill_buffer;
+
+       int yy_buffer_status;
+
+#define YY_BUFFER_NEW 0
+#define YY_BUFFER_NORMAL 1
+       /* When an EOF's been seen but there's still some text to process
+        * then we mark the buffer as YY_EOF_PENDING, to indicate that we
+        * shouldn't try reading from the input source any more.  We might
+        * still have a bunch of tokens to match, though, because of
+        * possible backing-up.
+        *
+        * When we actually see the EOF, we change the status to "new"
+        * (via yyrestart()), so that the user can continue scanning by
+        * just pointing yyin at a new input file.
+        */
+#define YY_BUFFER_EOF_PENDING 2
+
+       };
+#endif /* !YY_STRUCT_YY_BUFFER_STATE */
+
+/* Stack of input buffers. */
+static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */
+static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */
+static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */
+
+/* We provide macros for accessing buffer states in case in the
+ * future we want to put the buffer states in a more general
+ * "scanner state".
+ *
+ * Returns the top of the stack, or NULL.
+ */
+#define YY_CURRENT_BUFFER ( (yy_buffer_stack) \
+                          ? (yy_buffer_stack)[(yy_buffer_stack_top)] \
+                          : NULL)
+
+/* Same as previous macro, but useful when we know that the buffer stack is not
+ * NULL or when we need an lvalue. For internal use only.
+ */
+#define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)]
+
+/* yy_hold_char holds the character lost when yytext is formed. */
+static char yy_hold_char;
+static int yy_n_chars;         /* number of characters read into yy_ch_buf */
+int yyleng;
+
+/* Points to current character in buffer. */
+static char *yy_c_buf_p = (char *) 0;
+static int yy_init = 0;                /* whether we need to initialize */
+static int yy_start = 0;       /* start state number */
+
+/* Flag which is used to allow yywrap()'s to do buffer switches
+ * instead of setting up a fresh yyin.  A bit of a hack ...
+ */
+static int yy_did_buffer_switch_on_eof;
+
+void yyrestart (FILE *input_file  );
+void yy_switch_to_buffer (YY_BUFFER_STATE new_buffer  );
+YY_BUFFER_STATE yy_create_buffer (FILE *file,int size  );
+void yy_delete_buffer (YY_BUFFER_STATE b  );
+void yy_flush_buffer (YY_BUFFER_STATE b  );
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer  );
+void yypop_buffer_state (void );
+
+static void yyensure_buffer_stack (void );
+static void yy_load_buffer_state (void );
+static void yy_init_buffer (YY_BUFFER_STATE b,FILE *file  );
+
+#define YY_FLUSH_BUFFER yy_flush_buffer(YY_CURRENT_BUFFER )
+
+YY_BUFFER_STATE yy_scan_buffer (char *base,yy_size_t size  );
+YY_BUFFER_STATE yy_scan_string (yyconst char *yy_str  );
+YY_BUFFER_STATE yy_scan_bytes (yyconst char *bytes,int len  );
+
+void *yyalloc (yy_size_t  );
+void *yyrealloc (void *,yy_size_t  );
+void yyfree (void *  );
+
+#define yy_new_buffer yy_create_buffer
+
+#define yy_set_interactive(is_interactive) \
+       { \
+       if ( ! YY_CURRENT_BUFFER ){ \
+        yyensure_buffer_stack (); \
+               YY_CURRENT_BUFFER_LVALUE =    \
+            yy_create_buffer(yyin,YY_BUF_SIZE ); \
+       } \
+       YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \
+       }
+
+#define yy_set_bol(at_bol) \
+       { \
+       if ( ! YY_CURRENT_BUFFER ){\
+        yyensure_buffer_stack (); \
+               YY_CURRENT_BUFFER_LVALUE =    \
+            yy_create_buffer(yyin,YY_BUF_SIZE ); \
+       } \
+       YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \
+       }
+
+#define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol)
+
+/* Begin user sect3 */
+
+typedef unsigned char YY_CHAR;
+
+FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0;
+
+typedef int yy_state_type;
+
+extern int yylineno;
+
+int yylineno = 1;
+
+extern char *yytext;
+#define yytext_ptr yytext
+
+static yy_state_type yy_get_previous_state (void );
+static yy_state_type yy_try_NUL_trans (yy_state_type current_state  );
+static int yy_get_next_buffer (void );
+static void yy_fatal_error (yyconst char msg[]  );
+
+/* Done after the current pattern has been matched and before the
+ * corresponding action - sets up yytext.
+ */
+#define YY_DO_BEFORE_ACTION \
+       (yytext_ptr) = yy_bp; \
+       yyleng = (size_t) (yy_cp - yy_bp); \
+       (yy_hold_char) = *yy_cp; \
+       *yy_cp = '\0'; \
+       (yy_c_buf_p) = yy_cp;
+
+#define YY_NUM_RULES 53
+#define YY_END_OF_BUFFER 54
+/* This struct is not used in this scanner,
+   but its presence is necessary. */
+struct yy_trans_info
+       {
+       flex_int32_t yy_verify;
+       flex_int32_t yy_nxt;
+       };
+static yyconst flex_int16_t yy_accept[514] =
+    {   0,
+        0,    0,   54,   52,    3,    2,   52,   52,   51,   41,
+       52,   52,   52,   52,   52,   52,   52,   52,   52,   50,
+       50,   50,   50,   50,   50,   50,   50,   50,    3,    0,
+        1,   42,    0,   41,    0,    0,   40,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,   50,    0,   50,   50,
+       50,   50,   50,   50,   45,   50,   50,   43,   41,    0,
+        0,   40,    0,    0,    0,    0,    0,    0,    0,    0,
+       50,   50,   50,   50,   50,   50,   47,   50,   46,   50,
+       50,   41,    0,    0,    0,   40,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+
+        0,    0,    0,    0,    0,    0,   50,   50,   49,   50,
+       50,   50,   50,   50,   41,    0,    0,   40,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    7,    0,   50,   50,   50,   50,   50,    6,
+        0,    0,    0,   40,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,   50,
+       50,   50,   48,    5,    0,    0,   40,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,   50,   50,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,   44,   50,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,   21,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    4,    0,    0,    0,    0,
+        0,    0,    0,    0,   14,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,   29,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,   36,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,   22,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,   25,
+        9,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+
+        0,    0,    0,   17,    0,    0,    0,    0,   27,   12,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,   40,
+        0,    0,    0,    0,    0,    0,    0,    0,    0,    0,
+       16,    0,    0,    0,    0,    0,    0,    0,    8,    0,
+        0,    0,    0,   40,    0,    0,    0,   26,   28,    0,
+        0,    0,   37,    0,   15,   34,    0,    0,   23,    0,
+        0,    0,    0,    0,    0,   40,    0,    0,    0,    0,
+        0,    0,    0,    0,    0,   30,   32,    0,   10,    0,
+       11,   40,    0,   18,    0,    0,   13,    0,   35,   33,
+
+       20,    0,   38,    0,    0,    0,    0,   31,    0,   19,
+       39,   24,    0
+    } ;
+
+static yyconst flex_int32_t yy_ec[256] =
+    {   0,
+        1,    1,    1,    1,    1,    1,    1,    1,    2,    3,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    2,    1,    1,    4,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    5,    6,    7,    8,    8,    8,
+        8,    9,    8,   10,    8,    8,    8,   11,   12,    1,
+        1,    1,    1,    1,   13,   14,   15,   16,   17,   18,
+        1,   19,   20,    1,    1,   21,   22,   23,   24,   25,
+        1,   26,   27,   28,   29,   30,    1,    1,    1,    1,
+        1,    1,    1,    1,   31,    1,   32,   33,   34,   35,
+
+       36,   37,   38,   39,   40,   41,   42,   43,   44,   45,
+       46,   47,   41,   48,   49,   50,   51,   52,   53,   54,
+       55,   41,   56,    1,   57,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1
+    } ;
+
+static yyconst flex_int32_t yy_meta[58] =
+    {   0,
+        1,    1,    1,    1,    1,    2,    1,    3,    3,    3,
+        4,    1,    5,    5,    5,    5,    5,    5,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        6,    3,    3,    3,    3,    3,    3,    6,    6,    6,
+        6,    6,    6,    6,    6,    6,    6,    6,    6,    6,
+        6,    6,    6,    6,    6,    1,    1
+    } ;
+
+static yyconst flex_int16_t yy_base[555] =
+    {   0,
+        0,    0,  884,  885,  881,  885,  879,   50,  885,   55,
+      870,   56,   62,   63,  834,  841,   38,  862,  832,   89,
+       65,   69,   66,   73,   76,  139,  104,  102,  874,  872,
+      885,   80,  108,  145,  863,   75,  885,  151,  152,  829,
+      827,  817,  825,  846,  828,  151,  196,  156,   90,  162,
+      171,  163,  164,  180,  172,  179,  183,  171,  187,  181,
+      856,    0,  222,  830,  829,  818,  837,   67,  835,  827,
+      210,  245,  214,  234,  196,  258,  245,  259,  260,  261,
+      277,  281,  849,  848,  847,  846,  805,  804,  818,  807,
+      807,  811,  254,  251,  802,  259,  238,  817,  838,  834,
+
+      798,  795,  808,  793,  815,  809,  291,  298,  304,  305,
+      306,  307,  308,  315,  314,  829,  828,  827,    0,  787,
+      788,  798,  790,  783,  787,  786,  797,  808,  789,  791,
+      803,  207,  774,  779,  772,  779,  771,  782,  783,  770,
+      774,  768,  885,  766,  320,  326,  327,  328,  329,  330,
+      803,  802,  801,  800,  764,  790,  776,  771,  770,  763,
+      772,  777,  762,  765,  763,  772,  764,  749,  746,  760,
+      746,  753,  746,  755,  770,  776,  756,  774,  736,  334,
+      341,  349,  350,  351,  774,  773,  772,  737,  735,  729,
+      766,  730,  755,  738,  725,  729,  725,  736,  744,  731,
+
+      737,  732,  754,  732,  730,  755,  718,  725,  726,  705,
+      724,  734,  357,  359,  746,  745,  744,  708,  706,  709,
+      713,  698,  721,  712,  699,  704,  730,  696,  350,  711,
+      697,  328,  706,  704,  718,  718,  687,  714,  683,  720,
+      681,  687,  367,  371,  720,  719,  685,  707,  677,  690,
+      693,  695,  688,  695,  885,  675,  672,  679,  671,  669,
+      683,  666,  674,  665,  699,  659,  689,  669,  663,  359,
+      667,  686,  669,  684,  660,  379,  691,  690,  689,  653,
+      658,  367,  652,  653,  885,  677,  643,  648,  656,  654,
+      654,  653,  645,  659,  649,  649,  649,  647,  661,  644,
+
+      630,  639,  630,  628,  631,  625,  629,  618,  661,  660,
+      619,  625,  628,  619,  616,  641,  621,  616,  625,  626,
+      624,  614,  621,  621,  616,  619,  617,  618,  604,  638,
+      614,  613,  611,  611,  597,  595,  591,  593,  885,  631,
+      630,  629,  590,  598,  600,  600,  129,  588,  602,  586,
+      592,  610,  580,  885,  593,  600,  583,  576,  589,  576,
+      573,  587,  571,  572,  583,  581,  577,  580,  579,  578,
+      602,  601,  885,  561,  574,  572,  565,  562,  556,  567,
+      558,  565,  562,  561,  552,  559,  562,  557,  548,  885,
+      885,  560,  554,  556,  542,  555,  545,  541,  552,  539,
+
+      575,  574,  573,  885,  533,  546,  549,  543,  885,  885,
+      531,  560,  540,  532,  539,  530,  525,  528,  535,  522,
+      525,  536,  527,  518,  527,  512,  518,  510,  550,  549,
+      519,  510,  519,  510,  505,  511,  517,  516,  506,  514,
+      885,  513,  503,  511,  510,  511,  500,  407,  885,  394,
+      385,  378,  398,  397,  395,  361,  368,  885,  885,  385,
+      370,  351,  885,  366,  885,  885,  365,  349,  885,  361,
+      360,  350,  351,  376,  344,  375,  368,  333,  322,  316,
+      308,  285,  268,  267,  244,  885,  885,  251,  885,  227,
+      885,  257,  239,  885,  193,  194,  885,  144,  885,  885,
+
+      885,  136,  885,  160,  110,   76,   56,  885,   74,  885,
+      885,  885,  885,  412,  417,  421,  426,  429,  433,  436,
+      439,  442,  445,  448,  451,  454,  457,  460,  463,  466,
+      469,  472,  475,  478,  481,  484,  487,  490,  493,  496,
+      499,  502,  505,  508,  511,  514,  517,  520,  523,  526,
+      529,  532,  535,  538
+    } ;
+
+static yyconst flex_int16_t yy_def[555] =
+    {   0,
+      513,    1,  513,  513,  513,  513,  514,  513,  513,  515,
+      513,  515,  515,  515,  513,  513,  513,  513,  513,  513,
+      516,  516,  516,  516,  516,  516,  516,  516,  513,  514,
+      513,  513,  513,  517,  518,  517,  513,  517,  517,  513,
+      513,  513,  513,  513,  513,  513,   20,  518,  516,  516,
+      516,  516,  516,  516,  516,  516,  516,  513,  519,  519,
+      520,  521,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,   20,  520,  516,  516,  516,  516,  516,  516,  516,
+      516,  513,  513,  522,  523,  524,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+
+      513,  513,  513,  513,  513,  513,  516,  522,  516,  516,
+      516,  516,  516,  516,  513,  525,  526,  527,  521,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  525,  516,  516,  516,  516,  516,
+      513,  528,  529,  530,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      516,  516,  516,  516,  531,  532,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  516,  516,  513,  533,  534,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  516,  516,  535,  536,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  516,  513,  537,  538,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+
+      513,  513,  513,  513,  513,  513,  513,  513,  539,  540,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      541,  542,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      543,  544,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+
+      513,  545,  546,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  547,  548,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  549,  550,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  551,  552,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  553,  513,  513,  513,  513,  513,  513,  513,
+
+      513,  513,  513,  554,  513,  513,  513,  513,  513,  513,
+      513,  513,    0,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513
+    } ;
+
+static yyconst flex_int16_t yy_nxt[943] =
+    {   0,
+        4,    5,    6,    7,    8,    4,    9,   10,   10,   10,
+       11,    9,   12,   13,   14,   14,   14,   14,   15,   16,
+        4,   17,    4,    4,    4,   18,    4,    4,   19,    4,
+        4,   20,   20,   20,   20,   20,   20,   21,   22,   23,
+       21,   21,   24,   25,   21,   26,   27,   28,   21,   21,
+       21,   21,   21,   21,   21,    9,    9,   32,   32,   32,
+       33,  513,   34,   34,   34,   35,   35,  513,  513,   42,
+       46,   46,   35,   35,   46,   46,   46,   43,   46,   46,
+      513,   46,  103,   46,  455,   35,   46,   32,   32,   32,
+       38,  512,  104,   39,   46,   46,   47,   47,   47,   48,
+
+       46,   36,   36,   36,   36,   36,   36,   46,   50,   46,
+       51,   53,   46,  511,   46,   58,   58,   58,   52,   49,
+       47,   47,   47,   47,   47,   47,   49,   49,   49,   49,
+       49,   49,   49,   49,   49,   49,   49,   49,   49,   49,
+       49,   49,   49,   49,   46,  510,  377,   57,  378,   46,
+       33,   56,   59,   59,   59,   35,  513,  513,   71,   71,
+       71,   35,   35,   73,   73,   73,   62,   46,   46,   46,
+      455,  508,   46,   46,   46,   54,   46,   46,   58,   58,
+       58,   46,   46,   55,   46,   46,  513,  507,   46,   46,
+       46,   35,   33,   46,   82,   82,   82,   35,   78,   74,
+
+       64,   46,   63,   72,   72,   72,   46,   75,   60,   60,
+       60,   60,   60,   60,   80,   77,   79,   71,   71,   71,
+       76,  108,  108,  108,   85,  506,  505,   72,   72,   72,
+       72,   72,   72,   81,   87,  110,   88,   89,  167,   46,
+       90,   91,   92,   93,   46,   94,   95,   96,   97,  455,
+       46,   98,  107,  107,  107,   46,  168,   83,   83,   83,
+       83,   83,   83,   46,   46,   46,   46,  455,   46,   46,
+       46,   46,  109,  134,  131,  503,  107,  107,  107,  107,
+      107,  107,   46,  135,  502,  126,   33,   46,  115,  115,
+      115,   35,  501,  111,  132,  128,   46,  113,  112,  127,
+
+      129,   48,  500,  499,  133,  145,  145,  145,   85,   46,
+       46,   46,   46,   46,   46,   46,   46,   46,   46,   33,
+       46,  115,  115,  115,  498,   46,  114,  180,  180,  180,
+       85,   46,   46,   46,   46,   46,   46,   46,   46,   46,
+       46,   71,   71,   71,   85,  497,   46,  149,  263,  146,
+      150,   46,  264,  147,   46,   46,   46,  148,  496,   46,
+       46,   46,   46,  182,   46,  181,  495,   46,  494,   46,
+      258,  183,   46,  259,  260,  265,   46,   46,  455,  302,
+      214,   46,  184,  303,   46,  455,  491,  313,  490,   46,
+      213,  314,  244,  489,  488,  487,  486,  485,  484,  483,
+
+      482,  481,  480,  479,  478,   62,  276,  455,  403,  475,
+      474,  243,   30,   30,   30,   30,   30,   30,   36,   36,
+       36,   36,   49,   49,   49,  473,   49,   60,   60,   60,
+       60,   61,   61,   61,   83,   83,   83,   83,   84,   84,
+       84,   86,  472,   86,  116,  116,  116,  117,  117,  117,
+      118,  118,  118,  151,  151,  151,  152,  152,  152,  154,
+      154,  154,  185,  185,  185,  186,  186,  186,  187,  187,
+      187,  215,  215,  215,  216,  216,  216,  245,  245,  245,
+      246,  246,  246,  277,  277,  277,  278,  278,  278,  309,
+      309,  309,  310,  310,  310,  340,  340,  340,  341,  341,
+
+      341,  371,  371,  371,  372,  372,  372,  401,  401,  401,
+      402,  402,  402,  429,  429,  429,  430,  430,  430,  453,
+      453,  453,  454,  454,  454,  476,  476,  476,  477,  477,
+      477,  492,  492,  492,  493,  493,  493,  504,  504,  504,
+      509,  509,  509,  471,  470,  469,  468,  467,  466,  465,
+      464,  463,  462,  461,  460,  459,  458,  457,  456,  455,
+      403,  452,  451,  450,  449,  448,  447,  446,  445,  444,
+      443,  442,  441,  440,  439,  438,  437,  436,  435,  434,
+      433,  432,  431,   62,  403,  342,  428,  427,  426,  425,
+      424,  423,  422,  421,  420,  419,  418,  417,  416,  415,
+
+      414,  413,  412,  411,  410,  409,  408,  407,  406,  405,
+      404,  403,  342,  400,  399,  398,  397,  396,  395,  394,
+      393,  392,  391,  390,  389,  388,  387,  386,  385,  384,
+      383,  382,  381,  380,  379,  376,  375,  374,  373,   62,
+      342,  279,  370,  369,  368,  367,  366,  365,  364,  363,
+      362,  361,  360,  359,  358,  357,  356,  355,  354,  353,
+      352,  351,  350,  349,  348,  347,  346,  345,  344,  343,
+      342,  279,  339,  338,  337,  336,  335,  334,  333,  332,
+      331,  330,  329,  328,  327,  326,  325,  324,  323,  322,
+      321,  320,  319,  318,  317,  316,  315,  312,  311,   62,
+
+      279,  217,  308,  307,  306,  305,  304,  301,  300,  299,
+      298,  297,  296,  295,  294,  293,  292,  291,  290,  289,
+      288,  287,  286,  285,  284,  283,  282,  281,  280,  279,
+      217,  275,  274,  273,  272,  271,  270,  269,  268,  267,
+      266,  262,  261,  257,  256,  255,  254,  253,  252,  251,
+      250,  249,  248,  247,   62,  217,  153,  242,  241,  240,
+      239,  238,  237,  236,  235,  234,  233,  232,  231,  230,
+      229,  228,  227,  226,  225,  224,  223,  222,  221,  220,
+      219,  218,  119,  217,  153,  212,  211,  210,  209,  208,
+      207,  206,  205,  204,  203,  202,  201,  200,  199,  198,
+
+      197,  196,  195,  194,  193,  192,  191,  190,  189,  188,
+      119,   62,  153,   85,  179,  178,  177,  176,  175,  174,
+      173,  172,  171,  170,  169,  166,  165,  164,  163,  162,
+      161,  160,  159,  158,  157,  156,  155,  119,  153,   85,
+      144,  143,  142,  141,  140,  139,  138,  137,  136,  130,
+      125,  124,  123,  122,  121,  120,  119,   62,   85,   35,
+      106,  105,  102,  101,  100,   99,   85,   70,   69,   68,
+       67,   66,   65,   62,   31,   29,   45,   44,   41,   40,
+       37,   31,   29,  513,    3,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513
+    } ;
+
+static yyconst flex_int16_t yy_chk[943] =
+    {   0,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    1,    1,    1,
+        1,    1,    1,    1,    1,    1,    1,    8,    8,    8,
+       10,   12,   10,   10,   10,   10,   12,   13,   14,   17,
+       21,   23,   13,   14,   22,   21,   23,   17,   24,   22,
+       36,   25,   68,   24,  509,   36,   25,   32,   32,   32,
+       12,  507,   68,   13,   20,   49,   20,   20,   20,   20,
+
+       49,   20,   20,   20,   20,   20,   20,   28,   22,   27,
+       23,   25,   28,  506,   27,   33,   33,   33,   24,   20,
+       20,   20,   20,   20,   20,   20,   20,   20,   20,   20,
+       20,   20,   20,   20,   20,   20,   20,   20,   20,   20,
+       20,   20,   20,   20,   26,  505,  347,   28,  347,   26,
+       34,   27,   34,   34,   34,   34,   38,   39,   46,   46,
+       46,   38,   39,   48,   48,   48,   48,   50,   52,   53,
+      504,  502,   50,   52,   53,   26,   51,   55,   58,   58,
+       58,   51,   55,   26,   56,   54,   60,  498,   57,   56,
+       54,   60,   59,   57,   59,   59,   59,   59,   53,   50,
+
+       39,   75,   38,   47,   47,   47,   75,   51,   47,   47,
+       47,   47,   47,   47,   56,   52,   54,   71,   71,   71,
+       51,   73,   73,   73,   73,  496,  495,   47,   47,   47,
+       47,   47,   47,   57,   63,   75,   63,   63,  132,   74,
+       63,   63,   63,   63,   74,   63,   63,   63,   63,  493,
+       77,   63,   72,   72,   72,   77,  132,   72,   72,   72,
+       72,   72,   72,   76,   78,   79,   80,  492,   76,   78,
+       79,   80,   74,   97,   96,  490,   72,   72,   72,   72,
+       72,   72,   81,   97,  488,   93,   82,   81,   82,   82,
+       82,   82,  485,   76,   96,   94,  107,   80,   78,   93,
+
+       94,  107,  484,  483,   96,  108,  108,  108,  108,  109,
+      110,  111,  112,  113,  109,  110,  111,  112,  113,  115,
+      114,  115,  115,  115,  482,  114,   81,  145,  145,  145,
+      145,  146,  147,  148,  149,  150,  146,  147,  148,  149,
+      150,  180,  180,  180,  180,  481,  181,  113,  232,  110,
+      114,  181,  232,  111,  182,  183,  184,  112,  480,  182,
+      183,  184,  213,  147,  214,  146,  479,  213,  478,  214,
+      229,  148,  243,  229,  229,  232,  244,  243,  477,  270,
+      182,  244,  149,  270,  276,  476,  475,  282,  474,  276,
+      181,  282,  214,  473,  472,  471,  470,  468,  467,  464,
+
+      462,  461,  460,  457,  456,  455,  244,  454,  453,  452,
+      451,  213,  514,  514,  514,  514,  514,  514,  515,  515,
+      515,  515,  516,  516,  516,  450,  516,  517,  517,  517,
+      517,  518,  518,  518,  519,  519,  519,  519,  520,  520,
+      520,  521,  448,  521,  522,  522,  522,  523,  523,  523,
+      524,  524,  524,  525,  525,  525,  526,  526,  526,  527,
+      527,  527,  528,  528,  528,  529,  529,  529,  530,  530,
+      530,  531,  531,  531,  532,  532,  532,  533,  533,  533,
+      534,  534,  534,  535,  535,  535,  536,  536,  536,  537,
+      537,  537,  538,  538,  538,  539,  539,  539,  540,  540,
+
+      540,  541,  541,  541,  542,  542,  542,  543,  543,  543,
+      544,  544,  544,  545,  545,  545,  546,  546,  546,  547,
+      547,  547,  548,  548,  548,  549,  549,  549,  550,  550,
+      550,  551,  551,  551,  552,  552,  552,  553,  553,  553,
+      554,  554,  554,  447,  446,  445,  444,  443,  442,  440,
+      439,  438,  437,  436,  435,  434,  433,  432,  431,  430,
+      429,  428,  427,  426,  425,  424,  423,  422,  421,  420,
+      419,  418,  417,  416,  415,  414,  413,  412,  411,  408,
+      407,  406,  405,  403,  402,  401,  400,  399,  398,  397,
+      396,  395,  394,  393,  392,  389,  388,  387,  386,  385,
+
+      384,  383,  382,  381,  380,  379,  378,  377,  376,  375,
+      374,  372,  371,  370,  369,  368,  367,  366,  365,  364,
+      363,  362,  361,  360,  359,  358,  357,  356,  355,  353,
+      352,  351,  350,  349,  348,  346,  345,  344,  343,  342,
+      341,  340,  338,  337,  336,  335,  334,  333,  332,  331,
+      330,  329,  328,  327,  326,  325,  324,  323,  322,  321,
+      320,  319,  318,  317,  316,  315,  314,  313,  312,  311,
+      310,  309,  308,  307,  306,  305,  304,  303,  302,  301,
+      300,  299,  298,  297,  296,  295,  294,  293,  292,  291,
+      290,  289,  288,  287,  286,  284,  283,  281,  280,  279,
+
+      278,  277,  275,  274,  273,  272,  271,  269,  268,  267,
+      266,  265,  264,  263,  262,  261,  260,  259,  258,  257,
+      256,  254,  253,  252,  251,  250,  249,  248,  247,  246,
+      245,  242,  241,  240,  239,  238,  237,  236,  235,  234,
+      233,  231,  230,  228,  227,  226,  225,  224,  223,  222,
+      221,  220,  219,  218,  217,  216,  215,  212,  211,  210,
+      209,  208,  207,  206,  205,  204,  203,  202,  201,  200,
+      199,  198,  197,  196,  195,  194,  193,  192,  191,  190,
+      189,  188,  187,  186,  185,  179,  178,  177,  176,  175,
+      174,  173,  172,  171,  170,  169,  168,  167,  166,  165,
+
+      164,  163,  162,  161,  160,  159,  158,  157,  156,  155,
+      154,  153,  152,  151,  144,  142,  141,  140,  139,  138,
+      137,  136,  135,  134,  133,  131,  130,  129,  128,  127,
+      126,  125,  124,  123,  122,  121,  120,  118,  117,  116,
+      106,  105,  104,  103,  102,  101,  100,   99,   98,   95,
+       92,   91,   90,   89,   88,   87,   86,   85,   84,   83,
+       70,   69,   67,   66,   65,   64,   61,   45,   44,   43,
+       42,   41,   40,   35,   30,   29,   19,   18,   16,   15,
+       11,    7,    5,    3,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513,  513,  513,  513,  513,  513,  513,  513,  513,
+      513,  513
+    } ;
+
+static yy_state_type yy_last_accepting_state;
+static char *yy_last_accepting_cpos;
+
+extern int yy_flex_debug;
+int yy_flex_debug = 0;
+
+/* The intent behind this definition is that it'll catch
+ * any uses of REJECT which flex missed.
+ */
+#define REJECT reject_used_but_not_detected
+#define yymore() yymore_used_but_not_detected
+#define YY_MORE_ADJ 0
+#define YY_RESTORE_YY_MORE_OFFSET
+char *yytext;
+#line 1 "scanner.l"
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996-2000 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+#line 17 "scanner.l"
+#include <config.h>
+#include <includes.h>
+#include <radvd.h>
+#include <gram.h>
+
+extern char *conf_file;
+
+int num_lines = 1;
+#line 864 "lex.yy.c"
+
+#define INITIAL 0
+
+#ifndef YY_NO_UNISTD_H
+/* Special case for "unistd.h", since it is non-ANSI. We include it way
+ * down here because we want the user's section 1 to have been scanned first.
+ * The user has a chance to override it with an option.
+ */
+#include <unistd.h>
+#endif
+
+#ifndef YY_EXTRA_TYPE
+#define YY_EXTRA_TYPE void *
+#endif
+
+static int yy_init_globals (void );
+
+/* Macros after this point can all be overridden by user definitions in
+ * section 1.
+ */
+
+#ifndef YY_SKIP_YYWRAP
+#ifdef __cplusplus
+extern "C" int yywrap (void );
+#else
+extern int yywrap (void );
+#endif
+#endif
+
+    static void yyunput (int c,char *buf_ptr  );
+    
+#ifndef yytext_ptr
+static void yy_flex_strncpy (char *,yyconst char *,int );
+#endif
+
+#ifdef YY_NEED_STRLEN
+static int yy_flex_strlen (yyconst char * );
+#endif
+
+#ifndef YY_NO_INPUT
+
+#ifdef __cplusplus
+static int yyinput (void );
+#else
+static int input (void );
+#endif
+
+#endif
+
+/* Amount of stuff to slurp up with each read. */
+#ifndef YY_READ_BUF_SIZE
+#define YY_READ_BUF_SIZE 8192
+#endif
+
+/* Copy whatever the last rule matched to the standard output. */
+#ifndef ECHO
+/* This used to be an fputs(), but since the string might contain NUL's,
+ * we now use fwrite().
+ */
+#define ECHO (void) fwrite( yytext, yyleng, 1, yyout )
+#endif
+
+/* Gets input and stuffs it into "buf".  number of characters read, or YY_NULL,
+ * is returned in "result".
+ */
+#ifndef YY_INPUT
+#define YY_INPUT(buf,result,max_size) \
+       if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \
+               { \
+               int c = '*'; \
+               size_t n; \
+               for ( n = 0; n < max_size && \
+                            (c = getc( yyin )) != EOF && c != '\n'; ++n ) \
+                       buf[n] = (char) c; \
+               if ( c == '\n' ) \
+                       buf[n++] = (char) c; \
+               if ( c == EOF && ferror( yyin ) ) \
+                       YY_FATAL_ERROR( "input in flex scanner failed" ); \
+               result = n; \
+               } \
+       else \
+               { \
+               errno=0; \
+               while ( (result = fread(buf, 1, max_size, yyin))==0 && ferror(yyin)) \
+                       { \
+                       if( errno != EINTR) \
+                               { \
+                               YY_FATAL_ERROR( "input in flex scanner failed" ); \
+                               break; \
+                               } \
+                       errno=0; \
+                       clearerr(yyin); \
+                       } \
+               }\
+\
+
+#endif
+
+/* No semi-colon after return; correct usage is to write "yyterminate();" -
+ * we don't want an extra ';' after the "return" because that will cause
+ * some compilers to complain about unreachable statements.
+ */
+#ifndef yyterminate
+#define yyterminate() return YY_NULL
+#endif
+
+/* Number of entries by which start-condition stack grows. */
+#ifndef YY_START_STACK_INCR
+#define YY_START_STACK_INCR 25
+#endif
+
+/* Report a fatal error. */
+#ifndef YY_FATAL_ERROR
+#define YY_FATAL_ERROR(msg) yy_fatal_error( msg )
+#endif
+
+/* end tables serialization structures and prototypes */
+
+/* Default declaration of generated scanner - a define so the user can
+ * easily add parameters.
+ */
+#ifndef YY_DECL
+#define YY_DECL_IS_OURS 1
+
+extern int yylex (void);
+
+#define YY_DECL int yylex (void)
+#endif /* !YY_DECL */
+
+/* Code executed at the beginning of each rule, after yytext and yyleng
+ * have been set up.
+ */
+#ifndef YY_USER_ACTION
+#define YY_USER_ACTION
+#endif
+
+/* Code executed at the end of each rule. */
+#ifndef YY_BREAK
+#define YY_BREAK break;
+#endif
+
+#define YY_RULE_SETUP \
+       YY_USER_ACTION
+
+/** The main scanner function which does all the work.
+ */
+YY_DECL
+{
+       register yy_state_type yy_current_state;
+       register char *yy_cp, *yy_bp;
+       register int yy_act;
+    
+#line 38 "scanner.l"
+
+
+#line 1020 "lex.yy.c"
+
+       if ( !(yy_init) )
+               {
+               (yy_init) = 1;
+
+#ifdef YY_USER_INIT
+               YY_USER_INIT;
+#endif
+
+               if ( ! (yy_start) )
+                       (yy_start) = 1; /* first start state */
+
+               if ( ! yyin )
+                       yyin = stdin;
+
+               if ( ! yyout )
+                       yyout = stdout;
+
+               if ( ! YY_CURRENT_BUFFER ) {
+                       yyensure_buffer_stack ();
+                       YY_CURRENT_BUFFER_LVALUE =
+                               yy_create_buffer(yyin,YY_BUF_SIZE );
+               }
+
+               yy_load_buffer_state( );
+               }
+
+       while ( 1 )             /* loops until end-of-file is reached */
+               {
+               yy_cp = (yy_c_buf_p);
+
+               /* Support of yytext. */
+               *yy_cp = (yy_hold_char);
+
+               /* yy_bp points to the position in yy_ch_buf of the start of
+                * the current run.
+                */
+               yy_bp = yy_cp;
+
+               yy_current_state = (yy_start);
+yy_match:
+               do
+                       {
+                       register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];
+                       if ( yy_accept[yy_current_state] )
+                               {
+                               (yy_last_accepting_state) = yy_current_state;
+                               (yy_last_accepting_cpos) = yy_cp;
+                               }
+                       while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+                               {
+                               yy_current_state = (int) yy_def[yy_current_state];
+                               if ( yy_current_state >= 514 )
+                                       yy_c = yy_meta[(unsigned int) yy_c];
+                               }
+                       yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+                       ++yy_cp;
+                       }
+               while ( yy_base[yy_current_state] != 885 );
+
+yy_find_action:
+               yy_act = yy_accept[yy_current_state];
+               if ( yy_act == 0 )
+                       { /* have to back up */
+                       yy_cp = (yy_last_accepting_cpos);
+                       yy_current_state = (yy_last_accepting_state);
+                       yy_act = yy_accept[yy_current_state];
+                       }
+
+               YY_DO_BEFORE_ACTION;
+
+do_action:     /* This label is used only to access EOF actions. */
+
+               switch ( yy_act )
+       { /* beginning of action switch */
+                       case 0: /* must back up */
+                       /* undo the effects of YY_DO_BEFORE_ACTION */
+                       *yy_cp = (yy_hold_char);
+                       yy_cp = (yy_last_accepting_cpos);
+                       yy_current_state = (yy_last_accepting_state);
+                       goto yy_find_action;
+
+case 1:
+*yy_cp = (yy_hold_char); /* undo effects of setting up yytext */
+(yy_c_buf_p) = yy_cp -= 1;
+YY_DO_BEFORE_ACTION; /* set up yytext again */
+YY_RULE_SETUP
+#line 40 "scanner.l"
+{/* ignore comments */}
+       YY_BREAK
+case 2:
+/* rule 2 can match eol */
+YY_RULE_SETUP
+#line 41 "scanner.l"
+{num_lines++;}
+       YY_BREAK
+case 3:
+YY_RULE_SETUP
+#line 42 "scanner.l"
+{}
+       YY_BREAK
+case 4:
+YY_RULE_SETUP
+#line 44 "scanner.l"
+{ return T_INTERFACE; }
+       YY_BREAK
+case 5:
+YY_RULE_SETUP
+#line 45 "scanner.l"
+{ return T_PREFIX; }
+       YY_BREAK
+case 6:
+YY_RULE_SETUP
+#line 46 "scanner.l"
+{ return T_ROUTE; }
+       YY_BREAK
+case 7:
+YY_RULE_SETUP
+#line 47 "scanner.l"
+{ return T_RDNSS; }
+       YY_BREAK
+case 8:
+YY_RULE_SETUP
+#line 49 "scanner.l"
+{ return T_IgnoreIfMissing; }
+       YY_BREAK
+case 9:
+YY_RULE_SETUP
+#line 50 "scanner.l"
+{ return T_AdvSendAdvert; }
+       YY_BREAK
+case 10:
+YY_RULE_SETUP
+#line 51 "scanner.l"
+{ return T_MaxRtrAdvInterval; }
+       YY_BREAK
+case 11:
+YY_RULE_SETUP
+#line 52 "scanner.l"
+{ return T_MinRtrAdvInterval; }
+       YY_BREAK
+case 12:
+YY_RULE_SETUP
+#line 53 "scanner.l"
+{ return T_AdvManagedFlag; }
+       YY_BREAK
+case 13:
+YY_RULE_SETUP
+#line 54 "scanner.l"
+{ return T_AdvOtherConfigFlag; }
+       YY_BREAK
+case 14:
+YY_RULE_SETUP
+#line 55 "scanner.l"
+{ return T_AdvLinkMTU; }
+       YY_BREAK
+case 15:
+YY_RULE_SETUP
+#line 56 "scanner.l"
+{ return T_AdvReachableTime; }
+       YY_BREAK
+case 16:
+YY_RULE_SETUP
+#line 57 "scanner.l"
+{ return T_AdvRetransTimer; }
+       YY_BREAK
+case 17:
+YY_RULE_SETUP
+#line 58 "scanner.l"
+{ return T_AdvCurHopLimit; }
+       YY_BREAK
+case 18:
+YY_RULE_SETUP
+#line 59 "scanner.l"
+{ return T_AdvDefaultLifetime; }
+       YY_BREAK
+case 19:
+YY_RULE_SETUP
+#line 60 "scanner.l"
+{ return T_AdvDefaultPreference; }
+       YY_BREAK
+case 20:
+YY_RULE_SETUP
+#line 61 "scanner.l"
+{ return T_AdvSourceLLAddress; }
+       YY_BREAK
+case 21:
+YY_RULE_SETUP
+#line 63 "scanner.l"
+{ return T_AdvOnLink; }
+       YY_BREAK
+case 22:
+YY_RULE_SETUP
+#line 64 "scanner.l"
+{ return T_AdvAutonomous; }
+       YY_BREAK
+case 23:
+YY_RULE_SETUP
+#line 65 "scanner.l"
+{ return T_AdvValidLifetime; }
+       YY_BREAK
+case 24:
+YY_RULE_SETUP
+#line 66 "scanner.l"
+{ return T_AdvPreferredLifetime; }
+       YY_BREAK
+case 25:
+YY_RULE_SETUP
+#line 68 "scanner.l"
+{ return T_AdvRouterAddr; }
+       YY_BREAK
+case 26:
+YY_RULE_SETUP
+#line 69 "scanner.l"
+{ return T_AdvHomeAgentFlag; }
+       YY_BREAK
+case 27:
+YY_RULE_SETUP
+#line 70 "scanner.l"
+{ return T_AdvIntervalOpt; }
+       YY_BREAK
+case 28:
+YY_RULE_SETUP
+#line 71 "scanner.l"
+{ return T_AdvHomeAgentInfo; }
+       YY_BREAK
+case 29:
+YY_RULE_SETUP
+#line 72 "scanner.l"
+{ return T_UnicastOnly; }
+       YY_BREAK
+case 30:
+YY_RULE_SETUP
+#line 74 "scanner.l"
+{ return T_Base6to4Interface; }
+       YY_BREAK
+case 31:
+YY_RULE_SETUP
+#line 76 "scanner.l"
+{ return T_HomeAgentPreference; }
+       YY_BREAK
+case 32:
+YY_RULE_SETUP
+#line 77 "scanner.l"
+{ return T_HomeAgentLifetime; }
+       YY_BREAK
+case 33:
+YY_RULE_SETUP
+#line 79 "scanner.l"
+{ return T_AdvRoutePreference; }
+       YY_BREAK
+case 34:
+YY_RULE_SETUP
+#line 80 "scanner.l"
+{ return T_AdvRouteLifetime; }
+       YY_BREAK
+case 35:
+YY_RULE_SETUP
+#line 82 "scanner.l"
+{ return T_AdvRDNSSPreference; }
+       YY_BREAK
+case 36:
+YY_RULE_SETUP
+#line 83 "scanner.l"
+{ return T_AdvRDNSSOpenFlag; }
+       YY_BREAK
+case 37:
+YY_RULE_SETUP
+#line 84 "scanner.l"
+{ return T_AdvRDNSSLifetime; }
+       YY_BREAK
+case 38:
+YY_RULE_SETUP
+#line 86 "scanner.l"
+{ return T_MinDelayBetweenRAs; }
+       YY_BREAK
+case 39:
+YY_RULE_SETUP
+#line 88 "scanner.l"
+{ return T_AdvMobRtrSupportFlag; }
+       YY_BREAK
+case 40:
+YY_RULE_SETUP
+#line 90 "scanner.l"
+{
+                       static struct in6_addr addr;
+                       int i;
+                               
+                       i = inet_pton(AF_INET6, yytext, &addr);
+
+                       dlog(LOG_DEBUG, 4, "inet_pton returned %d", i);
+
+                       /* BSD API draft and NRL's code don't aggree on
+                        * this. the draft specifies a return value of 1 on 
+                        * success, NRL's code returns the address length in 
+                        * bytes on success (16 for an IPv6 address)
+                        */
+                       if (i < 1) {
+                               flog(LOG_ERR, "invalid address in %s, line %d", conf_file,
+                                       num_lines);
+                               return T_BAD_TOKEN;
+                       }
+
+                       yylval.addr = &addr;
+                       return IPV6ADDR;
+               }
+       YY_BREAK
+case 41:
+YY_RULE_SETUP
+#line 113 "scanner.l"
+{
+                       unsigned long lnum;
+                       char *endp;
+                       lnum = strtoul(yytext, &endp, 10);
+                       if (*yytext == '\0' || *endp != '\0')
+                               return T_BAD_TOKEN;
+                       if (lnum > 0xFFFFFFFFUL)
+                               return T_BAD_TOKEN;     /* XXX */
+                       yylval.num = lnum;
+                       return NUMBER;
+               }
+       YY_BREAK
+case 42:
+YY_RULE_SETUP
+#line 125 "scanner.l"
+{ yylval.snum = atoi(yytext); return SIGNEDNUMBER; }
+       YY_BREAK
+case 43:
+YY_RULE_SETUP
+#line 127 "scanner.l"
+{ yylval.dec = atof(yytext); return DECIMAL; }
+       YY_BREAK
+case 44:
+YY_RULE_SETUP
+#line 129 "scanner.l"
+{ return INFINITY; }
+       YY_BREAK
+case 45:
+YY_RULE_SETUP
+#line 131 "scanner.l"
+{ yylval.bool = 1; return SWITCH; }
+       YY_BREAK
+case 46:
+YY_RULE_SETUP
+#line 133 "scanner.l"
+{ yylval.bool = 0; return SWITCH; }
+       YY_BREAK
+case 47:
+YY_RULE_SETUP
+#line 135 "scanner.l"
+{ yylval.snum = -1; return SIGNEDNUMBER; }
+       YY_BREAK
+case 48:
+YY_RULE_SETUP
+#line 137 "scanner.l"
+{ yylval.snum = 0; return SIGNEDNUMBER; }
+       YY_BREAK
+case 49:
+YY_RULE_SETUP
+#line 139 "scanner.l"
+{ yylval.snum = 1; return SIGNEDNUMBER; }
+       YY_BREAK
+case 50:
+YY_RULE_SETUP
+#line 141 "scanner.l"
+{
+                       static char name[IFNAMSIZ];
+                               
+                       strncpy(name, yytext, IFNAMSIZ-1);
+                       name[IFNAMSIZ-1] = '\0';
+                       yylval.str = name;
+                       return STRING;
+               }
+       YY_BREAK
+case 51:
+YY_RULE_SETUP
+#line 150 "scanner.l"
+{ return *yytext; }
+       YY_BREAK
+case 52:
+YY_RULE_SETUP
+#line 152 "scanner.l"
+{ return T_BAD_TOKEN; }
+       YY_BREAK
+case 53:
+YY_RULE_SETUP
+#line 153 "scanner.l"
+ECHO;
+       YY_BREAK
+#line 1410 "lex.yy.c"
+case YY_STATE_EOF(INITIAL):
+       yyterminate();
+
+       case YY_END_OF_BUFFER:
+               {
+               /* Amount of text matched not including the EOB char. */
+               int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1;
+
+               /* Undo the effects of YY_DO_BEFORE_ACTION. */
+               *yy_cp = (yy_hold_char);
+               YY_RESTORE_YY_MORE_OFFSET
+
+               if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW )
+                       {
+                       /* We're scanning a new file or input source.  It's
+                        * possible that this happened because the user
+                        * just pointed yyin at a new source and called
+                        * yylex().  If so, then we have to assure
+                        * consistency between YY_CURRENT_BUFFER and our
+                        * globals.  Here is the right place to do so, because
+                        * this is the first action (other than possibly a
+                        * back-up) that will match for the new input source.
+                        */
+                       (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+                       YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin;
+                       YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL;
+                       }
+
+               /* Note that here we test for yy_c_buf_p "<=" to the position
+                * of the first EOB in the buffer, since yy_c_buf_p will
+                * already have been incremented past the NUL character
+                * (since all states make transitions on EOB to the
+                * end-of-buffer state).  Contrast this with the test
+                * in input().
+                */
+               if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
+                       { /* This was really a NUL. */
+                       yy_state_type yy_next_state;
+
+                       (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text;
+
+                       yy_current_state = yy_get_previous_state(  );
+
+                       /* Okay, we're now positioned to make the NUL
+                        * transition.  We couldn't have
+                        * yy_get_previous_state() go ahead and do it
+                        * for us because it doesn't know how to deal
+                        * with the possibility of jamming (and we don't
+                        * want to build jamming into it because then it
+                        * will run more slowly).
+                        */
+
+                       yy_next_state = yy_try_NUL_trans( yy_current_state );
+
+                       yy_bp = (yytext_ptr) + YY_MORE_ADJ;
+
+                       if ( yy_next_state )
+                               {
+                               /* Consume the NUL. */
+                               yy_cp = ++(yy_c_buf_p);
+                               yy_current_state = yy_next_state;
+                               goto yy_match;
+                               }
+
+                       else
+                               {
+                               yy_cp = (yy_c_buf_p);
+                               goto yy_find_action;
+                               }
+                       }
+
+               else switch ( yy_get_next_buffer(  ) )
+                       {
+                       case EOB_ACT_END_OF_FILE:
+                               {
+                               (yy_did_buffer_switch_on_eof) = 0;
+
+                               if ( yywrap( ) )
+                                       {
+                                       /* Note: because we've taken care in
+                                        * yy_get_next_buffer() to have set up
+                                        * yytext, we can now set up
+                                        * yy_c_buf_p so that if some total
+                                        * hoser (like flex itself) wants to
+                                        * call the scanner after we return the
+                                        * YY_NULL, it'll still work - another
+                                        * YY_NULL will get returned.
+                                        */
+                                       (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ;
+
+                                       yy_act = YY_STATE_EOF(YY_START);
+                                       goto do_action;
+                                       }
+
+                               else
+                                       {
+                                       if ( ! (yy_did_buffer_switch_on_eof) )
+                                               YY_NEW_FILE;
+                                       }
+                               break;
+                               }
+
+                       case EOB_ACT_CONTINUE_SCAN:
+                               (yy_c_buf_p) =
+                                       (yytext_ptr) + yy_amount_of_matched_text;
+
+                               yy_current_state = yy_get_previous_state(  );
+
+                               yy_cp = (yy_c_buf_p);
+                               yy_bp = (yytext_ptr) + YY_MORE_ADJ;
+                               goto yy_match;
+
+                       case EOB_ACT_LAST_MATCH:
+                               (yy_c_buf_p) =
+                               &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)];
+
+                               yy_current_state = yy_get_previous_state(  );
+
+                               yy_cp = (yy_c_buf_p);
+                               yy_bp = (yytext_ptr) + YY_MORE_ADJ;
+                               goto yy_find_action;
+                       }
+               break;
+               }
+
+       default:
+               YY_FATAL_ERROR(
+                       "fatal flex scanner internal error--no action found" );
+       } /* end of action switch */
+               } /* end of scanning one token */
+} /* end of yylex */
+
+/* yy_get_next_buffer - try to read in a new buffer
+ *
+ * Returns a code representing an action:
+ *     EOB_ACT_LAST_MATCH -
+ *     EOB_ACT_CONTINUE_SCAN - continue scanning from current position
+ *     EOB_ACT_END_OF_FILE - end of file
+ */
+static int yy_get_next_buffer (void)
+{
+       register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf;
+       register char *source = (yytext_ptr);
+       register int number_to_move, i;
+       int ret_val;
+
+       if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] )
+               YY_FATAL_ERROR(
+               "fatal flex scanner internal error--end of buffer missed" );
+
+       if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 )
+               { /* Don't try to fill the buffer, so this is an EOF. */
+               if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 )
+                       {
+                       /* We matched a single character, the EOB, so
+                        * treat this as a final EOF.
+                        */
+                       return EOB_ACT_END_OF_FILE;
+                       }
+
+               else
+                       {
+                       /* We matched some text prior to the EOB, first
+                        * process it.
+                        */
+                       return EOB_ACT_LAST_MATCH;
+                       }
+               }
+
+       /* Try to read more data. */
+
+       /* First move last chars to start of buffer. */
+       number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1;
+
+       for ( i = 0; i < number_to_move; ++i )
+               *(dest++) = *(source++);
+
+       if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING )
+               /* don't do the read, it's not guaranteed to return an EOF,
+                * just force an EOF
+                */
+               YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0;
+
+       else
+               {
+                       int num_to_read =
+                       YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1;
+
+               while ( num_to_read <= 0 )
+                       { /* Not enough room in the buffer - grow it. */
+
+                       /* just a shorter name for the current buffer */
+                       YY_BUFFER_STATE b = YY_CURRENT_BUFFER;
+
+                       int yy_c_buf_p_offset =
+                               (int) ((yy_c_buf_p) - b->yy_ch_buf);
+
+                       if ( b->yy_is_our_buffer )
+                               {
+                               int new_size = b->yy_buf_size * 2;
+
+                               if ( new_size <= 0 )
+                                       b->yy_buf_size += b->yy_buf_size / 8;
+                               else
+                                       b->yy_buf_size *= 2;
+
+                               b->yy_ch_buf = (char *)
+                                       /* Include room in for 2 EOB chars. */
+                                       yyrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2  );
+                               }
+                       else
+                               /* Can't grow it, we don't own it. */
+                               b->yy_ch_buf = 0;
+
+                       if ( ! b->yy_ch_buf )
+                               YY_FATAL_ERROR(
+                               "fatal error - scanner input buffer overflow" );
+
+                       (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset];
+
+                       num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size -
+                                               number_to_move - 1;
+
+                       }
+
+               if ( num_to_read > YY_READ_BUF_SIZE )
+                       num_to_read = YY_READ_BUF_SIZE;
+
+               /* Read in more data. */
+               YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]),
+                       (yy_n_chars), (size_t) num_to_read );
+
+               YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
+               }
+
+       if ( (yy_n_chars) == 0 )
+               {
+               if ( number_to_move == YY_MORE_ADJ )
+                       {
+                       ret_val = EOB_ACT_END_OF_FILE;
+                       yyrestart(yyin  );
+                       }
+
+               else
+                       {
+                       ret_val = EOB_ACT_LAST_MATCH;
+                       YY_CURRENT_BUFFER_LVALUE->yy_buffer_status =
+                               YY_BUFFER_EOF_PENDING;
+                       }
+               }
+
+       else
+               ret_val = EOB_ACT_CONTINUE_SCAN;
+
+       (yy_n_chars) += number_to_move;
+       YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR;
+       YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR;
+
+       (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0];
+
+       return ret_val;
+}
+
+/* yy_get_previous_state - get the state just before the EOB char was reached */
+
+    static yy_state_type yy_get_previous_state (void)
+{
+       register yy_state_type yy_current_state;
+       register char *yy_cp;
+    
+       yy_current_state = (yy_start);
+
+       for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp )
+               {
+               register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1);
+               if ( yy_accept[yy_current_state] )
+                       {
+                       (yy_last_accepting_state) = yy_current_state;
+                       (yy_last_accepting_cpos) = yy_cp;
+                       }
+               while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+                       {
+                       yy_current_state = (int) yy_def[yy_current_state];
+                       if ( yy_current_state >= 514 )
+                               yy_c = yy_meta[(unsigned int) yy_c];
+                       }
+               yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+               }
+
+       return yy_current_state;
+}
+
+/* yy_try_NUL_trans - try to make a transition on the NUL character
+ *
+ * synopsis
+ *     next_state = yy_try_NUL_trans( current_state );
+ */
+    static yy_state_type yy_try_NUL_trans  (yy_state_type yy_current_state )
+{
+       register int yy_is_jam;
+       register char *yy_cp = (yy_c_buf_p);
+
+       register YY_CHAR yy_c = 1;
+       if ( yy_accept[yy_current_state] )
+               {
+               (yy_last_accepting_state) = yy_current_state;
+               (yy_last_accepting_cpos) = yy_cp;
+               }
+       while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state )
+               {
+               yy_current_state = (int) yy_def[yy_current_state];
+               if ( yy_current_state >= 514 )
+                       yy_c = yy_meta[(unsigned int) yy_c];
+               }
+       yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c];
+       yy_is_jam = (yy_current_state == 513);
+
+       return yy_is_jam ? 0 : yy_current_state;
+}
+
+    static void yyunput (int c, register char * yy_bp )
+{
+       register char *yy_cp;
+    
+    yy_cp = (yy_c_buf_p);
+
+       /* undo effects of setting up yytext */
+       *yy_cp = (yy_hold_char);
+
+       if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+               { /* need to shift things up to make room */
+               /* +2 for EOB chars. */
+               register int number_to_move = (yy_n_chars) + 2;
+               register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[
+                                       YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2];
+               register char *source =
+                               &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move];
+
+               while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf )
+                       *--dest = *--source;
+
+               yy_cp += (int) (dest - source);
+               yy_bp += (int) (dest - source);
+               YY_CURRENT_BUFFER_LVALUE->yy_n_chars =
+                       (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size;
+
+               if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 )
+                       YY_FATAL_ERROR( "flex scanner push-back overflow" );
+               }
+
+       *--yy_cp = (char) c;
+
+       (yytext_ptr) = yy_bp;
+       (yy_hold_char) = *yy_cp;
+       (yy_c_buf_p) = yy_cp;
+}
+
+#ifndef YY_NO_INPUT
+#ifdef __cplusplus
+    static int yyinput (void)
+#else
+    static int input  (void)
+#endif
+
+{
+       int c;
+    
+       *(yy_c_buf_p) = (yy_hold_char);
+
+       if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR )
+               {
+               /* yy_c_buf_p now points to the character we want to return.
+                * If this occurs *before* the EOB characters, then it's a
+                * valid NUL; if not, then we've hit the end of the buffer.
+                */
+               if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] )
+                       /* This was really a NUL. */
+                       *(yy_c_buf_p) = '\0';
+
+               else
+                       { /* need more input */
+                       int offset = (yy_c_buf_p) - (yytext_ptr);
+                       ++(yy_c_buf_p);
+
+                       switch ( yy_get_next_buffer(  ) )
+                               {
+                               case EOB_ACT_LAST_MATCH:
+                                       /* This happens because yy_g_n_b()
+                                        * sees that we've accumulated a
+                                        * token and flags that we need to
+                                        * try matching the token before
+                                        * proceeding.  But for input(),
+                                        * there's no matching to consider.
+                                        * So convert the EOB_ACT_LAST_MATCH
+                                        * to EOB_ACT_END_OF_FILE.
+                                        */
+
+                                       /* Reset buffer status. */
+                                       yyrestart(yyin );
+
+                                       /*FALLTHROUGH*/
+
+                               case EOB_ACT_END_OF_FILE:
+                                       {
+                                       if ( yywrap( ) )
+                                               return EOF;
+
+                                       if ( ! (yy_did_buffer_switch_on_eof) )
+                                               YY_NEW_FILE;
+#ifdef __cplusplus
+                                       return yyinput();
+#else
+                                       return input();
+#endif
+                                       }
+
+                               case EOB_ACT_CONTINUE_SCAN:
+                                       (yy_c_buf_p) = (yytext_ptr) + offset;
+                                       break;
+                               }
+                       }
+               }
+
+       c = *(unsigned char *) (yy_c_buf_p);    /* cast for 8-bit char's */
+       *(yy_c_buf_p) = '\0';   /* preserve yytext */
+       (yy_hold_char) = *++(yy_c_buf_p);
+
+       return c;
+}
+#endif /* ifndef YY_NO_INPUT */
+
+/** Immediately switch to a different input stream.
+ * @param input_file A readable stream.
+ * 
+ * @note This function does not reset the start condition to @c INITIAL .
+ */
+    void yyrestart  (FILE * input_file )
+{
+    
+       if ( ! YY_CURRENT_BUFFER ){
+        yyensure_buffer_stack ();
+               YY_CURRENT_BUFFER_LVALUE =
+            yy_create_buffer(yyin,YY_BUF_SIZE );
+       }
+
+       yy_init_buffer(YY_CURRENT_BUFFER,input_file );
+       yy_load_buffer_state( );
+}
+
+/** Switch to a different input buffer.
+ * @param new_buffer The new input buffer.
+ * 
+ */
+    void yy_switch_to_buffer  (YY_BUFFER_STATE  new_buffer )
+{
+    
+       /* TODO. We should be able to replace this entire function body
+        * with
+        *              yypop_buffer_state();
+        *              yypush_buffer_state(new_buffer);
+     */
+       yyensure_buffer_stack ();
+       if ( YY_CURRENT_BUFFER == new_buffer )
+               return;
+
+       if ( YY_CURRENT_BUFFER )
+               {
+               /* Flush out information for old buffer. */
+               *(yy_c_buf_p) = (yy_hold_char);
+               YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
+               YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
+               }
+
+       YY_CURRENT_BUFFER_LVALUE = new_buffer;
+       yy_load_buffer_state( );
+
+       /* We don't actually know whether we did this switch during
+        * EOF (yywrap()) processing, but the only time this flag
+        * is looked at is after yywrap() is called, so it's safe
+        * to go ahead and always set it.
+        */
+       (yy_did_buffer_switch_on_eof) = 1;
+}
+
+static void yy_load_buffer_state  (void)
+{
+       (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars;
+       (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos;
+       yyin = YY_CURRENT_BUFFER_LVALUE->yy_input_file;
+       (yy_hold_char) = *(yy_c_buf_p);
+}
+
+/** Allocate and initialize an input buffer state.
+ * @param file A readable stream.
+ * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE.
+ * 
+ * @return the allocated buffer state.
+ */
+    YY_BUFFER_STATE yy_create_buffer  (FILE * file, int  size )
+{
+       YY_BUFFER_STATE b;
+    
+       b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state )  );
+       if ( ! b )
+               YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+       b->yy_buf_size = size;
+
+       /* yy_ch_buf has to be 2 characters longer than the size given because
+        * we need to put in 2 end-of-buffer characters.
+        */
+       b->yy_ch_buf = (char *) yyalloc(b->yy_buf_size + 2  );
+       if ( ! b->yy_ch_buf )
+               YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" );
+
+       b->yy_is_our_buffer = 1;
+
+       yy_init_buffer(b,file );
+
+       return b;
+}
+
+/** Destroy the buffer.
+ * @param b a buffer created with yy_create_buffer()
+ * 
+ */
+    void yy_delete_buffer (YY_BUFFER_STATE  b )
+{
+    
+       if ( ! b )
+               return;
+
+       if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */
+               YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0;
+
+       if ( b->yy_is_our_buffer )
+               yyfree((void *) b->yy_ch_buf  );
+
+       yyfree((void *) b  );
+}
+
+#ifndef __cplusplus
+extern int isatty (int );
+#endif /* __cplusplus */
+    
+/* Initializes or reinitializes a buffer.
+ * This function is sometimes called more than once on the same buffer,
+ * such as during a yyrestart() or at EOF.
+ */
+    static void yy_init_buffer  (YY_BUFFER_STATE  b, FILE * file )
+
+{
+       int oerrno = errno;
+    
+       yy_flush_buffer(b );
+
+       b->yy_input_file = file;
+       b->yy_fill_buffer = 1;
+
+    /* If b is the current buffer, then yy_init_buffer was _probably_
+     * called from yyrestart() or through yy_get_next_buffer.
+     * In that case, we don't want to reset the lineno or column.
+     */
+    if (b != YY_CURRENT_BUFFER){
+        b->yy_bs_lineno = 1;
+        b->yy_bs_column = 0;
+    }
+
+        b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0;
+    
+       errno = oerrno;
+}
+
+/** Discard all buffered characters. On the next scan, YY_INPUT will be called.
+ * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER.
+ * 
+ */
+    void yy_flush_buffer (YY_BUFFER_STATE  b )
+{
+       if ( ! b )
+               return;
+
+       b->yy_n_chars = 0;
+
+       /* We always need two end-of-buffer characters.  The first causes
+        * a transition to the end-of-buffer state.  The second causes
+        * a jam in that state.
+        */
+       b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR;
+       b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR;
+
+       b->yy_buf_pos = &b->yy_ch_buf[0];
+
+       b->yy_at_bol = 1;
+       b->yy_buffer_status = YY_BUFFER_NEW;
+
+       if ( b == YY_CURRENT_BUFFER )
+               yy_load_buffer_state( );
+}
+
+/** Pushes the new state onto the stack. The new state becomes
+ *  the current state. This function will allocate the stack
+ *  if necessary.
+ *  @param new_buffer The new state.
+ *  
+ */
+void yypush_buffer_state (YY_BUFFER_STATE new_buffer )
+{
+       if (new_buffer == NULL)
+               return;
+
+       yyensure_buffer_stack();
+
+       /* This block is copied from yy_switch_to_buffer. */
+       if ( YY_CURRENT_BUFFER )
+               {
+               /* Flush out information for old buffer. */
+               *(yy_c_buf_p) = (yy_hold_char);
+               YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p);
+               YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars);
+               }
+
+       /* Only push if top exists. Otherwise, replace top. */
+       if (YY_CURRENT_BUFFER)
+               (yy_buffer_stack_top)++;
+       YY_CURRENT_BUFFER_LVALUE = new_buffer;
+
+       /* copied from yy_switch_to_buffer. */
+       yy_load_buffer_state( );
+       (yy_did_buffer_switch_on_eof) = 1;
+}
+
+/** Removes and deletes the top of the stack, if present.
+ *  The next element becomes the new top.
+ *  
+ */
+void yypop_buffer_state (void)
+{
+       if (!YY_CURRENT_BUFFER)
+               return;
+
+       yy_delete_buffer(YY_CURRENT_BUFFER );
+       YY_CURRENT_BUFFER_LVALUE = NULL;
+       if ((yy_buffer_stack_top) > 0)
+               --(yy_buffer_stack_top);
+
+       if (YY_CURRENT_BUFFER) {
+               yy_load_buffer_state( );
+               (yy_did_buffer_switch_on_eof) = 1;
+       }
+}
+
+/* Allocates the stack if it does not exist.
+ *  Guarantees space for at least one push.
+ */
+static void yyensure_buffer_stack (void)
+{
+       int num_to_alloc;
+    
+       if (!(yy_buffer_stack)) {
+
+               /* First allocation is just for 2 elements, since we don't know if this
+                * scanner will even need a stack. We use 2 instead of 1 to avoid an
+                * immediate realloc on the next call.
+         */
+               num_to_alloc = 1;
+               (yy_buffer_stack) = (struct yy_buffer_state**)yyalloc
+                                                               (num_to_alloc * sizeof(struct yy_buffer_state*)
+                                                               );
+               
+               memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*));
+                               
+               (yy_buffer_stack_max) = num_to_alloc;
+               (yy_buffer_stack_top) = 0;
+               return;
+       }
+
+       if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){
+
+               /* Increase the buffer to prepare for a possible push. */
+               int grow_size = 8 /* arbitrary grow size */;
+
+               num_to_alloc = (yy_buffer_stack_max) + grow_size;
+               (yy_buffer_stack) = (struct yy_buffer_state**)yyrealloc
+                                                               ((yy_buffer_stack),
+                                                               num_to_alloc * sizeof(struct yy_buffer_state*)
+                                                               );
+
+               /* zero only the new slots.*/
+               memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*));
+               (yy_buffer_stack_max) = num_to_alloc;
+       }
+}
+
+/** Setup the input buffer state to scan directly from a user-specified character buffer.
+ * @param base the character buffer
+ * @param size the size in bytes of the character buffer
+ * 
+ * @return the newly allocated buffer state object. 
+ */
+YY_BUFFER_STATE yy_scan_buffer  (char * base, yy_size_t  size )
+{
+       YY_BUFFER_STATE b;
+    
+       if ( size < 2 ||
+            base[size-2] != YY_END_OF_BUFFER_CHAR ||
+            base[size-1] != YY_END_OF_BUFFER_CHAR )
+               /* They forgot to leave room for the EOB's. */
+               return 0;
+
+       b = (YY_BUFFER_STATE) yyalloc(sizeof( struct yy_buffer_state )  );
+       if ( ! b )
+               YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" );
+
+       b->yy_buf_size = size - 2;      /* "- 2" to take care of EOB's */
+       b->yy_buf_pos = b->yy_ch_buf = base;
+       b->yy_is_our_buffer = 0;
+       b->yy_input_file = 0;
+       b->yy_n_chars = b->yy_buf_size;
+       b->yy_is_interactive = 0;
+       b->yy_at_bol = 1;
+       b->yy_fill_buffer = 0;
+       b->yy_buffer_status = YY_BUFFER_NEW;
+
+       yy_switch_to_buffer(b  );
+
+       return b;
+}
+
+/** Setup the input buffer state to scan a string. The next call to yylex() will
+ * scan from a @e copy of @a str.
+ * @param yystr a NUL-terminated string to scan
+ * 
+ * @return the newly allocated buffer state object.
+ * @note If you want to scan bytes that may contain NUL values, then use
+ *       yy_scan_bytes() instead.
+ */
+YY_BUFFER_STATE yy_scan_string (yyconst char * yystr )
+{
+    
+       return yy_scan_bytes(yystr,strlen(yystr) );
+}
+
+/** Setup the input buffer state to scan the given bytes. The next call to yylex() will
+ * scan from a @e copy of @a bytes.
+ * @param bytes the byte buffer to scan
+ * @param len the number of bytes in the buffer pointed to by @a bytes.
+ * 
+ * @return the newly allocated buffer state object.
+ */
+YY_BUFFER_STATE yy_scan_bytes  (yyconst char * yybytes, int  _yybytes_len )
+{
+       YY_BUFFER_STATE b;
+       char *buf;
+       yy_size_t n;
+       int i;
+    
+       /* Get memory for full buffer, including space for trailing EOB's. */
+       n = _yybytes_len + 2;
+       buf = (char *) yyalloc(n  );
+       if ( ! buf )
+               YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" );
+
+       for ( i = 0; i < _yybytes_len; ++i )
+               buf[i] = yybytes[i];
+
+       buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR;
+
+       b = yy_scan_buffer(buf,n );
+       if ( ! b )
+               YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" );
+
+       /* It's okay to grow etc. this buffer, and we should throw it
+        * away when we're done.
+        */
+       b->yy_is_our_buffer = 1;
+
+       return b;
+}
+
+#ifndef YY_EXIT_FAILURE
+#define YY_EXIT_FAILURE 2
+#endif
+
+static void yy_fatal_error (yyconst char* msg )
+{
+       (void) fprintf( stderr, "%s\n", msg );
+       exit( YY_EXIT_FAILURE );
+}
+
+/* Redefine yyless() so it works in section 3 code. */
+
+#undef yyless
+#define yyless(n) \
+       do \
+               { \
+               /* Undo effects of setting up yytext. */ \
+        int yyless_macro_arg = (n); \
+        YY_LESS_LINENO(yyless_macro_arg);\
+               yytext[yyleng] = (yy_hold_char); \
+               (yy_c_buf_p) = yytext + yyless_macro_arg; \
+               (yy_hold_char) = *(yy_c_buf_p); \
+               *(yy_c_buf_p) = '\0'; \
+               yyleng = yyless_macro_arg; \
+               } \
+       while ( 0 )
+
+/* Accessor  methods (get/set functions) to struct members. */
+
+/** Get the current line number.
+ * 
+ */
+int yyget_lineno  (void)
+{
+        
+    return yylineno;
+}
+
+/** Get the input stream.
+ * 
+ */
+FILE *yyget_in  (void)
+{
+        return yyin;
+}
+
+/** Get the output stream.
+ * 
+ */
+FILE *yyget_out  (void)
+{
+        return yyout;
+}
+
+/** Get the length of the current token.
+ * 
+ */
+int yyget_leng  (void)
+{
+        return yyleng;
+}
+
+/** Get the current token.
+ * 
+ */
+
+char *yyget_text  (void)
+{
+        return yytext;
+}
+
+/** Set the current line number.
+ * @param line_number
+ * 
+ */
+void yyset_lineno (int  line_number )
+{
+    
+    yylineno = line_number;
+}
+
+/** Set the input stream. This does not discard the current
+ * input buffer.
+ * @param in_str A readable stream.
+ * 
+ * @see yy_switch_to_buffer
+ */
+void yyset_in (FILE *  in_str )
+{
+        yyin = in_str ;
+}
+
+void yyset_out (FILE *  out_str )
+{
+        yyout = out_str ;
+}
+
+int yyget_debug  (void)
+{
+        return yy_flex_debug;
+}
+
+void yyset_debug (int  bdebug )
+{
+        yy_flex_debug = bdebug ;
+}
+
+static int yy_init_globals (void)
+{
+        /* Initialization is the same as for the non-reentrant scanner.
+     * This function is called from yylex_destroy(), so don't allocate here.
+     */
+
+    (yy_buffer_stack) = 0;
+    (yy_buffer_stack_top) = 0;
+    (yy_buffer_stack_max) = 0;
+    (yy_c_buf_p) = (char *) 0;
+    (yy_init) = 0;
+    (yy_start) = 0;
+
+/* Defined in main.c */
+#ifdef YY_STDINIT
+    yyin = stdin;
+    yyout = stdout;
+#else
+    yyin = (FILE *) 0;
+    yyout = (FILE *) 0;
+#endif
+
+    /* For future reference: Set errno on error, since we are called by
+     * yylex_init()
+     */
+    return 0;
+}
+
+/* yylex_destroy is for both reentrant and non-reentrant scanners. */
+int yylex_destroy  (void)
+{
+    
+    /* Pop the buffer stack, destroying each element. */
+       while(YY_CURRENT_BUFFER){
+               yy_delete_buffer(YY_CURRENT_BUFFER  );
+               YY_CURRENT_BUFFER_LVALUE = NULL;
+               yypop_buffer_state();
+       }
+
+       /* Destroy the stack itself. */
+       yyfree((yy_buffer_stack) );
+       (yy_buffer_stack) = NULL;
+
+    /* Reset the globals. This is important in a non-reentrant scanner so the next time
+     * yylex() is called, initialization will occur. */
+    yy_init_globals( );
+
+    return 0;
+}
+
+/*
+ * Internal utility routines.
+ */
+
+#ifndef yytext_ptr
+static void yy_flex_strncpy (char* s1, yyconst char * s2, int n )
+{
+       register int i;
+       for ( i = 0; i < n; ++i )
+               s1[i] = s2[i];
+}
+#endif
+
+#ifdef YY_NEED_STRLEN
+static int yy_flex_strlen (yyconst char * s )
+{
+       register int n;
+       for ( n = 0; s[n]; ++n )
+               ;
+
+       return n;
+}
+#endif
+
+void *yyalloc (yy_size_t  size )
+{
+       return (void *) malloc( size );
+}
+
+void *yyrealloc  (void * ptr, yy_size_t  size )
+{
+       /* The cast to (char *) in the following accommodates both
+        * implementations that use char* generic pointers, and those
+        * that use void* generic pointers.  It works with the latter
+        * because both ANSI C and C++ allow castless assignment from
+        * any pointer type to void*, and deal with argument conversions
+        * as though doing an assignment.
+        */
+       return (void *) realloc( (char *) ptr, size );
+}
+
+void yyfree (void * ptr )
+{
+       free( (char *) ptr );   /* see yyrealloc() for (char *) cast */
+}
+
+#define YYTABLES_NAME "yytables"
+
+#line 153 "scanner.l"
+
+
+
diff --git a/support/sdk/c/blip/driver/radvd-1.0/scanner.l b/support/sdk/c/blip/driver/radvd-1.0/scanner.l
new file mode 100644 (file)
index 0000000..45c3a17
--- /dev/null
@@ -0,0 +1,153 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996-2000 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+%{
+#include <config.h>
+#include <includes.h>
+#include <radvd.h>
+#include <gram.h>
+
+extern char *conf_file;
+
+int num_lines = 1;
+%}
+
+digit          [0-9]
+number         ({digit})+
+snum           -?({digit})+
+decimal                ({number}"."{number})
+hexdigit       ([a-f]|[A-F]|[0-9])
+addr1          {hexdigit}{1,4}":"({hexdigit}{1,4}":")*(":"{hexdigit}{1,4})+
+addr2          {hexdigit}{1,4}(":"{hexdigit}{1,4})*"::"
+addr3          ({hexdigit}{1,4}":"){7}{hexdigit}{1,4}
+addr           ({addr1}|{addr2}|{addr3}|"::")
+whitespace     ([ \t])+
+string         [a-z]([a-z]|{digit}|_)*([:.]{digit}+)?
+%%
+
+#.*$                   {/* ignore comments */}
+\n                     {num_lines++;}
+{whitespace}           {}
+
+interface              { return T_INTERFACE; }
+prefix                 { return T_PREFIX; }
+route                  { return T_ROUTE; }
+RDNSS                  { return T_RDNSS; }
+
+IgnoreIfMissing                { return T_IgnoreIfMissing; }
+AdvSendAdvert          { return T_AdvSendAdvert; }
+MaxRtrAdvInterval      { return T_MaxRtrAdvInterval; }
+MinRtrAdvInterval      { return T_MinRtrAdvInterval; }
+AdvManagedFlag         { return T_AdvManagedFlag; }
+AdvOtherConfigFlag     { return T_AdvOtherConfigFlag; }
+AdvLinkMTU             { return T_AdvLinkMTU; }
+AdvReachableTime       { return T_AdvReachableTime; }
+AdvRetransTimer                { return T_AdvRetransTimer; }
+AdvCurHopLimit         { return T_AdvCurHopLimit; }
+AdvDefaultLifetime     { return T_AdvDefaultLifetime; }
+AdvDefaultPreference   { return T_AdvDefaultPreference; }
+AdvSourceLLAddress     { return T_AdvSourceLLAddress; }
+
+AdvOnLink              { return T_AdvOnLink; }
+AdvAutonomous          { return T_AdvAutonomous; }
+AdvValidLifetime       { return T_AdvValidLifetime; }
+AdvPreferredLifetime   { return T_AdvPreferredLifetime; }
+
+AdvRouterAddr          { return T_AdvRouterAddr; }
+AdvHomeAgentFlag       { return T_AdvHomeAgentFlag; }
+AdvIntervalOpt         { return T_AdvIntervalOpt; }
+AdvHomeAgentInfo       { return T_AdvHomeAgentInfo; }
+UnicastOnly            { return T_UnicastOnly; }
+
+Base6to4Interface      { return T_Base6to4Interface; }
+
+HomeAgentPreference    { return T_HomeAgentPreference; }
+HomeAgentLifetime      { return T_HomeAgentLifetime; }
+
+AdvRoutePreference     { return T_AdvRoutePreference; }
+AdvRouteLifetime       { return T_AdvRouteLifetime; }
+
+AdvRDNSSPreference     { return T_AdvRDNSSPreference; }
+AdvRDNSSOpen           { return T_AdvRDNSSOpenFlag; }
+AdvRDNSSLifetime       { return T_AdvRDNSSLifetime; }
+
+MinDelayBetweenRAs      { return T_MinDelayBetweenRAs; }
+
+AdvMobRtrSupportFlag   { return T_AdvMobRtrSupportFlag; }
+
+{addr}         {
+                       static struct in6_addr addr;
+                       int i;
+                               
+                       i = inet_pton(AF_INET6, yytext, &addr);
+
+                       dlog(LOG_DEBUG, 4, "inet_pton returned %d", i);
+
+                       /* BSD API draft and NRL's code don't aggree on
+                        * this. the draft specifies a return value of 1 on 
+                        * success, NRL's code returns the address length in 
+                        * bytes on success (16 for an IPv6 address)
+                        */
+                       if (i < 1) {
+                               flog(LOG_ERR, "invalid address in %s, line %d", conf_file,
+                                       num_lines);
+                               return T_BAD_TOKEN;
+                       }
+
+                       yylval.addr = &addr;
+                       return IPV6ADDR;
+               }
+
+{number}       {
+                       unsigned long lnum;
+                       char *endp;
+                       lnum = strtoul(yytext, &endp, 10);
+                       if (*yytext == '\0' || *endp != '\0')
+                               return T_BAD_TOKEN;
+                       if (lnum > 0xFFFFFFFFUL)
+                               return T_BAD_TOKEN;     /* XXX */
+                       yylval.num = lnum;
+                       return NUMBER;
+               }
+
+{snum}         { yylval.snum = atoi(yytext); return SIGNEDNUMBER; }
+
+{decimal}      { yylval.dec = atof(yytext); return DECIMAL; }
+
+infinity       { return INFINITY; }
+
+on                     { yylval.bool = 1; return SWITCH; }
+
+off                    { yylval.bool = 0; return SWITCH; }
+
+low            { yylval.snum = -1; return SIGNEDNUMBER; }
+
+medium         { yylval.snum = 0; return SIGNEDNUMBER; }
+
+high           { yylval.snum = 1; return SIGNEDNUMBER; }
+
+{string}       {
+                       static char name[IFNAMSIZ];
+                               
+                       strncpy(name, yytext, IFNAMSIZ-1);
+                       name[IFNAMSIZ-1] = '\0';
+                       yylval.str = name;
+                       return STRING;
+               }
+
+"{"|"}"|";"|"/"        { return *yytext; }
+
+.              { return T_BAD_TOKEN; }
+%%
diff --git a/support/sdk/c/blip/driver/radvd-1.0/send.c b/support/sdk/c/blip/driver/radvd-1.0/send.c
new file mode 100644 (file)
index 0000000..32d84fd
--- /dev/null
@@ -0,0 +1,359 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+
+
+uint16_t routing_get_seqno();
+
+#define ICMP_EXT_TYPE_BEACON 17
+
+/* SDH : copied from ICMP.h */
+struct AdvMetric {
+  uint8_t type;
+  uint8_t length;
+  uint16_t metric;
+  uint16_t seqno;
+  uint8_t pad[2];
+};
+
+
+void
+send_ra(int sock, struct Interface *iface, struct in6_addr *dest)
+{
+       uint8_t all_hosts_addr[] = {0xff,0x02,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
+       struct sockaddr_in6 addr;
+       struct in6_pktinfo *pkt_info;
+       struct msghdr mhdr;
+       struct cmsghdr *cmsg;
+       struct iovec iov;
+       char chdr[CMSG_SPACE(sizeof(struct in6_pktinfo))];
+       struct nd_router_advert *radvert;
+       struct AdvPrefix *prefix;
+       struct AdvRoute *route;
+       struct AdvRDNSS *rdnss;
+       /* XXX: we don't keep track if buff gets overflowed.  In theory the sysadmin could
+          do that with e.g., too many advertised prefixes or routes, but buff is just so
+          large that this should never happen and if it does, it's admin's fault :-)  */
+       unsigned char buff[MSG_SIZE];
+       int len = 0;
+       int err;
+
+       /* First we need to check that the interface hasn't been removed or deactivated */
+       if(check_device(sock, iface) < 0) {
+               if (iface->IgnoreIfMissing)  /* a bit more quiet warning message.. */
+                       dlog(LOG_DEBUG, 4, "interface %s does not exist, ignoring the interface", iface->Name);
+               else {
+                       flog(LOG_WARNING, "interface %s does not exist, ignoring the interface", iface->Name);
+               }
+               iface->HasFailed = 1;
+       } else {
+               /* check_device was successful, act if it has failed previously */
+               if (iface->HasFailed == 1) {
+                       flog(LOG_WARNING, "interface %s seems to have come back up, trying to reinitialize", iface->Name);
+                       iface->HasFailed = 0;
+                       /* XXX: reinitializes 'iface', so this probably isn't going to work until next send_ra().. */
+                        /* SDH : don't do this since we're not doing config the same way */
+                       /* reload_config(); */
+               }
+       }
+
+       /* Make sure that we've joined the all-routers multicast group */
+       if (check_allrouters_membership(sock, iface) < 0)
+               flog(LOG_WARNING, "problem checking all-routers membership on %s", iface->Name);
+
+       dlog(LOG_DEBUG, 3, "sending RA on %s", iface->Name);
+
+       if (dest == NULL)
+       {
+               struct timeval tv;
+
+               dest = (struct in6_addr *)all_hosts_addr;
+               gettimeofday(&tv, NULL);
+
+               iface->last_multicast_sec = tv.tv_sec;
+               iface->last_multicast_usec = tv.tv_usec;
+       }
+       
+       memset((void *)&addr, 0, sizeof(addr));
+       addr.sin6_family = AF_INET6;
+       addr.sin6_port = htons(IPPROTO_ICMPV6);
+       memcpy(&addr.sin6_addr, dest, sizeof(struct in6_addr));
+
+       memset(&buff, 0, sizeof(buff));
+       radvert = (struct nd_router_advert *) buff;
+
+       radvert->nd_ra_type  = ND_ROUTER_ADVERT;
+       radvert->nd_ra_code  = 0;
+       radvert->nd_ra_cksum = 0;
+
+       radvert->nd_ra_curhoplimit      = iface->AdvCurHopLimit;
+       radvert->nd_ra_flags_reserved   = 
+               (iface->AdvManagedFlag)?ND_RA_FLAG_MANAGED:0;
+       radvert->nd_ra_flags_reserved   |= 
+               (iface->AdvOtherConfigFlag)?ND_RA_FLAG_OTHER:0;
+       /* Mobile IPv6 ext */
+       radvert->nd_ra_flags_reserved   |=
+               (iface->AdvHomeAgentFlag)?ND_RA_FLAG_HOME_AGENT:0;
+
+       /* if forwarding is disabled, send zero router lifetime */
+        /* SDH : disable this check too */
+       /* radvert->nd_ra_router_lifetime        =  !check_ip6_forwarding() ? htons(iface->AdvDefaultLifetime) : 0; */
+       radvert->nd_ra_flags_reserved   |=
+               (iface->AdvDefaultPreference << ND_OPT_RI_PRF_SHIFT) & ND_OPT_RI_PRF_MASK;
+
+       radvert->nd_ra_reachable  = htonl(iface->AdvReachableTime);
+       radvert->nd_ra_retransmit = htonl(iface->AdvRetransTimer);
+
+       len = sizeof(struct nd_router_advert);
+
+       prefix = iface->AdvPrefixList;
+
+       /*
+        *      add prefix options
+        */
+
+       while(prefix)
+       {
+               if( prefix->enabled )
+               {
+                       struct nd_opt_prefix_info *pinfo;
+                       
+                       pinfo = (struct nd_opt_prefix_info *) (buff + len);
+
+                       pinfo->nd_opt_pi_type        = ND_OPT_PREFIX_INFORMATION;
+                       pinfo->nd_opt_pi_len         = 4;
+                       pinfo->nd_opt_pi_prefix_len  = prefix->PrefixLen;
+                       
+                       pinfo->nd_opt_pi_flags_reserved  = 
+                               (prefix->AdvOnLinkFlag)?ND_OPT_PI_FLAG_ONLINK:0;
+                       pinfo->nd_opt_pi_flags_reserved |=
+                               (prefix->AdvAutonomousFlag)?ND_OPT_PI_FLAG_AUTO:0;
+                       /* Mobile IPv6 ext */
+                       pinfo->nd_opt_pi_flags_reserved |=
+                               (prefix->AdvRouterAddr)?ND_OPT_PI_FLAG_RADDR:0;
+
+                       pinfo->nd_opt_pi_valid_time     = htonl(prefix->AdvValidLifetime);
+                       pinfo->nd_opt_pi_preferred_time = htonl(prefix->AdvPreferredLifetime);
+                       pinfo->nd_opt_pi_reserved2      = 0;
+                       
+                       memcpy(&pinfo->nd_opt_pi_prefix, &prefix->Prefix,
+                              sizeof(struct in6_addr));
+
+                       len += sizeof(*pinfo);
+               }
+
+               prefix = prefix->next;
+       }
+       
+       route = iface->AdvRouteList;
+
+       /*
+        *      add route options
+        */
+
+       while(route)
+       {
+               struct nd_opt_route_info_local *rinfo;
+               
+               rinfo = (struct nd_opt_route_info_local *) (buff + len);
+
+               rinfo->nd_opt_ri_type        = ND_OPT_ROUTE_INFORMATION;
+               /* XXX: the prefixes are allowed to be sent in smaller chunks as well */
+               rinfo->nd_opt_ri_len         = 3;
+               rinfo->nd_opt_ri_prefix_len  = route->PrefixLen;
+                       
+               rinfo->nd_opt_ri_flags_reserved  =
+                       (route->AdvRoutePreference << ND_OPT_RI_PRF_SHIFT) & ND_OPT_RI_PRF_MASK;
+               rinfo->nd_opt_ri_lifetime       = htonl(route->AdvRouteLifetime);
+                       
+               memcpy(&rinfo->nd_opt_ri_prefix, &route->Prefix,
+                      sizeof(struct in6_addr));
+               len += sizeof(*rinfo);
+
+               route = route->next;
+       }
+       
+       rdnss = iface->AdvRDNSSList;
+       
+       /*
+        *      add rdnss options
+        */
+
+       while(rdnss)
+       {
+               struct nd_opt_rdnss_info_local *rdnssinfo;
+               
+               rdnssinfo = (struct nd_opt_rdnss_info_local *) (buff + len);
+
+               rdnssinfo->nd_opt_rdnssi_type        = ND_OPT_RDNSS_INFORMATION;
+               rdnssinfo->nd_opt_rdnssi_len         = 1 + 2*rdnss->AdvRDNSSNumber;
+               rdnssinfo->nd_opt_rdnssi_pref_flag_reserved = 
+               ((rdnss->AdvRDNSSPreference << ND_OPT_RDNSSI_PREF_SHIFT) & ND_OPT_RDNSSI_PREF_MASK);
+               rdnssinfo->nd_opt_rdnssi_pref_flag_reserved |=
+               ((rdnss->AdvRDNSSOpenFlag)?ND_OPT_RDNSSI_FLAG_S:0);
+
+               rdnssinfo->nd_opt_rdnssi_lifetime       = htonl(rdnss->AdvRDNSSLifetime);
+                       
+               memcpy(&rdnssinfo->nd_opt_rdnssi_addr1, &rdnss->AdvRDNSSAddr1,
+                      sizeof(struct in6_addr));
+               memcpy(&rdnssinfo->nd_opt_rdnssi_addr2, &rdnss->AdvRDNSSAddr2,
+                      sizeof(struct in6_addr));
+               memcpy(&rdnssinfo->nd_opt_rdnssi_addr3, &rdnss->AdvRDNSSAddr3,
+                      sizeof(struct in6_addr));
+               len += sizeof(*rdnssinfo) - (3-rdnss->AdvRDNSSNumber)*sizeof(struct in6_addr);
+
+               rdnss = rdnss->next;
+       }
+       
+       /*
+        *      add MTU option
+        */
+
+       if (iface->AdvLinkMTU != 0) {
+               struct nd_opt_mtu *mtu;
+               
+               mtu = (struct nd_opt_mtu *) (buff + len);
+       
+               mtu->nd_opt_mtu_type     = ND_OPT_MTU;
+               mtu->nd_opt_mtu_len      = 1;
+               mtu->nd_opt_mtu_reserved = 0; 
+               mtu->nd_opt_mtu_mtu      = htonl(iface->AdvLinkMTU);
+
+               len += sizeof(*mtu);
+       }
+
+       /*
+        * add Source Link-layer Address option
+        */
+
+       if (iface->AdvSourceLLAddress && iface->if_hwaddr_len != -1)
+       {
+               uint8_t *ucp;
+               unsigned int i;
+
+               ucp = (uint8_t *) (buff + len);
+       
+               *ucp++  = ND_OPT_SOURCE_LINKADDR;
+               *ucp++  = (uint8_t) ((iface->if_hwaddr_len + 16 + 63) >> 6);
+
+               len += 2 * sizeof(uint8_t);
+
+               i = (iface->if_hwaddr_len + 7) >> 3;
+               memcpy(buff + len, iface->if_hwaddr, i);
+               len += i;
+       }
+
+       /*
+        * Mobile IPv6 ext: Advertisement Interval Option to support
+        * movement detection of mobile nodes
+        */
+
+       if(iface->AdvIntervalOpt)
+       {
+               struct AdvInterval a_ival;
+                uint32_t ival;
+                if(iface->MaxRtrAdvInterval < Cautious_MaxRtrAdvInterval){
+                       ival  = ((iface->MaxRtrAdvInterval +
+                                 Cautious_MaxRtrAdvInterval_Leeway ) * 1000);
+
+                }
+                else {
+                       ival  = (iface->MaxRtrAdvInterval * 1000);
+                }
+               a_ival.type     = ND_OPT_RTR_ADV_INTERVAL;
+               a_ival.length   = 1;
+               a_ival.reserved = 0;
+               a_ival.adv_ival = htonl(ival);
+
+               memcpy(buff + len, &a_ival, sizeof(a_ival));
+               len += sizeof(a_ival);
+       }
+
+       /*
+        * Mobile IPv6 ext: Home Agent Information Option to support
+        * Dynamic Home Agent Address Discovery
+        */
+
+       if(iface->AdvHomeAgentInfo &&
+          (iface->AdvMobRtrSupportFlag || iface->HomeAgentPreference != 0 ||
+           iface->HomeAgentLifetime != iface->AdvDefaultLifetime))
+
+       {
+               struct HomeAgentInfo ha_info;
+               ha_info.type            = ND_OPT_HOME_AGENT_INFO;
+               ha_info.length          = 1;
+               ha_info.flags_reserved  =
+                       (iface->AdvMobRtrSupportFlag)?ND_OPT_HAI_FLAG_SUPPORT_MR:0;
+               ha_info.preference      = htons(iface->HomeAgentPreference);
+               ha_info.lifetime        = htons(iface->HomeAgentLifetime);
+
+               memcpy(buff + len, &ha_info, sizeof(ha_info));
+               len += sizeof(ha_info);
+       }
+
+  {
+    /* add routing metric */
+    struct AdvMetric metric;
+    metric.type = ICMP_EXT_TYPE_BEACON;
+    metric.length = 1;
+    metric.metric = htons(0);
+    metric.seqno = htons(routing_get_seqno());
+    memset(metric.pad, 0, sizeof(metric.pad));
+
+    memcpy(buff + len, &metric, sizeof(struct AdvMetric));
+    len += sizeof(struct AdvMetric);
+  }
+       
+       iov.iov_len  = len;
+       iov.iov_base = (caddr_t) buff;
+       
+       memset(chdr, 0, sizeof(chdr));
+       cmsg = (struct cmsghdr *) chdr;
+       
+       cmsg->cmsg_len   = CMSG_LEN(sizeof(struct in6_pktinfo));
+       cmsg->cmsg_level = IPPROTO_IPV6;
+       cmsg->cmsg_type  = IPV6_PKTINFO;
+       
+       pkt_info = (struct in6_pktinfo *)CMSG_DATA(cmsg);
+       pkt_info->ipi6_ifindex = iface->if_index;
+       memcpy(&pkt_info->ipi6_addr, &iface->if_addr, sizeof(struct in6_addr));
+
+#ifdef HAVE_SIN6_SCOPE_ID
+       if (IN6_IS_ADDR_LINKLOCAL(&addr.sin6_addr) ||
+               IN6_IS_ADDR_MC_LINKLOCAL(&addr.sin6_addr))
+                       addr.sin6_scope_id = iface->if_index;
+#endif
+
+       memset(&mhdr, 0, sizeof(mhdr));
+       mhdr.msg_name = (caddr_t)&addr;
+       mhdr.msg_namelen = sizeof(struct sockaddr_in6);
+       mhdr.msg_iov = &iov;
+       mhdr.msg_iovlen = 1;
+       mhdr.msg_control = (void *) cmsg;
+       mhdr.msg_controllen = sizeof(chdr);
+
+       err = sendmsg(sock, &mhdr, 0);
+       
+       if (err < 0) {
+               if (!iface->IgnoreIfMissing || !(errno == EINVAL || errno == ENODEV))
+                       flog(LOG_WARNING, "sendmsg: %s", strerror(errno));
+               else
+                       dlog(LOG_DEBUG, 3, "sendmsg: %s", strerror(errno));
+       }
+}
diff --git a/support/sdk/c/blip/driver/radvd-1.0/socket.c b/support/sdk/c/blip/driver/radvd-1.0/socket.c
new file mode 100644 (file)
index 0000000..8c7ad6c
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+
+/* Note: these are applicable to receiving sockopts only */
+#if defined IPV6_HOPLIMIT && !defined IPV6_RECVHOPLIMIT
+# define IPV6_RECVHOPLIMIT IPV6_HOPLIMIT
+#endif
+
+#if defined IPV6_PKTINFO && !defined IPV6_RECVPKTINFO
+# define IPV6_RECVPKTINFO IPV6_PKTINFO
+#endif
+
+int
+open_icmpv6_socket(void)
+{
+       int sock;
+       struct icmp6_filter filter;
+       int err, val;
+
+        sock = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
+       if (sock < 0)
+       {
+               flog(LOG_ERR, "can't create socket(AF_INET6): %s", strerror(errno));
+               return (-1);
+       }
+
+       val = 1;
+       err = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val));
+       if (err < 0)
+       {
+               flog(LOG_ERR, "setsockopt(IPV6_RECVPKTINFO): %s", strerror(errno));
+               return (-1);
+       }
+
+       val = 2;
+#ifdef __linux__
+       err = setsockopt(sock, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val));
+#else
+       err = setsockopt(sock, IPPROTO_IPV6, IPV6_CHECKSUM, &val, sizeof(val));
+#endif
+       if (err < 0)
+       {
+               flog(LOG_ERR, "setsockopt(IPV6_CHECKSUM): %s", strerror(errno));
+               return (-1);
+       }
+
+       val = 255;
+       err = setsockopt(sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, sizeof(val));
+       if (err < 0)
+       {
+               flog(LOG_ERR, "setsockopt(IPV6_UNICAST_HOPS): %s", strerror(errno));
+               return (-1);
+       }
+
+       val = 255;
+       err = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val));
+       if (err < 0)
+       {
+               flog(LOG_ERR, "setsockopt(IPV6_MULTICAST_HOPS): %s", strerror(errno));
+               return (-1);
+       }
+
+#ifdef IPV6_RECVHOPLIMIT
+       val = 1;
+       err = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &val, sizeof(val));
+       if (err < 0)
+       {
+               flog(LOG_ERR, "setsockopt(IPV6_RECVHOPLIMIT): %s", strerror(errno));
+               return (-1);
+       }
+#endif
+
+       /*
+        * setup ICMP filter
+        */
+       
+       ICMP6_FILTER_SETBLOCKALL(&filter);
+       ICMP6_FILTER_SETPASS(ND_ROUTER_SOLICIT, &filter);
+       ICMP6_FILTER_SETPASS(ND_ROUTER_ADVERT, &filter);
+
+       err = setsockopt(sock, IPPROTO_ICMPV6, ICMP6_FILTER, &filter,
+                        sizeof(filter));
+       if (err < 0)
+       {
+               flog(LOG_ERR, "setsockopt(ICMPV6_FILTER): %s", strerror(errno));
+               return (-1);
+       }
+
+       return sock;
+}
diff --git a/support/sdk/c/blip/driver/radvd-1.0/stamp-h b/support/sdk/c/blip/driver/radvd-1.0/stamp-h
new file mode 100644 (file)
index 0000000..9788f70
--- /dev/null
@@ -0,0 +1 @@
+timestamp
diff --git a/support/sdk/c/blip/driver/radvd-1.0/stamp-h.in b/support/sdk/c/blip/driver/radvd-1.0/stamp-h.in
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/support/sdk/c/blip/driver/radvd-1.0/timer.c b/support/sdk/c/blip/driver/radvd-1.0/timer.c
new file mode 100644 (file)
index 0000000..4879c66
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Pedro Roque              <roque@di.fc.ul.pt>
+ *    Lars Fenneberg           <lf@elemental.net>
+ *
+ *   This software is Copyright 1996-2000 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+
+static struct timer_lst timers_head = {
+       {LONG_MAX, LONG_MAX},
+       NULL, NULL,
+       &timers_head, &timers_head
+};
+
+static void alarm_handler(int sig);
+int inline check_time_diff(struct timer_lst *tm, struct timeval tv);
+
+static void
+schedule_timer(void)
+{
+       struct timer_lst *tm = timers_head.next;
+       struct timeval tv;
+
+       gettimeofday(&tv, NULL);
+
+       if (tm != &timers_head)
+       {
+               struct itimerval next;
+              
+               memset(&next, 0, sizeof(next));
+              
+               timersub(&tm->expires, &tv, &next.it_value);
+
+               signal(SIGALRM, alarm_handler);
+
+               if ((next.it_value.tv_sec > 0) || 
+                               ((next.it_value.tv_sec == 0) && (next.it_value.tv_usec > 0)))
+               {
+                       dlog(LOG_DEBUG, 4, "calling alarm: %ld secs, %ld usecs", 
+                                       next.it_value.tv_sec, next.it_value.tv_usec);
+
+                       if(setitimer(ITIMER_REAL, &next,  NULL))
+                               flog(LOG_WARNING, "schedule_timer setitimer for %ld.%ld failed: %s",
+                                       next.it_value.tv_sec, next.it_value.tv_usec, strerror(errno));
+               }
+               else
+               {
+                       dlog(LOG_DEBUG, 4, "next timer has already expired, queueing signal");  
+                       kill(getpid(), SIGALRM);
+               }
+       }
+}
+
+void
+set_timer(struct timer_lst *tm, double secs)
+{
+       struct timeval tv;
+       struct timer_lst *lst;
+       sigset_t bmask, oldmask;
+       struct timeval firein;
+
+       dlog(LOG_DEBUG, 3, "setting timer: %.2f secs", secs);
+
+       firein.tv_sec = (long)secs;
+       firein.tv_usec = (long)((secs - (double)firein.tv_sec) * 1000000);
+
+       dlog(LOG_DEBUG, 5, "setting timer: %ld secs %ld usecs", firein.tv_sec, firein.tv_usec);
+
+       gettimeofday(&tv, NULL);
+       timeradd(&tv, &firein, &tm->expires);
+
+       sigemptyset(&bmask);
+       sigaddset(&bmask, SIGALRM);
+       sigprocmask(SIG_BLOCK, &bmask, &oldmask);
+
+       lst = &timers_head;
+
+       /* the timers are in the list in the order they expire, the soonest first */
+       do {
+               lst = lst->next;
+       } while ((tm->expires.tv_sec > lst->expires.tv_sec) ||
+                ((tm->expires.tv_sec == lst->expires.tv_sec) && 
+                 (tm->expires.tv_usec > lst->expires.tv_usec)));
+
+       tm->next = lst;
+       tm->prev = lst->prev;
+       lst->prev = tm;
+       tm->prev->next = tm;
+
+       dlog(LOG_DEBUG, 5, "calling schedule_timer from set_timer context");
+       schedule_timer();
+
+       sigprocmask(SIG_SETMASK, &oldmask, NULL);
+}
+
+void
+clear_timer(struct timer_lst *tm)
+{
+       sigset_t bmask, oldmask;
+
+       sigemptyset(&bmask);
+       sigaddset(&bmask, SIGALRM);
+       sigprocmask(SIG_BLOCK, &bmask, &oldmask);
+       
+       tm->prev->next = tm->next;
+       tm->next->prev = tm->prev;
+       
+       tm->prev = tm->next = NULL;
+       
+       dlog(LOG_DEBUG, 5, "calling schedule_timer from clear_timer context");
+       schedule_timer();
+
+       sigprocmask(SIG_SETMASK, &oldmask, NULL);
+}
+
+static void
+alarm_handler(int sig)
+{
+       struct timer_lst *tm, *back;
+       struct timeval tv;
+       gettimeofday(&tv, NULL);
+       tm = timers_head.next;
+
+       /*
+        * This handler is called when the alarm goes off, so at least one of
+        * the interfaces' timers should satisfy the while condition.
+        *
+        * Sadly, this is not always the case, at least on Linux kernels:
+        * see http://lkml.org/lkml/2005/4/29/163. :-(.  It seems some
+        * versions of timers are not accurate and get called up to a couple of
+        * hundred microseconds before they expire.
+        *
+        * Therefore we allow some inaccuracy here; it's sufficient for us
+        * that a timer should go off in a millisecond.
+        */
+
+       /* unused timers are initialized to LONG_MAX so we skip them */
+       while (tm->expires.tv_sec != LONG_MAX && check_time_diff(tm, tv))
+       {               
+               tm->prev->next = tm->next;
+               tm->next->prev = tm->prev;
+
+               back = tm;
+               tm = tm->next;
+               back->prev = back->next = NULL;
+
+               (*back->handler)(back->data);
+       }
+
+       dlog(LOG_DEBUG, 5, "calling schedule_timer from alarm_handler context");
+       schedule_timer();
+}
+
+
+void
+init_timer(struct timer_lst *tm, void (*handler)(void *), void *data)
+{
+       memset(tm, 0, sizeof(struct timer_lst));
+       tm->handler = handler;
+       tm->data = data;
+}
+
+int inline
+check_time_diff(struct timer_lst *tm, struct timeval tv)
+{
+       struct itimerval diff;
+       memset(&diff, 0, sizeof(diff));
+
+       #define ALLOW_CLOCK_USEC 1000
+
+       timersub(&tm->expires, &tv, &diff.it_value);
+       dlog(LOG_DEBUG, 5, "check_time_diff, difference: %ld sec + %ld usec",
+               diff.it_value.tv_sec, diff.it_value.tv_usec);
+
+       if (diff.it_value.tv_sec <= 0) {
+               /* already gone, this is the "good" case */
+               if (diff.it_value.tv_sec < 0)
+                       return 1;
+#ifdef __linux__ /* we haven't seen this on other OSes */
+               /* still OK if the expiry time is not too much in the future */
+               else if (diff.it_value.tv_usec > 0 &&
+                           diff.it_value.tv_usec <= ALLOW_CLOCK_USEC) {
+                       dlog(LOG_DEBUG, 4, "alarm_handler clock was probably off by %ld usec, allowing %u",
+                            tm->expires.tv_usec-tv.tv_usec, ALLOW_CLOCK_USEC);
+                       return 2;
+               }
+#endif /* __linux__ */
+               else /* scheduled intentionally in the future? */
+                       return 0;
+       }
+       return 0;
+}
diff --git a/support/sdk/c/blip/driver/radvd-1.0/util.c b/support/sdk/c/blip/driver/radvd-1.0/util.c
new file mode 100644 (file)
index 0000000..70029df
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ *   $Id$
+ *
+ *   Authors:
+ *    Lars Fenneberg           <lf@elemental.net>       
+ *
+ *   This software is Copyright 1996,1997 by the above mentioned author(s), 
+ *   All Rights Reserved.
+ *
+ *   The license which is distributed with this software in the file COPYRIGHT
+ *   applies to this software. If your distribution is missing this file, you
+ *   may request it from <pekkas@netcore.fi>.
+ *
+ */
+
+#include "config.h"
+#include "includes.h"
+#include "radvd.h"
+               
+void
+mdelay(double msecs)
+{
+       struct timeval tv;
+                
+       tv.tv_sec = (time_t)(msecs / 1000.0);
+       tv.tv_usec = (suseconds_t)((msecs - tv.tv_sec * 1000.0) * 1000.0);
+
+       select(0,(fd_set *)NULL,(fd_set *)NULL,(fd_set *)NULL, &tv);
+}
+
+double
+rand_between(double lower, double upper)
+{
+       return ((upper - lower) / (RAND_MAX + 1.0) * rand() + lower);
+}
+
+void
+print_addr(struct in6_addr *addr, char *str)
+{
+       const char *res;
+
+       /* XXX: overflows 'str' if it isn't big enough */
+       res = inet_ntop(AF_INET6, (void *)addr, str, INET6_ADDRSTRLEN);
+       
+       if (res == NULL) 
+       {
+               flog(LOG_ERR, "print_addr: inet_ntop: %s", strerror(errno));            
+               strcpy(str, "[invalid address]");       
+       }
+}
+
+/* Check if an in6_addr exists in the rdnss list */
+int
+check_rdnss_presence(struct AdvRDNSS *rdnss, struct in6_addr *addr)
+{
+       while (rdnss) {
+               if (    !memcmp(&rdnss->AdvRDNSSAddr1, addr, sizeof(struct in6_addr)) 
+                    || !memcmp(&rdnss->AdvRDNSSAddr2, addr, sizeof(struct in6_addr))
+                    || !memcmp(&rdnss->AdvRDNSSAddr3, addr, sizeof(struct in6_addr)) )
+                       break; /* rdnss address found in the list */
+               else
+                       rdnss = rdnss->next; /* no match */
+       }
+       return (rdnss != NULL);
+}
diff --git a/support/sdk/c/blip/driver/radvd-wrapper.c b/support/sdk/c/blip/driver/radvd-wrapper.c
new file mode 100644 (file)
index 0000000..97723e4
--- /dev/null
@@ -0,0 +1,198 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/* 
+ * radvd-wrapper.c
+ * author: Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
+ *
+ * Alternate set of call points for the IPv6 router advertisement
+ * daemon.  Using this interface the daemon may be integrated into
+ * another program (like ip-driver).  radvd is distributed under a
+ * BSD-like license.
+ *
+ * radvd_init() must be called to set up state for the specified
+ *   interface.  If successful, it will return a file descriptor;
+ *   radvd_process() must be called whenever there is pending data on
+ *   this descriptor (ie, from a select() loop.)
+ *
+ * radvd has its own logging infrastructure; by default radvd_init()
+ * sends that log to stderr and makes no attempt to integrate it with
+ * whatever logging facilities may be availabile.  See radvd/log.c for
+ * more.
+ *
+ * NB: radvd uses SIGALRM for its internal timer.  Thus, once
+ * radvd_init() has been called, SIGALRM must not be used elsewhere in
+ * the application.
+ *
+ */
+
+
+#include "radvd-1.0/includes.h"
+#include "radvd-1.0/radvd.h"
+#include "radvd-1.0/pathnames.h"
+
+#include "logging.h"
+#include "config.h"
+
+struct Interface *iface;
+int sock;
+
+void radvd_timer_handler(void *data) {
+  struct Interface *iface = (struct Interface *) data;
+  double next;
+
+  dlog(LOG_DEBUG, 4, "timer_handler called for %s", iface->Name);
+
+  send_ra(sock, iface, NULL);
+
+  next = rand_between(iface->MinRtrAdvInterval, iface->MaxRtrAdvInterval); 
+
+  if (iface->init_racount < MAX_INITIAL_RTR_ADVERTISEMENTS) {
+    iface->init_racount++;
+    next = min(MAX_INITIAL_RTR_ADVERT_INTERVAL, next);
+  }
+
+  set_timer(&iface->tm, next);
+}
+
+void radvd_reset_adverts(void) {
+  if (iface->AdvSendAdvert) {
+    /* send an initial advertisement */
+    send_ra(sock, iface, NULL);
+    
+    iface->init_racount = 0;
+
+    set_timer(&iface->tm,
+              min(MAX_INITIAL_RTR_ADVERT_INTERVAL,
+                  iface->MaxRtrAdvInterval));
+  }
+}
+
+
+void radvd_kickoff_adverts(void) {
+  init_timer(&iface->tm, radvd_timer_handler, (void *) iface);
+  if (iface->AdvSendAdvert) {
+    /* send an initial advertisement */
+    send_ra(sock, iface, NULL);
+    
+    iface->init_racount++;
+
+    set_timer(&iface->tm,
+              min(MAX_INITIAL_RTR_ADVERT_INTERVAL,
+                  iface->MaxRtrAdvInterval));
+  }
+}
+
+void radvd_process() {
+  unsigned char msg[MSG_SIZE];
+  int len, hoplimit;
+  struct sockaddr_in6 rcv_addr;
+  struct in6_pktinfo *pkt_info = NULL;
+  
+  len = recv_rs_ra(sock, msg, &rcv_addr, &pkt_info, &hoplimit);
+  if (len > 0)
+    process(sock, iface, msg, len, 
+            &rcv_addr, pkt_info, hoplimit);
+  
+}
+
+
+/* Set up all the radvd internal stuff from our own configuration */
+int radvd_init(char *ifname, struct config *c) {
+  struct AdvPrefix *prefix;
+  sigset_t oset, nset;
+
+
+  if (log_open(L_STDERR, "radvd", NULL, -1) < 0) {
+    error("log_open\n");
+    return -1;
+  }
+  srand((unsigned int)time(NULL));
+  info("starting radvd on device %s\n", ifname);
+
+  sock = open_icmpv6_socket();
+  if (sock < 0) {
+    error("open_icmpv6_socket\n");
+    return -1;
+  }
+  sigemptyset(&nset);
+  sigaddset(&nset, SIGALRM);
+  sigprocmask(SIG_UNBLOCK, &nset, &oset);
+  if (sigismember(&oset, SIGALRM))
+    flog(LOG_WARNING, "SIGALRM has been unblocked. Your startup environment might be wrong.");
+
+
+  /* setup the radvd struct Interface to know about all our defaults */
+  iface = malloc(sizeof(struct Interface));
+  if (iface == NULL)
+    return -1;
+
+  iface_init_defaults(iface);
+  strncpy(iface->Name, ifname, IFNAMSIZ-1);
+  iface->Name[IFNAMSIZ-1] = '\0';
+
+  iface->next = NULL;
+  iface->AdvSendAdvert = 1;
+
+  /* check the interface exists... this probably shouldn't fail */
+  if (check_device(sock, iface) < 0) {
+    error("check_device!\n");
+    return -1;
+  }
+  
+  if (setup_deviceinfo(sock, iface) < 0) {
+    error("setup_deviceinfo\n");
+    return -1;
+  }
+  if (check_iface(iface) < 0) {
+    error("check_iface\n");
+    return -1;
+  }
+  if (setup_linklocal_addr(sock, iface) < 0) {
+    error("setup_linklocal_addr\n");
+    return -1;
+  }
+  if (setup_allrouters_membership(sock, iface) < 0) {
+    error("setup_allrouters_membership\n");
+    return -1;
+  }
+
+
+  /* set up the prefix we're advertising from the config struct we get passed in. */
+  prefix = malloc(sizeof(struct AdvPrefix));
+  if (prefix == NULL)
+    return -1;
+
+  prefix_init_defaults(prefix);
+  prefix->PrefixLen = 64;
+  memcpy(&prefix->Prefix, c->router_addr.s6_addr, sizeof(struct in6_addr));
+  prefix->next = NULL;
+
+  iface->AdvPrefixList = prefix;
+
+
+  // config_interface();
+  radvd_kickoff_adverts();
+
+  set_debuglevel(0);
+
+  return sock;
+}
diff --git a/support/sdk/c/blip/driver/routing.c b/support/sdk/c/blip/driver/routing.c
new file mode 100644 (file)
index 0000000..5640e36
--- /dev/null
@@ -0,0 +1,425 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <net/if.h>
+#include <arpa/inet.h>
+#include <sys/select.h>
+#include <net/route.h>
+#include <sys/ioctl.h>
+#include <sys/time.h>
+
+#include <lib6lowpan/6lowpan.h>
+#include <lib6lowpan/lib6lowpan.h>
+#include "routing.h"
+#include "nwstate.h"
+#include "logging.h"
+#include "config.h"
+#include "mcast.h"
+#include "netlink.h"
+
+static ieee154_saddr_t my_short_addr;
+static uint16_t current_seqno;
+extern struct in6_addr  __my_address;
+
+char proxy_dev[IFNAMSIZ], tun_dev[IFNAMSIZ];
+int mcast_sock;
+
+char report_buf[ROUTMSGSIZ];
+
+/*
+ * Call to setup routing tables.
+ *
+ */
+int routing_init(struct config *c, char *tun_name) {
+  FILE *fd;
+  char buf[256];
+  my_short_addr = ntohs(__my_address.s6_addr16[7]);
+  strncpy(proxy_dev, c->proxy_dev, IFNAMSIZ);
+  strncpy(tun_dev, tun_name, IFNAMSIZ);
+
+  // set up the network state data structures
+  nw_init();
+
+  // start a netlink session to the kernel
+  nl_init();
+
+  mcast_sock = mcast_start(proxy_dev);;
+
+  if ((fd = fopen("/proc/sys/net/ipv6/conf/all/forwarding", "w")) == NULL) {
+    log_fatal_perror("enable forwarding");
+    return -1;
+  }
+  fprintf(fd, "1");
+  fclose(fd);
+
+  snprintf(buf, sizeof(buf), "/proc/sys/net/ipv6/conf/%s/proxy_ndp", proxy_dev);
+  if ((fd = fopen(buf, "w")) == NULL) {
+    warn("unable to enable IPv6 ND proxy on %s\n", proxy_dev);
+  } else {
+    fprintf(fd, "1");
+    fclose(fd);
+  }
+
+  if ((fd = fopen("/var/run/ip-driver.seq", "r")) != NULL) {
+    if (fscanf(fd, "%hi\n", &current_seqno) != 1) {
+      current_seqno = 0;
+    }
+    fclose(fd);
+  }
+
+  return (mcast_sock >= 0) ? 0 : -1;
+}
+
+int routing_add_fds(fd_set *fds) {
+  if (mcast_sock >=0) {
+    FD_SET(mcast_sock, fds);
+  }
+  return mcast_sock;
+}
+
+int route_cmd(int cmd, struct in6_addr *dest, char *dev) {
+  struct in6_rtmsg rt;
+  memset((char *) &rt, 0, sizeof(struct in6_rtmsg));
+  memcpy(&rt.rtmsg_dst, dest, sizeof(struct in6_addr));
+
+  rt.rtmsg_flags = RTF_UP | RTF_HOST;
+  rt.rtmsg_metric = 1;
+  rt.rtmsg_dst_len = 128;
+  rt.rtmsg_ifindex = if_nametoindex(dev);
+
+  return ioctl(mcast_sock, cmd, &rt);
+}        
+
+
+int routing_process(fd_set *fds) {
+  struct sockaddr_in6 from;
+  char buf[ROUTMSGSIZ], *cur, printbuf[100];
+  struct routing_message *rmsg;
+  struct topology_header_package *th;
+  int len;
+  struct in6_addr addr;
+
+  if (mcast_sock < 0 || !FD_ISSET(mcast_sock, fds)) return 0;
+
+  len = mcast_recvfrom(&from, buf, sizeof(buf));
+  rmsg = (struct routing_message *)buf;
+
+  inet_ntop(AF_INET6, &from.sin6_addr, printbuf, sizeof(printbuf));
+  debug("processing routing message from %s type %i\n", printbuf, rmsg->type);
+
+  memset(&addr, 0, sizeof(struct in6_addr));
+  memcpy(addr.s6_addr, __my_address.s6_addr, 8);
+
+  switch (rmsg->type) {
+  case RMSG_TOPOLOGY:
+    cur = rmsg->data;
+    len -= sizeof(struct routing_message);
+    while (len > 0) {
+      router_t *router;
+      int header_len, i;
+      node_id_t reporter;
+
+      th = (struct topology_header_package *)cur;
+      header_len = ntohs(th->len);
+      reporter = ntohs(th->reporter);
+
+      nw_unmark_links(reporter);
+      for (i = 0; i < (header_len - sizeof(struct topology_header_package))/sizeof(struct topology_entry); i++) {
+
+        nw_add_incr_edge(reporter, &th->topo[i]);
+
+        router = nw_get_router(reporter);
+        gettimeofday(&router->lastReport, NULL);
+        
+        if (router == NULL) continue;
+        addr.s6_addr16[7] = htons(reporter);
+
+        if (rmsg->source == __my_address.s6_addr16[7] && !router->isProxying) {
+          // if I sent this report, make sure we are proxying for him
+          info("Starting to proxy for 0x%x\n", reporter);
+
+          if (route_cmd(SIOCADDRT, &addr, tun_dev) < 0) {
+            log_fatal_perror("route_add");
+          }
+
+          nl_nd_add_proxy(&addr, proxy_dev);
+          router->isProxying = TRUE;
+        }
+        if (rmsg->source != __my_address.s6_addr16[7] && router->isProxying) {
+          info("Was proxying 0x%x, but he has moved\n", reporter);
+          if (route_cmd(SIOCDELRT, &addr, tun_dev) < 0) {
+            log_fatal_perror("route_del");
+          }
+
+          nl_nd_del_neigh(&addr, proxy_dev);
+          router->isProxying = FALSE;
+        }
+      }
+      nw_clear_unmarked(reporter);
+
+      router = nw_get_router(ntohs(rmsg->source));
+      if (router != NULL && !router->isController) {
+        nw_add_controller(ntohs(rmsg->source));
+      }
+      
+      cur += header_len;
+      len -= header_len;
+    }
+    break;
+  }
+  return 0;
+}
+
+int routing_add_report(node_id_t reporter, struct tlv_hdr *tlv) {
+  struct topology_header *th = (struct topology_header *)(tlv + 1);
+  struct routing_message *rmsg;
+  struct topology_header_package *pack;
+
+  rmsg = (struct routing_message *)report_buf;
+  pack = (struct topology_header_package *)&rmsg->data[0];
+
+  memset(report_buf, 0, sizeof(report_buf));
+
+  debug("routing_add_report: report from 0x%x seq: %i\n", reporter, th->seqno);
+
+  rmsg->type = RMSG_TOPOLOGY;
+  rmsg->source = __my_address.s6_addr16[7];
+  pack->reporter = htons(reporter);
+  pack->seqno = th->seqno;
+  pack->len      = htons(tlv->len - 
+                         sizeof(struct tlv_hdr) -
+                         sizeof(struct topology_header) + 
+                         sizeof(struct topology_header_package));
+
+  memcpy(pack->topo, th->topo, tlv->len - sizeof(struct tlv_hdr) -
+         sizeof(struct topology_header));
+  
+  mcast_send(report_buf, ntohs(pack->len) + sizeof(struct routing_message));
+
+  return 0;
+}
+
+
+/*
+ * @returns: truth value indicating if the destination of the packet
+ * is a single hop, and requires no source route.
+ */
+int routing_is_onehop(struct split_ip_msg *msg) {
+  path_t *path;
+  int ret = ROUTE_NO_ROUTE;
+
+  if (msg->hdr.ip6_dst.s6_addr[0] == 0xff &&
+      (msg->hdr.ip6_dst.s6_addr[1] & 0xf) <= 0x2)
+    return ROUTE_ONEHOP;
+
+
+#if 0
+  if (msg->hdr.nxt_hdr == NXTHDR_SOURCE) {
+    debug("routing_is_onehop: Source header\n");
+    return ROUTE_SOURCE;
+  }
+#endif
+
+  path = nw_get_route(my_short_addr, ntohs(msg->hdr.ip6_dst.s6_addr16[7]));
+  
+  if (path != NULL) {
+    if (path->isController) {
+      ret = ROUTE_WORMHOLE;
+    } else if (path->length == 1) {
+      ret = ROUTE_ONEHOP;
+    } else {
+      ret = ROUTE_MHOP;
+    }
+  }
+  debug("routing_is_onehop: 0x%x\n", ret);
+  nw_free_path(path);
+  return ret;
+}
+
+/*
+ * Identical to routing_insert_route, except allows for a detour route
+ */
+/*uint8_t routing_insert_route_indirect(struct split_ip_msg *orig, ip6_addr_t detour) {
+  int offset = 0;
+  path_t *path = nw_get_route(my_short_addr, l2fromIP(detour));
+  path_t *path_second = nw_get_route(l2fromIP(detour), l2fromIP(orig->hdr.dst_addr));
+  path_t *i;
+  struct generic_header *g_hdr = (struct generic_header *)malloc(sizeof(struct generic_header));
+  struct source_header *sh;
+
+  debug("routing_insert_route_indirect len1: 0x%x, len2: 0x%x\n", path->length, path_second->length);
+
+  if (ntoh16(orig->hdr.plen) + sizeof(struct source_header) + ((path->length + path_second->length) * sizeof(uint16_t)) + sizeof(struct ip6_hdr) > INET_MTU) {
+    warn("packet plus source header too long\n");
+    return 1;
+  }
+
+  sh = (struct source_header *)malloc(sizeof(struct source_header) + (path->length + path_second->length)*sizeof(uint16_t));
+  if (sh == NULL || g_hdr == NULL) return 1;
+
+  sh->nxt_hdr = orig->hdr.nxt_hdr;
+  sh->len = sizeof(struct source_header) + ((path->length + path_second->length) * sizeof(uint16_t));
+  sh->dispatch = IP_EXT_SOURCE_DISPATCH;
+  sh->current = 0;
+  orig->hdr.nxt_hdr = NXTHDR_SOURCE;
+
+  fprintf(stderr, "to 0x%x [%i]: ", noths(orig->hdr.ip6_dst.s6_addr16[7]), path->length + path_second->length);
+  for (i = path; i != NULL; i = i->next) {
+    fprintf(stderr, "0x%x ", i->node);
+    sh->hops[offset++] = hton16(i->node);
+  }
+  for (i = path_second; i != NULL; i = i->next) {
+    fprintf(stderr, "0x%x ", i->node);
+    sh->hops[offset++] = hton16(i->node);
+  }
+
+  fprintf(stderr, "\n");
+
+  orig->hdr.plen = hton16(ntoh16(orig->hdr.plen) + sh->len);
+
+  g_hdr->payload_malloced = 1;
+  g_hdr->len = sh->len;
+  g_hdr->hdr.sh = sh;
+  g_hdr->next = orig->headers;
+  orig->headers = g_hdr;
+
+  nw_free_path(path);
+  nw_free_path(path_second);
+
+  return 0;
+}
+*/
+
+/*
+ */
+uint8_t routing_insert_route(struct split_ip_msg *orig) {
+  int offset = 0;
+  path_t *path = nw_get_route(my_short_addr, ntohs(orig->hdr.ip6_dst.s6_addr16[7]));
+  path_t *i;
+  struct generic_header *g_hdr = (struct generic_header *)malloc(sizeof(struct generic_header));
+  struct ip6_route *sh;
+
+  if (g_hdr == NULL || path == NULL) {
+    if (g_hdr) free(g_hdr);
+    if (path) nw_free_path(path);
+    return 1;
+  }
+#if 0
+  if (path->length == 1) {
+    free(g_hdr);
+    nw_free_path(path);
+    return 1;
+  }
+#endif
+
+  debug("routing_insert_route len: 0x%x\n", path->length);
+
+  // if the packet with the source route is longer then the buffer
+  // we're putting it into, drop it.
+  if (ntoh16(orig->hdr.plen) + sizeof(struct ip6_route) + 
+      (path->length * sizeof(uint16_t)) + sizeof(struct ip6_hdr) > INET_MTU) {
+    warn("packet plus source header too long\n");
+    free(g_hdr);
+    nw_free_path(path);
+    return 1;
+  }
+  
+  sh = (struct ip6_route *)malloc(sizeof(struct ip6_route) + path->length * sizeof(uint16_t));
+  if (sh == NULL) {
+    free (g_hdr);
+    nw_free_path(path);
+    return 1;
+  }
+
+  sh->nxt_hdr = orig->hdr.nxt_hdr;
+  sh->len = sizeof(struct ip6_route) + (path->length * sizeof(uint16_t));
+  sh->type = IP6ROUTE_FLAG_CONTROLLER | IP6ROUTE_TYPE_SOURCE;
+  sh->segs_remain = path->length;
+  
+  orig->hdr.nxt_hdr = IPV6_ROUTING;
+
+  log_clear(LOGLVL_DEBUG, "to 0x%x [%i]: ", ntohs(orig->hdr.ip6_dst.s6_addr16[7]), path->length);
+  for (i = path; i != NULL; i = i->next) {
+    log_clear(LOGLVL_DEBUG, "0x%x ", i->node);
+    sh->hops[offset++] = hton16(i->node);
+  }
+  log_clear(LOGLVL_DEBUG, "\n");
+
+  orig->hdr.plen = hton16(ntoh16(orig->hdr.plen) + sh->len);
+
+  g_hdr->payload_malloced = 1;
+  g_hdr->len = sh->len;
+  g_hdr->hdr.sh = sh;
+  g_hdr->next = orig->headers;
+  orig->headers = g_hdr;
+
+  nw_free_path(path);
+
+  return 0;
+
+}
+
+/*
+ * Returns the address of the next router this packet should be send to.
+ */
+ieee154_saddr_t routing_get_nexthop(struct split_ip_msg *msg) {
+  ieee154_saddr_t ret = 0xffff;;
+  path_t * path;
+  if (msg->hdr.ip6_dst.s6_addr[0] == 0xff &&
+      (msg->hdr.ip6_dst.s6_addr[1] & 0xf) <= 0x2) {
+    return ret;
+  }
+
+  // If it's source routed, just grab the next hop out of the header 
+#if 0
+  if (msg->hdr.nxt_hdr == NXTHDR_SOURCE) {
+    debug("routing_get_nexthop: src header\n"); 
+    return ntoh16((msg->headers->hdr.sh->hops[msg->headers->hdr.sh->current]));
+  }
+#endif
+
+  path = nw_get_route(my_short_addr, ntohs(msg->hdr.ip6_dst.s6_addr16[7]));
+
+  if (path != NULL)
+    ret = path->node;
+
+  nw_free_path(path);
+
+  return ret;
+}
+
+uint16_t routing_get_seqno() {
+  return current_seqno;
+}
+
+uint16_t routing_incr_seqno() {
+  FILE *fd;
+  ++current_seqno;
+  if ((fd = fopen("/var/run/ip-driver.seq", "w")) != NULL) {
+    fprintf(fd, "%hi\n", current_seqno);
+    fclose(fd);
+  }
+  return current_seqno;
+}
diff --git a/support/sdk/c/blip/driver/routing.h b/support/sdk/c/blip/driver/routing.h
new file mode 100644 (file)
index 0000000..0bb536e
--- /dev/null
@@ -0,0 +1,90 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef __ROUTING_H_
+#define __ROUTING_H_
+
+#include <lib6lowpan/ip.h>
+#include <string.h>
+#include "nwstate.h"
+#include "config.h"
+
+enum {
+  ROUTE_NO_ROUTE,
+  ROUTE_ONEHOP,
+  ROUTE_MHOP,
+  ROUTE_SOURCE,
+  ROUTE_WORMHOLE,
+};
+
+// the maximum size of a set of topology entries we send out over the network
+#define ROUTMSGSIZ 1400
+
+enum {
+  RMSG_TOPOLOGY = 1,
+};
+
+struct routing_message {
+  uint16_t type;
+  uint16_t source;
+  char    data[0];
+};
+
+int routing_init(struct config *c, char *tun_dev);
+
+/* 
+ * handles for  the blocking loop
+ */
+int routing_add_fds(fd_set *fds);
+int routing_process(fd_set *fds);
+
+
+/*
+ * @returns: truth value indicating if the destination of the packet
+ * is a single hop, and requires no source route.
+ */
+int routing_is_onehop(struct split_ip_msg  *msg);
+
+
+/*
+ * Copys the IP message at orig to the empty one at ret, inserting
+ * necessary routing information.
+ */
+uint8_t routing_insert_route(struct split_ip_msg *orig);
+
+/*
+ * Returns the address of the next router this packet should be send to.
+ */
+ieee154_saddr_t routing_get_nexthop(struct split_ip_msg *msg);
+
+
+/*
+ * Called for all reconstructed packets off serial.
+ * allows the router to inpect and remove any extra headers in the message.
+ */
+int routing_add_report(node_id_t reporter, struct tlv_hdr *tlv);
+
+uint16_t routing_get_seqno();
+
+uint16_t routing_incr_seqno();
+
+#endif 
diff --git a/support/sdk/c/blip/driver/serial_tun.c b/support/sdk/c/blip/driver/serial_tun.c
new file mode 100644 (file)
index 0000000..90c97a1
--- /dev/null
@@ -0,0 +1,1501 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * Copyright (c) 2007 Matus Harvan
+ * All rights reserved
+ *
+ * Copyright (c) 2008 Stephen Dawson-Haggerty
+ * Extensivly modified to use lib6lowpan / b6lowpan.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ *       copyright notice, this list of conditions and the following
+ *       disclaimer in the documentation and/or other materials provided
+ *       with the distribution.
+ *     * The name of the author may not be used to endorse or promote
+ *       products derived from this software without specific prior
+ *       written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <string.h>
+#include <time.h>
+#include <stdarg.h>
+#include <termios.h>
+#include <errno.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <lib6lowpan/TrackFlows.h>
+#include <lib6lowpan/6lowpan.h>
+#include <lib6lowpan/ip.h>
+#include <lib6lowpan/lib6lowpan.h>
+#include <lib6lowpan/devconf.h>
+#include <lib6lowpan/IEEE154Packet.h>
+
+#include "serialsource.h"
+#include "serialpacket.h"
+#include "serialprotocol.h"
+#include "sfsource.h"
+
+#include "tun_dev.h"
+#include "routing.h"
+#include "logging.h"
+#include "config.h"
+#include "nwstate.h"
+#include "vty/vty.h"
+
+#define min(a,b) ( (a>b) ? b : a )
+#define max(a,b) ( (a>b) ? a : b )
+
+int tun_fd, radvd_fd = -1, fifo_fd = -1, keepalive_needed = 1;
+int opt_listenonly = 0, opt_trackflows = 0;
+
+int radvd_init(char *ifname, struct config *c);
+void radvd_process();
+void radvd_reset_adverts(void);
+
+#ifndef SF_SRC
+serial_source ser_src;
+#define write_pan_packet(DATA, LEN) write_serial_packet(ser_src, DATA, LEN)
+#define read_pan_packet(LENP) read_serial_packet(ser_src, LENP)
+#define close_pan()   close_serial_source(ser_src);
+#else
+int sf_fd;
+#define write_pan_packet(DATA, LEN) write_sf_packet(sf_fd, DATA, LEN)
+#define read_pan_packet(LENP) read_sf_packet(sf_fd, LENP)
+#define close_pan()           close(sf_fd)
+#endif
+
+sig_atomic_t do_shutdown = 0;
+
+void driver_shutdown() {
+  do_shutdown = 1;
+}
+
+
+enum {
+  N_RECONSTRUCTIONS = 10,
+};
+
+/*
+ */ 
+#ifdef __TARGET_mips__
+const char *def_configfile = "/etc/lowpan/serial_tun.conf";
+#else
+const char *def_configfile = "serial_tun.conf";
+#endif
+
+
+
+extern struct in6_addr __my_address;
+uint16_t local_seqno = 0;
+
+volatile sig_atomic_t config_success = 0;
+struct config driver_config;
+char dev[IFNAMSIZ];
+struct {
+  time_t boot_time;
+  unsigned long tx_pkts;
+  unsigned long tx_frags;
+  unsigned long tx_bytes;
+  unsigned long rx_pkts;
+  unsigned long rx_frags;
+  unsigned long rx_bytes;
+  unsigned long fw_pkts;
+} stats = {0, 0, 0, 0, 0, 0, 0, 0};
+
+#ifdef CENTRALIZED_ROUTING
+void install_route(struct split_ip_msg *amsg, uint8_t flags);
+void uninstall_route(uint16_t n1, uint16_t n2);
+#endif
+
+
+/* ------------------------------------------------------------------------- */
+
+void stderr_msg(serial_source_msg problem)
+{
+  // fprintf(stderr, "Note: %s\n", msgs[problem]);
+}
+
+
+void print_ip_packet(struct split_ip_msg *msg) {
+  int i;
+  struct generic_header *g_hdr;
+  if (log_getlevel() > LOGLVL_DEBUG) return;
+
+  printf("  nxthdr: 0x%x hlim: 0x%x plen: %i\n", msg->hdr.nxt_hdr, msg->hdr.hlim, ntohs(msg->hdr.plen));
+  printf("  src: ");
+  for (i = 0; i < 16; i++) printf("0x%x ", msg->hdr.ip6_src.s6_addr[i]);
+  printf("\n");
+  printf("  dst: ");
+  for (i = 0; i < 16; i++) printf("0x%x ", msg->hdr.ip6_dst.s6_addr[i]);
+  printf("\n");
+
+  g_hdr = msg->headers;
+  while (g_hdr != NULL) {
+    printf("header [%i]: ", g_hdr->len);
+    for (i = 0; i < g_hdr->len; i++)
+      printf("0x%x ", g_hdr->hdr.data[i]);
+    printf("\n");
+    g_hdr = g_hdr->next;
+  }
+
+  printf("data [%i]:\n\t", msg->data_len);
+  for (i = 0; i < msg->data_len; i++) {
+    if (i == 0x40) {
+      printf (" ...\n");
+      break;
+    }
+    printf("0x%x ", msg->data[i]);
+    if (i % 16 == 15) printf("\n\t");
+    if (i % 16 == 7) printf ("  ");
+  }
+  printf("\n");
+}
+
+
+const char *fifo_name = "/var/run/ip-driver/flows";
+void fifo_open() {
+  struct stat stat_buf;
+
+  if (opt_trackflows) {
+    if (stat(fifo_name, &stat_buf) < 0) {
+      error("fifo does not exist -- track flows will be diabled\n");
+      return;
+    }
+    fifo_fd = open(fifo_name, O_WRONLY | O_NONBLOCK );
+    if (fifo_fd < 0) {
+      error("unable to open fifo %i %s: is a reader connected?\n", fifo_fd, fifo_name);
+      fifo_fd = -1;
+      return;
+    }
+  }
+}
+void fifo_close() {
+  if (fifo_fd >= 0) {
+    close(fifo_fd);
+  }
+}
+
+enum { N_OUTGOING_CACHE = 10, }; int outgoing_cache_idx = 0;
+struct flow_id_msg outgoing_cache[N_OUTGOING_CACHE];
+
+void fifo_report(struct split_ip_msg *msg, uint16_t dest, int nxt_hdr) {
+  if (fifo_fd >= 0) {
+    outgoing_cache_idx = (outgoing_cache_idx + 1) % N_OUTGOING_CACHE;
+    outgoing_cache[outgoing_cache_idx].flow = msg->flow_id;
+    outgoing_cache[outgoing_cache_idx].src  = ntohs(msg->hdr.ip6_src.s6_addr16[7]);
+    outgoing_cache[outgoing_cache_idx].dst  = ntohs(msg->hdr.ip6_dst.s6_addr16[7]);
+    outgoing_cache[outgoing_cache_idx].local_address = ntohs(__my_address.s6_addr16[7]);
+    outgoing_cache[outgoing_cache_idx].nxt_hdr = nxt_hdr;
+    outgoing_cache[outgoing_cache_idx].n_attempts = 1;
+    outgoing_cache[outgoing_cache_idx].attempts[0].next_hop = (dest);
+    debug("adding cache entry: %i %i\n",  outgoing_cache[outgoing_cache_idx].src,
+          outgoing_cache[outgoing_cache_idx].flow);
+  }
+}
+
+void flow_insert_label(struct split_ip_msg *msg) {
+  uint8_t *buf;
+  struct generic_header *g_hdr;
+
+
+  if (opt_trackflows) {
+    buf = malloc(sizeof(struct ip6_ext) + sizeof(struct tlv_hdr) + sizeof(struct flow_id));
+    g_hdr = (struct generic_header *)malloc(sizeof(struct generic_header));
+    struct ip6_ext *ext = (struct ip6_ext *)buf;
+    struct tlv_hdr *tlv = (struct tlv_hdr *)(ext + 1);
+    struct flow_id *id  = (struct flow_id *)(tlv + 1);
+
+    ext->nxt_hdr = msg->hdr.nxt_hdr;
+    msg->hdr.nxt_hdr = IPV6_HOP;
+    ext->len = sizeof(struct ip6_ext) + sizeof(struct tlv_hdr) + sizeof(struct flow_id);
+    tlv->type = TLV_TYPE_FLOW;
+    tlv->len = ext->len - sizeof(struct ip6_ext);
+    id->id = msg->flow_id;
+  
+    g_hdr->payload_malloced = 1;
+    g_hdr->hdr.ext = ext;
+    g_hdr->len = ext->len;
+    g_hdr->next = msg->headers;
+    msg->headers = g_hdr;
+    
+    msg->hdr.plen = htons(ntohs(msg->hdr.plen) + ext->len);
+  }
+}
+
+/*
+ * frees the linked list structs, and their payloads if we have
+ * malloc'ed them at some other point.
+ *
+ * does not free the payload buffer or the actual split_ip_msg struct,
+ * since those are malloc'ed seperatly in this implementation.
+ */
+void free_split_msg(struct split_ip_msg *msg) {
+  struct generic_header *cur, *next;
+  cur = msg->headers;
+  while (cur != NULL) {
+    next = cur->next;
+    if (cur->payload_malloced)
+      free(cur->hdr.data);
+    free(cur);
+    cur = next;
+  }
+}
+
+void configure_timeout() {
+  if (config_success == 0) {
+    fatal("configuring interface failed!  aborting!\n");
+    exit(2);
+  } else {
+    signal(SIGALRM, SIG_DFL);
+  }
+}
+
+void configure_reboot() {
+  uint8_t buf[sizeof(config_cmd_t) + 1];
+  config_cmd_t *cmd = (config_cmd_t *)(&buf[1]);
+  memset(buf, 0, sizeof(config_cmd_t) + 1);
+  buf[0] = TOS_SERIAL_DEVCONF;
+  cmd->cmd = CONFIG_REBOOT;
+
+  signal(SIGALRM, configure_timeout);
+  write_pan_packet(buf, CONFIGURE_MSG_SIZE + 1);
+  alarm(5);
+}
+
+void configure_setparms(struct config *c, int cmdno) {
+  uint8_t buf[sizeof(config_cmd_t) + 1];
+  config_cmd_t *cmd = (config_cmd_t *)(&buf[1]);
+  memset(buf, 0, sizeof(config_cmd_t) + 1);
+  buf[0] = TOS_SERIAL_DEVCONF;
+  cmd->cmd = cmdno;
+  cmd->rf.addr = c->router_addr.s6_addr16[7]; // is network byte-order
+  cmd->rf.channel = c->channel;
+  cmd->retx.retries = htons(c->retries);
+  cmd->retx.delay = htons(30);
+
+  write_pan_packet(buf, CONFIGURE_MSG_SIZE + 1);
+}
+
+
+/* ------------------------------------------------------------------------- */
+/*
+ * the first byte the TOS serial stack sends is a dispatch byte.  One
+ * dispatch value is for forwarded 802;.15.4 packets; we use a few
+ * others to talk directly to the attached IPBaseStation.
+ */
+void handle_other_pkt(uint8_t *data, int len) {
+  config_reply_t *rep;
+  switch (data[0]) {
+  case TOS_SERIAL_DEVCONF:
+    rep = (config_reply_t *)(&data[1]);
+    debug("interface configured (0x%x) addr: 0x%x\n", rep->error, ntohs(rep->addr));
+    switch (rep->error) {
+    case CONFIG_ERROR_BOOTED:
+      configure_setparms(&driver_config, CONFIG_SET_PARM);
+      break;
+    default:
+      info("interface device successfully initialized\n");
+      config_success = 1;
+
+      /* put this here because we already use SIGALRM for the
+         configure timeout, and radvd needs it for its own timer. */
+      if (radvd_fd < 0 && (radvd_fd = radvd_init(dev, &driver_config)) < 0) {
+        fatal("radvd init failed!\n");
+        exit(1);
+      } 
+    }
+    break;
+  default:
+    warn("received serial packet with unknown dispatch 0x%x\n",data[0]);
+    log_dump_serial_packet(data, len);
+  }
+}
+
+
+/* ------------------------------------------------------------------------- */
+/* handling of data arriving on the tun interface */
+void write_radio_header(uint8_t *serial, ieee154_saddr_t dest, uint16_t payload_len) {
+  IEEE154_header_t *radioPacket = (IEEE154_header_t *)(serial + 1);
+  radioPacket->length = payload_len + MAC_HEADER_SIZE + MAC_FOOTER_SIZE;
+
+  // don't include the length byte
+  radioPacket->fcf = htons(0x4188);
+  // dsn will get set on mote
+  radioPacket->destpan = 0;
+  radioPacket->dest = htole16(dest);
+  // src will get set on mote 
+  
+  serial[0] = SERIAL_TOS_SERIAL_802_15_4_ID;
+}
+
+void send_fragments (struct split_ip_msg *msg, ieee154_saddr_t dest) {
+  int result;
+  uint16_t frag_len;
+  fragment_t progress;
+  uint8_t serial[LOWPAN_LINK_MTU + 1];
+  IEEE154_header_t *radioPacket = (IEEE154_header_t *)(serial + 1);
+#define PKTLEN(X) ((X)->length + 2)
+
+  uint8_t *lowpan = (uint8_t *)(radioPacket + 1);
+
+#define LOWPAN_PAYLOAD_LENGTH (LOWPAN_LINK_MTU - MAC_HEADER_SIZE \
+                              - MAC_FOOTER_SIZE)
+
+  progress.offset = 0;
+
+  // and IEEE 802.15.4 header
+  // write_radio_header(serial, dest, frag_len);
+
+  while ((frag_len = getNextFrag(msg, &progress, lowpan, 
+                                 LOWPAN_PAYLOAD_LENGTH)) > 0) {
+
+    //debug("frag len: 0x%x offset: 0x%x plen: 0x%x\n", frag_len, progress.offset * 8, ntohs(ip_header->plen));
+
+    write_radio_header(serial, dest, frag_len);
+
+    // if this is sent too fast, the base station can't keep up.  The effect of this is
+    // we send incomplete fragment.  25ms seems to work pretty well.
+    //   6-9-08 : SDH : this is a bad fix that does not address the
+    //   problem.  
+    //   at the very least, the serial ack's seem to be
+    //   working, so we should be retrying if the ack is failing
+    //   because the hardware cannot keep up.
+    //   9-17-09 : SDH : it seems we've tracked this down to packets
+    //   arriving too fast to enqueue, especially at higher baud rates
+    //   (115200).  reenabled to prevent retries, which are very slow.
+#ifdef __TARGET_mips__
+    usleep(50000);
+#else
+    usleep(25000);
+#endif
+    log_dump_serial_packet(serial, PKTLEN(radioPacket));
+    result = write_pan_packet(serial, PKTLEN(radioPacket));
+    if (result != 0) 
+      result = write_pan_packet(serial, PKTLEN(radioPacket));
+
+    debug("send_fragments: result: 0x%x len: 0x%x\n", result, frag_len);
+    log_dump_serial_packet(serial, PKTLEN(radioPacket));
+    stats.tx_frags++;
+    stats.tx_bytes += PKTLEN(radioPacket);
+  }
+  keepalive_needed = 0;
+  stats.tx_pkts++;
+}
+
+void icmp_unreachable(struct split_ip_msg *msg) {
+  
+}
+
+/*
+ * this function takes a complete IP packet, and sends it out to a
+ * destination in the PAN.  It will insert source routing headers and
+ * recompute L4 checksums as necessary.
+ *
+ */ 
+uint8_t ip_to_pan(struct split_ip_msg *msg) {
+  int nxt_hdr = msg->hdr.nxt_hdr;
+  uint16_t dest;
+
+  debug("ip_to_pan\n");
+  print_ip_packet(msg);
+  // if this packet has a source route (rinstall header, or prexisting
+  // source header, we don't want to mess with it
+  switch (routing_is_onehop(msg)) {
+  case ROUTE_MHOP:
+    debug("Multihop packet\n");
+    if (routing_insert_route(msg)) goto fail;
+    break;
+    
+  case ROUTE_WORMHOLE:
+    debug("Wormhole packet\n");
+
+    // fall through
+  case ROUTE_NO_ROUTE:
+    tun_write(tun_fd, msg);
+    // info("destination unreachable: 0x%x: dropping\n", ntohs(msg->hdr.ip6_dst.s6_addr16[7]));
+    return 0;
+  }
+
+  dest = routing_get_nexthop(msg);
+  debug("next hop: 0x%x\n", dest);
+  flow_insert_label(msg);
+  print_ip_packet(msg);
+
+  fifo_report(msg, dest, nxt_hdr);
+
+  send_fragments(msg, dest);
+  return 0;
+ fail:
+  error("ip_to_pan: no route to host\n");
+  return 1;
+}
+
+void upd_source_route(struct ip6_route *sh, ieee154_saddr_t addr) {
+  if (sh->segs_remain > 0) {
+    sh->hops[ROUTE_NENTRIES(sh) - sh->segs_remain] = leton16(addr);
+    sh->segs_remain--;
+  }
+}
+
+int process_dest_tlv(struct ip6_hdr *iph, struct ip6_ext *hdr, int len) {
+  struct tlv_hdr *tlv = (struct tlv_hdr *)(hdr + 1);
+  node_id_t reporter = ntohs(iph->ip6_src.s6_addr16[7]);
+
+  if (len != hdr-> len) return 1;
+  len -= sizeof(struct ip6_ext);
+
+  while (tlv != NULL && len > 0) {
+    if (tlv->len == 0) return 1;
+
+    switch(tlv->type) {
+    case TLV_TYPE_TOPOLOGY:
+      routing_add_report(reporter, tlv);
+      break;
+    }
+    
+    len -= tlv->len;
+    tlv = (struct tlv_hdr *)(((uint8_t *)tlv) + tlv->len);
+  }
+  return 0;
+}
+
+int process_hop_tlv(struct split_ip_msg *msg, struct ip6_ext *hdr, int len) {
+  struct tlv_hdr *tlv = (struct tlv_hdr *)(hdr + 1);
+  uint16_t *fl;
+
+  if (len != hdr-> len) return 1;
+  len -= sizeof(struct ip6_ext);
+
+  while (tlv != NULL && len > 0) {
+    if (tlv->len == 0) return 1;
+
+    switch(tlv->type) {
+    case TLV_TYPE_FLOW:
+      fl = (uint16_t *)(tlv + 1);
+      msg->flow_id = *fl;
+      debug("process_hop_tlv: flow 0x%x\n", msg->flow_id);
+      break;
+    }
+
+    len -= tlv->len;
+    tlv = (struct tlv_hdr *)(((uint8_t *)tlv) + tlv->len);
+  }
+  return 0;
+}
+
+int process_extensions(struct split_ip_msg *msg) {
+  struct generic_header *prev = NULL, *cur = msg->headers;
+  struct ip6_route *route;
+  uint8_t nxt_hdr = msg->hdr.nxt_hdr;
+  int lendelta = 0;
+
+  while (cur != NULL && EXTENSION_HEADER(nxt_hdr)) {
+    debug("dropping header type 0x%x, len %i\n", nxt_hdr, cur->len);
+    msg->headers = cur->next;
+    msg->hdr.nxt_hdr = cur->hdr.ext->nxt_hdr;
+    lendelta += cur->len;
+
+    switch (nxt_hdr) {
+    case IPV6_DEST:
+      if (process_dest_tlv(&msg->hdr, cur->hdr.ext, cur->len)) 
+        return 1;
+      break;
+    case IPV6_HOP:
+      if (process_hop_tlv(msg, cur->hdr.ext, cur->len)) {
+        warn("dropping packet due to hop tlv\n");
+        return 1;
+      }
+      break;
+    case IPV6_ROUTING:
+
+      route = cur->hdr.sh;
+
+      if ((route->type & ~IP6ROUTE_FLAG_MASK) == IP6ROUTE_TYPE_INVAL || route->segs_remain == 0) {
+/*         if (route->type == IP6ROUTE_TYPE_INVAL) { */
+/*           if (route->hops[0] == __my_address.s6_addr16[7]) { */
+/*             warn("dropping packet since it has an invalid source route and I sent it\n"); */
+/*             return 1; */
+/*           } */
+/*         } */
+      } else {
+        uint16_t target_hop = ntohs(route->hops[ROUTE_NENTRIES(route) - route->segs_remain]);
+        // if this is actually a valid source route, maybe update it
+        // (even though we're going to delete it shortly)
+        if (target_hop != __my_address.s6_addr16[7]) {
+          if (ROUTE_NENTRIES(route) >= 2) {
+            route->hops[0] = htons(msg->prev_hop);
+            route->hops[1] = htons(target_hop);
+          }
+          route->type = (route->type & IP6ROUTE_FLAG_MASK) | IP6ROUTE_TYPE_INVAL;
+        } else {
+          route->hops[ROUTE_NENTRIES(route) - route->segs_remain] = htons(msg->prev_hop);
+          route->segs_remain--;
+        }
+      }
+      
+      if ((route->type & ~IP6ROUTE_FLAG_MASK) == IP6ROUTE_TYPE_INVAL && ROUTE_NENTRIES(route) >= 2) {
+        node_id_t n1 = ntohs(route->hops[0]);
+        node_id_t n2 = ntohs(route->hops[1]);
+        warn ("broken link was %i -> %i\n", n1, n2);
+        nw_remove_link(n1, n2);
+        if (route->type & IP6ROUTE_FLAG_CONTROLLER) {
+          warn("dropping packet since it has an invalid source route and I sent it\n");
+          return 1;
+        } else {
+          warn("received broken source route based on installed route-- uninstalling\n");
+/*           uninstall_route(ntohs(msg->hdr.ip6_src.s6_addr16[7]), */
+/*                           ntohs(msg->hdr.ip6_dst.s6_addr16[7])); */
+        }
+      }
+    }
+
+    nxt_hdr = cur->hdr.ext->nxt_hdr;
+    prev = cur;
+    cur = cur->next;
+    free(prev);
+  }
+
+  msg->hdr.plen = htons(ntohs(msg->hdr.plen) - lendelta);
+  return 0;
+}
+
+#if 0
+int remove_sourceroute(struct split_ip_msg *msg) {
+  struct source_header *s;
+  struct rinstall_header *rih;
+  struct generic_header *g_hdr;
+  uint8_t removeSource = 1;
+  if (msg->hdr.nxt_hdr == NXTHDR_SOURCE) {
+    sh = msg->headers->hdr.sh;
+    upd_source_route(sh, msg->metadata.sender);
+
+    // Our thinking here is that if something is source_routed
+    //  from inside the network and it is not destined to us
+    //  then its either a rinstall being forwarded, or a path
+    //  that's been set up, so we shouldn't strip it away
+    if (cmpPfx(msg->hdr.ip6_dst.s6_addr, __my_address.s6_addr) &&
+        msg->hdr.ip6_dst.s6_addr16[7] != __my_address.s6_addr16[7]) {
+/*         ((msg->hdr.ip6_dst.s6_addr[14] != __my_address[14] || */
+/*           msg->hdr.ip6_dst.s6_addr[15] != __my_address[15]))) { */
+      info("Packet with source header not destined for me\n");
+  
+      if ((sh->dispatch & IP_EXT_SOURCE_INVAL) != IP_EXT_SOURCE_INVAL) {
+        debug("Removing invalid source header\n");
+        removeSource = 0;
+      }
+      
+      if ((sh->dispatch & IP_EXT_SOURCE_CONTROLLER) == IP_EXT_SOURCE_CONTROLLER) {
+        debug("WE sent this packet! dropping...\n");
+        return 1;
+      }
+    
+
+      // If this is an rinstall header moving through, we need to
+      //  updated the current position of the path, similar to
+      //  what we do for source headers.
+      if (sh->nxt_hdr == NXTHDR_INSTALL) {
+        rih = msg->headers->next->hdr.rih;
+        rih->current++;
+        info("Incrementing current of rih to 0x%x\n", rih->current);
+      }
+    }
+    if (removeSource) {
+      msg->hdr.nxt_hdr = sh->nxt_hdr;
+      msg->hdr.plen = htons(ntohs(msg->hdr.plen) - sh->len);
+      g_hdr = msg->headers;
+      msg->headers = msg->headers->next;
+      free(g_hdr);
+    }
+  }
+  return 0;
+}
+#endif
+
+void handle_serial_packet(struct split_ip_msg *msg) {
+  path_t* tPath;
+  path_t* i;
+#ifdef CENTRALIZED_ROUTING
+  uint8_t flags = 0x00;
+#endif
+  if (ntohs(msg->hdr.plen) > INET_MTU - sizeof(struct ip6_hdr)) {
+    warn("handle_ip_packet: too long: 0x%x\n", ntohs(msg->hdr.plen));
+    return;
+  }
+
+  // print_ip_packet(msg);
+  print_ip_packet(msg);
+  if (process_extensions(msg))
+    return;
+
+  if (cmpPfx(msg->hdr.ip6_dst.s6_addr, __my_address.s6_addr) && 
+      msg->hdr.ip6_dst.s6_addr16[7] != __my_address.s6_addr16[7]) {
+      debug("Received packet destined to 0x%x\n", msg->hdr.ip6_dst.s6_addr[15]); 
+      stats.fw_pkts++;
+    
+     // If this packet is not source routed, check to see if we're on the best path before
+     //  issuing a route install
+       tPath = nw_get_route(ntohs(msg->hdr.ip6_src.s6_addr16[7]), ntohs(msg->hdr.ip6_dst.s6_addr16[7]));
+        for (i = tPath; i != NULL; i = i->next) {
+          if (i->node == ntohs(__my_address.s6_addr16[7])) {
+            debug("Not installing route for packet from 0x%x to 0x%x (on best path)\n", 
+                  ntohs(msg->hdr.ip6_src.s6_addr16[7]), ntohs(msg->hdr.ip6_dst.s6_addr16[7]));
+            nw_free_path(tPath);
+            ip_to_pan(msg);
+            return;
+          }
+        }
+        nw_free_path(tPath);
+        // }
+      
+      // We send the route installation packet before forwarding the actual
+      //  packet, with the thinking being that the route can be set up, in
+      //  case acks are issued by the destination on the packet
+      //
+      // We have to first select the flags that we want:
+     
+      //  At this point, if it's not source routed, then this packet
+      //  shouldn't be coming through us so we install a route
+        // if (msg->hdr.nxt_hdr != NXTHDR_SOURCE) {
+        debug("installing route for packet from 0x%x to 0x%x\n", 
+              ntohs(msg->hdr.ip6_src.s6_addr16[7]), ntohs(msg->hdr.ip6_dst.s6_addr16[7]));
+#ifdef CENTRALIZED_ROUTING
+#ifndef FULL_PATH_INSTALL
+        flags = HYDRO_METHOD_SOURCE | HYDRO_INSTALL_REVERSE;
+#else
+        flags = HYDRO_METHOD_HOP | HYDRO_INSTALL_REVERSE;
+#endif
+        //        install_route(msg, flags);
+#endif
+        // } else {
+        // info("Packet had a source header so no route install\n"); 
+        // }
+      ip_to_pan(msg);
+      // do routing
+  } else {
+    // give it to linux
+    // need to remove route info here.
+    stats.rx_pkts++;
+    tun_write(tun_fd, msg);
+    debug("tun_write: wrote 0x%x bytes\n", sizeof(struct ip6_hdr) + ntohs(msg->hdr.plen));
+  }
+}
+
+void add_header_list(struct split_ip_msg *msg) {
+  uint8_t nxt_hdr;
+  struct generic_header *g_hdr, **g_list;
+  struct ip6_ext *ext = (struct ip6_ext *)msg->next;
+  uint16_t hdr_len = 0;
+  // debug("add_header_list for message destined to 0x%x\n", ntohs(msg->hdr.ip6_dst.s6_addr16[7]));
+  nxt_hdr = msg->hdr.nxt_hdr;
+  msg->headers = NULL;
+  g_list = &(msg->headers);
+  while (EXTENSION_HEADER(nxt_hdr)) {
+    g_hdr = (struct generic_header *)malloc(sizeof(struct generic_header));
+    g_hdr->payload_malloced = 0;
+    g_hdr->hdr.ext = ext;
+    g_hdr->next = NULL;
+    *g_list = g_hdr;
+    g_list = &g_hdr->next;
+
+    g_hdr->len = ext->len;
+    
+    nxt_hdr = ext->nxt_hdr;
+    ext = (struct ip6_ext *)(((uint8_t *)ext) + ext->len);
+    
+    hdr_len += g_hdr->len;
+  }
+  if (COMPRESSIBLE_TRANSPORT(nxt_hdr)) {
+      int transport_len;
+      switch (nxt_hdr) {
+      case IANA_UDP:
+        transport_len = sizeof(struct udp_hdr); break;
+      }
+
+      g_hdr = (struct generic_header *)malloc(sizeof(struct generic_header));
+      g_hdr->payload_malloced = 0;
+      g_hdr->hdr.ext = ext;
+      g_hdr->next = NULL;
+      *g_list = g_hdr;
+      g_list = &g_hdr->next;
+
+      g_hdr->len = transport_len;
+      ext = (struct ip6_ext *)(((uint8_t *)ext) + transport_len);
+      hdr_len += transport_len;
+  }
+
+  msg->data = (uint8_t *)ext;
+  msg->data_len = ntohs(msg->hdr.plen) - hdr_len;
+}
+
+#ifdef CENTRALIZED_ROUTING
+/*
+ * Given a source and destination, send a source-routed route install message
+ * that will install the correct routes.
+ *
+ * NOTE: Make sure that this is the correct way to create a new packet
+ */
+time_t last_install;
+void install_route(struct split_ip_msg *amsg, uint8_t flags) {
+  uint8_t buf[sizeof(struct split_ip_msg) + INET_MTU];
+  struct split_ip_msg *msg = (struct split_ip_msg *)buf;
+  int offset = 0;
+
+
+  struct ip6_ext *ext = (struct ip6_ext *)(msg->next);
+  struct tlv_hdr *tlv = (struct tlv_hdr *)(ext + 1);
+  struct rinstall_header *rih = (struct rinstall_header *)(tlv + 1);
+
+  path_t* path = nw_get_route(ntohs(amsg->hdr.ip6_src.s6_addr16[7]), ntohs(amsg->hdr.ip6_dst.s6_addr16[7]));
+  path_t* i;
+  time_t current_time;
+
+#if 0
+  time(&current_time);
+
+  if (current_time < last_install + 2) {
+    debug("Not sending install\n");
+    return;
+  }
+  time(&last_install);
+#endif 
+
+
+  if (path == NULL || path->isController) return;
+  fprintf(stderr, "install_route for src: 0x%x, dest: 0x%x, flags: %x\n", 
+          ntohs(amsg->hdr.ip6_src.s6_addr16[7]), ntohs(amsg->hdr.ip6_dst.s6_addr16[7]), path->length);
+  if (path->length > 10) return;
+
+  memset((uint8_t *)&msg->hdr, 0, sizeof(struct ip6_hdr));
+
+  // Set IP Header options
+  msg->hdr.hlim = 0x64; // CHECK THIS
+  msg->hdr.nxt_hdr = IPV6_DEST;
+  msg->hdr.vlfc[0] = IPV6_VERSION << 4;
+  msg->flow_id = local_seqno++;
+
+  memcpy(&msg->hdr.ip6_src, &__my_address, sizeof(struct in6_addr));
+  memcpy(&msg->hdr.ip6_dst, &amsg->hdr.ip6_src, sizeof(struct in6_addr));
+  msg->headers = NULL;
+
+  ext->nxt_hdr = IPV6_NONEXT;
+  ext->len = sizeof(struct ip6_ext) + sizeof(struct tlv_hdr) + sizeof(struct rinstall_header)
+    + (path->length * sizeof(uint16_t));
+
+  tlv->len = ext->len - sizeof(struct ip6_ext);
+  tlv->type = TLV_TYPE_INSTALL;
+
+  // Setup rinstall_header
+ // Size is longer because we put the src in there
+  rih->flags = flags;
+  rih->match.src = htons(T_INVAL_NEIGH);
+  rih->match.dest = amsg->hdr.ip6_dst.s6_addr16[7]; 
+  rih->path_len = path->length;
+
+  // Convert to host so add_headers_list works
+  msg->hdr.plen = htons(ext->len); 
+
+  info("install_route len: 0x%x\n", rih->path_len);
+
+  fprintf(stderr, "from 0x%x to 0x%x [%i]: ", 
+          ntohs(amsg->hdr.ip6_src.s6_addr16[7]), ntohs(amsg->hdr.ip6_dst.s6_addr16[7]), path->length);
+  // rih->path[0] = amsg->hdr.ip6_src.s6_addr16[7]; //htons(l2fromIP(amsg->hdr.ip6_src.s6_addr));
+  for (i = path; i != NULL; i = i->next) {
+    fprintf(stderr, "0x%x ", i->node);
+    rih->path[offset++] = htons(i->node);
+  }
+
+  nw_free_path(path);
+
+  add_header_list(msg);
+  print_ip_packet(msg);
+  loglevel_t old_lvl = log_setlevel(LOGLVL_DEBUG);
+  ip_to_pan(msg);
+  log_setlevel(old_lvl);
+  free_split_msg(msg);
+}
+
+void uninstall_route(uint16_t n1, uint16_t n2) {
+  uint8_t buf[sizeof(struct split_ip_msg) + INET_MTU];
+  struct split_ip_msg *msg = (struct split_ip_msg *)buf;
+  struct ip6_ext *ext = (struct ip6_ext *)(msg->next);
+  struct tlv_hdr *tlv = (struct tlv_hdr *)(ext + 1);
+  struct rinstall_header *rih = (struct rinstall_header *)(tlv + 1);
+
+  // Set IP Header options
+  msg->hdr.hlim = 0x64; // CHECK THIS
+  msg->hdr.nxt_hdr = IPV6_DEST;
+  msg->hdr.vlfc[0] = IPV6_VERSION << 4;
+  msg->flow_id = local_seqno++;
+
+  memcpy(&msg->hdr.ip6_src, &__my_address, sizeof(struct in6_addr));
+  memcpy(&msg->hdr.ip6_dst, &__my_address, sizeof(struct in6_addr));
+  msg->hdr.ip6_dst.s6_addr16[7] = htons(n1);
+  msg->headers = NULL;
+
+  ext->nxt_hdr = IPV6_NONEXT;
+  ext->len = sizeof(struct ip6_ext) + sizeof(struct tlv_hdr) + sizeof(struct rinstall_header);
+
+  tlv->len = ext->len - sizeof(struct ip6_ext);
+  tlv->type = TLV_TYPE_INSTALL;
+
+  // Convert to host so add_headers_list works
+  msg->hdr.plen = htons(ext->len); 
+
+  rih->flags = HYDRO_INSTALL_UNINSTALL_MASK | HYDRO_METHOD_SOURCE;
+  rih->match.src = htons(n1);
+  rih->match.dest = htons(n2);
+  rih->path_len = 0;
+    
+
+  add_header_list(msg);
+  print_ip_packet(msg);
+  loglevel_t old_lvl = log_setlevel(LOGLVL_DEBUG);
+  ip_to_pan(msg);
+  log_setlevel(old_lvl);
+  free_split_msg(msg);
+}
+
+#endif
+
+/*
+ * read data from the tun device and send it to the serial port
+ * does also fragmentation
+ */
+int tun_input()
+{
+  uint8_t buf[sizeof(struct split_ip_msg) + INET_MTU];
+  struct split_ip_msg *msg = (struct split_ip_msg *)buf;
+  int len;
+
+  len = tun_read(tun_fd, (void *)(&msg->pi), INET_MTU + sizeof(struct ip6_hdr));
+
+  if (len <= 0) {
+    return 0;
+  }
+  debug("tun_read: read 0x%x bytes\n", len);
+
+  if ((msg->hdr.vlfc[0] >> 4) != IPV6_VERSION) {
+    warn("tun_read: discarding non-ip packet\n");
+    goto fail;
+  }
+  if (ntohs(msg->hdr.plen) > INET_MTU - sizeof(struct ip6_hdr)) {
+    debug("tun_input: dropping packet due to length: 0x%x\n", ntohs(msg->hdr.plen));
+    goto fail;
+  }
+  if (msg->hdr.nxt_hdr == 0) {
+    debug("tun_input: dropping packet with IPv6 options\n");
+    goto fail;
+  }
+  
+  add_header_list(msg);
+  msg->flow_id = local_seqno++;
+
+  ip_to_pan(msg);
+
+  free_split_msg(msg);
+  
+  return 1;
+ fail:
+  /* error("Invalid packet or version received\n"); */
+  return 1;
+}
+
+/* ------------------------------------------------------------------------- */
+/* handling of data arriving on the serial port */
+
+reconstruct_t reconstructions [N_RECONSTRUCTIONS];
+
+void age_reconstructions() {
+  int i;
+  for (i = 0; i < N_RECONSTRUCTIONS; i++) {
+    // switch "active" buffers to "zombie"
+    if (reconstructions[i].timeout == T_ACTIVE) {
+      reconstructions[i].timeout = T_ZOMBIE;
+    } else if (reconstructions[i].timeout == T_ZOMBIE) {
+      reconstructions[i].timeout = T_UNUSED;
+      free(reconstructions[i].buf);
+      reconstructions[i].buf = NULL;
+    }
+  }
+}
+
+
+reconstruct_t *getReassembly(packed_lowmsg_t *lowmsg) {
+  int i, free_spot = N_RECONSTRUCTIONS + 1;
+  uint16_t mytag, size;
+  if (getFragDgramTag(lowmsg, &mytag)) return NULL;
+  if (getFragDgramSize(lowmsg, &size)) return NULL;
+  
+  for (i = 0; i < N_RECONSTRUCTIONS; i++) {
+    if (reconstructions[i].timeout > T_UNUSED && reconstructions[i].tag == mytag) {
+      reconstructions[i].timeout = T_ACTIVE;
+      return &(reconstructions[i]);
+    }
+    if (reconstructions[i].timeout == T_UNUSED) free_spot = i;
+  }
+  // allocate a new struct for doing reassembly.
+  if (free_spot != N_RECONSTRUCTIONS + 1) {
+    // if we don't get the packet with the protocol in it first, we
+    // don't know who to ask for a buffer, and so give up.
+
+    reconstructions[free_spot].tag = mytag;
+
+    reconstructions[free_spot].size = size;
+    reconstructions[free_spot].buf = malloc(size + offsetof(struct split_ip_msg, hdr));
+    reconstructions[free_spot].bytes_rcvd = 0;
+    reconstructions[free_spot].timeout = T_ACTIVE;
+
+    debug("checking buffer size 0x%x\n", reconstructions[free_spot].size);
+    if (reconstructions[free_spot].buf == NULL) {
+      reconstructions[free_spot].timeout = T_UNUSED;
+      return NULL;
+    }
+    return &(reconstructions[free_spot]);
+  }
+  return NULL;
+}
+
+/* 
+ * read data on serial port and send it to the tun interface
+ * does fragment reassembly
+ */
+int serial_input() {
+    packed_lowmsg_t pkt;
+    reconstruct_t *recon;
+    struct split_ip_msg *msg;
+    IEEE154_header_t *mac_hdr;
+    
+    uint8_t *ser_data = NULL;          /* data read from serial port */
+    int ser_len = 0;                    /* length of data read from serial port */
+    uint8_t shortMsg[INET_MTU];
+    uint8_t *payload;
+
+#ifdef SF_SRC
+    int rv = 0;
+#else
+    int rv = 1;
+#endif
+
+    /* read data from serial port */
+    ser_data = (uint8_t *)read_pan_packet(&ser_len);
+
+    /* process the packet we have received */
+    if (ser_len && ser_data) {
+      if (ser_data[0] != TOS_SERIAL_802_15_4_ID) {
+        handle_other_pkt(ser_data, ser_len);
+        goto discard_packet;
+      }
+      mac_hdr = (IEEE154_header_t *)(ser_data + 1);
+
+      // size is  one for the length byte, minus two for the checksum
+      pkt.len = mac_hdr->length - MAC_HEADER_SIZE - MAC_FOOTER_SIZE;
+      // add one for the dispatch byte.
+      pkt.data = ser_data + 1 + sizeof(IEEE154_header_t);
+
+      // for some reason these are little endian so we don't do any conversion.
+      pkt.src = mac_hdr->src;
+      pkt.dst = mac_hdr->dest;
+
+      log_dump_serial_packet(ser_data, ser_len);
+
+      pkt.headers = getHeaderBitmap(&pkt);
+      if (pkt.headers == LOWPAN_NALP_PATTERN) goto discard_packet;
+
+      stats.rx_frags++;
+      stats.rx_bytes += ser_len - 1;
+      if (hasFrag1Header(&pkt) || hasFragNHeader(&pkt)) {
+        unpack_info_t u_info;
+        uint8_t amount_here;
+
+        recon = getReassembly(&pkt);
+        if (recon == NULL || recon->buf == NULL) goto discard_packet;
+        msg = (struct split_ip_msg *)recon->buf;
+        msg->prev_hop = pkt.src;
+
+        if (hasFrag1Header(&pkt)) {
+          if (unpackHeaders(&pkt, &u_info,
+                            (uint8_t *)&msg->hdr, recon->size) == NULL) goto discard_packet;
+          amount_here = pkt.len - (u_info.payload_start - pkt.data);
+          // adjustPlen(&msg->hdr, &u_info);
+
+          ip_memcpy(u_info.header_end, u_info.payload_start, amount_here);
+          recon->bytes_rcvd = sizeof(struct ip6_hdr) + u_info.payload_offset + amount_here;
+        } else {
+          uint8_t offset_cmpr;
+          uint16_t offset;
+          if (getFragDgramOffset(&pkt, &offset_cmpr)) goto discard_packet;
+          offset = offset_cmpr * 8;
+          payload = getLowpanPayload(&pkt);
+          amount_here = pkt.len - (payload - pkt.data);
+
+          if (offset + amount_here > recon->size) goto discard_packet;
+          ip_memcpy(((uint8_t *)&msg->hdr) + offset, payload, amount_here);
+          recon->bytes_rcvd += amount_here;
+          
+          if (recon->size == recon->bytes_rcvd) {
+            // got all the fragments...
+            debug ("serial: reconstruction finished\n");
+            add_header_list(msg);
+
+            msg->metadata.sender = pkt.src;
+
+            handle_serial_packet(msg);
+
+            recon->timeout = T_UNUSED;
+            free_split_msg(msg);
+            free(recon->buf);
+          }
+        }
+
+      } else {
+        unpack_info_t u_info;
+        // u_info.rih = NULL;
+        msg = (struct split_ip_msg *)shortMsg;
+        msg->prev_hop = pkt.src;
+
+        if (unpackHeaders(&pkt, &u_info,
+                          (uint8_t *)&msg->hdr, INET_MTU) == NULL) goto discard_packet;
+        if (ntohs(msg->hdr.plen) > INET_MTU - sizeof(struct ip6_hdr)) goto discard_packet;
+        // adjustPlen(&msg->hdr, &u_info);
+
+        msg->metadata.sender = pkt.src;
+/*         if (u_info.rih != NULL) */
+/*           info("Has a rinstall_header for src 0x%x with match: 0x%x\n",  */
+/*                pkt.src, ntohs(u_info.rih->match.dest));; */
+
+        ip_memcpy(u_info.header_end, u_info.payload_start, ntohs(msg->hdr.plen));
+
+        add_header_list(msg);
+        
+        handle_serial_packet(msg);
+        free_split_msg(msg);
+      }
+    } else {
+      //printf("no data on serial port, but FD triggered select\n");
+      rv = 0;
+    }
+  discard_packet:
+    // debug("serial_input: discard packet\n");
+    free(ser_data);
+    return rv;
+}
+
+void print_stats(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  
+  VTY_printf("Up since %s", ctime(&stats.boot_time));
+  VTY_printf("  receive  packets: %lu fragments: %lu bytes: %lu\r\n",
+             stats.rx_pkts, stats.rx_frags, stats.rx_bytes);
+  VTY_printf("  transmit packets: %lu fragments: %lu bytes: %lu\r\n",
+             stats.tx_pkts, stats.tx_frags, stats.tx_bytes);
+  VTY_printf("  forward  packets: %lu\r\n", stats.fw_pkts);
+  VTY_printf("  dag seqno: %hi\r\n", routing_get_seqno());
+  VTY_flush();
+}
+
+void print_help(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  VTY_printf("ip-driver console\r\n");
+  VTY_printf("  conf      : print configuration info\r\n");
+  VTY_printf("  stats     : print statistics\r\n");
+  VTY_printf("  shutdown  : shutdown the driver\r\n");
+  VTY_printf("  chan <c>  : switch to channel 'c'\r\n");
+  VTY_printf("  dot <dotfile>: print dot-file of topology\r\n");
+  VTY_printf("  log {DEBUG INFO WARN ERROR FATAL}: set loglevel\r\n");
+  
+  VTY_printf("\r\n Routing commands:\r\n");
+  VTY_printf("  inval <nodeid> : invalidate a router\r\n");
+  VTY_printf("  add <n1> <n2>  : add a persistent link between n1 and n2\r\n");
+  VTY_printf("  links          : print link detail\r\n");
+  VTY_printf("  routes         : print routes\r\n");
+  VTY_printf("  newroutes      : recalculate routes\r\n");
+  VTY_printf("  rebuild        : initiate a DAG recomputation\r\n");
+  VTY_printf("  controller <n> : add a new controller\r\n");
+#ifdef CENTRALIZED_ROUTING
+  VTY_printf("  install <HOP | SRC> <n1> <n2> [reverse]: install a route between n1 and n2\r\n");
+  VTY_printf("  uninstall <n1> <n2>: uninstall a route between n1 and n2\r\n");
+#endif
+  
+  VTY_printf("\r\n");
+  VTY_printf("  help: print this help\r\n");
+  VTY_flush();
+}
+
+void sh_loglevel(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  int i;
+
+  if (argc != 2) return;
+  for (i = 0; i < 5; i++) {
+    if (strcmp(log_names[i], argv[1]) == 0) {
+      VTY_printf("setting verbosity to %s\r\n", log_names[i]);
+      log_setlevel(i);
+    }
+  }
+  VTY_flush();
+}
+
+void sh_dotfile(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  if (argc == 2) {
+    VTY_printf("writing topology to %s\r\n", argv[1]);
+    nw_print_dotfile(argv[1]);
+  } else {
+    VTY_printf("error: include a filename!\r\n");
+  }
+  VTY_flush();
+}
+
+void sh_chan(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  if (argc != 2) {
+    VTY_printf("%s <channel>\r\n", argv[0]);
+  } else {
+    int channel = atoi(argv[1]);
+    if (channel < 11 || channel > 26) {
+      VTY_printf("channel must be in [11:26]\r\n");
+    } else {
+      driver_config.channel = channel;
+      VTY_printf("setting channel to %i\r\n", channel);
+      configure_setparms(&driver_config, CONFIG_SET_PARM);
+    }
+  }
+  VTY_flush();
+}
+
+#ifdef CENTRALIZED_ROUTING
+void sh_install(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  int flags = 0;
+  struct split_ip_msg msg;
+  if (argc < 4) {
+    goto usage;
+  } 
+  if (strcmp("HOP", argv[1]) == 0) 
+    flags |= HYDRO_METHOD_HOP;
+  else if (strcmp("SRC", argv[1]) == 0) {
+    flags |= HYDRO_METHOD_SOURCE;
+  } else goto usage;
+
+  argc -= 4;
+  while (argc > 0) {
+    if (argv[argc+3][0] == 'R') {
+      flags |= HYDRO_INSTALL_REVERSE;
+    } else goto usage;
+    argc--;
+  }
+  memset(&msg, 0, sizeof(struct split_ip_msg));
+  memcpy(msg.hdr.ip6_src.s6_addr, __my_address.s6_addr, 8);
+  memcpy(msg.hdr.ip6_dst.s6_addr, __my_address.s6_addr, 8);
+  msg.hdr.ip6_src.s6_addr16[7] = htons(atoi(argv[2]));
+  msg.hdr.ip6_dst.s6_addr16[7] = htons(atoi(argv[3]));
+
+  VTY_printf("installing route between 0x%x and 0x%x\r\n", atoi(argv[2]), atoi(argv[3]));
+  install_route(&msg, flags);
+
+  VTY_flush();
+  return;
+ usage:
+  VTY_printf("%s <HOP | SRC> <n1> <n2> [REV]\r\n", argv[0]);
+  VTY_flush();
+}
+
+void sh_uninstall(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  if (argc != 3) {
+    VTY_printf("%s <n1> <n2>\r\n", argv[0]);
+    VTY_flush();
+    return;
+  }
+  int n1 = atoi(argv[1]);
+  int n2 = atoi(argv[2]);
+  VTY_printf("uninstalling route from 0x%x to 0x%x\r\n", n1, n2);
+  uninstall_route(n1, n2);
+  VTY_flush();
+}
+#endif
+
+void sh_controller(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  if (argc != 2) {
+    VTY_printf("%s <cid>\r\n", argv[0]);
+  } else {
+    int n = atoi(argv[1]);
+    get_insert_router(n);
+    nw_add_controller(n);
+  }
+  VTY_flush();
+}
+
+void sh_incr_seqno(int fd, int argc, char **argv) {
+  VTY_HEAD;
+  VTY_printf("DAG seqno now %i\r\n", routing_incr_seqno());
+  radvd_reset_adverts();
+
+  VTY_flush();
+}
+
+struct vty_cmd vty_cmd_list[] = {{"help", print_help},
+                                 {"stats",  print_stats},
+                                 {"links", nw_print_links},
+                                 {"routes", nw_print_routes},
+                                 {"newroutes", nw_test_routes},
+                                 {"add", nw_add_sticky_edge},
+                                 {"inval", nw_inval_node_sh},
+                                 {"conf", config_print},
+                                 {"log", sh_loglevel},
+                                 {"dot", sh_dotfile},
+                                 {"chan", sh_chan},
+                                 {"rebuild", sh_incr_seqno},
+#ifdef CENTRALIZED_ROUTING
+                                 {"install", sh_install},
+                                 {"uninstall", sh_uninstall},
+#endif
+                                 {"controller", sh_controller},
+                                 {"shutdown", (void(*)(int,int,char**))driver_shutdown}};
+
+/* shifts data between the serial port and the tun interface */
+int serial_tunnel(int tun_fd) {
+  fd_set fs;
+  int maxfd = -1;
+  int usecs_remain = KEEPALIVE_INTERVAL;
+  time_t last_aging, current_time;
+  time(&last_aging);
+#ifndef SF_SRC
+  int pan_fd = opt_listenonly ? -1 : serial_source_fd(ser_src);
+#else
+  int pan_fd = opt_listenonly ? -1 : sf_fd;
+#endif
+
+  while (1) {
+    int n_fds;
+    struct timeval tv;
+    if (do_shutdown) return 0;
+
+    FD_ZERO(&fs);
+
+    if (opt_listenonly) {
+      maxfd = -1;
+    } else {
+      FD_SET(tun_fd, &fs);
+      FD_SET(pan_fd, &fs);
+
+      maxfd = max(tun_fd, pan_fd);
+    }
+
+    if (radvd_fd >= 0) {
+      FD_SET(radvd_fd, &fs);
+      maxfd = max(radvd_fd, maxfd);
+    }
+
+    maxfd = max(vty_add_fds(&fs), maxfd);
+    maxfd = max(routing_add_fds(&fs), maxfd);
+
+    // having a timeout also means that we poll for new packets every
+    // so often, which is apparently A Good Thing
+    tv.tv_sec  = 0;
+    tv.tv_usec = KEEPALIVE_TIMEOUT;
+    if ((n_fds = select(maxfd + 1, &fs, NULL, NULL, &tv)) < 0) {
+      continue;
+    }
+    usecs_remain -= (KEEPALIVE_TIMEOUT - tv.tv_usec);
+    if (usecs_remain <= 0) {
+      if (keepalive_needed && !opt_listenonly) {
+        configure_setparms(&driver_config, CONFIG_KEEPALIVE);
+      } else keepalive_needed = 1;
+
+      usecs_remain = KEEPALIVE_INTERVAL;
+    }
+    
+    if (!opt_listenonly) {
+      int more_data;
+      /* check for data */
+      do {
+        more_data = tun_input();
+        more_data = serial_input() || more_data ;
+      } while (more_data);
+    }
+
+    vty_process(&fs);
+    routing_process(&fs);
+
+    if (radvd_fd >= 0 && FD_ISSET(radvd_fd, &fs)) {
+      radvd_process();
+    }
+
+    /* end of data available */
+    time(&current_time);
+    if (current_time > last_aging + (FRAG_EXPIRE_TIME / 1024)) {
+      last_aging = current_time;
+      age_reconstructions();
+    }
+  }
+
+}
+
+int main(int argc, char **argv) {
+  int i, c;
+
+  time(&stats.boot_time);
+
+  log_init();
+  while ((c = getopt(argc, argv, "c:lt")) != -1) {
+    switch (c) {
+    case 'c':
+      def_configfile = optarg;
+      break;
+    case 'l':
+      opt_listenonly = 1;
+      info("Listen Only: will not attach to interface device\n");
+      break;
+    case 't':
+      info("TrackFlows: will insert flow id on outgoing packets\n");
+      opt_trackflows = 1;
+      break;
+    default:
+      fatal("Invalid command line argument.\n");
+      exit(1);
+    }
+  }
+
+  if (argc - optind != 2 && !opt_listenonly) {
+#ifndef SF_SRC
+    fatal("usage: %s [-c config] [-l] <device> <rate>\n", argv[0]);
+#else
+    fatal("usage: %s [-c config] <host> <port>\n", argv[0]);
+#endif
+    exit(2);
+  }
+    
+  fifo_open();
+  signal(SIGINT,  driver_shutdown);
+
+  if (config_parse(def_configfile, &driver_config) != 0) {
+    fatal ("config parse of %s failed!\n", def_configfile);
+    exit(1);
+  }
+  globalPrefix = 1;
+  memcpy(&__my_address, &driver_config.router_addr, sizeof(struct in6_addr));
+
+
+  struct vty_cmd_table t;
+  short vty_port = 6106;
+  t.n = sizeof(vty_cmd_list) / sizeof(struct vty_cmd);
+  t.table = vty_cmd_list;
+  if (vty_init(&t, vty_port) < 0) {
+    error("could not start debug console server\n");
+    error("the console will be available only on stdin\n");
+  } else {
+    info("telnet console server running on port %i\n", vty_port);
+  }
+
+
+  dev[0] = 0;
+  if (opt_listenonly) {
+    tun_fd = -1;
+#ifndef SF_SRC
+    ser_src = NULL;
+#endif
+  } else {
+    /* create the tunnel device */
+    tun_fd = tun_open(dev);
+    if (tun_fd < 1) {
+      fatal("Could not create tunnel device. Fatal.\n");
+      return 1;
+    } else {
+      info("created tun device: %s\n", dev);
+    }
+    if (tun_setup(dev, &__my_address) < 0) {
+      fatal("configuring the tun failed; aborting\n");
+      perror("tun_setup");
+      return 1;
+    }
+    
+    
+    for (i = 0; i < N_RECONSTRUCTIONS; i++) {
+      reconstructions[i].timeout = T_UNUSED;
+    }
+
+    /* open the serial port */
+#ifndef SF_SRC
+    ser_src = open_serial_source(argv[optind], platform_baud_rate(argv[optind + 1]),
+                                 1, stderr_msg);
+    if (!ser_src) {
+      fatal("Couldn't open serial port at %s:%s\n", argv[optind], argv[optind + 1]);
+      exit(1);
+    }
+#else
+    sf_fd = open_sf_source(argv[optind], atoi(argv[optind + 1]));
+    if (sf_fd < 0) {
+      fatal("Couldn't connect to serial forwarder sf@%s:%s\n", argv[optind], argv[optind + 1]);
+      exit(1);
+    }
+#endif
+
+#ifndef SIM
+  configure_reboot();
+#endif
+
+  }
+
+  if (routing_init(&driver_config, dev) < 0) {
+    fatal("could not start routing engine!\n");
+    exit(1);
+  }
+
+  /* start tunneling */
+  serial_tunnel(tun_fd);
+
+  /* clean up */
+  info("driver shutting down\n");
+  vty_shutdown();
+  if (!opt_listenonly)  {
+    tun_close(tun_fd, dev);
+    close_pan();
+  }
+  fifo_close();
+  return 0;
+}
diff --git a/support/sdk/c/blip/driver/tun_dev.c b/support/sdk/c/blip/driver/tun_dev.c
new file mode 100644 (file)
index 0000000..ef05d9c
--- /dev/null
@@ -0,0 +1,212 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * Copyright (c) 2007 Matus Harvan
+ * All rights reserved
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ *       copyright notice, this list of conditions and the following
+ *       disclaimer in the documentation and/or other materials provided
+ *       with the distribution.
+ *     * The name of the author may not be used to endorse or promote
+ *       products derived from this software without specific prior
+ *       written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <syslog.h>
+#include <errno.h>
+
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <linux/if.h>
+#include <linux/if_ether.h>
+
+#include <netinet/in.h>
+#include <lib6lowpan/lib6lowpan.h>
+
+#include "tun_dev.h"
+#include "logging.h"
+
+
+/*
+ *    This is in linux/include/net/ipv6.h.
+ *    Thanks, net-tools!
+ */
+struct in6_ifreq {
+    struct in6_addr ifr6_addr;
+    __u32 ifr6_prefixlen;
+    unsigned int ifr6_ifindex;
+};
+
+
+int tun_open(char *dev)
+{
+    struct ifreq ifr;
+    int fd;
+
+    if ((fd = open("/dev/net/tun", O_RDWR | O_NONBLOCK)) < 0)
+       return -1;
+
+    memset(&ifr, 0, sizeof(ifr));
+    /* By default packets are tagged as IPv4. To tag them as IPv6,
+     * they need to be prefixed by struct tun_pi.
+     */
+    //ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
+    ifr.ifr_flags = IFF_TUN;
+    if (*dev)
+       strncpy(ifr.ifr_name, dev, IFNAMSIZ);
+
+    if (ioctl(fd, TUNSETIFF, (void *) &ifr) < 0)
+       goto failed;
+
+    strcpy(dev, ifr.ifr_name);
+    return fd;
+
+  failed:
+    log_fatal_perror("tun_open");
+    close(fd);
+    return -1;
+}
+
+int tun_setup(char *dev, struct in6_addr *addr) {
+  struct in6_ifreq ifr6;
+  struct ifreq ifr;
+  int fd;
+
+  if ((fd = socket(PF_INET6, SOCK_DGRAM, 0)) < 0)
+    return -1;
+
+  memset(&ifr, 0, sizeof(struct ifreq));
+  strncpy(ifr.ifr_name, dev, IFNAMSIZ);
+
+  /* set the interface up */
+  if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0) {
+    log_fatal_perror("SIOCGIFFLAGS");
+    return -1;
+  }
+  ifr.ifr_flags |= IFF_UP;
+  if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0) {
+    log_fatal_perror("SIOCSIFFLAGS");
+    return -1;
+  }
+
+  /* MTU */
+  ifr.ifr_mtu = 1280;
+  if (ioctl(fd, SIOCSIFMTU, &ifr) < 0) {
+    log_fatal_perror("SIOCSIFMTU");
+    return -1;
+  }
+
+  /* Global address */
+  memset(&ifr6, 0, sizeof(struct in6_ifreq));
+  memcpy(&ifr6.ifr6_addr, addr, 16);
+  if (ioctl(fd, SIOGIFINDEX, &ifr) < 0) {
+    log_fatal_perror("SIOGIFINDEX");
+    return -1;
+  }
+
+  ifr6.ifr6_ifindex = ifr.ifr_ifindex;
+  ifr6.ifr6_prefixlen = 128;
+  if (ioctl(fd, SIOCSIFADDR, &ifr6) < 0) {
+    log_fatal_perror("SIOCSIFADDR (global)");
+    return -1;
+  }
+
+  memset(&ifr6.ifr6_addr.s6_addr[0], 0, 16);
+  ifr6.ifr6_addr.s6_addr16[0] = htons(0xfe80);
+  ifr6.ifr6_addr.s6_addr16[7] = addr->s6_addr16[7];
+  
+  if (ioctl(fd, SIOCSIFADDR, &ifr6) < 0) {
+    log_fatal_perror("SIOCSIFADDR (local)");
+    return -1;
+  }
+
+  close(fd);
+
+  return 0;
+}
+
+int tun_close(int fd, char *dev)
+{
+    return close(fd);
+}
+
+/* Read/write frames from TUN device */
+int tun_write(int fd, struct split_ip_msg *msg)
+{
+  uint8_t buf[INET_MTU + sizeof(struct tun_pi)], *packet;
+  struct tun_pi *pi = (struct tun_pi *)buf;
+  struct generic_header *cur;
+  packet = (uint8_t *)(pi + 1);
+
+
+  if (ntohs(msg->hdr.plen) + sizeof(struct ip6_hdr) >= INET_MTU)
+    return 1;
+
+  pi->flags = 0;
+  pi->proto = htons(ETH_P_IPV6);
+
+  memcpy(packet, &msg->hdr, sizeof(struct ip6_hdr));
+  packet += sizeof(struct ip6_hdr);
+
+  cur = msg->headers;
+  while (cur != NULL) {
+    memcpy(packet, cur->hdr.data, cur->len);
+    packet += cur->len;
+    cur = cur->next;
+  }
+
+  memcpy(packet, msg->data, msg->data_len);
+
+  return write(fd, buf, sizeof(struct tun_pi) + sizeof(struct ip6_hdr) + ntohs(msg->hdr.plen));
+}
+
+int tun_read(int fd, char *buf, int len)
+{
+  int out;
+  out = read(fd, buf, sizeof(struct tun_pi) + len);
+
+  return out - sizeof(struct tun_pi);
+}
diff --git a/support/sdk/c/blip/driver/tun_dev.h b/support/sdk/c/blip/driver/tun_dev.h
new file mode 100644 (file)
index 0000000..9986ae6
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * Copyright (c) 2007 Matus Harvan
+ * All rights reserved
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ *       copyright notice, this list of conditions and the following
+ *       disclaimer in the documentation and/or other materials provided
+ *       with the distribution.
+ *     * The name of the author may not be used to endorse or promote
+ *       products derived from this software without specific prior
+ *       written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _TUN_DEV_H
+#define _TUN_DEV_H
+
+#include <lib6lowpan/ip.h>
+
+int tun_open(char *dev);
+int tun_close(int fd, char *dev);
+int tun_setup(char *dev, struct in6_addr *addr);
+int tun_write(int fd, struct split_ip_msg *msg);
+int tun_read(int fd, char *buf, int len);
+
+#endif
diff --git a/support/sdk/c/blip/driver/tunnel.c b/support/sdk/c/blip/driver/tunnel.c
new file mode 100644 (file)
index 0000000..6d6a64e
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * Implementation of user-mode driver and IP gateway using a node
+ * running IPBaseStation as 802.15.4 hardware.  Uses kernel tun
+ * interface to route addresses.
+ * 
+ */
+#include <stdio.h>
+#include <stdint.h>
+#include <unistd.h>
+
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+uint16_t shortAddr;
+int tun_fd;
+char *tun_dev = "/dev/net/tun";
+
+void usage(char **args) {
+  fprintf(stderr, "\n\t%s <my-short-addr>\n\n", args[0]);
+}
+
+int create_tunnel() {
+  struct ifreq ifr;
+  if ((tun_fd = open(tun_dev, O_RDWR)) < 0) {
+    fprintf(stderr, "Failed to open '%s' : ", tun_dev);
+    perror("");
+    return 1;
+  }
+  ifr.irf_flags = IFF_TAP | IFF_NO_PI;
+  str
+
+  return 0;
+}
+
+int main(int argc, char **argv) {
+  if (argc != 2) {
+    usage(argv);
+    return 1;
+  }
+  shortAddr = atoi(argv[1]);
+
+  if (create_tunnel())
+    return 1;
+
+  sleep(20);
+
+  return 0;
+}
diff --git a/support/sdk/c/blip/driver/vty/Makefile b/support/sdk/c/blip/driver/vty/Makefile
new file mode 100644 (file)
index 0000000..69bf9a7
--- /dev/null
@@ -0,0 +1,6 @@
+
+test_SOURCE=test_srv.c vty.c util.c ../logging.c
+CFLAGS=-I.. -g
+
+test: $(test_SOURCE)
+       gcc $(test_SOURCE) -o $@ $(CFLAGS)
\ No newline at end of file
diff --git a/support/sdk/c/blip/driver/vty/test_srv.c b/support/sdk/c/blip/driver/vty/test_srv.c
new file mode 100644 (file)
index 0000000..a3c8f03
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdlib.h>
+#include <signal.h>
+#include <string.h>
+#include "logging.h"
+#include "vty.h"
+
+
+void do_echo(int fd, int argc, char ** argv) {
+  VTY_HEAD;
+  if (argc > 1) {
+    VTY_printf("%s\r\n", argv[1]);
+    VTY_flush();
+  }
+}
+
+struct vty_cmd echo = {"echo", do_echo};
+
+void shutdown() {
+  vty_shutdown();
+  exit(0);
+}
+
+int main(int argc, char **argv) {
+  int maxfd;
+  fd_set fds;
+  struct vty_cmd_table t;
+  log_init();
+  log_setlevel(LOGLVL_DEBUG);
+  
+  signal(SIGINT, shutdown);
+
+  t.n = 1;
+  t.table = &echo;
+
+
+  vty_init(&t, atoi(argv[1]));
+  while (1) {
+    FD_ZERO(&fds);
+    maxfd = vty_add_fds(&fds);
+
+    select(maxfd+1, &fds, NULL, NULL, NULL);
+
+    vty_process(&fds);
+  }
+  info("Done, exiting\n");
+
+}
diff --git a/support/sdk/c/blip/driver/vty/vty-util.c b/support/sdk/c/blip/driver/vty/vty-util.c
new file mode 100644 (file)
index 0000000..583e41d
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include "vty.h"
+
+void init_argv(char *cmd, int len, char **argv, int *argc) {
+  int inArg = 0;
+  *argc = 0;
+  while (len > 0 && *argc < N_ARGS) {
+    if (*cmd == ' ' || *cmd == '\n' || 
+        *cmd == '\t' || *cmd == '\0' || 
+        *cmd == '\r' || *cmd == '\4' ||
+        len == 1){
+      if (inArg) {
+        *argc = *argc + 1;
+        inArg = 0;
+        *cmd = '\0';
+      }
+    } else if (!inArg) {
+      argv[*argc] = cmd;
+        inArg = 1;
+    }
+    cmd ++;
+    len --;
+  }
+}
diff --git a/support/sdk/c/blip/driver/vty/vty.c b/support/sdk/c/blip/driver/vty/vty.c
new file mode 100644 (file)
index 0000000..10fed9b
--- /dev/null
@@ -0,0 +1,335 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * @author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <signal.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <string.h>
+#include <stdarg.h>
+
+#include "vty.h"
+#include "../logging.h"
+
+#define max(X,Y)  (((X) > (Y)) ?  (X) : (Y))
+
+typedef enum {
+  FALSE = 0,
+  TRUE  = 1,
+} bool;
+
+enum {
+  VTY_REMOVE_PENDING = 0x1,
+};
+
+struct vty_client {
+  int                 flags;
+  int                 readfd;
+  int                 writefd;
+  struct sockaddr_in6 ep;
+  struct vty_client  *next;
+  
+  int                 buf_off;
+  unsigned char       buf[2][1024];
+  int                 argc;
+  char                *argv[N_ARGS];
+};
+
+static int sock = -1;
+static struct vty_client *conns = NULL;
+static struct vty_cmd_table *cmd_tab;
+static char prompt_str[40];
+
+int vty_init(struct vty_cmd_table * cmds, short port) {
+  struct sockaddr_in6 si_me = {
+    .sin6_family = AF_INET6,
+    .sin6_port = htons(port),
+    .sin6_addr = IN6ADDR_ANY_INIT,
+  };
+  struct vty_client *tty_client;
+  int len, yes = 1;
+
+  conns = NULL;
+  cmd_tab = cmds;
+
+  strncpy(prompt_str, "blip:", 5);
+  gethostname(prompt_str+5, sizeof(prompt_str)- 5);
+  len=strlen(prompt_str+5);
+  prompt_str[len+5]='>';
+  prompt_str[len+6]=' ';
+  prompt_str[len+7]='\0';
+
+  if (isatty(fileno(stdin))) {
+    setbuf(stdin, NULL);
+    tty_client = (struct vty_client *)malloc(sizeof(struct vty_client));
+    memset(tty_client, 0, sizeof(struct vty_client));
+    tty_client->flags = 0;
+    tty_client->readfd = fileno(stdin);
+    tty_client->writefd = fileno(stdout);
+    tty_client->next = NULL;
+    conns = tty_client;
+  }
+
+  sock = socket(PF_INET6, SOCK_STREAM, 0);
+  if (sock < 0) {
+    log_fatal_perror("vty: socket");
+    return -1;
+  }
+
+  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0) {
+    log_fatal_perror("vty: setsockopt");
+    goto abort;
+  }
+
+  if (bind(sock, (struct sockaddr *)&si_me, sizeof(si_me)) < 0) {
+    log_fatal_perror("vty: bind");
+    goto abort;
+  }
+
+  if (listen(sock, 2) < 0) {
+    log_fatal_perror("vty: listen");
+    goto abort;
+  }
+
+  return 0;
+ abort:
+  close(sock);
+  sock = -1;
+  return -1;
+}
+
+int vty_add_fds(fd_set *fds) {
+  int maxfd;
+  struct vty_client *cur;
+  if (sock >= 0) FD_SET(sock, fds);
+  maxfd = sock;
+
+  for (cur = conns; cur != NULL; cur = cur->next) {
+    if (cur->flags & VTY_REMOVE_PENDING) continue;
+    FD_SET(cur->readfd, fds);
+    maxfd = max(maxfd, cur->readfd);
+  }
+  return maxfd;
+}
+
+static void vty_print_string(struct vty_client *c, const char *fmt, ...) {
+  char buf[1024];
+  int len;
+  va_list ap;
+  va_start(ap, fmt);
+  len = vsnprintf(buf, 1024, fmt, ap);
+  len = write(c->writefd, buf, len);
+}
+
+static void prompt(struct vty_client *c) {
+  vty_print_string(c, prompt_str);
+}
+
+static void vty_new_connection() {
+  char addr_buf[512];
+  struct vty_client * c = malloc(sizeof(struct vty_client));
+  socklen_t len;
+  if (c == NULL) return;
+
+  len = sizeof(struct sockaddr_in6);
+  c->readfd = c->writefd = accept(sock, (struct sockaddr *)&c->ep, &len);
+  if (c->readfd < 0) {
+    error("Accept failed!\n");
+    log_fatal_perror(0);
+    free(c);
+    return;
+  }
+  c->buf_off = 0;
+  memset(c->buf, 0, sizeof(c->buf));
+
+  inet_ntop(AF_INET6, c->ep.sin6_addr.s6_addr, addr_buf, 512);
+  info("VTY: new connection accepted from %s\n", addr_buf);
+  vty_print_string(c, "Welcome to the blip console!\r\n");
+  vty_print_string(c, " type 'help' to print the command options\r\n");
+  prompt(c);
+  c->flags = 0;
+  c->next = conns;
+  conns = c;
+}
+
+void vty_close_connection(struct vty_client *c) {
+  close(c->readfd);
+  if (c->readfd != c->writefd) close(c->writefd);
+  c->flags |= VTY_REMOVE_PENDING;
+}
+
+
+void vty_dispatch_command(struct vty_client *c) {
+  int i;
+
+  if (c->argc > 0) {
+    for (i = 0; i < cmd_tab->n; i++) {
+      if (strncmp(c->argv[0], cmd_tab->table[i].name, 
+                  strlen(cmd_tab->table[i].name) + 1) == 0) {
+        cmd_tab->table[i].fn(c->writefd, c->argc, c->argv);
+        break;
+      }
+      
+      if (strncmp(c->argv[0], "quit", 4) == 0) {
+        vty_close_connection(c);
+        return;
+      }
+    }
+    if (i == cmd_tab->n) {
+      vty_print_string(c, "vty: %s: command not found\r\n", c->argv[0]);
+    }
+  }
+  prompt(c);
+}
+
+void vty_handle_data(struct vty_client *c) {
+  int len, i;
+  char addr_buf[512];
+  bool prompt_pending = FALSE;
+  len = read(c->readfd, c->buf[0] + c->buf_off, sizeof(c->buf) - c->buf_off);
+  if (len <= 0) {
+    inet_ntop(AF_INET6, c->ep.sin6_addr.s6_addr, addr_buf, 512);
+    warn("Invalid read on connection from %s: closing\n", addr_buf);
+    vty_close_connection(c);
+  }
+  c->buf_off += len;
+  // try to scan the whole line we're building up and remove/process
+  // any telnet escapes in there
+  
+  for (i = 0; i < c->buf_off; i++) {
+    int escape_len;
+
+    if (c->buf[0][i] == 255) {
+      escape_len = 2;
+      // process and remove a command;
+      // the command code is in buf[i+1]
+      switch (c->buf[0][i+1]) {
+      case TELNET_INTERRUPT:
+        // ignore the command buffer we've accumulated
+        memmove(&c->buf[0][0], &c->buf[0][i+2], c->buf_off - i - 2);
+        c->buf_off -= i + 2;
+        i = -1;
+        prompt_pending = TRUE;
+        continue;
+      }
+      if (c->buf[0][i+1] >= 250) {
+        unsigned char response[3];
+        // we don't do __anything__
+        response[0] = 255;
+        response[1] = TELNET_WONT;
+        response[2] = c->buf[0][i+2];
+        len = write(c->writefd, response, 3);
+        escape_len++;
+      }
+
+      // this isn't like the most efficient parser ever, but since we
+      // don't ask for anything and reply to everyone with DONT it seems okay.
+      memmove(&c->buf[0][i], &c->buf[0][i+escape_len], 
+              c->buf_off - (i + escape_len));
+      c->buf_off -= escape_len;
+      // restart processing at the same place
+      i--;
+    } else if (c->buf[0][i] == 4) {
+      // EOT : make C-d work
+      vty_close_connection(c);
+    }
+    // technically, clients are supposed to send \r\n as a newline.
+    // however, the client in busybox (an important one) doesn't
+    // escape the terminal input and so only sends \n.
+    if (/* i > 0 && c->buf[i-1] == '\r' && */ c->buf[0][i] == '\n') {
+
+      if (!(i <= 1 && (c->buf[0][i] == '\n' || c->buf[0][i] == '\r'))) {
+        c->buf[0][i] = '\0';
+        memcpy(c->buf[1], c->buf[0], i + 1);
+        init_argv((char *)c->buf[1], i + 1, c->argv, &c->argc);
+      }
+
+      prompt_pending = FALSE;
+      vty_dispatch_command(c);
+
+      // start a new command at the head of the buffer
+      memmove(&c->buf[0][0], &c->buf[0][i+1], c->buf_off - i - 1);
+      c->buf_off -= i + 1;
+      i = -1;
+    }
+  }
+
+  
+  if (prompt_pending) {
+    vty_print_string(c, "\r\n");
+    prompt(c);
+    prompt_pending = FALSE;
+  }
+}
+
+int vty_process(fd_set *fds) {
+  struct vty_client *prev, *cur, *next;
+  if (sock >= 0 && FD_ISSET(sock, fds)) {
+    vty_new_connection();
+  }
+  for (cur = conns; cur != NULL; cur = cur->next) {
+    if (FD_ISSET(cur->readfd, fds)) {
+      vty_handle_data(cur);
+    }
+  }
+
+  prev = NULL;
+  cur = conns;
+  while (cur != NULL) {
+    next = cur->next;
+    if (cur->flags & VTY_REMOVE_PENDING) {
+      char addr_buf[512];
+      inet_ntop(AF_INET6, cur->ep.sin6_addr.s6_addr, addr_buf, 512);
+      info("VTY: removing connection with endpoint %s\n", addr_buf);
+      free(cur);
+      if (cur == conns) conns = next;
+      if (prev != NULL) prev->next = next;
+    } else {
+      prev = cur;
+    }
+    cur = next;
+  }
+
+  return 0;
+}
+
+void vty_shutdown() {
+  struct vty_client *cur = conns, *next;
+  if (sock >= 0) close(sock);
+
+  while (cur != NULL) {
+    next = cur->next;
+    if (!(cur->flags & VTY_REMOVE_PENDING)) {
+      close(cur->readfd);
+      if (cur->readfd != cur->writefd) close(cur->writefd);
+    }
+    free(cur);
+    cur = next;
+  }
+}
diff --git a/support/sdk/c/blip/driver/vty/vty.h b/support/sdk/c/blip/driver/vty/vty.h
new file mode 100644 (file)
index 0000000..0c95dff
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * @author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
+ *
+ * This is a very simple set of functions to allow a program using a
+ * single blocking select() loop to include a telnet server.  Most of
+ * the telnet RFC854 protocol is not implemented; this just gives you
+ * an easy way to add a simple shell that doesn't do much.
+ *
+ * Readline-like editing would be nice; unfortunatly readline itself
+ * is GPL, so it's not an option.
+ */
+
+#ifndef _VTY_H_
+#define _VTY_H_
+
+#include <unistd.h>
+#include <sys/select.h>
+
+// helpful macros since you can't do straight printf() on a socket
+#define VTY_HEAD                  char __vty_buf[4096]; int __vty_len = 0
+#define VTY_printf(fmt, args...)  __vty_len += snprintf(__vty_buf + __vty_len, 4096 - __vty_len, \
+                                                        fmt, ## args)
+#define VTY_flush()               __vty_len = write(fd, __vty_buf, __vty_len); __vty_len = 0
+
+#define VTYNAMSIZ 16
+
+// set these up and pass it to vty_init().  the only builtin is 'quit'.
+struct vty_cmd {
+  char name[VTYNAMSIZ];
+  void (*fn)(int fd, int argc, char **argv);
+};
+
+struct vty_cmd_table {
+  int              n;
+  struct vty_cmd * table;
+};
+
+int  vty_init(struct vty_cmd_table *cmd_tab, short port);
+int  vty_add_fds(fd_set *fds);
+int  vty_process(fd_set *fds);
+void vty_shutdown();
+
+// defined in util.c  N_ARGS is the maximum number length of argv.
+#define N_ARGS  30
+void init_argv(char *cmd, int len, char **argv, int *argc);
+
+
+// values from telnet rfc854.  We don't implement very much at all of
+// the telnet protocol
+#define TELNET_INTERRUPT 244
+#define TELNET_WONT      252
+
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/6lowpan.h b/support/sdk/c/blip/lib6lowpan/6lowpan.h
new file mode 100644 (file)
index 0000000..636c341
--- /dev/null
@@ -0,0 +1,190 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+
+/*
+ * Header file for the 6lowpan/IPv6 stack.
+ *
+ * @author Stephen Dawson-Haggerty
+ * 
+ */
+
+#ifndef __6LOWPAN_H__
+#define __6LOWPAN_H__
+
+#include <stdint.h>
+
+#include "blip-platform.h"
+/*
+ * Typedefs and static library data.
+ */
+typedef uint8_t ip6_addr_t [16];
+typedef uint16_t cmpr_ip6_addr_t;
+#ifdef PC
+#include "../config.h"
+typedef uint16_t ieee154_saddr_t;
+typedef uint16_t hw_pan_t;
+enum {
+  HW_BROADCAST_ADDR = 0xffff,
+};
+#else
+#include <Ieee154.h>
+#endif
+
+/*
+ * shared variables which contain addressing information for 6lowpan
+ * devices
+ */
+extern uint8_t globalPrefix;
+extern uint8_t multicast_prefix[8];
+extern uint8_t linklocal_prefix[8];
+
+uint8_t cmpPfx(ip6_addr_t a, uint8_t *pfx);
+
+void ip_memclr(uint8_t *buf, uint16_t len);
+void *ip_memcpy(void *dst0, const void *src0, uint16_t len);  
+
+/*
+ * A packed 6lowpan packet. 
+ *
+ * The data buffer points at the start of 6lowpan packed data.  We
+ * included a few other fields from L2 with this information so that
+ * we are able to infer things like source and destination IP from it.
+ *
+ */
+typedef struct packed_lowmsg {
+  uint8_t headers;
+  uint8_t len;
+  // we preprocess the headers bitmap for easy processing.
+  ieee154_saddr_t src;
+  ieee154_saddr_t dst;
+  uint8_t *data;
+} packed_lowmsg_t;
+
+/*
+ * bit fields we use to keep track of which optional header fields are
+ * present in a message
+ */
+enum {
+  LOWMSG_MESH_HDR  = (1 << 0),
+  LOWMSG_BCAST_HDR = (1 << 1),
+  LOWMSG_FRAG1_HDR = (1 << 2),
+  LOWMSG_FRAGN_HDR = (1 << 3),
+  LOWMSG_NALP      = (1 << 4),
+  LOWMSG_IPNH_HDR  = (1 << 5),
+};
+
+/*
+ * lengths of different lowpan headers
+ */
+enum {
+  LOWMSG_MESH_LEN = 5,
+  LOWMSG_BCAST_LEN = 2,
+  LOWMSG_FRAG1_LEN = 4,
+  LOWMSG_FRAGN_LEN = 5,
+};
+
+enum {
+  LOWPAN_LINK_MTU = 110,
+  INET_MTU = 1280,
+  LIB6LOWPAN_MAX_LEN = LOWPAN_LINK_MTU,
+};
+
+/*
+ * magic numbers from rfc4944; some of them shifted: mostly dispatch values.
+ */
+enum {
+  LOWPAN_NALP_PATTERN = 0x0,
+  LOWPAN_MESH_PATTERN = 0x2,
+  LOWPAN_FRAG1_PATTERN = 0x18,
+  LOWPAN_FRAGN_PATTERN = 0x1c,
+  LOWPAN_BCAST_PATTERN = 0x50,
+  LOWPAN_HC1_PATTERN = 0x42,
+  LOWPAN_HC_LOCAL_PATTERN = 0x3,
+  LOWPAN_HC_CRP_PATTERN = 0x4,
+};
+
+enum {
+  LOWPAN_MESH_V_MASK = 0x20,
+  LOWPAN_MESH_F_MASK = 0x10,
+  LOWPAN_MESH_HOPS_MASK = 0x0f,
+};
+
+/*
+ * constants to unpack HC-packed headers
+ */
+enum {
+  LOWPAN_IPHC_VTF_MASK      = 0x80,
+  LOWPAN_IPHC_VTF_INLINE    = 0,
+  LOWPAN_IPHC_NH_MASK       = 0x40,
+  LOWPAN_IPHC_NH_INLINE     = 0,
+  LOWPAN_IPHC_HLIM_MASK     = 0x20,
+  LOWPAN_IPHC_HLIM_INLINE   = 0,
+
+  LOWPAN_IPHC_SC_OFFSET      = 3,
+  LOWPAN_IPHC_DST_OFFSET     = 1,
+  LOWPAN_IPHC_ADDRFLAGS_MASK = 0x3,
+
+  LOWPAN_IPHC_ADDR_128       = 0x0,
+  LOWPAN_IPHC_ADDR_64        = 0x1,
+  LOWPAN_IPHC_ADDR_16        = 0x2,
+  LOWPAN_IPHC_ADDR_0         = 0x3,
+
+  LOWPAN_IPHC_SHORT_MASK     = 0x80,
+  LOWPAN_IPHC_SHORT_LONG_MASK= 0xe0,
+
+  LOWPAN_IPHC_HC1_MCAST      = 0x80,
+  LOWPAN_IPHC_HC_MCAST       = 0xa0,
+
+  LOWPAN_HC_MCAST_SCOPE_MASK = 0x1e,
+  LOWPAN_HC_MCAST_SCOPE_OFFSET = 1,
+
+  LOWPAN_UDP_PORT_BASE_MASK  = 0xfff0,
+  LOWPAN_UDP_PORT_BASE       = 0xf0b0,
+  LOWPAN_UDP_DISPATCH        = 0x80,
+
+  LOWPAN_UDP_S_MASK          = 0x40,
+  LOWPAN_UDP_D_MASK          = 0x20,
+  LOWPAN_UDP_C_MASK          = 0x10,
+};
+
+
+
+// AT: These are really 16 bit values, but after a certain point the numbers
+//  beyond 255 aren't important to us, or rather no different than 255
+struct topology_entry {
+  uint8_t etx;
+  uint8_t conf;
+  ieee154_saddr_t hwaddr;
+};
+struct topology_header {
+  uint16_t seqno;
+  struct topology_entry topo[0];
+};
+struct topology_header_package {
+  uint16_t reporter;
+  uint16_t len;
+  uint16_t seqno;
+  struct topology_entry topo[0];
+};
+
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/IEEE154Packet.h b/support/sdk/c/blip/lib6lowpan/IEEE154Packet.h
new file mode 100644 (file)
index 0000000..4a47e16
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _IEEE154_H_
+#define _IEEE154_H_
+
+typedef struct IEEE154_header {
+  uint8_t length;
+  uint16_t fcf;
+  uint8_t dsn;
+  uint16_t destpan;
+  uint16_t dest;
+  uint16_t src;
+} __attribute__((packed)) IEEE154_header_t;
+
+typedef struct serial_header {
+  uint16_t dest;
+  uint16_t src;
+  uint8_t length;
+  uint8_t group;
+  uint8_t type;
+} __attribute__((packed)) serial_header_t;
+
+enum {
+  // size of the header not including the length byte
+  MAC_HEADER_SIZE = sizeof( IEEE154_header_t ) - 1,
+  // size of the footer (FCS field)
+  MAC_FOOTER_SIZE = sizeof( uint16_t ),
+};
+
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/Makefile.am b/support/sdk/c/blip/lib6lowpan/Makefile.am
new file mode 100644 (file)
index 0000000..f6248ab
--- /dev/null
@@ -0,0 +1,8 @@
+
+AM_CFLAGS = -DPC
+noinst_LIBRARIES = lib6lowpan.a
+
+lib6lowpan_h = 6lowpan.h  devconf.h  IEEE154Packet.h  in_cksum.h  \
+       ip.h  ip_malloc.h  lib6lowpan.h  TrackFlows.h blip-platform.h
+lib6lowpan_a_SOURCES = lib6lowpan.c lib6lowpanIP.c lib6lowpanFrag.c $(lib6lowpan_h)
+
diff --git a/support/sdk/c/blip/lib6lowpan/TrackFlows.h b/support/sdk/c/blip/lib6lowpan/TrackFlows.h
new file mode 100644 (file)
index 0000000..0e90c51
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef TRACKFLOWS_H_
+#define TRACKFLOWS_H_
+
+#ifndef PC
+enum {
+  AM_FLOW_ID_MSG = 248,
+};
+
+nx_struct flow_id {
+  nxle_uint16_t id;
+};
+
+nx_struct flow_id_msg {
+  nx_struct flow_id flow;
+  nxle_uint16_t src;
+  nxle_uint16_t dst;
+  nxle_uint16_t local_address;
+  nxle_uint8_t nxt_hdr;
+  nxle_uint8_t n_attempts;
+  nx_struct {
+    nxle_uint16_t next_hop;
+    nxle_uint16_t tx;
+  } attempts[3];
+};
+#else
+
+#include <stdint.h>
+struct flow_id {
+  uint16_t id;
+};
+
+
+struct flow_id_msg {
+  uint16_t flow;
+  uint16_t src;
+  uint16_t dst;
+  uint16_t local_address;
+  uint8_t nxt_hdr;
+  uint8_t n_attempts;
+  struct {
+    uint16_t next_hop;
+    uint16_t tx;
+  } attempts[3];
+};
+#endif
+
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/blip-platform.h b/support/sdk/c/blip/lib6lowpan/blip-platform.h
new file mode 100644 (file)
index 0000000..d93029c
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _BLIP_PLATFORM_H
+#define _BLIP_PLATFORM_H
+
+/* this file has platform-specific configuration settings that don't
+   belong anywhere else */
+
+/* bring in  */
+#if defined(PC)
+// use library versions if on linux
+#include <netinet/in.h>
+#include <endian.h>
+#else
+// if we're not on a pc, assume little endian for now
+#define __LITTLE_ENDIAN 1234
+#define __BYTE_ORDER __LITTLE_ENDIAN
+#endif
+
+/* buffer sizes are defined here. */
+#if !defined(PLATFORM_MICAZ)
+#define IP_MALLOC_HEAP_SIZE 1500
+enum {
+  IP_NUMBER_FRAGMENTS = 14,
+};
+#else
+#define IP_MALLOC_HEAP_SIZE 500
+enum {
+  IP_NUMBER_FRAGMENTS = 4,
+};
+#endif
+
+
+#ifndef BLIP_L2_RETRIES
+#define BLIP_L2_RETRIES 5
+#endif
+
+#ifndef BLIP_L2_DELAY
+#define BLIP_L2_DELAY 15
+#endif
+
+
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/devconf.h b/support/sdk/c/blip/lib6lowpan/devconf.h
new file mode 100644 (file)
index 0000000..8d8a34c
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _CONFIGURE_H_
+#define _CONFIGURE_H_
+
+#include "6lowpan.h"
+
+enum {
+  CONFIG_ECHO = 0,       // ping the device for status information
+  CONFIG_SET_PARM = 1,   // instruct the device to set its hardware addr
+  CONFIG_REBOOT = 2,
+  CONFIG_KEEPALIVE = 3,
+};
+
+enum {
+  CONFIG_ERROR_OK,
+  CONFIG_ERROR_FAIL,
+  CONFIG_ERROR_BOOTED,
+};
+
+enum {
+  KEEPALIVE_INTERVAL = 500000,
+  KEEPALIVE_TIMEOUT = 5000,
+};
+                                  
+#ifndef PC
+
+
+typedef nx_struct config_cmd {
+  nx_uint8_t cmd;
+  nx_struct {
+    nx_uint16_t retries;
+    nx_uint16_t delay;
+  } retx;
+  nx_struct {
+    nx_uint16_t addr;
+    nx_uint8_t channel;
+  } rf;
+} config_cmd_t;
+
+
+typedef nx_struct {
+  nx_uint8_t error;
+  nx_uint16_t addr;
+  nx_uint16_t serial_read;
+  nx_uint16_t radio_read;
+  nx_uint16_t serial_fail;
+  nx_uint16_t radio_fail;
+} config_reply_t; 
+
+#else
+
+enum {
+  CONFIGURE_MSG_SIZE = 8,
+};
+typedef struct config_cmd {
+  uint8_t cmd;
+  struct {
+    uint16_t retries;
+    uint16_t delay;
+  } retx;
+  struct {
+    ieee154_saddr_t addr;
+    uint8_t channel;
+  } rf;
+} __attribute__((packed)) config_cmd_t;
+
+
+
+typedef struct {
+  uint8_t error;
+  ieee154_saddr_t addr;
+  uint16_t serial_read;
+  uint16_t radio_read;
+  uint16_t serial_fail;
+  uint16_t radio_fail;
+} __attribute__((packed)) config_reply_t;
+
+enum {
+  TOS_SERIAL_802_15_4_ID = 2,
+  TOS_SERIAL_DEVCONF = 3,
+};
+
+#endif
+
+#endif
+
diff --git a/support/sdk/c/blip/lib6lowpan/in_cksum.c b/support/sdk/c/blip/lib6lowpan/in_cksum.c
new file mode 100644 (file)
index 0000000..bcad3fd
--- /dev/null
@@ -0,0 +1,222 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/* in_cksum.c
+ * 4.4-Lite-2 Internet checksum routine, modified to take a vector of
+ * pointers/lengths giving the pieces to be checksummed.
+ *
+ * $Id$
+ */
+
+/*
+ * Copyright (c) 1988, 1992, 1993
+ *      The Regents of the University of California.  All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ *      @(#)in_cksum.c  8.1 (Berkeley) 6/10/93
+ */
+
+#include <stdlib.h>
+#include "in_cksum.h"
+#include "lib6lowpan.h"
+
+
+#define ADDCARRY(x)  (x > 65535 ? x -= 65535 : x)
+#define REDUCE {l_util.l = sum; sum = l_util.s[0] + l_util.s[1]; ADDCARRY(sum);}
+
+int
+in_cksum(const vec_t *vec, int veclen) {
+
+  uint32_t sum = 0;
+  uint16_t res = 0;
+  uint16_t cur = 0;
+  int i;
+
+
+  uint8_t *w;
+  for (; veclen != 0; vec++, veclen--) {
+    if (vec->len == 0)
+      continue;
+   
+    w = (uint8_t *)vec->ptr;
+    for (i = 0; i < vec->len; i++) {
+      if (i % 2 == 0) {
+        cur |= ((uint16_t)w[i]) << 8;
+        if (i + 1 == vec->len) {
+          goto finish;
+        }
+      } else {
+        cur |= w[i];
+      finish:
+        sum += cur;
+        res = (sum & 0xffff) + (sum >> 16);
+        cur = 0;
+      }
+    }
+  }
+  return ~res ;
+#if 0
+       register const uint16_t *w;
+       register uint32_t sum = 0;
+       register uint32_t mlen = 0;
+       int byte_swapped = 0;
+
+       union {
+               uint8_t c[2];
+               uint16_t        s;
+       } s_util;
+       union {
+               uint16_t s[2];
+               uint32_t        l;
+       } l_util;
+
+       for (; veclen != 0; vec++, veclen--) {
+               if (vec->len == 0)
+                       continue;
+               w = (const uint16_t *)vec->ptr;
+               if (mlen == -1) {
+                       /*
+                        * The first byte of this chunk is the continuation
+                        * of a word spanning between this chunk and the
+                        * last chunk.
+                        *
+                        * s_util.c[0] is already saved when scanning previous
+                        * chunk.
+                        */
+                       s_util.c[1] = *(const uint8_t *)w;
+                       sum += s_util.s;
+                       w = (const uint16_t *)((const uint8_t *)w + 1);
+                       mlen = vec->len - 1;
+               } else
+                       mlen = vec->len;
+               /*
+                * Force to even boundary.
+                */
+               if ((1 & (int) w) && (mlen > 0)) {
+                       REDUCE;
+                       sum <<= 8;
+                       s_util.c[0] = *(const uint8_t *)w;
+                       w = (const uint16_t *)((const uint8_t *)w + 1);
+                       mlen--;
+                       byte_swapped = 1;
+               }
+               /*
+                * Unroll the loop to make overhead from
+                * branches &c small.
+                */
+               while ((mlen -= 32) >= 0) {
+                       sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
+                       sum += w[4]; sum += w[5]; sum += w[6]; sum += w[7];
+                       sum += w[8]; sum += w[9]; sum += w[10]; sum += w[11];
+                       sum += w[12]; sum += w[13]; sum += w[14]; sum += w[15];
+                       w += 16;
+               }
+               mlen += 32;
+               while ((mlen -= 8) >= 0) {
+                       sum += w[0]; sum += w[1]; sum += w[2]; sum += w[3];
+                       w += 4;
+               }
+               mlen += 8;
+               if (mlen == 0 && byte_swapped == 0)
+                       continue;
+               REDUCE;
+               while ((mlen -= 2) >= 0) {
+                       sum += *w++;
+               }
+               if (byte_swapped) {
+                       REDUCE;
+                       sum <<= 8;
+                       byte_swapped = 0;
+                       if (mlen == -1) {
+                               s_util.c[1] = *(const uint8_t *)w;
+                               sum += s_util.s;
+                               mlen = 0;
+                       } else
+                               mlen = -1;
+               } else if (mlen == -1)
+                       s_util.c[0] = *(const uint8_t *)w;
+       }
+       if (mlen == -1) {
+               /* The last mbuf has odd # of bytes. Follow the
+                  standard (the odd byte may be shifted left by 8 bits
+                  or not as determined by endian-ness of the machine) */
+               s_util.c[1] = 0;
+               sum += s_util.s;
+       }
+       REDUCE;
+       return (~sum & 0xffff);
+#endif
+}
+
+/* SDH : Added to allow for friendly message checksumming */
+uint16_t msg_cksum(struct split_ip_msg *msg, uint8_t nxt_hdr) {
+  struct generic_header *cur;
+  int n_headers = 4;
+  vec_t cksum_vec[7];
+  uint32_t hdr[2];
+
+  cksum_vec[0].ptr = (uint8_t *)(msg->hdr.ip6_src.s6_addr);
+  cksum_vec[0].len = 16;
+  cksum_vec[1].ptr = (uint8_t *)(msg->hdr.ip6_dst.s6_addr);
+  cksum_vec[1].len = 16;
+  cksum_vec[2].ptr = (uint8_t *)hdr;
+  cksum_vec[2].len = 8;
+  hdr[0] = msg->data_len;
+  hdr[1] = htonl(nxt_hdr);
+  cksum_vec[3].ptr = msg->data;
+  cksum_vec[3].len = msg->data_len;
+
+  cur = msg->headers;
+  while (cur != NULL) {
+    cksum_vec[n_headers].ptr = cur->hdr.data;
+    cksum_vec[n_headers].len = cur->len;
+    hdr[0] += cur->len;
+    n_headers++;
+    cur = cur->next;
+  }
+  hdr[0] = htonl(hdr[0]);
+  
+  return in_cksum(cksum_vec, n_headers);
+}
diff --git a/support/sdk/c/blip/lib6lowpan/in_cksum.h b/support/sdk/c/blip/lib6lowpan/in_cksum.h
new file mode 100644 (file)
index 0000000..b6108fa
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _IN_CKSUM_H_
+#define _IN_CKSUM_H_
+
+/* in_cksum.h
+ * Declaration of  Internet checksum routine.
+ *
+ * $Id$
+ */
+
+#include <stdint.h>
+#include "ip.h"
+
+typedef struct {
+       const uint8_t *ptr;
+       int     len;
+} vec_t;
+
+extern int in_cksum(const vec_t *vec, int veclen);
+
+// extern uint16_t in_cksum(const vec_t *vec, int veclen);
+
+extern uint16_t msg_cksum(struct split_ip_msg *msg, uint8_t nxt_hdr);
+
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/ip.h b/support/sdk/c/blip/lib6lowpan/ip.h
new file mode 100644 (file)
index 0000000..6a4be2c
--- /dev/null
@@ -0,0 +1,332 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _IP_H_
+#define _IP_H_
+
+/*
+ * define message structures for internet communication
+ *
+ */
+
+#ifdef PC
+#include <linux/if_tun.h>
+#include <netinet/in.h>
+#endif
+
+#include "6lowpan.h"
+#include "blip-platform.h"
+
+enum {
+  /*
+   * The time, in binary milliseconds, after which we stop waiting for
+   * fragments and report a failed receive.  We 
+   */
+  FRAG_EXPIRE_TIME = 4096,
+};
+
+
+#ifndef PC
+// update to use netinet/in definition of an IPv6 address; this is a
+//  lot more elegent.
+struct in6_addr
+  {
+    union
+      {
+       uint8_t u6_addr8[16];
+       uint16_t u6_addr16[8];
+       uint32_t u6_addr32[4];
+      } in6_u;
+#define s6_addr                        in6_u.u6_addr8
+#define s6_addr16              in6_u.u6_addr16
+#define s6_addr32              in6_u.u6_addr32
+  };
+
+struct sockaddr_in6 {
+  uint16_t sin6_port;
+  struct in6_addr sin6_addr;
+};
+#endif
+
+/*
+ * Definition for internet protocol version 6.
+ * RFC 2460
+ */
+struct ip6_hdr {
+  uint8_t   vlfc[4];
+  uint16_t  plen;          /* payload length */
+  uint8_t   nxt_hdr;       /* next header */
+  uint8_t   hlim;          /* hop limit */
+  struct in6_addr ip6_src; /* source address */
+  struct in6_addr ip6_dst; /* destination address */
+} __attribute__((packed));
+
+#define IPV6_VERSION            0x6
+#define IPV6_VERSION_MASK       0xf0
+
+
+/*
+ * Extension Headers
+ */
+
+struct ip6_ext {
+  uint8_t nxt_hdr;
+  uint8_t len;
+  uint8_t data[0];
+};
+
+struct tlv_hdr {
+  uint8_t type;
+  uint8_t len;
+};
+/*
+ * IP protocol numbers
+ */
+enum {
+  IANA_ICMP = 58,
+  IANA_UDP = 17,
+  IANA_TCP = 6,
+
+  // IPV6 defined extention header types.  All other next header
+  // values are supposed to be transport protocols, with TLVs used
+  IPV6_HOP = 0,
+  IPV6_DEST = 60,
+  IPV6_ROUTING = 43,
+  IPV6_FRAG = 44,
+  IPV6_AUTH = 51,
+  IPV6_SEC = 50,
+  IPV6_MOBILITY = 135,
+  IPV6_NONEXT = 59,
+};
+#define EXTENSION_HEADER(X) ((X) == IPV6_HOP || (X) == IPV6_ROUTING || (X) == IPV6_DEST)
+#define COMPRESSIBLE_TRANSPORT(X) ((X) == IANA_UDP)
+
+/*
+ * nonstandard source routing header fields
+ */
+enum {
+  IP6ROUTE_TYPE_SOURCE  = 0,
+  IP6ROUTE_TYPE_INVAL   = 1,
+  IP6ROUTE_FLAG_CONTROLLER = 0x8,
+  IP6ROUTE_FLAG_MASK = IP6ROUTE_FLAG_CONTROLLER,
+
+  IP_EXT_SOURCE_DISPATCH    = 0x40,
+  IP_EXT_SOURCE_MASK        = 0xc0,
+
+  // dispatch values
+  IP_EXT_SOURCE_CONTROLLER  = 0x40,
+
+  // dispatch values for route installation if this flag is set, the
+  // source_header must be immediately followed by a
+  // source_install_opt struct.
+  IP_EXT_SOURCE_INSTALL     = 0x10,
+  IP_EXT_SOURCE_INSTALL_MASK= 0x10,
+
+  // indicates weather the forward and reverse paths should be
+  // installed.  Are these needed?  the only case when we don't want
+  // to install the reverse path is when the destination is a
+  // multicast?
+  IP_EXT_SOURCE_INST_SRC    = 0x20,
+  IP_EXT_SOURCE_INST_DST    = 0x40,
+
+  // a topology TLV inside a destination option
+  TLV_TYPE_TOPOLOGY = 0x0a,
+  // a route install message, inside a hop-by-hop or destination
+  // option message.
+  TLV_TYPE_INSTALL  = 0x0b,
+  TLV_TYPE_FLOW     = 0x0c,
+  TLV_TYPE_MCASTSEQ = 0x0d,
+};
+
+struct ip6_route {
+  uint8_t nxt_hdr;
+  uint8_t len;
+  uint8_t type;
+  uint8_t segs_remain;
+  uint16_t hops[0];
+};
+#define ROUTE_NENTRIES(SH)   (((SH)->len - (sizeof(struct ip6_route))) / (sizeof(uint16_t)))
+
+
+/*
+ * icmp
+ */
+struct  icmp6_hdr {
+  uint8_t        type;     /* type field */
+  uint8_t        code;     /* code field */
+  uint16_t       cksum;    /* checksum field */
+};
+
+enum {
+    ICMP_TYPE_ECHO_DEST_UNREACH     = 1,
+    ICMP_TYPE_ECHO_PKT_TOO_BIG      = 2, 
+    ICMP_TYPE_ECHO_TIME_EXCEEDED    = 3,
+    ICMP_TYPE_ECHO_PARAM_PROBLEM    = 4,
+    ICMP_TYPE_ECHO_REQUEST          = 128,
+    ICMP_TYPE_ECHO_REPLY            = 129,
+    ICMP_TYPE_ROUTER_SOL            = 133,
+    ICMP_TYPE_ROUTER_ADV            = 134,
+    ICMP_TYPE_NEIGHBOR_SOL          = 135,
+    ICMP_TYPE_NEIGHBOR_ADV          = 136,
+    ICMP_NEIGHBOR_HOPLIMIT          = 255,
+
+    ICMP_CODE_HOPLIMIT_EXCEEDED     = 0,
+    ICMP_CODE_ASSEMBLY_EXCEEDED     = 1,
+};
+
+/*
+ * UDP protocol header.
+ */
+struct udp_hdr {
+    uint16_t srcport;               /* source port */
+    uint16_t dstport;               /* destination port */
+    uint16_t len;                   /* udp length */
+    uint16_t chksum;                /* udp checksum */
+};
+
+/*
+ * TCP transport headers and flags
+ */
+enum {
+  TCP_FLAG_FIN = 0x1,
+  TCP_FLAG_SYN = 0x2,
+  TCP_FLAG_RST = 0x4,
+  TCP_FLAG_PSH = 0x8,
+  TCP_FLAG_ACK = 0x10,
+  TCP_FLAG_URG = 0x20,
+  TCP_FLAG_ECE = 0x40,
+  TCP_FLAG_CWR = 0x80,
+};
+
+struct tcp_hdr {
+  uint16_t srcport;
+  uint16_t dstport;
+  uint32_t seqno;
+  uint32_t ackno;
+  uint8_t offset;
+  uint8_t flags;
+  uint16_t window;
+  uint16_t chksum;
+  uint16_t urgent;
+};
+
+/*
+ * IP metadata and routing structures
+ */
+struct ip_metadata {
+  ieee154_saddr_t sender;
+  uint8_t   lqi;
+  uint8_t   padding[1];
+};
+
+struct flow_match {
+  cmpr_ip6_addr_t src;
+  cmpr_ip6_addr_t dest; // Need to make this more extensible at some point
+};
+
+struct rinstall_header {
+  struct flow_match match;
+  uint8_t flags;
+  uint8_t path_len;
+  cmpr_ip6_addr_t path[0];
+};
+
+enum {
+  // is this a hop-by-hop or source install command
+  HYDRO_INSTALL_METHOD_MASK    = 0x03,
+  HYDRO_METHOD_HOP             = 0x01,
+  HYDRO_METHOD_SOURCE          = 0x02,
+
+  // should we also apply the action to the reverse path?
+  HYDRO_INSTALL_REVERSE        = 0x04,
+
+  // is this an uninstallation?
+  HYDRO_INSTALL_UNINSTALL_MASK = 0x08,
+
+};
+
+enum {
+  T_INVAL_NEIGH =  0xef,
+  T_SET_NEIGH = 0xee,
+};
+
+
+/*
+ * These are data structures to hold IP messages.  We used a linked
+ * list of headers so that we can easily add extra headers with no
+ * copy; similar to the linux iovec's or BSD mbuf structs.  
+ * Every split_ip_msg contains a full IPv6 header (40 bytes), but it
+ * is placed at the end of the struct so that we can read() a message
+ * straight into one of these structs, and then just set up the header
+ * chain.
+ *
+ * Due to the way fragmentation is currently implemented, the total
+ * length of the data referenced from this chain must not be longer
+ * then what can fit into a single fragment.  This is a limitation of
+ * the current fragmentation code, but is perfectly usable in most
+ * cases.
+ */
+struct generic_header {
+#ifdef PC
+  int payload_malloced:1;
+#endif
+  uint8_t len;
+  union {
+    // this could be an eumeration of all the valid headers we can have here.
+    struct ip6_ext *ext;
+    struct ip6_route *sh;
+    struct udp_hdr *udp;
+    uint8_t *data;
+  } hdr;
+  struct generic_header *next;
+};
+
+enum {
+  IP_NOHEADERS = 1 << 0,
+  IP_MCAST     = 1 << 1,
+  IP_NOADDRESS = 1 << 2,
+};
+
+struct split_ip_msg {
+  struct generic_header *headers;
+  uint16_t data_len;
+  uint8_t *data;
+#ifdef PC
+  uint16_t foo;
+  uint16_t flow_id;
+  uint16_t prev_hop;
+  struct ip_metadata metadata;
+  // this must be last so we can read() straight into the end of the buffer.
+  struct tun_pi pi;
+#endif
+  struct ip6_hdr hdr;
+  uint8_t next[0];
+};
+
+#ifndef NO_LIB6LOWPAN_ASCII
+/*
+ * parse a string representation of an IPv6 address
+ */ 
+void inet_pton6(char *addr, struct in6_addr *dest);
+int  inet_ntop6(struct in6_addr *addr, char *buf, int cnt);
+#endif
+
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/ip_malloc.c b/support/sdk/c/blip/lib6lowpan/ip_malloc.c
new file mode 100644 (file)
index 0000000..9149efd
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef NO_IP_MALLOC
+#include <stdint.h>
+#include <stdio.h>
+#include "ip_malloc.h"
+
+uint8_t heap[IP_MALLOC_HEAP_SIZE];
+
+void ip_malloc_init() {
+  bndrt_t *b = (bndrt_t *)heap;
+  *b = IP_MALLOC_HEAP_SIZE  & IP_MALLOC_LEN;
+}
+
+void *ip_malloc(uint16_t sz) {
+  bndrt_t *cur = (bndrt_t *)heap;
+  sz += sizeof(bndrt_t) * 2;
+  sz += (sz % IP_MALLOC_ALIGN);
+
+  while (((*cur & IP_MALLOC_LEN) < sz || (*cur & IP_MALLOC_INUSE) != 0) 
+         && (uint8_t *)cur - heap < IP_MALLOC_HEAP_SIZE) {
+    cur = (bndrt_t *)(((uint8_t *)cur) + ((*cur) & IP_MALLOC_LEN));
+  }
+
+  if ((uint8_t *)cur < heap + IP_MALLOC_HEAP_SIZE) {
+    uint16_t oldsize = *cur & IP_MALLOC_LEN;
+    bndrt_t *next;
+    sz -= sizeof(bndrt_t);
+    next = ((bndrt_t *)(((uint8_t *)cur) + sz));
+
+    *cur = (sz & IP_MALLOC_LEN) | IP_MALLOC_INUSE;
+    *next = (oldsize - sz) & IP_MALLOC_LEN;
+
+    return cur + 1;
+  } else return NULL;
+}
+
+void ip_free(void *ptr) {
+  bndrt_t *prev = NULL, *cur, *next = NULL;
+  cur = (bndrt_t *)heap;
+
+  while (cur + 1 != ptr && (uint8_t *)cur - heap < IP_MALLOC_HEAP_SIZE) {
+    prev = cur;
+    cur = (bndrt_t *)(((uint8_t *)cur) + ((*cur) & IP_MALLOC_LEN));
+  }
+  if (cur + 1 == ptr) {
+    next = (bndrt_t *)((*cur & IP_MALLOC_LEN) + ((uint8_t *)cur));
+
+    *cur &= ~IP_MALLOC_INUSE;
+    if ((((uint8_t *)next) - heap) < IP_MALLOC_HEAP_SIZE && 
+        (*next & IP_MALLOC_INUSE) == 0) {
+      *cur = (*cur & IP_MALLOC_LEN) + (*next & IP_MALLOC_LEN);
+    }
+    if (prev != NULL && (*prev & IP_MALLOC_INUSE) == 0) {
+      *prev = (*prev & IP_MALLOC_LEN) + (*cur & IP_MALLOC_LEN);
+    }
+  }
+}
+
+uint16_t ip_malloc_freespace() {
+  uint16_t ret = 0;
+  bndrt_t *cur = (bndrt_t *)heap;
+
+  while ((uint8_t *)cur - heap < IP_MALLOC_HEAP_SIZE) {
+    if ((*cur & IP_MALLOC_INUSE) == 0)
+      ret += *cur & IP_MALLOC_LEN;
+    cur = (bndrt_t *)(((uint8_t *)cur) + ((*cur) & IP_MALLOC_LEN));
+  }
+  return ret;
+}
+
+#ifdef PC
+void dump_heap() {
+  int i;
+  for (i = 0; i < IP_MALLOC_HEAP_SIZE; i++) {
+    printf("0x%x ", heap[i]);
+    if (i % 8 == 7) printf("  ");
+    if (i % 16 == 15) printf ("\n");
+    if (i > 64) break;
+  }
+  printf("\n");
+}
+
+void ip_print_heap() {
+  bndrt_t *cur = (bndrt_t *)heap;
+  while (((uint8_t *)cur)  - heap < IP_MALLOC_HEAP_SIZE) {
+    printf ("heap region start: 0x%x length: %i used: %i\n", 
+            cur, (*cur & IP_MALLOC_LEN), (*cur & IP_MALLOC_INUSE) >> 15);
+    if ((*cur & IP_MALLOC_LEN) == 0) {
+      printf("ERROR: zero length cell detected!\n");
+      dump_heap();
+      exit(1);
+    }
+    cur = (bndrt_t *)(((uint8_t *)cur) + ((*cur) & IP_MALLOC_LEN));
+
+  }
+}
+#endif
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/ip_malloc.h b/support/sdk/c/blip/lib6lowpan/ip_malloc.h
new file mode 100644 (file)
index 0000000..6249e6a
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef NO_IP_MALLOC
+#ifndef IP_MALLOC_H_
+#define IP_MALLOC_H_
+
+#include <stdint.h>
+#include <blip-platform.h>
+
+// align on this number of byte boundarie#s
+#define IP_MALLOC_ALIGN   2
+#define IP_MALLOC_LEN     0x0fff
+#define IP_MALLOC_FLAGS   0x7000
+#define IP_MALLOC_INUSE   0x8000
+
+extern uint8_t heap[IP_MALLOC_HEAP_SIZE];
+typedef uint16_t bndrt_t;
+
+void ip_malloc_init();
+void *ip_malloc(uint16_t sz);
+void ip_free(void *ptr);
+uint16_t ip_malloc_freespace();
+
+#ifndef PC
+#define malloc(X) ip_malloc(X)
+#define free(X)   ip_free(X)
+#endif
+
+#endif
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/lib6lowpan.c b/support/sdk/c/blip/lib6lowpan/lib6lowpan.c
new file mode 100644 (file)
index 0000000..b7b676c
--- /dev/null
@@ -0,0 +1,346 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#include "6lowpan.h"
+#include "ip.h"
+#include "lib6lowpan.h"
+
+
+#ifndef __6LOWPAN_16BIT_ADDRESS
+#error "Only 16-bit short addresses are supported"
+#endif
+
+/*
+ *  Library implementation of packing of 6lowpan packets.  
+ *
+ *  This should allow uniform code treatment between pc and mote code;
+ *  the goal is to write ANSI C here...  This means no nx_ types,
+ *  unfortunately.
+ *
+ *  Accessing fields programtically is probably a little less
+ *  efficient, but that can be improved.  By precomputing the packet
+ *  headers present, we can make the overhead not too bad.  The #1
+ *  goal of this library is portability and readability.
+ *
+ *  The broadcast and mesh headers may or may not be useful, and are
+ *  off by default to reduce code size.  Removing them reduces the
+ *  library size by about 600 bytes.
+ */
+
+
+/*
+ * Return the length (in bytes) of the buffer required to pack lowmsg
+ * into a buffer.
+ */
+inline uint8_t *getLowpanPayload(packed_lowmsg_t *lowmsg) {
+  uint8_t len = 0;
+#if LIB6LOWPAN_FULL
+  if (lowmsg->headers & LOWMSG_MESH_HDR)
+    len += LOWMSG_MESH_LEN;
+  if (lowmsg->headers & LOWMSG_BCAST_HDR)
+    len += LOWMSG_BCAST_LEN;
+#endif
+  if (lowmsg->headers & LOWMSG_FRAG1_HDR)
+    len += LOWMSG_FRAG1_LEN;
+  if (lowmsg->headers & LOWMSG_FRAGN_HDR)
+    len += LOWMSG_FRAGN_LEN;
+  return lowmsg->data + len;
+}
+
+/*
+ * Return a bitmap indicating which lowpan headers are
+ *  present in the message pointed to by lowmsg.
+ *
+ */
+inline uint16_t getHeaderBitmap(packed_lowmsg_t *lowmsg) {
+  uint16_t headers = 0;
+  uint8_t *buf = lowmsg->data;
+  uint16_t len = lowmsg->len;
+  if (buf == NULL) return headers;
+
+  if (len > 0 && ((*buf) >> 6) == LOWPAN_NALP_PATTERN) {
+    return LOWMSG_NALP;
+  }
+  
+#if LIB6LOWPAN_FULL
+  if (len > 0 && ((*buf) >> 6) == LOWPAN_MESH_PATTERN) {
+    if (!(*buf & LOWPAN_MESH_V_MASK) ||
+        !(*buf & LOWPAN_MESH_F_MASK)) {
+      // we will not parse a packet with 64-bit addressing.
+      return LOWMSG_NALP;
+    }
+    headers |= LOWMSG_MESH_HDR;
+    buf += LOWMSG_MESH_LEN;
+    len -= LOWMSG_MESH_LEN;
+  }
+  if (len > 0 && (*buf) == LOWPAN_BCAST_PATTERN) {
+    headers |= LOWMSG_BCAST_HDR;
+    buf += LOWMSG_BCAST_LEN;
+    len -= LOWMSG_BCAST_LEN;
+  }
+#endif 
+
+  if (len > 0 && ((*buf) >> 3) == LOWPAN_FRAG1_PATTERN) {
+    headers |= LOWMSG_FRAG1_HDR;
+    buf += LOWMSG_FRAG1_LEN;
+    len -= LOWMSG_FRAG1_LEN;
+  }
+  if (len > 0 && ((*buf) >> 3) == LOWPAN_FRAGN_PATTERN) {
+    headers |= LOWMSG_FRAGN_HDR;
+    buf += LOWMSG_FRAGN_LEN;
+    len -= LOWMSG_FRAGN_LEN;
+  }
+  return headers;
+}
+
+/*
+ * Fill in dispatch values
+ */
+inline uint8_t setupHeaders(packed_lowmsg_t *packed, uint16_t headers) {
+  uint8_t *buf = packed->data;
+  uint16_t len = packed->len;
+  if (packed == NULL) return 1;
+  if (buf == NULL) return 1;
+  packed->headers = 0;
+#if LIB6LOWPAN_FULL
+  if (headers & LOWMSG_MESH_HDR)  {
+    if (len < LOWMSG_MESH_LEN) return 1;
+    packed->headers |= LOWMSG_MESH_HDR;
+    *buf = LOWPAN_MESH_PATTERN << 6 | LOWPAN_MESH_V_MASK | LOWPAN_MESH_F_MASK;
+    buf += LOWMSG_MESH_LEN;
+    len -= LOWMSG_MESH_LEN;
+  }
+  if (headers & LOWMSG_BCAST_HDR) {
+    if (len < LOWMSG_BCAST_LEN) return 1;
+    packed->headers |= LOWMSG_BCAST_HDR;
+    *buf = LOWPAN_BCAST_PATTERN;
+    buf += LOWMSG_BCAST_LEN;
+    len -= LOWMSG_BCAST_LEN;
+  }
+#endif
+  if (headers & LOWMSG_FRAG1_HDR) {
+    if (len < LOWMSG_FRAG1_HDR) return 1;
+    packed->headers |= LOWMSG_FRAG1_HDR;
+    *buf = LOWPAN_FRAG1_PATTERN << 3;
+    buf += LOWMSG_FRAG1_LEN;
+    len -= LOWMSG_FRAG1_LEN;
+  }
+  if (headers & LOWMSG_FRAGN_HDR) {
+    if (len < LOWMSG_FRAGN_HDR) return 1;
+    packed->headers |= LOWMSG_FRAGN_HDR;
+    *buf = LOWPAN_FRAGN_PATTERN << 3;
+  }
+  return 0;
+  
+}
+
+/*
+ * Test if various headers are present are enabled
+ */
+#ifdef LIB6LOWPAN_FULL
+inline uint8_t hasMeshHeader(packed_lowmsg_t *msg) {
+  return (msg->headers & LOWMSG_MESH_HDR);
+}
+inline uint8_t hasBcastHeader(packed_lowmsg_t *msg) {
+  return (msg->headers & LOWMSG_BCAST_HDR);
+}
+#endif
+inline uint8_t hasFrag1Header(packed_lowmsg_t *msg) {
+  return (msg->headers & LOWMSG_FRAG1_HDR);
+}
+inline uint8_t hasFragNHeader(packed_lowmsg_t *msg) {
+  return (msg->headers & LOWMSG_FRAGN_HDR);
+}
+#ifdef LIB6LOWPAN_FULL
+/*
+ * Mesh header fields
+ *
+ *  return FAIL if the message doesn't have a mesh header
+ */
+inline uint8_t getMeshHopsLeft(packed_lowmsg_t *msg, uint8_t *hops) {
+  uint8_t *buf = msg->data;
+  if (!hasMeshHeader(msg) || msg->data == NULL || hops == NULL) return 1;
+  *hops = (*buf) & LOWPAN_MESH_HOPS_MASK;
+  return 0;
+}
+inline uint8_t getMeshOriginAddr(packed_lowmsg_t *msg, ieee154_saddr_t *origin) {
+  uint8_t *buf = msg->data;
+  if (!hasMeshHeader(msg) || msg->data == NULL || origin == NULL) return 1;
+  // skip 64-bit addresses
+  if (!(*buf & LOWPAN_MESH_V_MASK)) return 1;
+  buf += 1;
+  *origin = ntoh16(*((uint16_t *)buf));
+  return 0;
+}
+inline uint8_t getMeshFinalAddr(packed_lowmsg_t *msg, ieee154_saddr_t *final) {
+  uint8_t *buf = msg->data;
+  if (!hasMeshHeader(msg) || msg->data == NULL || final == NULL) return 1;
+  // skip 64-bit addresses
+  if (!(*buf & LOWPAN_MESH_F_MASK)) return 1;
+  buf += 3;
+  *final = ntoh16(*((uint16_t *)buf));
+  return 0;
+}
+
+
+inline uint8_t setMeshHopsLeft(packed_lowmsg_t *msg, uint8_t hops) {
+  uint8_t *buf = msg->data;
+  if (!hasMeshHeader(msg) || msg->data == NULL) return 1;
+  
+  *buf = 0xb0;
+  *buf |= hops & LOWPAN_MESH_HOPS_MASK;
+  return 0;
+}
+inline uint8_t setMeshOriginAddr(packed_lowmsg_t *msg, ieee154_saddr_t origin) {
+  uint8_t *buf = msg->data;
+  if (!hasMeshHeader(msg) || msg->data == NULL) return 1;
+  // skip 64-bit addresses
+  if (!(*buf & LOWPAN_MESH_V_MASK)) return 1;
+  buf += 1;
+  *((uint16_t *)buf) = hton16(origin);
+  return 0;
+}
+inline uint8_t setMeshFinalAddr(packed_lowmsg_t *msg, ieee154_saddr_t final) {
+  uint8_t *buf = msg->data;
+  if (!hasMeshHeader(msg) || msg->data == NULL) return 1;
+  // skip 64-bit addresses
+  if (!(*buf & LOWPAN_MESH_F_MASK)) return 1;
+  buf += 3;
+  *((uint16_t *)buf) = hton16(final);
+  return 0;
+}
+/*
+ * Broadcast header fields
+ */
+inline uint8_t getBcastSeqno(packed_lowmsg_t *msg, uint8_t *seqno) {
+  uint8_t *buf = msg->data;
+  if (buf == NULL || seqno == NULL || !hasBcastHeader(msg)) return 1;
+  if (hasMeshHeader(msg)) buf += LOWMSG_MESH_LEN;
+  if (*buf != LOWPAN_BCAST_PATTERN) return 2;
+  buf += 1;
+  *seqno = *buf;
+  return 0;
+}
+
+inline uint8_t setBcastSeqno(packed_lowmsg_t *msg, uint8_t seqno) {
+  uint8_t *buf = msg->data;
+  if (buf == NULL || !hasBcastHeader(msg)) return 1;
+  if (hasMeshHeader(msg)) buf += LOWMSG_MESH_LEN;
+  if (*buf != LOWPAN_BCAST_PATTERN) return 2;
+  buf += 1;
+  *buf = seqno;
+  return 0;
+}
+#endif
+
+/*
+ * Fragmentation header fields
+ */
+inline uint8_t getFragDgramSize(packed_lowmsg_t *msg, uint16_t *size) {
+  uint8_t *buf = msg->data;
+  uint8_t s[2];
+  if (buf == NULL || size == NULL) return 1;
+#ifdef LIB6LOWPAN_FULL
+  if (hasMeshHeader(msg)) buf += LOWMSG_MESH_LEN;
+  if (hasBcastHeader(msg)) buf += LOWMSG_BCAST_LEN;
+#endif
+  if ((*buf >> 3) != LOWPAN_FRAG1_PATTERN &&
+      (*buf >> 3) != LOWPAN_FRAGN_PATTERN) return 1;
+
+  s[0] = *buf & 0x7;
+  buf++;
+  s[1] = *buf;
+  *size = ntoh16 ( *(uint16_t *)s);
+  return 0;
+}
+inline uint8_t getFragDgramTag(packed_lowmsg_t *msg, uint16_t *tag) {
+  uint8_t *buf = msg->data;
+  if (buf == NULL || tag == NULL) return 1;
+#ifdef LIB6LOWPAN_FULL
+  if (hasMeshHeader(msg)) buf += LOWMSG_MESH_LEN;
+  if (hasBcastHeader(msg)) buf += LOWMSG_BCAST_LEN;
+#endif
+  if ((*buf >> 3) != LOWPAN_FRAG1_PATTERN &&
+      (*buf >> 3) != LOWPAN_FRAGN_PATTERN) return 1;
+  buf += 2;
+  //*tag = (*buf << 8) | *(buf + 1);  ;
+  *tag = ntoh16( *(uint16_t *)buf);
+  return 0;
+}
+inline uint8_t getFragDgramOffset(packed_lowmsg_t *msg, uint8_t *size) {
+  uint8_t *buf = msg->data;
+  if (buf == NULL || size == NULL) return 1;
+#ifdef LIB6LOWPAN_FULL
+  if (hasMeshHeader(msg)) buf += LOWMSG_MESH_LEN;
+  if (hasBcastHeader(msg)) buf += LOWMSG_BCAST_LEN;
+#endif
+  if ((*buf >> 3) != LOWPAN_FRAGN_PATTERN) return 1;
+  buf += 4;
+  *size = *buf;
+  return 0;
+
+}
+
+
+inline uint8_t setFragDgramSize(packed_lowmsg_t *msg, uint16_t size) {
+  uint8_t *buf = msg->data;
+  if (buf == NULL) return 1;
+#ifdef LIB6LOWPAN_FULL
+  if (hasMeshHeader(msg)) buf += LOWMSG_MESH_LEN;
+  if (hasBcastHeader(msg)) buf += LOWMSG_BCAST_LEN;
+#endif
+  if ((*buf >> 3) != LOWPAN_FRAG1_PATTERN &&
+      (*buf >> 3) != LOWPAN_FRAGN_PATTERN) return 1;
+  // zero out the dgram size first.
+  *buf &= 0xf8;
+  *(buf + 1) = 0;
+  *((uint16_t *)buf) |= hton16(size & 0x7ff);
+  return 0;
+}
+
+inline uint8_t setFragDgramTag(packed_lowmsg_t *msg, uint16_t tag) {
+  uint8_t *buf = msg->data;
+  if (buf == NULL) return 1;
+#ifdef LIB6LOWPAN_FULL
+  if (hasMeshHeader(msg)) buf += LOWMSG_MESH_LEN;
+  if (hasBcastHeader(msg)) buf += LOWMSG_BCAST_LEN;
+#endif
+  
+  if ((*buf >> 3) != LOWPAN_FRAG1_PATTERN &&
+      (*buf >> 3) != LOWPAN_FRAGN_PATTERN) return 1;
+  buf += 2;
+  *(uint16_t *)buf = ntoh16(tag);
+  return 0;
+}
+inline uint8_t setFragDgramOffset(packed_lowmsg_t *msg, uint8_t size) {
+  uint8_t *buf = msg->data;
+  if (buf == NULL) return 1;
+#ifdef LIB6LOWPAN_FULL
+  if (hasMeshHeader(msg)) buf += LOWMSG_MESH_LEN;
+  if (hasBcastHeader(msg)) buf += LOWMSG_BCAST_LEN;
+#endif
+
+  if ((*buf >> 3) != LOWPAN_FRAGN_PATTERN) return 1;
+  buf += 4;
+  *buf = size;
+  return 0;
+}
diff --git a/support/sdk/c/blip/lib6lowpan/lib6lowpan.h b/support/sdk/c/blip/lib6lowpan/lib6lowpan.h
new file mode 100644 (file)
index 0000000..0278c55
--- /dev/null
@@ -0,0 +1,212 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _LIB6LOWPAN_H_
+#define _LIB6LOWPAN_H_
+#include <stdint.h>
+#include <stddef.h>
+
+#include "6lowpan.h"
+#include "ip.h"
+#include "nwbyte.h"
+
+
+#ifdef DEF_MEMCPY
+#define memcpy(X,Y,Z) ip_memcpy(X,Y,Z)
+#endif
+
+/*
+ * This interface implements the 6loWPAN header structures.  Support
+ * for the HC1 and HC2 compressed IP and UDP headers is also
+ * available, and the interface is presented in lib6lowpanIP.h.
+ *
+ */
+
+// only 16-bit address handling modes
+#define __6LOWPAN_16BIT_ADDRESS
+
+/*
+ *  Library implementation of packing of 6lowpan packets.  
+ *
+ *  This should allow uniform code treatment between pc and mote code;
+ *  the goal is to write ANSI C here...  This means no nx_ types,
+ *  unfortunately.
+ */
+
+/*
+ * 6lowpan header functions
+ */
+
+uint16_t getHeaderBitmap(packed_lowmsg_t *lowmsg);
+/*
+ * Return the length of the buffer required to pack lowmsg
+ *  into a buffer.
+ */
+
+uint8_t *getLowpanPayload(packed_lowmsg_t *lowmsg);
+
+/*
+ * Initialize the header bitmap in 'packed' so that
+ *  we know how long the headers are.
+ *
+ * @return FAIL if the buffer is not long enough.
+ */
+uint8_t setupHeaders(packed_lowmsg_t *packed, uint16_t headers);
+
+/*
+ * Test if various protocol features are enabled
+ */
+inline uint8_t hasMeshHeader(packed_lowmsg_t *msg);
+inline uint8_t hasBcastHeader(packed_lowmsg_t *msg);
+inline uint8_t hasFrag1Header(packed_lowmsg_t *msg);
+inline uint8_t hasFragNHeader(packed_lowmsg_t *msg);
+
+/*
+ * Mesh header fields
+ *
+ *  return FAIL if the message doesn't have a mesh header
+ */
+uint8_t getMeshHopsLeft(packed_lowmsg_t *msg, uint8_t *hops);
+uint8_t getMeshOriginAddr(packed_lowmsg_t *msg, ieee154_saddr_t *origin);
+uint8_t getMeshFinalAddr(packed_lowmsg_t *msg, ieee154_saddr_t *final);
+
+uint8_t setMeshHopsLeft(packed_lowmsg_t *msg, uint8_t hops);
+uint8_t setMeshOriginAddr(packed_lowmsg_t *msg, ieee154_saddr_t origin);
+uint8_t setMeshFinalAddr(packed_lowmsg_t *msg, ieee154_saddr_t final);
+
+/*
+ * Broadcast header fields
+ */
+uint8_t getBcastSeqno(packed_lowmsg_t *msg, uint8_t *seqno);
+
+uint8_t setBcastSeqno(packed_lowmsg_t *msg, uint8_t seqno);
+
+/*
+ * Fragmentation header fields
+ */
+inline uint8_t getFragDgramSize(packed_lowmsg_t *msg, uint16_t *size);
+inline uint8_t getFragDgramTag(packed_lowmsg_t *msg, uint16_t *tag);
+inline uint8_t getFragDgramOffset(packed_lowmsg_t *msg, uint8_t *size);
+
+inline uint8_t setFragDgramSize(packed_lowmsg_t *msg, uint16_t size);
+inline uint8_t setFragDgramTag(packed_lowmsg_t *msg, uint16_t tag);
+inline uint8_t setFragDgramOffset(packed_lowmsg_t *msg, uint8_t size);
+
+/*
+ * IP header compression functions
+ *
+ */
+
+// int getCompressedLen(packed_lowmsg_t *pkt);
+
+/*
+ * Pack the header fields of msg into buffer 'buf'.
+ *  it returns the number of bytes written to 'buf', or zero if it encountered a problem.
+ *
+ * it will pack the IP header and all headers in the header chain of
+ * msg into the buffer; the only thing it will not pack is the
+ * payload.
+ */
+uint8_t packHeaders(struct split_ip_msg *msg,
+                    uint8_t *buf, uint8_t len);
+/*
+ * Unpack the packed data from pkt into dest.
+ *
+ * It turns out that we need to keep track of a lot of different
+ * locations in order to be able to unpack and forward efficiently.
+ * If we don't save these during the unpack, we end up reconstructing
+ * them in various places so it's less error-prone to compute them
+ * while we're parsing the packed fields.
+ */
+typedef struct {
+  // the final header in the header chain; should be the transport header
+  uint8_t nxt_hdr;
+  // a pointer to the point in the source where we stopped unpacking
+  uint8_t *payload_start;
+  // a pointer to the point in the destination right after all headers
+  uint8_t *header_end;
+  // the total, uncompressed length of the headers which were unpacked
+  uint8_t payload_offset;
+  // points to the hop limit field of the packet message
+  uint8_t *hlim;
+  // points to the tranport header in the destination region, 
+  //  if it was within the unpacked region header.
+  //  if it was not, it is the same as header_end
+  uint8_t *transport_ptr;
+  // points to the source header within the packed fields, IF it contains one.
+  struct ip6_ext   *hdr_hop;
+  struct ip6_route *hdr_route;
+  struct ip6_ext   *hdr_dest;
+} unpack_info_t;
+
+uint8_t *unpackHeaders(packed_lowmsg_t *pkt, unpack_info_t *u_info,
+                       uint8_t *dest, uint16_t len);
+
+void adjustPlen(struct ip6_hdr *ip, unpack_info_t *u_info);
+
+/*
+ * Fragmentation routines.
+ */
+
+extern uint16_t lib6lowpan_frag_tag;
+
+typedef struct {
+  uint16_t tag;            /* datagram label */
+  uint16_t size;           /* the size of the packet we are reconstructing */
+  void    *buf;            /* the reconstruction location */
+  uint16_t bytes_rcvd;     /* how many bytes from the packet we have
+                              received so far */
+  uint8_t timeout;
+  uint8_t nxt_hdr;
+  uint8_t *transport_hdr;
+  struct ip_metadata metadata;
+} reconstruct_t;
+
+typedef struct {
+  uint16_t tag;    /* the label of the datagram */
+  uint16_t offset; /* how far into the packet we have sent, in bytes */
+} fragment_t;
+
+
+/*
+ *  this function writes the next fragment which needs to be sent into
+ *  the buffer passed in.  It updates the structures in process to
+ *  reflect how much of the packet has been sent so far.
+ *
+ *  if the packet does not require fragmentation, this function will
+ *  not insert a fragmentation header and will merely compress the
+ *  headers into the packet.
+ *
+ */
+uint8_t getNextFrag(struct split_ip_msg *msg, fragment_t *progress,
+                    uint8_t *buf, uint16_t len);
+
+
+enum {
+  T_FAILED1 = 0,
+  T_FAILED2 = 1,
+  T_UNUSED =  2,
+  T_ACTIVE =  3,
+  T_ZOMBIE =  4,
+};
+
+uint8_t* getLinkLocalPrefix();
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/lib6lowpanFrag.c b/support/sdk/c/blip/lib6lowpan/lib6lowpanFrag.c
new file mode 100644 (file)
index 0000000..dfb4df4
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * @author Stephen Dawson-Haggerty <stevedh@cs.berkeley.edu>
+ */
+
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+
+#include "ip.h"
+#include "ip_malloc.h"
+#include "6lowpan.h"
+#include "lib6lowpan.h"
+
+#define min(a,b) ( ((a)>(b)) ? (b) : (a) )
+#define max(a,b) ( ((a)<(b)) ? (b) : (a) )
+
+uint16_t lib6lowpan_frag_tag = 0;
+
+void ip_memclr(uint8_t *buf, uint16_t len) {
+  for (; len > 0; len--)
+    *buf++ = 0;
+  
+}
+
+void *ip_memcpy(void *dst0, const void *src0, uint16_t len) {
+  uint8_t *dst = (uint8_t *) dst0;
+  uint8_t *src = (uint8_t *) src0;
+  void *ret = dst0;
+  
+  for (; len > 0; len--)
+    *dst++ = *src++;
+  
+  return ret;
+}
+
+/*
+ *  this function writes the next fragment which needs to be sent into
+ *  the buffer passed in.  It updates the structures in process to
+ *  reflect how much of the packet has been sent so far.
+ *
+ *  if the packet does not require fragmentation, this function will
+ *  not insert a fragmentation header and will merely compress the
+ *  headers into the packet.
+ *
+ *  returns the number of bytes used in buf, or zero if there was no
+ *  fragment to be sent.
+ *
+ */
+uint8_t getNextFrag(struct split_ip_msg *msg, fragment_t *progress,
+                    uint8_t *buf, uint16_t len) {
+  if (msg == NULL || progress == NULL || buf == NULL) return 0;
+  packed_lowmsg_t pkt;
+  uint16_t frag_length = 0;
+  pkt.headers = 0;
+  pkt.data = buf;
+  pkt.len = len;
+
+  // if this is the first fragment, we will compress the headers in
+  // the ip message, and only insert a fragmentation header if
+  // necessary to pack it into buffer
+  if (progress->offset == 0) {
+    uint8_t *compressed_headers;
+    uint8_t lowpan_len = 0;
+    uint8_t cmpr_header_len = 0, header_length = 0;
+    
+    compressed_headers = malloc(LIB6LOWPAN_MAX_LEN);
+    if (compressed_headers == NULL) return 0;
+
+    // pack the headers into a temporary buffer
+    cmpr_header_len = packHeaders(msg, compressed_headers, LIB6LOWPAN_MAX_LEN);
+    
+    {
+      struct generic_header *cur = msg->headers;
+      while (cur != NULL) {
+        header_length += cur->len;
+        cur = cur->next;
+      }
+    }
+
+    // printBuf(compressed_headers, compressed_len);
+    // printf("payload: %p\n", payload);
+
+    // maybe add a fragmentation header
+    if (cmpr_header_len + msg->data_len > len) {
+      pkt.headers |= LOWMSG_FRAG1_HDR;
+      if (setupHeaders(&pkt, pkt.headers)) goto free_fail;
+      if (setFragDgramTag(&pkt, ++lib6lowpan_frag_tag)) goto free_fail;
+      if (setFragDgramSize(&pkt, ntoh16(msg->hdr.plen) + sizeof(struct ip6_hdr))) goto free_fail;
+      lowpan_len += LOWMSG_FRAG1_LEN;
+    } else {
+      if (setupHeaders(&pkt, pkt.headers)) goto free_fail;
+    }
+    ip_memcpy(getLowpanPayload(&pkt), compressed_headers, cmpr_header_len);
+    
+    /*
+     * calculate how much to put into this fragment
+     *
+     * if the whole packet fits in the buffer, this is easy; it's the
+     * compressed headers plus the payload length.
+     *
+     * given fragmentation, we need to do a little more work.
+     */
+    if (pkt.headers & LOWMSG_FRAG1_HDR) {
+      frag_length = len - cmpr_header_len - LOWMSG_FRAG1_LEN + sizeof(struct ip6_hdr) + header_length;
+      frag_length -= (frag_length % 8);
+      frag_length -= (sizeof(struct ip6_hdr) + header_length);
+    } else {
+      frag_length = ntoh16(msg->hdr.plen) - header_length;
+    }
+    // frag_length contains the number of bytes in uncompressed headers.
+
+    ip_memcpy(getLowpanPayload(&pkt) + cmpr_header_len,
+              msg->data, frag_length);
+
+    progress->tag = lib6lowpan_frag_tag;
+    progress->offset = frag_length + sizeof(struct ip6_hdr) + header_length;
+
+    // printfUART("frag: 0x%x 0x%x 0x%x\n", header_len, frag_length, compressed_len);
+
+    // return the length we wrote, which comes in three pieces;
+    free(compressed_headers);
+    return lowpan_len + cmpr_header_len + frag_length;
+  free_fail:
+    free(compressed_headers);
+    goto fail;
+  } else {
+    /*
+     * we've already sent the first fragment; we only need to send a
+     * subsequent one or return zero if we're at the end of the buffer;
+     *
+     */
+    //printf("offset: 0x%x plen: 0x%x\n", progress->offset, ntoh16(ip->plen) + sizeof(struct ip6_hdr));
+
+    // NOTE : this should be a >= to detect runaway lengths.  However,
+    // it is useful for debugging to require equality.
+    if (progress->offset == ntoh16(msg->hdr.plen) + sizeof(struct ip6_hdr)) return 0;
+    // the only headers we need now is the fragn header.
+
+    pkt.headers |= LOWMSG_FRAGN_HDR;
+    
+    // send out the fragments some frasgments.
+    //printf ("--- sending fragment\n");
+    // now we're pointing at the start of the 6loWPAN frame in the packet.
+    pkt.data = buf;
+    pkt.len = len;
+    // setup the fragmentation headers
+    if (setupHeaders(&pkt, pkt.headers)) goto fail;
+    if (setFragDgramTag(&pkt, progress->tag)) goto fail;
+
+    //printf ("frag dgram size 0x%x progress: 0x%x\n", ntoh16(ip->plen) + sizeof(struct ip6_hdr),
+/*     progress->offset); */
+
+    if (setFragDgramSize(&pkt, ntoh16(msg->hdr.plen) + sizeof(struct ip6_hdr))) goto fail;
+    if (setFragDgramOffset(&pkt, (progress->offset) / 8)) goto fail;
+
+    frag_length = min(len - LOWMSG_FRAGN_LEN, 
+                      ntoh16(msg->hdr.plen) + sizeof(struct ip6_hdr) - progress->offset);
+
+    
+
+    // unless this is the last fragment, we must sent a multiple of 8 bytes;
+    if (frag_length + progress->offset != ntoh16(msg->hdr.plen) + sizeof(struct ip6_hdr))
+      frag_length -= (frag_length % 8);
+
+    pkt.len = frag_length + LOWMSG_FRAGN_LEN;
+
+    {
+      uint8_t header_length = sizeof(struct ip6_hdr);
+      struct generic_header *cur = msg->headers;
+      while (cur != NULL) {
+        header_length += cur->len;
+        cur = cur->next;
+      }
+      ip_memcpy(buf + LOWMSG_FRAGN_LEN, msg->data + progress->offset - header_length, frag_length);
+    } 
+    progress->offset += frag_length;
+    //printf("frag length is: 0x%x offset: 0x%x max: 0x%x\n", frag_length, progress->offset, LOWPAN_MTU);
+    
+    return frag_length + LOWMSG_FRAGN_LEN;
+  }
+ fail:
+  return 0;
+}
diff --git a/support/sdk/c/blip/lib6lowpan/lib6lowpanIP.c b/support/sdk/c/blip/lib6lowpan/lib6lowpanIP.c
new file mode 100644 (file)
index 0000000..d16f9bd
--- /dev/null
@@ -0,0 +1,678 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <string.h>
+#include "lib6lowpan.h"
+/*
+ * This file presents an interface for parsing IP and UDP headers in a
+ * 6loWPAN packet.  
+ *
+ * @author Stephen Dawson-Haggerty <stevedh@cs.berkeley.edu>
+ */
+
+uint8_t linklocal_prefix [] = {0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+
+struct in6_addr __my_address       = {{{0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+                                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65}}};
+uint8_t globalPrefix = 0;
+
+uint8_t *getLinkLocalPrefix() {
+  return &linklocal_prefix[0];
+}
+
+uint8_t cmpPfx(ip6_addr_t a, uint8_t *pfx) {
+  return (memcmp(a, pfx, 8) == 0);
+#if 0
+    (a[0] == pfx[0] &&
+          a[1] == pfx[1] &&
+          a[2] == pfx[2] &&
+          a[3] == pfx[3] &&
+          a[4] == pfx[4] &&
+          a[5] == pfx[5] &&
+          a[6] == pfx[6] &&
+          a[7] == pfx[7]);
+#endif
+}
+
+static inline int ipv6_addr_suffix_is_long(const ip6_addr_t addr) {
+  return (!(addr[8] == 0 &&
+            addr[9] == 0 &&
+            addr[10] == 0 &&
+            addr[11] == 0 &&
+            addr[12] == 0 &&
+            addr[13] == 0));
+}
+
+#if LIB6LOWPAN_FULL
+/*
+ * return the length of the compressed fields in buf
+ */
+int getCompressedLen(packed_lowmsg_t *pkt) {
+  // min lenght is DISPATCH + ENCODING
+  uint8_t encoding, len = 2;
+  uint8_t *buf = getLowpanPayload(pkt);
+
+  if (!(*buf == LOWPAN_HC_LOCAL_PATTERN || *buf == LOWPAN_HC_CRP_PATTERN))
+    return 0;
+
+  encoding = *(buf + 1);
+  if ((encoding & LOWPAN_IPHC_VTF_MASK) == LOWPAN_IPHC_VTF_INLINE)
+    len += 4;
+  if ((encoding & LOWPAN_IPHC_NH_MASK) == LOWPAN_IPHC_NH_INLINE)
+    len += 1;
+  if ((encoding &LOWPAN_IPHC_HLIM_MASK) == LOWPAN_IPHC_HLIM_INLINE)
+    len += 1;
+
+  switch ((encoding >> LOWPAN_IPHC_SC_OFFSET) & LOWPAN_IPHC_ADDRFLAGS_MASK) { 
+  case LOWPAN_IPHC_ADDR_128: len += 16; break; 
+  case LOWPAN_IPHC_ADDR_64: len += 8; break;  
+  case LOWPAN_IPHC_ADDR_16: len += 2; break;  
+  case LOWPAN_IPHC_ADDR_0: len += 0; break;   
+  }
+  switch ((encoding >> LOWPAN_IPHC_DST_OFFSET) & LOWPAN_IPHC_ADDRFLAGS_MASK) { 
+  case LOWPAN_IPHC_ADDR_128: len += 16; break; 
+  case LOWPAN_IPHC_ADDR_64: len += 8; break;  
+  case LOWPAN_IPHC_ADDR_16: len += 2; break;  
+  case LOWPAN_IPHC_ADDR_0: len += 0; break;   
+  }
+
+  if ((encoding & LOWPAN_IPHC_NH_MASK) != LOWPAN_IPHC_NH_INLINE) {
+    // figure out how long the next header encoding is
+      uint8_t *nh = buf + len;
+    if ((*nh & LOWPAN_UDP_DISPATCH) == LOWPAN_UDP_DISPATCH) {
+      // are at a udp packet
+      len += 1; // add LOWPAN_HCNH
+      uint8_t udp_enc = *nh;
+      //printf("udp_enc: 0x%x\n", udp_enc);
+      if ((udp_enc & LOWPAN_UDP_S_MASK) && (udp_enc & LOWPAN_UDP_D_MASK))
+        len += 1;
+      else if ((udp_enc & LOWPAN_UDP_S_MASK) || (udp_enc & LOWPAN_UDP_D_MASK))
+        len += 3;
+      else
+        len += 4;
+      if ((udp_enc & LOWPAN_UDP_C_MASK) == 0)
+        len += 2;
+    }
+  }
+
+  len += (buf - pkt->data);
+  return len;
+}
+#endif
+
+static inline int decompressShortAddress(uint8_t dispatch, uint8_t *s_addr, uint8_t *dest) {
+  if ((*s_addr & LOWPAN_IPHC_SHORT_MASK) == 0) {
+    // simplest case, just use the appropriate prefix.
+    if (dispatch == LOWPAN_HC_LOCAL_PATTERN)
+      ip_memcpy(dest, linklocal_prefix, 8);
+    else
+      ip_memcpy(dest, __my_address.s6_addr, 8);
+    ip_memclr(dest + 8, 8);
+    dest[14] = (*s_addr) & ~LOWPAN_IPHC_SHORT_MASK;
+    dest[15] = *(s_addr + 1);
+    return 0;
+  }
+  // otherwise we either have an invalid compression, or else it's a
+  // multicast address
+  // ip_memcpy(dest, multicast_prefix, 8);
+  ip_memclr(dest, 16);
+  dest[0] = 0xff;
+  dest[1] = 0x02;
+  switch (*s_addr & LOWPAN_IPHC_SHORT_LONG_MASK) {
+  case LOWPAN_IPHC_HC1_MCAST:
+    dest[14] = (*s_addr) & ~LOWPAN_IPHC_SHORT_LONG_MASK;
+    dest[15] = *(s_addr + 1);
+    break;
+  case LOWPAN_IPHC_HC_MCAST:
+    dest[1] = ((*s_addr) & LOWPAN_HC_MCAST_SCOPE_MASK) >> LOWPAN_HC_MCAST_SCOPE_OFFSET;
+
+    // we'll just direct map the bottom 9 bits in for the moment,
+    // since HC doesn't specify anything that would break this.  In
+    // the future, a more complicated mapping is likely.
+    dest[14] = (*s_addr) & 0x1;
+    dest[15] = *(s_addr + 1);
+    break;
+  default:
+    return 1;
+  }
+  return 0;
+}
+
+static inline int decompressAddress(uint8_t dispatch, uint16_t src, uint8_t addr_flags, 
+                                    uint8_t **buf, uint8_t *dest) {
+  uint8_t *prefix;
+  uint16_t tmp;
+  int rc = 0;
+  if (dispatch == LOWPAN_HC_LOCAL_PATTERN)
+    prefix = linklocal_prefix;
+  else
+    prefix = __my_address.s6_addr;
+
+  switch (addr_flags) {
+  case LOWPAN_IPHC_ADDR_128:
+    ip_memcpy(dest, *buf, 16); 
+    *buf += 16;
+    break;
+  case LOWPAN_IPHC_ADDR_64:
+    ip_memcpy(dest, prefix, 8);
+    ip_memcpy(dest + 8, *buf, 8);
+    *buf += 8;
+    break;
+  case LOWPAN_IPHC_ADDR_16:
+    rc = decompressShortAddress(dispatch, *buf, dest);
+    *buf += 2;
+    break;
+  case LOWPAN_IPHC_ADDR_0:
+    ip_memcpy(dest, prefix, 8);
+    ip_memclr(dest + 8, 6);
+    tmp = hton16(src);
+    ip_memcpy(dest + 14, (uint8_t *)&tmp, 2);
+    break;
+  }
+  return rc;
+}
+
+void adjustPlen(struct ip6_hdr *ip, unpack_info_t *u_info) {
+  uint16_t adjust_amt = u_info->payload_offset;
+  
+  switch (ip->nxt_hdr) {
+  case IANA_UDP:
+    adjust_amt -= sizeof(struct udp_hdr); break;
+  }
+  ip->plen = htons(ntohs(ip->plen) - adjust_amt);
+}
+
+/*
+ * Unpacks all headers, including any compressed transport headers if
+ * there is a compression scheme defined for them.
+ *
+ * @pkt  - the wrapped struct pointing to the compressed headers
+ * @dest - buffer to unpack the headers into
+ * @len  - the len of 'dest'
+ * @return the number of bytes written to dest, or zero if decompression failed.
+ *         should be >= sizeof(struct ip6_hdr)
+ */
+uint8_t *unpackHeaders(packed_lowmsg_t *pkt, unpack_info_t *u_info,
+                       uint8_t *dest, uint16_t len) {
+  uint8_t dispatch, encoding;
+  uint16_t size, extra_header_length = 0;
+  uint8_t *buf = (uint8_t *)getLowpanPayload(pkt);
+
+  // pointers to fields  we may come back to fill in later
+  uint8_t *plen, *prot_len, *nxt_hdr;
+
+  ip_memclr((void *)u_info, sizeof(unpack_info_t));
+
+  // a buffer we can write addresses prefixes and suffexes into.
+  // now we don't need to check sizes until we get to next headers
+  if (buf == NULL || len < sizeof(struct ip6_hdr)) return NULL;
+  len -= sizeof(struct ip6_hdr);
+
+  dispatch = *buf; buf++;
+  encoding = *buf; buf++;
+
+  if (dispatch != LOWPAN_HC_LOCAL_PATTERN && dispatch != LOWPAN_HC_CRP_PATTERN)
+    return NULL;
+
+  if ((encoding & LOWPAN_IPHC_VTF_MASK) == LOWPAN_IPHC_VTF_INLINE) {
+    // copy the inline 4 bytes of fields.
+    ip_memcpy(dest, buf, 4);
+    buf += 4;
+  } else {
+    // cler the traffic class and flow label fields, and write the version.
+    ip_memclr(dest, 4);
+    *dest = IPV6_VERSION << 4;
+  }
+  dest += 4;
+
+  plen = dest;
+  prot_len = dest;
+  // payload length field requires some computation...
+  dest += 2;
+
+  if ((encoding & LOWPAN_IPHC_NH_MASK) == LOWPAN_IPHC_NH_INLINE) {
+    *dest = *buf;
+    buf++;
+  }
+  nxt_hdr = dest;
+
+  dest += 1;
+  // otherwise, decompress IPNH compression once we reach the end of
+  // the packed data.
+
+  u_info->hlim = NULL;
+  if ((encoding & LOWPAN_IPHC_HLIM_MASK) == LOWPAN_IPHC_HLIM_INLINE) {
+    *dest = *buf;
+    u_info->hlim = buf;
+    buf++;
+  }
+  dest += 1;
+  // otherwise, follow instructions for reconstructing hop limit once
+  // destination address is known.
+
+
+  // dest points at the start of the source address IP header field.
+  decompressAddress(dispatch, pkt->src,
+                    (encoding >> LOWPAN_IPHC_SC_OFFSET) & LOWPAN_IPHC_ADDRFLAGS_MASK,
+                    &buf, dest);
+  dest += 16;
+
+  decompressAddress(dispatch, pkt->src,
+                    (encoding >> LOWPAN_IPHC_DST_OFFSET) & LOWPAN_IPHC_ADDRFLAGS_MASK,
+                    &buf, dest);
+  dest += 16;
+  // we're done with the IP headers; time to decompress any compressed
+  // headers which follow...  We need to re-check that there's enough
+  // buffer to do this.
+
+
+  if ((encoding & LOWPAN_IPHC_NH_MASK) != LOWPAN_IPHC_NH_INLINE) {
+    // time to decode some next header fields
+    // we ought to be pointing at the HCNH encoding byte now.
+    if ((*buf & LOWPAN_UDP_DISPATCH) == LOWPAN_UDP_DISPATCH) {
+      pkt->headers |= LOWMSG_IPNH_HDR;
+      if (len < sizeof(struct udp_hdr)) return NULL;
+      len -= sizeof(struct udp_hdr);
+      struct udp_hdr *udp = (struct udp_hdr *)dest;
+      uint8_t udp_enc = *buf;
+      uint8_t dst_shift = 4;
+
+      extra_header_length = sizeof(struct udp_hdr);
+      buf += 1;
+      // UDP
+      *nxt_hdr = IANA_UDP;
+      if (udp_enc & LOWPAN_UDP_S_MASK) {
+        // recover from 4 bit packing
+        udp->srcport = hton16((*buf >> 4) + LOWPAN_UDP_PORT_BASE);
+        dst_shift = 0;
+      } else {
+        ip_memcpy((uint8_t *)&udp->srcport, buf, 2);
+        buf += 2;
+      }
+
+      if (udp_enc & LOWPAN_UDP_D_MASK) {
+        udp->dstport = hton16((((*buf >> dst_shift)) & 0x0f) + LOWPAN_UDP_PORT_BASE);
+        buf += 1;
+      } else {
+        if (dst_shift == 0) buf += 1;
+        ip_memcpy((uint8_t *)&udp->dstport, buf, 2);
+        buf += 2;
+      }
+
+      if (udp_enc & LOWPAN_UDP_C_MASK) {
+        // we elided the checksum and so are supposed to recompute it here.
+        // however, we won't do this.
+      } else {
+        ip_memcpy((uint8_t *)&udp->chksum, buf, 2);
+        buf += 2;
+      }
+
+      // still must fill in the length field, but we must first
+      // recompute the IP length, which we couldn't do until now.
+      // lamers...
+      prot_len = (uint8_t *)&udp->len;
+      dest += sizeof(struct udp_hdr);
+
+      u_info->nxt_hdr = IANA_UDP;
+      u_info->payload_offset += sizeof(struct udp_hdr);
+      u_info->transport_ptr = (uint8_t *)udp;
+
+    } else {
+      // otherwise who knows what's here... it's an error because the
+      // NH bit said we were inline but when we got here, we didn't
+      // recognize the NH encoding.
+      return NULL;
+    }
+  } else {
+    // there was no IPNH field, but there might be uncompressed fields
+    // we want to copy out for consistency (since we always unpack all
+    // headers not part of the payload).
+    uint8_t nhdr = *nxt_hdr;
+    uint8_t nhdr_len = 0;
+    struct ip6_ext *hdr;
+    u_info->nxt_hdr = nhdr;
+
+    // copy any IPv6 extension headers out of the packet.
+    // the rule is that the extension headers must fit in the first
+    // fragment so we can route on them after only one fragment.
+    while (EXTENSION_HEADER(nhdr)) {
+      hdr = (struct ip6_ext *)buf;
+
+      switch (nhdr) {
+      case IPV6_HOP:
+        u_info->hdr_hop = (struct ip6_ext *)buf;
+        break;
+      case IPV6_ROUTING:
+        u_info->hdr_route = (struct ip6_route *)buf;
+        break;
+      case IPV6_DEST:
+        u_info->hdr_dest = (struct ip6_ext *)buf;
+        break;
+      }
+      nhdr = hdr->nxt_hdr;
+      nhdr_len = hdr->len;
+      u_info->nxt_hdr = nhdr;
+
+      if (len < nhdr_len) return NULL;
+      ip_memcpy(dest, buf, nhdr_len);
+      dest += nhdr_len;
+      buf += nhdr_len;
+
+      u_info->payload_offset += nhdr_len;
+      extra_header_length += nhdr_len;
+    }
+
+    u_info->transport_ptr = dest;
+  }
+
+  u_info->payload_start = buf;
+  u_info->header_end = dest;
+  if (u_info->transport_ptr == NULL)
+    u_info->transport_ptr = dest;
+
+  // we can go back and figure out the payload length now that we know
+  // how long the compressed headers were
+  if (hasFrag1Header(pkt) || hasFragNHeader(pkt)) {
+    getFragDgramSize(pkt, &size);
+    size -= sizeof(struct ip6_hdr);
+  } else {
+    // it's a one fragment packet
+    size = pkt->len - (buf - pkt->data);
+    size += extra_header_length;
+    size -= getLowpanPayload(pkt) - pkt->data;
+  }
+
+  *plen = size >> 8;
+  *(plen + 1) = size & 0xff;
+
+  // finally fill in the udp length field that we finally can recompute
+  switch (*nxt_hdr) {
+  case IANA_UDP:
+    *prot_len = size >> 8;
+    *(prot_len + 1) = size & 0xff;
+  }
+  
+
+  return buf;
+}
+
+/* packs addr into *buf, and updates the pointer relative to the length
+ * that was needed.
+ * @returns the bit flags indicating which length was used
+ */
+static uint8_t packAddress(uint8_t dispatch, uint8_t **buf, ip6_addr_t addr) {
+
+  if ((dispatch == LOWPAN_HC_CRP_PATTERN && globalPrefix &&
+      cmpPfx(addr, __my_address.s6_addr)) ||
+      (dispatch == LOWPAN_HC_LOCAL_PATTERN &&
+       cmpPfx(addr, linklocal_prefix))) {
+    // only choice here are 64-bit and 16-bit addresses
+    if (ipv6_addr_suffix_is_long(addr)) {
+      // use the 64-bit compression
+      ip_memcpy(*buf, &addr[8], 8);
+      *buf += 8;
+      return LOWPAN_IPHC_ADDR_64;
+    } else {
+      // down to 16 bits: we never use the 0-bit compression
+      // (althought we could for link local).
+      ip_memcpy(*buf, &addr[14], 2);
+      *buf += 2;
+      return LOWPAN_IPHC_ADDR_16;
+    }
+  } else if (addr[0] == 0xff && // is multicast
+             addr[1] < 0x0f) { // the scope is small enough
+    // XXX : SDH : Need to check that the group is small enough
+    **buf = LOWPAN_IPHC_HC_MCAST; // set the encoding bits
+    **buf |= (addr[1] << LOWPAN_HC_MCAST_SCOPE_OFFSET); // scope
+
+    // direct mapped group id
+    **buf |= addr[14] & 0x1;
+    *(*buf + 1) = addr[15];
+    *buf += 2;
+    return LOWPAN_IPHC_ADDR_16;
+  } else {
+    // fuck it, send the whole thing
+    ip_memcpy(*buf, addr, 16);
+    *buf += 16;
+    return LOWPAN_IPHC_ADDR_128;
+  }
+}
+
+/*
+ * pack the headers of msg into the buffer pointed to by buf.
+ * 
+ * @returns a pointer to where we stopped writing
+ */
+uint8_t packHeaders(struct split_ip_msg *msg,
+                    uint8_t *buf, uint8_t len) {
+  uint8_t *dispatch, *encoding, addr_enc, nxt_hdr;
+  struct ip6_hdr *hdr = &msg->hdr;
+  dispatch = buf;
+  buf += 1;
+  encoding = buf;
+  buf += 1;
+  *encoding = 0;
+
+  if (!(hdr->vlfc[0] == (IPV6_VERSION << 4) && 
+        hdr->vlfc[1] == 0 &&
+        hdr->vlfc[2] == 0 &&
+        hdr->vlfc[3] == 0)) {
+    ip_memcpy(buf, &hdr->vlfc, 4);
+    buf += 4;
+  } else {
+    *encoding |= LOWPAN_IPHC_VTF_MASK;
+  }
+
+  nxt_hdr = hdr->nxt_hdr;
+  if (hdr->nxt_hdr == IANA_UDP && /* or other compressed values... */
+      msg->headers != NULL) {
+    // we will add the HCNH encoding at the end of the header
+    *encoding |= LOWPAN_IPHC_NH_MASK;
+  } else {
+    *buf = hdr->nxt_hdr;
+    buf += 1;
+  }
+
+  // always carry hop limit
+  *buf = hdr->hlim;
+  buf += 1;
+
+  if (globalPrefix && cmpPfx(hdr->ip6_src.s6_addr, __my_address.s6_addr)) {
+    *dispatch = LOWPAN_HC_CRP_PATTERN;
+  } else if (globalPrefix && cmpPfx(hdr->ip6_dst.s6_addr, __my_address.s6_addr)) {
+    *dispatch = LOWPAN_HC_CRP_PATTERN;
+  } else if (cmpPfx(hdr->ip6_src.s6_addr, linklocal_prefix)) {
+    *dispatch = LOWPAN_HC_LOCAL_PATTERN;
+  } else {
+    *dispatch = LOWPAN_HC_LOCAL_PATTERN;
+  }
+
+  addr_enc = packAddress(*dispatch, &buf, hdr->ip6_src.s6_addr);
+  *encoding |= addr_enc << LOWPAN_IPHC_SC_OFFSET;
+
+  addr_enc = packAddress(*dispatch, &buf, hdr->ip6_dst.s6_addr);
+  *encoding |= addr_enc << LOWPAN_IPHC_DST_OFFSET;
+
+  len -= (buf - dispatch);
+  // now come the compressions for special next header values.
+  // we pack all the headers in the split message into this fragment, and fail if we cannot;
+  {
+    int i = 0;
+    struct generic_header *cur = msg->headers;
+    while (cur != NULL) {
+      if (nxt_hdr == IANA_UDP && i == 0) {
+        struct udp_hdr *udp = cur->hdr.udp;
+  
+        uint8_t *udp_enc = buf;
+        uint8_t *cmpr_port = NULL;
+        // do the LOWPAN_UDP coding
+        
+        if (len < sizeof(struct udp_hdr)) return (buf - dispatch);
+        
+        *udp_enc = LOWPAN_UDP_DISPATCH;;
+        buf += 1;
+
+
+        if ((ntoh16(udp->srcport) & LOWPAN_UDP_PORT_BASE_MASK) == 
+            LOWPAN_UDP_PORT_BASE) {
+          //printf("compr to 4b\n");
+          cmpr_port = buf;
+          *cmpr_port = (ntoh16(udp->srcport) & ~LOWPAN_UDP_PORT_BASE_MASK) << 4;
+          *udp_enc |= LOWPAN_UDP_S_MASK;
+          buf += 1;
+        } else {
+          ip_memcpy(buf, (uint8_t *)&udp->srcport, 2);
+          buf += 2;
+        }
+        
+        if ((ntoh16(udp->dstport) & LOWPAN_UDP_PORT_BASE_MASK) == 
+            LOWPAN_UDP_PORT_BASE) {
+          if (cmpr_port == NULL) {
+            // the source port must not have been compressed, so 
+            // allocate a new byte for this guy
+            *buf = ((ntoh16(udp->dstport) & ~LOWPAN_UDP_PORT_BASE_MASK) << 4);
+            buf += 1;
+          } else {
+            // already in the middle of a byte for the port compression,
+            // so fill in the rest of the byte
+            *cmpr_port = *cmpr_port | ((ntoh16(udp->dstport) & ~LOWPAN_UDP_PORT_BASE_MASK));
+          }
+          *udp_enc |= LOWPAN_UDP_D_MASK;
+        } else {
+          ip_memcpy(buf, (uint8_t *)&udp->dstport, 2);
+          buf += 2;
+        }
+        
+        // we never elide the checksum
+        ip_memcpy(buf, (uint8_t *)&udp->chksum, 2);
+        buf += 2;
+      } else {
+        // otherwise we just need to copy the extension header
+        if (len < cur->len) return 0;
+        ip_memcpy(buf, (uint8_t *)cur->hdr.ext, cur->len);
+        len -= cur->len;
+        buf += cur->len;
+      }
+      cur = cur->next;
+      i++;
+    }
+  }
+  // I think we're done here...
+  return buf - dispatch;
+}
+
+/*
+ * indicates how much of the packet after the IP header we will pack
+ *
+ */
+/* int packs_header(struct split_ip_msg *msg) { */
+/*   switch (hdr->nxt_hdr) { */
+/*   case IANA_UDP: */
+/*     return sizeof(struct udp_hdr); */
+/*   default: */
+/*     return 0; */
+/*   } */
+/* } */
+
+
+
+#ifndef NO_LIB6LOWPAN_ASCII
+
+#define TO_CHAR(X) (((X) < 10) ? ('0' + (X)) : ('a' + ((X) - 10)))
+#define CHAR_VAL(X)  (((X) >= '0' && (X) <= '9') ? ((X) - '0') : \
+                      (((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : ((X) - 'a' + 10)))
+
+
+void inet_pton6(char *addr, struct in6_addr *dest) {
+  uint16_t cur = 0;
+  char *p = addr;
+  uint8_t block = 0, shift = 0;
+  if (addr == NULL || dest == NULL) return;
+  ip_memclr(dest->s6_addr, 16);
+
+  // first fill in from the front
+  while (*p != '\0') {
+    if (*p != ':') {
+      cur <<= 4;
+      cur |= CHAR_VAL(*p);
+    } else {
+      dest->s6_addr16[block++] = hton16(cur);
+      cur = 0;
+    }
+    p++;
+    if (*p == '\0') {
+      dest->s6_addr16[block++] = hton16(cur);
+      return;
+    }
+    if (*(p - 1) == ':' && *p == ':') {
+      break;
+    }
+  }
+  // we must have hit a "::" which means we need to start filling in from the end.
+  block = 7;
+  cur = 0;
+  while (*p != '\0') p++;
+  p--;
+  // now pointing at the end of the address string
+  while (p > addr) {
+    if (*p != ':') {
+      cur |= (CHAR_VAL(*p) << shift);
+      shift += 4;
+    } else {
+      dest->s6_addr16[block--] = hton16(cur);
+      cur = 0; shift = 0;
+    }
+    p --;
+    if (*(p + 1) == ':' && *p == ':') break;
+  }
+}
+
+
+
+int inet_ntop6(struct in6_addr *addr, char *buf, int cnt) {
+  uint16_t block;
+  char *end = buf + cnt;
+  int i, j, compressed = 0;
+
+  for (j = 0; j < 8; j++) {
+    if (buf > end - 7) return -1;
+
+    block = ntohs(addr->s6_addr16[j]);
+    for (i = 4; i <= 16; i+=4) {
+      if (block > (0xffff >> i) || (compressed == 2 && i == 16)) {
+        *buf++ = TO_CHAR((block >> (16 - i)) & 0xf);
+      }
+    }
+    if (addr->s6_addr16[j] == 0 && compressed == 0) {
+      *buf++ = ':';
+      compressed++;
+    }
+    if (addr->s6_addr16[j] != 0 && compressed == 1) compressed++;
+
+    if (j < 7 && compressed != 1) *buf++ = ':';
+  }
+  *buf++ = '\0';
+  return buf - (end - cnt);
+}
+
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/nwbyte.h b/support/sdk/c/blip/lib6lowpan/nwbyte.h
new file mode 100644 (file)
index 0000000..f94b3a5
--- /dev/null
@@ -0,0 +1,54 @@
+#ifndef _NWBYTE_H
+#define _NWBYTE_H_
+
+#include "blip-platform.h"
+
+/* define normal network byte-orders routines  */
+#if defined(PC) 
+
+#define ntoh16(X)   ntohs(X)
+#define hton16(X)   htons(X)
+#define ntoh32(X)   ntohl(X)
+#define hton32(X)   htonl(X)
+#else
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+// otherwise have to provide our own 
+
+#define ntoh16(X)   (((((uint16_t)(X)) >> 8) | ((uint16_t)(X) << 8)) & 0xffff)
+#define hton16(X)   (((((uint16_t)(X)) << 8) | ((uint16_t)(X) >> 8)) & 0xffff)
+
+/* this is much more efficient since gcc can insert swpb now.  */
+static inline uint32_t __attribute__((unused))  ntoh32(uint32_t i) {
+  uint16_t lo = (uint16_t)i;
+  uint16_t hi = (uint16_t)(i >> 16);
+  lo = (lo << 8) | (lo >> 8);
+  hi = (hi << 8) | (hi >> 8);
+  return (((uint32_t)lo) << 16) | ((uint32_t)hi);
+}
+
+#define hton32(X) ntoh32(X)
+#define ntohs(X) ntoh16(X)
+#define htons(X) hton16(X)
+#define ntohl(X) ntoh32(X)
+#define htonl(X) hton32(X)
+
+#else 
+#error "No byte-order conversions defined!"
+#endif
+#endif
+
+/* little-endian conversion routines */
+
+#if __BYTE_ORDER == __LITTLE_ENDIAN
+#define leton16(X)  hton16(X)
+#ifndef htole16
+#define htole16(X)  (X)
+#endif
+
+#else
+//  big-endian byte-order
+#define leton16(X) (((((uint16_t)(X)) << 8) | ((uint16_t)(X) >> 8)) & 0xffff)
+#define htole16(X) (((((uint16_t)(X)) << 8) | ((uint16_t)(X) >> 8)) & 0xffff)
+#endif
+
+#endif
diff --git a/support/sdk/c/blip/lib6lowpan/printpacket.c b/support/sdk/c/blip/lib6lowpan/printpacket.c
new file mode 100644 (file)
index 0000000..effa083
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdint.h>
+#include <stdio.h>
+// #include <arpa/inet.h>
+#include "6lowpan.h"
+#include "lib6lowpan.h"
+#include "lib6lowpanIP.h"
+
+
+void printBuf(uint8_t *buf, uint16_t len) {
+  int i;
+  for (i = 1; i <= len; i++) {
+    printf(" 0x%02x", buf[i-1]);
+    if (i % 16 == 0) printf("\n");
+
+  }
+  printf("\n\n");
+}
+
+
+void printPacket(uint8_t *buf, int len) {
+  uint8_t val;
+  uint16_t origin, final;
+  packed_lowmsg_t pkt;
+
+  // used for autoconfiguration; would be provided by lower layers.
+  pkt.src = 0xaa;
+  pkt.dst = 0xbb;
+
+  printBuf(buf, len);
+
+  pkt.data = buf;
+  pkt.len = len;
+  pkt.headers = getHeaderBitmap(&pkt);
+  printf("6loWPAN Packet (headers: 0x%x)\n", pkt.headers);
+  if (hasBcastHeader(&pkt)) {
+    getBcastSeqno(&pkt, &val);
+    printf("   BCast seqno: 0x%x\n", val);
+  }
+  if (hasMeshHeader(&pkt)) {
+    getMeshHopsLeft(&pkt, &val);
+    getMeshOriginAddr(&pkt, &origin);
+    getMeshFinalAddr(&pkt, &final);
+    printf("   Mesh hops: 0x%x origin: 0x%x final: 0x%x\n", val, origin, final);
+  }
+  if (hasFrag1Header(&pkt) || hasFragNHeader(&pkt)) {
+    getFragDgramSize(&pkt, &origin);
+    getFragDgramTag(&pkt, &final);
+    printf("   Frag size: 0x%x tag: 0x%x\n", origin, final);
+  }
+  if (hasFragNHeader(&pkt)) {
+    getFragDgramOffset(&pkt, &val);
+    printf("   Frag offset: 0x%x\n", val);
+  }
+
+  
+  uint8_t data[100];
+  struct ip6_hdr *h = (struct ip6_hdr *)data;
+  unpackHeaders(&pkt, (uint8_t *)h, 100);
+
+  printf(" ip first bytes: 0x%x\n", ntohl(*((uint32_t *)h->vlfc)));
+  printf("   plen: 0x%x next: 0x%x hlim: 0x%x\n", ntohs(h->plen), h->nxt_hdr, h->hlim);
+  printf("   src: ");
+  for (val = 0; val < 16; val++)
+    printf("0x%x ", h->src_addr[val]);
+  printf("\n   dst: ");
+  for (val = 0; val < 16; val++)
+    printf("0x%x ", h->dst_addr[val]);
+  printf("\n");
+
+  if (h->nxt_hdr == IANA_UDP) {
+    struct udp_hdr *udp = (struct udp_hdr *)&data[sizeof(struct ip6_hdr)];
+    printf("udp src: 0x%x dst: 0x%x len: 0x%x cksum: 0x%x\n",
+           ntoh16(udp->srcport), ntoh16(udp->dstport),
+           ntoh16(udp->len), ntoh16(udp->chksum));
+  }
+           
+
+  printf("\n\n");
+}
diff --git a/support/sdk/c/blip/libtcp/Makefile b/support/sdk/c/blip/libtcp/Makefile
new file mode 100644 (file)
index 0000000..6c5a45d
--- /dev/null
@@ -0,0 +1,20 @@
+
+GCC=gcc
+CFLAGS=-I../include -I../driver/ -DPC -g -Wall
+
+
+all: test_client test_server
+
+test_circ: test_circ.c circ.c circ.h
+       $(GCC) -o $@ $^ $(CFLAGS)
+
+test_client: test_client.c  # tcplib.h tcplib.c circ.c
+       $(GCC) -o $@ $< $(CFLAGS)
+#      $(GCC) -o $@ $< tcplib.c circ.c ../driver/tun_dev.c ../lib6lowpan/ip_malloc.c ../lib6lowpan/in_cksum.c $(CFLAGS)
+
+test_server: test_server.c  tcplib.h tcplib.c circ.c
+       $(GCC) -o $@ $< tcplib.c circ.c ../driver/tun_dev.c ../lib6lowpan/ip_malloc.c ../lib6lowpan/in_cksum.c $(CFLAGS)
+
+clean:
+       rm -rf test_server test_circ
+
diff --git a/support/sdk/c/blip/libtcp/circ.c b/support/sdk/c/blip/libtcp/circ.c
new file mode 100644 (file)
index 0000000..cd91d8e
--- /dev/null
@@ -0,0 +1,147 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+
+#include "tcplib.h"
+
+struct circ_buf {
+  uint8_t  *data_start;
+  uint8_t  *data_head;
+  uint16_t  data_len;
+  uint32_t  head_seqno;
+};
+
+int circ_buf_init(void *data, int len, uint32_t seqno) {
+  struct circ_buf *b = (struct circ_buf *)data;
+
+  if (len < sizeof(struct circ_buf))
+    return -1;
+
+  b->data_head = b->data_start = (uint8_t *)(b + 1);
+  b->data_len = len - sizeof(struct circ_buf);
+  b->head_seqno = seqno;
+  return 0;
+}
+
+uint32_t circ_get_seqno(void *buf) {
+  struct circ_buf *b = (struct circ_buf *)buf;
+  return b->head_seqno;
+}
+
+static void get_ptr_off_1(struct circ_buf *b, uint32_t sseqno, int len,
+                          uint8_t **writeptr, int *w_len) {
+  uint8_t *endptr =  b->data_start + b->data_len;
+  int offset;
+
+  *writeptr = NULL;
+  *w_len = len;
+
+  /* write up to either the end of the buffer */
+  offset = sseqno - b->head_seqno;
+  if (b->data_head + offset < endptr) {
+    *writeptr = b->data_head + offset;
+  } else {
+    offset -= (endptr - b->data_head);
+    *writeptr = b->data_start + offset;
+  }
+  if (*writeptr + *w_len > endptr) {
+    *w_len = endptr - *writeptr;
+  }
+}
+
+int circ_shorten_head(void *buf, uint32_t seqno) {
+  struct circ_buf *b = (struct circ_buf *)buf;
+  int offset = seqno - b->head_seqno;
+
+  b->head_seqno = seqno;
+  b->data_head += offset;
+
+  while (b->data_head > b->data_start + b->data_len)
+    b->data_head -= b->data_len;
+
+  return 0;
+}
+
+int circ_buf_read(void *buf, uint32_t sseqno,
+                  uint8_t *data, int len) {
+  struct circ_buf *b = (struct circ_buf *)buf;
+  uint8_t *readptr;
+  int r_len, rc = 0;
+
+  get_ptr_off_1(b, sseqno, len, &readptr, &r_len);
+  memcpy(data, readptr, r_len);
+  data += r_len;
+  rc += r_len;
+  
+  if (r_len != len) {
+    readptr = b->data_start;
+    r_len = min(len - r_len, b->data_head - b->data_start);
+    memcpy(data, readptr, r_len);
+    rc += r_len;
+  }
+  return rc;
+}
+
+int circ_buf_write(char *buf, uint32_t sseqno,
+                   uint8_t *data, int len) {
+  struct circ_buf *b = (struct circ_buf *)buf;
+  uint8_t *writeptr;
+  int w_len;
+  /* we can't write any bytes since we're trying to write too far
+     ahead  */
+  if (sseqno > b->head_seqno + b->data_len)
+    return -1;
+  if (len == 0) return 0;
+
+  get_ptr_off_1(b, sseqno, len, &writeptr, &w_len);
+
+  memcpy(writeptr, data, w_len);
+  data += w_len;
+
+  if (w_len != len) {
+    writeptr = b->data_start;
+    w_len = min(len - w_len, b->data_head - b->data_start);
+    memcpy(writeptr, data, w_len);
+  }
+
+  return 0;
+}
+
+#ifdef PC             
+void circ_buf_dump(void *buf) {
+  struct circ_buf *b = (struct circ_buf *)buf;
+  uint8_t *d;
+  int i;
+/*   printf("circ buf: %p\n\tmap: %p\n\tmap_len: %i\n\tdata_start: %p\n\t" */
+/*          "data_head: %p\n\tdata_len: %i\n\thead_seqno: %i\n",  */
+/*          b, b->map, */
+/*          b->map_len, b->data_start, b->data_head, b->data_len, b->head_seqno); */
+  for (d = b->data_start; d < b->data_start + b->data_len; d++) {
+    if (d == b->data_head) putc('|', stdout);
+    printf("%2.x ", *d);
+  }
+  putc('\n', stdout);
+}
+#endif
diff --git a/support/sdk/c/blip/libtcp/circ.h b/support/sdk/c/blip/libtcp/circ.h
new file mode 100644 (file)
index 0000000..d71f3a0
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef __CIRC_H_
+#define __CIRC_H_
+
+#include <stdint.h>
+
+int circ_buf_init(void *data, int len, uint32_t seqno);
+
+
+int circ_buf_write(char *buf, uint32_t sseqno,
+                   uint8_t *data, int len);
+
+
+int circ_buf_read(void *buf, uint32_t sseqno,
+                  uint8_t *data, int len);
+
+
+int circ_shorten_head(void *buf, uint32_t seqno);
+
+/* read from the head of the buffer, moving the data pointer forward */
+// int circ_buf_read_head(char *buf, char **data);
+
+void circ_buf_dump(void *buf);
+
+uint32_t circ_get_seqno(void *buf);
+void circ_set_seqno(void *buf, uint32_t seqno);
+
+#endif
diff --git a/support/sdk/c/blip/libtcp/tcplib.c b/support/sdk/c/blip/libtcp/tcplib.c
new file mode 100644 (file)
index 0000000..7c498e2
--- /dev/null
@@ -0,0 +1,712 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/* A nonblocking library-based implementation of TCP
+ *
+ * There are some things like timers which need to be handled
+ * externally with callbacks.
+ *
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include "ip_malloc.h"
+#include "in_cksum.h"
+#include "6lowpan.h"
+#include "ip.h"
+#include "tcplib.h"
+#include "circ.h"
+
+static struct tcplib_sock *conns = NULL;
+
+#define ONE_SEGMENT(X)  ((X)->mss)
+
+uint16_t alloc_local_port() {
+  return 32012;
+}
+
+static inline void conn_add_once(struct tcplib_sock *sock) {
+  struct tcplib_sock *iter;
+
+  for (iter = conns; iter != NULL; iter = iter->next) {
+    if (iter == sock) break;
+  }
+  if (iter == NULL) {
+    sock->next = conns;
+    conns = sock;
+  }
+
+}
+static int isInaddrAny(struct in6_addr *addr) {
+  int i;
+  for (i = 0; i < 8; i++)
+    if (addr->s6_addr16[i] != 0) break;
+  if (i != 8) return 0;
+  return 1;
+}
+
+#ifdef PC
+#include <arpa/inet.h>
+
+void print_conn(struct tcplib_sock *sock) {
+  char addr_buf[32];
+  printf("tcplib socket state: %i:\n", sock->state);
+  inet_ntop(AF_INET6, sock->l_ep.sin6_addr.s6_addr, addr_buf, 32);
+  printf(" local ep: %s port: %u\n", addr_buf, ntohs(sock->l_ep.sin6_port));
+  inet_ntop(AF_INET6, sock->r_ep.sin6_addr.s6_addr, addr_buf, 32);
+  printf(" remote ep: %s port: %u\n", addr_buf, ntohs(sock->r_ep.sin6_port));
+  printf(" tx buf length: %i\n", sock->tx_buf_len);
+}
+void print_headers(struct ip6_hdr *iph, struct tcp_hdr *tcph) {
+  char addr_buf[32];
+  printf("headers ip length: %i:\n", ntohs(iph->plen));
+  inet_ntop(AF_INET6, iph->ip6_src.s6_addr, addr_buf, 32);
+  printf(" source: %s port: %u\n", addr_buf, ntohs(tcph->srcport));
+  inet_ntop(AF_INET6, iph->ip6_dst.s6_addr, addr_buf, 32);
+  printf(" remote ep: %s port: %u\n", addr_buf, ntohs(tcph->dstport));
+  printf(" tcp seqno: %u ackno: %u\n", ntohl(tcph->seqno), ntohl(tcph->ackno));
+}
+#endif
+
+static struct tcplib_sock *conn_lookup(struct ip6_hdr *iph, 
+                                       struct tcp_hdr *tcph) {
+  struct tcplib_sock *iter;
+  //printf("looking up conns: %p %p\n", iph, tcph);
+  // print_headers(iph, tcph);
+  for (iter = conns; iter != NULL; iter = iter->next) {
+    // print_conn(iter);
+    printf("conn lport: %i\n", ntohs(iter->l_ep.sin6_port));
+    if (((memcmp(iph->ip6_dst.s6_addr, iter->l_ep.sin6_addr.s6_addr, 16) == 0) ||
+         isInaddrAny(&iter->l_ep.sin6_addr)) &&
+        tcph->dstport == iter->l_ep.sin6_port &&
+        (iter->r_ep.sin6_port == 0 ||
+         (memcmp(&iph->ip6_src, &iter->r_ep.sin6_addr, 16) == 0 &&
+          tcph->srcport == iter->r_ep.sin6_port)))
+      return iter;
+  }
+  return NULL;
+}
+
+static int conn_checkport(uint16_t port) {
+  struct tcplib_sock *iter;
+
+  for (iter = conns; iter != NULL; iter = iter->next) {
+    if (iter->l_ep.sin6_port == port)
+      return -1;
+  }
+  return 0;
+}
+
+struct tcp_hdr *find_tcp_hdr(struct split_ip_msg *msg) {
+  if (msg->hdr.nxt_hdr == IANA_TCP) {
+    return (struct tcp_hdr *)((msg->headers == NULL) ? msg->data :
+                              msg->headers->hdr.data);
+  }
+  return NULL;
+}
+
+static struct split_ip_msg *get_ipmsg(int plen) {
+  struct split_ip_msg *msg = 
+    (struct split_ip_msg *)ip_malloc(sizeof(struct split_ip_msg) + sizeof(struct tcp_hdr) + plen);
+  if (msg == NULL) return NULL;
+  memset(msg, 0, sizeof(struct split_ip_msg) + sizeof(struct tcp_hdr));
+  msg->hdr.nxt_hdr = IANA_TCP;
+  msg->hdr.plen = htons(sizeof(struct tcp_hdr) + plen);
+
+  msg->headers = NULL;
+  msg->data = (void *)(msg + 1);
+  msg->data_len = sizeof(struct tcp_hdr) + plen;
+
+  return msg;
+}
+
+static void __tcplib_send(struct tcplib_sock *sock,
+                          struct split_ip_msg *msg) {
+  struct tcp_hdr *tcph = find_tcp_hdr(msg);
+  if (tcph == NULL) return;
+  memcpy(&msg->hdr.ip6_dst, &sock->r_ep.sin6_addr, 16);
+
+  sock->flags &= ~TCP_ACKPENDING;
+  // sock->ackno = ntohl(tcph->ackno);
+
+  tcph->srcport = sock->l_ep.sin6_port;
+  tcph->dstport = sock->r_ep.sin6_port;
+  tcph->offset = sizeof(struct tcp_hdr) * 4;
+  tcph->window = htons(sock->my_wind);
+  tcph->chksum = 0;
+  tcph->urgent = 0;
+
+  tcplib_send_out(msg, tcph);
+}
+
+static void tcplib_send_ack(struct tcplib_sock *sock, int fin_seqno, uint8_t flags) {
+  struct split_ip_msg *msg = get_ipmsg(0);
+      
+  if (msg != NULL) {
+    struct tcp_hdr *tcp_rep = (struct tcp_hdr *)(msg + 1);
+    tcp_rep->flags = flags;
+
+
+    tcp_rep->seqno = htonl(sock->seqno);
+    tcp_rep->ackno = htonl(sock->ackno +
+                           (fin_seqno ? 1 : 0));
+    // printf("sending ACK seqno: %u ackno: %u\n", ntohl(tcp_rep->seqno), ntohl(tcp_rep->ackno));
+    __tcplib_send(sock, msg);
+    ip_free(msg);
+  } else {
+    printf("Could not send ack-- no memory!\n");
+  }
+}
+
+static void tcplib_send_rst(struct ip6_hdr *iph, struct tcp_hdr *tcph) {
+  struct split_ip_msg *msg = get_ipmsg(0);
+  struct tcp_hdr *tcp_rep;
+      
+  if (msg == NULL) {
+    return;
+  }  
+  tcp_rep = (struct tcp_hdr *)(msg + 1);
+
+  tcp_rep->flags = TCP_FLAG_RST | TCP_FLAG_ACK;
+
+  tcp_rep->ackno = htonl(ntohl(tcph->seqno) + 1);
+  tcp_rep->seqno = tcph->ackno;;
+
+  tcp_rep->srcport = tcph->dstport;
+  tcp_rep->dstport = tcph->srcport;
+  tcp_rep->offset = sizeof(struct tcp_hdr) * 4;
+  tcp_rep->window = 0;
+  tcp_rep->chksum = 0;
+  tcp_rep->urgent = 0;
+
+  memcpy(&msg->hdr.ip6_dst, &iph->ip6_src, 16);
+  
+  tcplib_send_out(msg, tcp_rep);
+  ip_free(msg);
+}
+
+/* send all the data in the tx buffer, starting at sseqno */
+static int tcplib_output(struct tcplib_sock *sock, uint32_t sseqno) {
+  // the output size is the minimum of the advertised window and the
+  // conjestion window.  of course, if we have less data we send even
+  // less.
+  int seg_size = min(sock->seqno - sseqno, sock->r_wind);
+  printf("r_wind: %i\n", sock->r_wind);
+  seg_size = min(seg_size, sock->cwnd);
+  while (seg_size > 0 && sock->seqno > sseqno) {
+    // printf("sending seg_size: %i\n", seg_size);
+    struct split_ip_msg *msg = get_ipmsg(seg_size);
+    struct tcp_hdr *tcph;
+    uint8_t *data;
+    if (msg == NULL) return -1;
+    tcph = (struct tcp_hdr *)(msg + 1);
+    data = (uint8_t *)(tcph + 1);
+
+    tcph->flags = TCP_FLAG_ACK;
+    tcph->seqno = htonl(sseqno);
+    tcph->ackno = htonl(sock->ackno);
+
+    printf("tcplib_output: seqno: %u ackno: %u len: %i headno: %u\n",
+           ntohl(tcph->seqno), ntohl(tcph->ackno), seg_size,
+           circ_get_seqno(sock->tx_buf));
+
+    if (seg_size != circ_buf_read(sock->tx_buf, sseqno, data, seg_size)) {
+      printf("WARN: circ could not read!\n");
+    }
+    __tcplib_send(sock, msg);
+    ip_free(msg);
+
+    sseqno += seg_size;
+    seg_size = min(sock->seqno - sseqno, sock->mss);
+  }
+  return 0;
+}
+
+int tcplib_init_sock(struct tcplib_sock *sock) {
+  memset(sock, 0, sizeof(struct tcplib_sock) - sizeof(struct tcplib_sock *));
+  sock->mss = 200;
+  sock->my_wind = 200;
+  sock->cwnd = ONE_SEGMENT(sock);
+  sock->ssthresh = 0xffff;
+  conn_add_once(sock);
+  return 0;
+}
+
+/* called when a new segment arrives. */
+/* deliver as much data to the app as possible, and update the ack
+ * number of the socket to reflect how much was delivered 
+ */
+static void receive_data(struct tcplib_sock *sock, struct tcp_hdr *tcph, int len) {
+  uint8_t *ptr;
+  int payload_len;
+
+  ptr = ((uint8_t *)tcph) + (tcph->offset / 4);
+  payload_len = len - (tcph->offset / 4);
+  sock->ackno = ntohl(tcph->seqno) + payload_len;
+
+  if (payload_len > 0) {
+    tcplib_extern_recv(sock, ptr, payload_len);
+  }
+}
+
+static void reset_ssthresh(struct tcplib_sock *conn) {
+  uint16_t new_ssthresh = min(conn->cwnd, conn->r_wind) / 2;
+  if (new_ssthresh < 2 * ONE_SEGMENT(conn))
+    new_ssthresh = 2 * ONE_SEGMENT(conn);
+  conn->ssthresh = new_ssthresh;
+}
+
+int tcplib_process(struct ip6_hdr *iph, void *payload) {
+  int rc = 0;
+  struct tcp_hdr *tcph;
+  struct tcplib_sock *this_conn;
+  //   uint8_t *ptr;
+  int len = ntohs(iph->plen) + sizeof(struct ip6_hdr);
+  int payload_len;
+  uint32_t hdr_seqno, hdr_ackno;
+
+  tcph = (struct tcp_hdr *)payload;
+  payload_len = len - sizeof(struct ip6_hdr) - (tcph->offset / 4);
+
+  /* if there's no local */
+  this_conn = conn_lookup(iph, tcph);
+  // printf("conn: %p\n", this_conn);
+  if (this_conn != NULL) {
+    hdr_seqno = ntohl(tcph->seqno);
+    hdr_ackno = ntohl(tcph->ackno);
+
+    if (tcph->flags & TCP_FLAG_RST) {
+      /* Really hose this connection if we get a RST packet.
+       * still TODO: RST generation for unbound ports */
+      printf("connection reset by peer\n");
+          
+      tcplib_extern_closedone(this_conn);
+      // tcplib_init_sock(this_conn);
+      return 0;
+    }
+    // always get window updates from new segments
+    // TODO : this should be after we detect out-of-sequence ACK
+    // numbers!
+    this_conn->r_wind = ntohs(tcph->window);
+    printf("State: %i\n", this_conn->state);
+
+    switch (this_conn->state) {
+    case TCP_LAST_ACK:
+      if (tcph->flags & TCP_FLAG_ACK && 
+          hdr_ackno == this_conn->seqno + 1) {
+
+        this_conn->state = TCP_CLOSED;
+        tcplib_extern_closedone(this_conn);
+        break;
+      }
+    case TCP_FIN_WAIT_1:
+      printf("IN FIN_WAIT_1, %i\n", (tcph->flags & TCP_FLAG_FIN));
+      if (tcph->flags & TCP_FLAG_ACK && 
+          hdr_ackno == this_conn->seqno + 1) {
+        if (tcph->flags & TCP_FLAG_FIN) {
+          this_conn->seqno++;
+          this_conn->state = TCP_TIME_WAIT;
+          
+          // the TIME_WAIT state is problematic, since it holds up the
+          // resources while we're in it...
+          this_conn->timer.retx = TCPLIB_TIMEWAIT_LEN;
+        } else {
+          this_conn->timer.retx = TCPLIB_2MSL;
+          this_conn->state = TCP_FIN_WAIT_2;
+        }
+      }
+      // this generate the ACK we need here
+      goto ESTABLISHED;
+    case TCP_FIN_WAIT_2:
+      if (tcph->flags & TCP_FLAG_FIN) {
+        this_conn->seqno++;
+        this_conn->state = TCP_TIME_WAIT;
+        
+        this_conn->timer.retx = TCPLIB_TIMEWAIT_LEN;
+        tcplib_send_ack(this_conn, 0, TCP_FLAG_ACK);
+      }
+      break;
+
+    case TCP_SYN_SENT:
+      if (tcph->flags & (TCP_FLAG_SYN | TCP_FLAG_ACK)) {
+        // got a syn-ack
+        // send the ACK this_conn
+        this_conn->state = TCP_ESTABLISHED;
+        this_conn->ackno = hdr_seqno + 1;
+        // skip the LISTEN processing
+        // this will also generate an ACK
+        goto ESTABLISHED;
+      } else if (this_conn->flags & TCP_FLAG_SYN) {
+        // otherwise the state machine says we're in a simultaneous open, so continue doen
+        this_conn->state = TCP_SYN_RCVD;
+      } else {
+        printf("sending RST on bad data in state SYN_SENT\n");
+        // we'll just let the timeout eventually close the socket, though
+        tcplib_send_rst(iph, tcph);
+        break;
+      }
+    case TCP_SYN_RCVD:
+    case TCP_LISTEN:
+      /* not connected. */
+      if (tcph->flags & TCP_FLAG_SYN) {
+        struct tcplib_sock *new_sock;
+
+        if (this_conn->state == TCP_LISTEN) {
+          memcpy(&this_conn->r_ep.sin6_addr, &iph->ip6_src, 16);
+          this_conn->r_ep.sin6_port = tcph->srcport;
+          new_sock = tcplib_accept(this_conn, &this_conn->r_ep);
+          if (new_sock != this_conn) {
+            memset(this_conn->r_ep.sin6_addr.s6_addr, 0, 16);
+            this_conn->r_ep.sin6_port = 0;
+            if (new_sock != NULL) {
+              memcpy(&new_sock->r_ep.sin6_addr, &iph->ip6_src, 16);
+              new_sock->r_ep.sin6_port = tcph->srcport;
+              conn_add_once(new_sock);
+            }
+          }
+          if (new_sock == NULL) {
+            tcplib_send_rst(iph, tcph);
+            break;
+          }
+          memcpy(&new_sock->l_ep.sin6_addr, &iph->ip6_dst, 16);
+          new_sock->l_ep.sin6_port = tcph->dstport;
+
+          new_sock->ackno = hdr_seqno + 1;
+          circ_buf_init(new_sock->tx_buf, new_sock->tx_buf_len,
+                        0xcafebabe + 1);
+        } else {
+          /* recieved a SYN retransmission. */
+          new_sock = this_conn;
+        }
+
+        if (new_sock != NULL) {
+          new_sock->seqno = 0xcafebabe + 1;
+          new_sock->state = TCP_SYN_RCVD;
+          tcplib_send_ack(new_sock, 0, TCP_FLAG_ACK | TCP_FLAG_SYN);
+          new_sock->seqno++;
+        } else {
+          memset(&this_conn->r_ep, 0, sizeof(struct sockaddr_in6));
+        }
+      } else if (this_conn->state == TCP_LISTEN) {
+        tcplib_send_rst(iph, tcph);
+        break;
+      }
+      /* this is SYN_RECVd */
+      if (tcph->flags & TCP_FLAG_ACK) {
+        this_conn->state = TCP_ESTABLISHED;
+      } 
+      /* fall through to handle any data. */
+      
+
+    case TCP_CLOSE_WAIT:
+    case TCP_ESTABLISHED:
+    ESTABLISHED:
+
+      /* ack any data in this packet */
+      if (this_conn->state == TCP_ESTABLISHED || this_conn->state == TCP_FIN_WAIT_1) {
+        if (payload_len > 0) {
+          if ((this_conn->flags & TCP_ACKPENDING) == TCP_ACKPENDING) {
+            // printf("Incr would overflow\n");
+          }
+          this_conn->flags ++;
+        }
+
+
+        // receive side sequence check and add data
+        printf("seqno: %u ackno: %u\n", hdr_seqno, hdr_ackno);
+
+
+        // send side recieve sequence check and congestion window updates.
+        if (hdr_ackno > circ_get_seqno(this_conn->tx_buf)) {
+          // new data is being ACKed
+          // or we haven't sent anything new
+          if (this_conn->cwnd <= this_conn->ssthresh) {
+            // in slow start; increase the cwnd by one segment
+            this_conn->cwnd += ONE_SEGMENT(this_conn);
+            // printf("in slow start\n");
+          } else {
+            // in congestion avoidance
+            this_conn->cwnd += (ONE_SEGMENT(this_conn) * ONE_SEGMENT(this_conn)) / this_conn->cwnd;
+            // printf("in congestion avoidence\n");
+          }
+          // printf("ACK new data: cwnd: %i ssthresh: %i\n", this_conn->cwnd, this_conn->ssthresh);
+          // reset the duplicate ack counter
+          UNSET_ACK_COUNT(this_conn->flags);
+          // truncates the ack buffer 
+          circ_shorten_head(this_conn->tx_buf, hdr_ackno);
+          // printf("ack_count: %i\n", GET_ACK_COUNT(this_conn->flags));
+
+          if (this_conn->seqno == hdr_ackno) {
+            tcplib_extern_acked(this_conn);
+          }
+        } else if (this_conn->seqno > circ_get_seqno(this_conn->tx_buf)) {
+          // this is a duplicate ACK
+          //  - increase the counter of the number of duplicate ACKs
+          //  - if we get to three duplicate ACK's, start resending at
+          //    the ACK number because this probably means we lost a segment
+
+          INCR_ACK_COUNT(this_conn->flags);
+          // printf("ack_count: %i\n", GET_ACK_COUNT(this_conn->flags));
+          // printf("dup ack count: %i\n", GET_ACK_COUNT(this_conn->flags));
+          // a "dup ack count" of 2 is really 3 total acks because we start with zero
+          if (GET_ACK_COUNT(this_conn->flags) == 2) {
+            UNSET_ACK_COUNT(this_conn->flags);
+            printf("detected multiple duplicate ACKs-- doing fast retransmit [%u, %u]\n",
+                   circ_get_seqno(this_conn->tx_buf),
+                   this_conn->seqno);
+
+            // this is our detection of a "duplicate ack" event.
+            // we are going to reset ssthresh and retransmit the data.
+            reset_ssthresh(this_conn);
+            tcplib_output(this_conn, circ_get_seqno(this_conn->tx_buf));
+            this_conn->timer.retx = 6;
+            
+          }
+        }
+
+        if (hdr_seqno != this_conn->ackno) {
+          printf("==> received forward segment\n");
+          if ((hdr_seqno > this_conn->ackno + this_conn->my_wind) ||
+              (hdr_seqno < this_conn->ackno - this_conn->my_wind)) {
+            // send a RST on really wild data 
+            tcplib_send_rst(iph, tcph);
+          } else {
+            tcplib_send_ack(this_conn, 0, TCP_FLAG_ACK);
+            this_conn->flags |= TCP_ACKSENT;
+          }
+        } else { // (hdr_seqno == this_conn->ackno) {
+          printf("receive data\n");
+          receive_data(this_conn, tcph, len - sizeof(struct ip6_hdr));
+
+          if (this_conn->flags & TCP_ACKSENT) {
+            this_conn->flags &= ~TCP_ACKSENT;
+            tcplib_send_ack(this_conn, 0, TCP_FLAG_ACK);
+          }
+        }          
+
+        // reset the retransmission timer
+        if (this_conn->timer.retx == 0)
+          this_conn->timer.retx = 6;
+      }
+    case TCP_TIME_WAIT:
+      if ((payload_len > 0 && (this_conn->flags & TCP_ACKPENDING) >= 1) 
+          || tcph->flags & TCP_FLAG_FIN) {
+        tcplib_send_ack(this_conn, (payload_len == 0 && (tcph->flags & TCP_FLAG_FIN)), TCP_FLAG_ACK);
+        /* only close the connection if we've gotten all the data */
+        if (this_conn->state == TCP_ESTABLISHED 
+            && (tcph->flags & TCP_FLAG_FIN)
+            && hdr_seqno  == this_conn->ackno) {
+          this_conn->state = TCP_CLOSE_WAIT;
+          tcplib_extern_closed(this_conn);
+        }
+      }
+      break;
+    case TCP_CLOSED:
+    default:
+      rc = -1;
+      // printf("sending RST\n");
+      // tcplib_send_ack(this_conn, 0, TCP_FLAG_ACK | TCP_FLAG_RST);
+    }
+  } else {
+    /* this_conn was NULL */
+    /* interestingly, TCP sends a RST on this condition, not an ICMP error.  go figure. */
+    printf("sending rst on missing connection\n");
+    tcplib_send_rst(iph, tcph);
+
+  }
+  return rc;
+}
+
+
+/* bind the socket to a local address */
+int tcplib_bind(struct tcplib_sock *sock,
+                struct sockaddr_in6 *addr) {
+  /* not using an already-bound port */
+  /* TODO : SDH : check local address */
+  if (conn_checkport(addr->sin6_port))
+    return -1;
+  
+  memcpy(&sock->l_ep, addr, sizeof(struct sockaddr_in6));
+  /* passive open */
+  sock->state = TCP_LISTEN;
+  return 0;
+}
+
+/* connect the socket to a remote endpoint */
+int tcplib_connect(struct tcplib_sock *sock,
+                   struct sockaddr_in6 *serv_addr) {
+  if (sock->tx_buf == NULL)
+    return -1;
+
+  switch (sock->state) {
+  case TCP_CLOSED:
+    // passive open; need to set up the local endpoint.
+    memset(&sock->l_ep, 0, sizeof(struct sockaddr_in6));
+    sock->l_ep.sin6_port = htons(alloc_local_port());
+    break;
+  case TCP_LISTEN:
+    // we got here by calling bind, so we're cool.
+    break;
+  default:
+    return -1;
+  }
+  circ_buf_init(sock->tx_buf, sock->tx_buf_len,
+                0xcafebabe + 1);
+
+  sock->ackno = 0;
+  sock->seqno = 0xcafebabe;
+  memcpy(&sock->r_ep, serv_addr, sizeof(struct sockaddr_in6));
+  tcplib_send_ack(sock, 0, TCP_FLAG_SYN);
+  sock->state = TCP_SYN_SENT;
+  sock->seqno++;
+  sock->timer.retx = 6;
+
+  return 0;
+}
+
+
+int tcplib_send(struct tcplib_sock *sock, void *data, int len) {
+  /* have enough tx buffer left? */
+  if (sock->state != TCP_ESTABLISHED)
+    return -1;
+  if (sock->seqno - circ_get_seqno(sock->tx_buf) + len > sock->tx_buf_len) // circ_get_window(sock->tx_buf))
+    return -1;
+  if (circ_buf_write(sock->tx_buf, sock->seqno, data, len) < 0)
+    return -1;
+
+  sock->seqno += len;
+  // printf("tcplib_output from send\n");
+  tcplib_output(sock, sock->seqno - len);
+  
+  // 3 seconds
+  if (sock->timer.retx == 0)
+    sock->timer.retx = 6;
+
+  return 0;
+}
+
+void tcplib_retx_expire(struct tcplib_sock *sock) {
+  // printf("retransmission timer expired!\n");
+  sock->retxcnt++;
+  switch (sock->state) {
+  case TCP_ESTABLISHED:
+    if (circ_get_seqno(sock->tx_buf) != sock->seqno) {
+      printf("retransmitting [%u, %u]\n", circ_get_seqno(sock->tx_buf),
+             sock->seqno);
+      reset_ssthresh(sock);
+      // restart slow start
+      sock->cwnd = ONE_SEGMENT(sock);
+      // printf("tcplib_output from timer\n");
+      tcplib_output(sock, circ_get_seqno(sock->tx_buf));
+      sock->timer.retx = 6;
+    } else {
+      sock->retxcnt--;
+    }
+    break;
+  case TCP_SYN_SENT:
+    tcplib_send_ack(sock, 0, TCP_FLAG_SYN);
+    sock->timer.retx = 6;
+    break;
+  case TCP_LAST_ACK:
+  case TCP_FIN_WAIT_1:
+    tcplib_send_ack(sock, 1, TCP_FLAG_ACK | TCP_FLAG_FIN);
+    sock->timer.retx = TCPLIB_2MSL;
+    break;
+  case TCP_FIN_WAIT_2:
+  case TCP_TIME_WAIT:
+    sock->state = TCP_CLOSED;
+    // exit TIME_WAIT
+    tcplib_extern_closedone(sock);
+    break;
+  default:
+    break;
+  }
+
+  /* if we've hit this timer a lot, give up
+   *
+   * do this by going into
+   * TIME_WAIT, which will generate a FIN if anyone sends to us but
+   * otherwise just do nothing.
+   *
+   * we don't do something like try to close it here, since we might
+   * have gotten here from doing that.
+   */
+  if (sock->retxcnt > TCPLIB_GIVEUP) {
+    sock->state = TCP_TIME_WAIT;
+    sock->timer.retx = TCPLIB_TIMEWAIT_LEN;
+   }
+}
+
+int tcplib_abort(struct tcplib_sock *sock) {
+  switch (sock->state) {
+    // nothing to abort
+  case TCP_CLOSED:
+  case TCP_LISTEN:
+    break;
+  default:
+    tcplib_send_ack(sock, 0, TCP_FLAG_RST);
+    memset(&sock->l_ep, 0, sizeof(struct sockaddr_in6));
+    memset(&sock->r_ep, 0, sizeof(struct sockaddr_in6));
+    sock->state = TCP_CLOSED;
+  }
+  return 0;
+}
+
+int tcplib_close(struct tcplib_sock *sock) {
+  int rc = 0;
+
+  switch (sock->state) {
+    /* passive close */
+  case TCP_CLOSE_WAIT:
+    tcplib_send_ack(sock, 1, TCP_FLAG_ACK | TCP_FLAG_FIN);
+    sock->timer.retx = 6;
+    sock->state = TCP_LAST_ACK;
+    break;
+    /* active close */
+  case TCP_ESTABLISHED:
+    // kick off the close
+    tcplib_send_ack(sock, 0, TCP_FLAG_ACK | TCP_FLAG_FIN);
+    sock->timer.retx = TCPLIB_2MSL;
+    sock->state = TCP_FIN_WAIT_1;
+    break;
+  case TCP_SYN_SENT:
+    sock->state = TCP_CLOSED;
+    break;
+  default:
+    /* this is meaningless in other states */
+    rc = -1;
+  }
+  return rc;
+}
+
+int tcplib_timer_process() {
+  struct tcplib_sock *iter;
+  for (iter = conns; iter != NULL; iter = iter->next) {
+    if (iter->timer.retx > 0 && (--iter->timer.retx) == 0)
+      tcplib_retx_expire(iter);
+    if ((iter->flags & TCP_ACKPENDING) >= 2) {
+      tcplib_send_ack(iter, 0, TCP_FLAG_ACK);
+    }
+  }
+  return 0;
+}
diff --git a/support/sdk/c/blip/libtcp/tcplib.h b/support/sdk/c/blip/libtcp/tcplib.h
new file mode 100644 (file)
index 0000000..71c235b
--- /dev/null
@@ -0,0 +1,206 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef TCPLIB_H_
+#define TCPLIB_H_
+
+/* 
+ * tcplib: a simple tcp implemented in a library
+ * @author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
+ *
+ *
+ */
+
+// #include <netinet/in.h>
+#include "ip.h"
+
+#define min(X,Y) (((X) > (Y)) ? (Y) : (X))
+#ifndef PC
+#define printf(X, args ...) dbg("stdout", X, ## args)
+#define fprintf(X, Y, args ...) dbg("fprintf", Y, ## args)
+#endif
+
+typedef enum {
+  TCP_CLOSED = 0,
+  TCP_LISTEN,
+  TCP_SYN_RCVD,
+  TCP_SYN_SENT,
+  TCP_ESTABLISHED,
+  TCP_CLOSE_WAIT,
+  TCP_LAST_ACK,
+  TCP_FIN_WAIT_1,
+  TCP_FIN_WAIT_2,
+  TCP_CLOSING,
+  TCP_TIME_WAIT,
+} tcplib_sock_state_t;
+
+enum {
+  TCP_ACKPENDING  = 0x3,
+  TCP_DUPACKS     = 0x3c,
+  TCP_DUPACKS_OFF = 2,
+  TCP_ACKSENT     = 0x80,
+};
+
+enum {
+  /* how many timer tics to stay in TIME_WAIT */
+  TCPLIB_TIMEWAIT_LEN = 1,
+  TCPLIB_2MSL = 4,
+  /* how many un-acked retransmissions before we give up the connection */
+  TCPLIB_GIVEUP = 6,
+};
+
+#define GET_ACK_COUNT(X)    (((X) & TCP_DUPACKS) >> TCP_DUPACKS_OFF)
+#define UNSET_ACK_COUNT(X)  ((X) &= ~TCP_DUPACKS)
+#define INCR_ACK_COUNT(X)   ((X) += 1 << TCP_DUPACKS_OFF)
+
+struct tcplib_sock {
+  uint8_t flags;
+  
+  /* local and remote endpoints */
+  struct sockaddr_in6 l_ep;
+  struct sockaddr_in6 r_ep;
+
+  /* current connection state */
+  tcplib_sock_state_t state;
+
+  void    *tx_buf;
+  uint16_t tx_buf_len;
+
+  /* max segment size, or default if
+     we didn't bother to pull it out
+     of the options field */
+  uint16_t mss;
+
+  uint16_t my_wind;
+  /* the window the other end is
+     reporting */
+  uint16_t r_wind;
+  uint16_t cwnd;
+  uint16_t ssthresh;
+
+  // the current next sequence number for ourgoing data.
+  uint32_t seqno;
+  // and the index of the last byte we've ACKed
+  uint32_t ackno;
+
+  struct {
+    int8_t retx;
+  } timer;
+
+  /* retransmission counter */
+  uint16_t retxcnt;
+
+  /* callbacks for this connection */
+/*   struct { */
+/*     /\* a previous connection request has finished *\/ */
+/*     void (*connect_done)(struct tcplib_sock *sock, int error); */
+
+/*     /\* a callback to signal new data is ready *\/ */
+/*     void (*recvfrom)(struct tcplib_sock *sock, void *data, int len); */
+
+/*     /\* the connection was closed by the other party *\/ */
+/*     void (*closed)(struct tcplib_sock *sock); */
+
+/*     /\* you called close(); we've finished closing the socket. *\/ */
+/*     void (*close_done)(struct tcplib_sock *sock); */
+/*   } ops; */
+
+  /* this needs to be at the end so
+     we can call init() on a socket
+     without blowing away the linked
+     list */
+  struct tcplib_sock *next;
+};
+
+/* EVENTS 
+ * ------------------------------------------------------------ 
+ *
+ * calls generated by tcplib that must be dealt with elsewhere in the
+ * program.
+ */
+
+
+/* called when a new connection request is recieved on a socket which
+ * is LISTENing.
+ *
+ *
+ * return 0 if it wants to accept the connection and allocated a
+ * buffer for it; -1 otherwise.
+ */
+struct tcplib_sock *tcplib_accept(struct tcplib_sock *conn,
+                                  struct sockaddr_in6 *from);
+
+/* a call-out point for tcplib to send a message */
+void tcplib_send_out(struct split_ip_msg *msg, struct tcp_hdr *tcph);
+
+/* upcall for new data; may be dispatched all the way out to a
+ * handler. 
+ *
+ * Returns: 0 on success,
+ * -1 otherwise.  The error may be safely ignored.
+ */
+int tcplib_process(struct ip6_hdr *ip_packet, void *payload);  
+
+/*
+ * should be called every 500ms to increment all the tcp timers
+ */
+int tcplib_timer_process();
+
+/* Just fill in the fields of the socket.
+ *
+ * If you perform a send on a socket in this state, an ephemeral port
+ * will be allocated to it.
+ *
+ * This must be called once on any socket that might be sent on, or
+ * might have bind() called.
+ */
+int tcplib_init_sock(struct tcplib_sock *sock);
+
+/* bind the socket to a local address */
+int tcplib_bind(struct tcplib_sock *sock,
+                struct sockaddr_in6 *addr);
+
+/* connect the socket to a remote endpoint */
+int tcplib_connect(struct tcplib_sock *sock,
+                   struct sockaddr_in6 *serv_addr);
+
+
+/* send data on an open socket.
+ *
+ * returns: 0 on success
+ *   other errors
+ *     - no local buffer is available,
+ *     
+ */
+int tcplib_send(struct tcplib_sock *sock,
+                 void *data, int len);
+
+int tcplib_close(struct tcplib_sock *sock);
+
+/* abort a connection 
+ *
+ * This will send a RST segment if the connection has been opened and
+ * immediately return the socket to the CLOSED, uninitialized state,
+ * although buffer pointers are maintained.
+ *
+ */
+int tcplib_abort(struct tcplib_sock *sock);
+#endif
diff --git a/support/sdk/c/blip/libtcp/test_circ.c b/support/sdk/c/blip/libtcp/test_circ.c
new file mode 100644 (file)
index 0000000..a8a6edd
--- /dev/null
@@ -0,0 +1,124 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include "circ.h"
+
+/* void do_head_read(void *buf) { */
+/*   char *read_data; */
+/*   int i, data_len; */
+/*   data_len = circ_buf_read_head(buf, (void **)&read_data); */
+/*   printf("buf_read_head: %i\n", data_len); */
+/*   for (i = 0; i < data_len; i++) */
+/*     putc(((char *)read_data)[i], stdout); */
+/*   putc('\n', stdout); */
+/* } */
+
+void do_read(void *buf, uint32_t sseqno) {
+  char data[20];
+  int data_len, i;
+  data_len = circ_buf_read(buf, sseqno, data, 20);
+
+  printf("buf_read: %i\n", data_len);
+  for (i = 0; i < data_len; i++)
+    putc(((char *)data)[i], stdout);
+  putc('\n', stdout);
+
+}
+
+int main(int argc, char **argv) {
+  char buf[200];
+  char data[20], readbuf[30];
+  int i = 20, data_len;
+  char *read_data;
+  memset(buf, 0, sizeof(buf));
+
+  if (circ_buf_init(buf, 200, 0) < 0)
+    printf("cir_buf_init: error\n");
+
+  for (i=0;i<20;i++)
+    data[i] = 'a' + i;
+
+  if (circ_buf_write(buf, 0, data, 20) < 0)
+    printf("circ_buf_write: error\n");
+
+  circ_buf_dump(buf);
+
+  if (circ_buf_write(buf, 10, data, 20) < 0)
+    printf("circ_buf_write: error\n");
+
+  circ_buf_dump(buf);
+
+
+  if (circ_buf_write(buf, 50, data, 20) < 0)
+    printf("circ_buf_write: error\n");
+
+  // circ_buf_dump(buf);
+
+  // do_head_read(buf);
+  // circ_buf_dump(buf);
+
+  if (circ_buf_write(buf, 30, data, 20) < 0)
+    printf("circ_buf_write: error\n");
+
+  // circ_buf_dump(buf);
+
+  if (circ_buf_write(buf, 70, data, 20) < 0)
+    printf("circ_buf_write: error\n");
+
+  circ_buf_dump(buf);
+
+  circ_shorten_head(buf, 10);
+  circ_buf_dump(buf);
+
+  memset(buf, 0, sizeof(buf));
+
+  if (circ_buf_init(buf, 200, 0) < 0)
+    printf("cir_buf_init: error\n");
+
+  printf("\n\nRESTART\n\n");
+  
+  for (i = 0; i < 25; i++) {
+    circ_buf_write(buf, i * 20, data, 20);
+    do_read(buf, i * 20);
+    circ_shorten_head(buf, (i > 0) ? (i - 1) * 20 : 0 * 10);
+    circ_buf_dump(buf);
+  }
+
+  // do_read(buf, 50);
+
+/*   do_head_read(buf); */
+/*   circ_buf_dump(buf); */
+
+/*   if (circ_buf_write(buf, 90, data, 20) < 0) */
+/*     printf("circ_buf_write: error\n"); */
+/*   if (circ_buf_write(buf, 110, data, 20) < 0) */
+/*     printf("circ_buf_write: error\n"); */
+/*   if (circ_buf_write(buf, 130, data, 20) < 0) */
+/*     printf("circ_buf_write: error\n"); */
+
+/*   circ_buf_dump(buf); */
+/*   do_head_read(buf); */
+/*   do_head_read(buf); */
+/*   circ_buf_dump(buf); */
+}
diff --git a/support/sdk/c/blip/libtcp/test_server.c b/support/sdk/c/blip/libtcp/test_server.c
new file mode 100644 (file)
index 0000000..418d164
--- /dev/null
@@ -0,0 +1,225 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <linux/if.h>
+#include <signal.h>
+#include <string.h>
+#include <limits.h>
+
+
+#include "ip.h"
+#include "tcplib.h"
+#include "tun_dev.h"
+#include "ip_malloc.h"
+
+
+#define BUFSZ 1000
+#define LOSS_RATE_RECPR 200
+#define LOSS_RATE_TRANS 200
+
+int sock = 0;
+struct in6_addr iface_addr[16] = {{{0x20, 0x05, 0x00, 0x00, 0x00, 0x0, 0x00, 0x00,
+                                    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}};
+struct sockaddr_in6 laddr;
+
+
+void printBuf(uint8_t *buf, uint16_t len) {
+  int i;
+  // print("len: %i: ", len);
+  for (i = 1; i <= len; i++) {
+    printf(" 0x%02x", buf[i-1]);
+    // if (i % 16 == 0) printf("\n");
+  }
+  printf("\n");
+}
+
+void print_split_msg(struct split_ip_msg *msg) {
+  int i;
+  printf("src_addr: ");
+  for (i = 0; i < 16; i++) printf("0x%x ", msg->hdr.ip6_src.s6_addr[i]);
+  printf("\ndst_addr: ");
+  for (i = 0; i < 16; i++) printf("0x%x ", msg->hdr.ip6_dst.s6_addr[i]);
+  printf("\nplen: %i hlim: %i\n", ntohs(msg->hdr.plen), msg->hdr.hlim);
+
+  printBuf(msg->data, msg->data_len);
+}
+
+void tcplib_extern_recv(struct tcplib_sock *sock, void *data, int len) {
+  // printBuf(data, len);
+  if (tcplib_send(sock, data, len) < 0)
+    printf("tcplib_send: fail\n");
+
+  if (strncmp((char *)data, "close", 5) == 0) {
+    printf("Server closing sock\n");
+    tcplib_close(sock);
+  }
+}
+
+void tcplib_extern_closed(struct tcplib_sock *sock) {
+  printf("remote conn closed\n");
+  tcplib_close(sock);
+}
+
+void tcplib_extern_closedone(struct tcplib_sock *sock) {
+  printf("close done\n");
+  free(sock->tx_buf);
+  tcplib_init_sock(sock);
+/*   printf("rebinding...\n"); */
+}
+
+/* called when a new connection request is received: not 
+ *
+ * return: a tcplib_struc, with the ops table filled in and send and
+ * receive buffers allocated.
+ */
+
+struct tcplib_sock *tcplib_accept(struct tcplib_sock *conn,
+                                  struct sockaddr_in6 *from) {
+  printf("tcplib_accept\n");
+  
+  conn->tx_buf = malloc(BUFSZ);
+  conn->tx_buf_len = BUFSZ;
+
+
+  return conn;
+}
+
+void tcplib_send_out(struct split_ip_msg *msg, struct tcp_hdr *tcph) {
+  uint8_t buf[8192];
+  struct timespec tv;
+  if (sock <= 0) return;
+
+  // printf("sending message\n");
+
+  memcpy(msg->hdr.ip6_src.s6_addr, iface_addr, 16);
+  msg->hdr.ip6_src.s6_addr[15] = 2;
+  msg->hdr.hlim = 64;
+
+  memset(msg->hdr.vlfc, 0, 4);
+  msg->hdr.vlfc[0] = 6 << 4;
+
+  tcph->chksum = htons(msg_cksum(msg, IANA_TCP));
+  
+  tv.tv_sec = 0;
+  // sleep for a ms to give up the cpu...
+  tv.tv_nsec = 1000000;
+  nanosleep(&tv);
+
+  // print_split_msg(msg);
+  if (rand() % LOSS_RATE_TRANS == 0) {
+    printf("dropping packet on write\n");
+  } else {
+    printf("tun_write\n");
+    tun_write(sock, msg);
+  }
+}
+
+/* practice accepting connections and transfering data */
+int main(int argg, char **argv) {
+  char buf[8192], dev[IFNAMSIZ];
+  uint8_t *payload;
+  int len, i, flags;
+
+  ip_malloc_init();
+
+  payload = buf + sizeof(struct tun_pi);
+  dev[0] = 0;
+  if ((sock = tun_open(dev)) < 0) 
+    exit(1);
+
+  if (tun_setup(dev, iface_addr) < 0)
+    exit(1);
+
+  /* tun_setup turns on non-blocking IO.  Turn it off. */
+  flags = fcntl(sock, F_GETFL);
+  flags &= ~O_NONBLOCK;
+  fcntl(sock,F_SETFL, flags);
+
+  struct tcplib_sock srv_sock;
+  tcplib_init_sock(&srv_sock);
+  memcpy(laddr.sin6_addr.s6_addr, iface_addr, 16);
+  laddr.sin6_addr.s6_addr[15] = 2;
+  laddr.sin6_port = htons(atoi(argv[1]));
+
+  tcplib_bind(&srv_sock, &laddr);
+
+  fd_set fds;
+  struct timeval timeout;
+  FD_ZERO(&fds);
+  FD_SET(sock, &fds);
+  FD_SET(fileno(stdin), &fds);
+
+  timeout.tv_sec = 0;
+  timeout.tv_usec = 500000;
+
+  while (select(sock + 1, &fds, NULL, NULL, &timeout) >= 0) {
+    if (FD_ISSET(sock, &fds)) {
+      if ((len = read(sock, buf, 8192)) <= 0) break;
+      // printf("read %i bytes\n", len);
+      struct ip6_hdr *iph = (struct ip6_hdr *)payload;
+      if (iph->nxt_hdr == IANA_TCP) {
+        if (rand() % LOSS_RATE_RECPR == 0) {
+          printf("dropping packet on rx\n");
+        } else {
+          void *p = buf + sizeof(struct tun_pi) + sizeof(struct ip6_hdr);
+          // printBuf(p, len - sizeof(struct tun_pi) - sizeof(struct tcp_hdr));
+          if (tcplib_process(iph, p)) // len - sizeof(struct tun_pi)))
+            printf("TCPLIB_PROCESS: ERROR!\n");
+        }
+      }
+    } else if (FD_ISSET(fileno(stdin), &fds)) {
+      char c = getchar();
+      switch (c) {
+      case 'a':
+        printf("ABORTING CONNETION\n");
+        tcplib_abort(&srv_sock);
+        break;
+      case 'c':
+        printf("CLOSING CONNETION\n");
+        tcplib_close(&srv_sock);
+        break;
+      case 's':
+        printf("connection state: %i\n", srv_sock.state);
+        break;
+      }
+    } else {
+      timeout.tv_sec = 0;
+      timeout.tv_usec = 500000;
+      tcplib_timer_process();
+    }
+    if (srv_sock.state == TCP_CLOSED) {
+      tcplib_bind(&srv_sock, &laddr);
+    }
+
+    FD_ZERO(&fds);
+    FD_SET(sock, &fds);
+    FD_SET(fileno(stdin), &fds);
+  }
+  tun_close(sock, dev);
+}
diff --git a/support/sdk/c/blip/serial_tun.conf b/support/sdk/c/blip/serial_tun.conf
new file mode 100644 (file)
index 0000000..db5cc17
--- /dev/null
@@ -0,0 +1,22 @@
+
+# Before you can run the adaptation layer and router, you must
+# configure the address your router will advertise to the subnet, and
+# which network interface to proxy neighbor advertisements on.  
+#
+
+# set the debug level of the output
+# choices are DEBUG, INFO, WARN, ERROR, and FATAL
+# log DEBUG
+
+# set the address of the router's 802.15.4 interface.  The interface
+# ID must be a 16-bit short identifier.
+addr fec0::64
+
+# the router can proxy neighbor IPv6 neighbor discovery on another
+# interface so that other machines on the subnet can discover hosts
+# routing through this router.  This specifies which interface to proxy
+# the NDP on.
+proxy lo #eth1
+
+# which 802.15.4 channel to operate on.  valid choices are 11-26.
+channel 15
index b26b8059285429e77197773bcfe4ed91a328de77..eb8adc035a3a3ebeb1227e138943848fc7d4c747 100644 (file)
@@ -1,5 +1,6 @@
 AUTOMAKE_OPTIONS = foreign
 
+MIGFLAGS = -D_POSIX_C_SOURCE
 TOS=$(shell ncc -print-tosdir)
 SERIAL_H = $(TOS)/lib/serial/Serial.h
 
@@ -34,7 +35,7 @@ libmote_a_SOURCES = \
        sfsource.c
 
 serialpacket.c serialpacket.h: $(SERIAL_H)
-       mig -o serialpacket.h -c-prefix=spacket c $(SERIAL_H) serial_packet
+       mig -o serialpacket.h -c-prefix=spacket c $(SERIAL_H) serial_packet $(MIGFLAGS)
 
 serialprotocol.h: $(SERIAL_H)
-       ncg -o $@ -c-prefix=SERIAL c $(SERIAL_H) Serial.h
+       ncg -o $@ -c-prefix=SERIAL c $(SERIAL_H) Serial.h $(MIGFLAGS)
index 9739c15a6440e4a3b2b3cd6a2356e596a00e1ef1..9aa0c32e040c1707305520322077f572158da59a 100644 (file)
@@ -36,6 +36,14 @@ void free_tmsg(tmsg_t *msg)
     free(msg);
 }
 
+void reset_tmsg(tmsg_t *msg, void *packet, size_t len)
+{
+  if (!msg)
+    return;
+  msg->data = packet;
+  msg->len  = len;
+}
+
 void *tmsg_data(tmsg_t *msg)
 {
   return msg->data;
index 8655f7b390957c1a731967e4eea80fbaa834852f..d1acc5c699e8e43743fbb653e1f59fea84911710 100644 (file)
@@ -43,6 +43,11 @@ tmsg_t *new_tmsg(void *packet, size_t len);
  */
 void free_tmsg(tmsg_t *msg);
 
+/** 
+ * Reuse an existing tmsg
+ */
+void reset_tmsg(tmsg_t *msg, void *packet, size_t len) ;
+
 /**
  * Return underlying array of a message buffer
  */
index 0ddde0f8a70f94b3e4c2b17a93ea31aba11eaf64..dd8c78a8ddbdb3415f1fac468d5e332cec8885d7 100644 (file)
@@ -1,3 +1,9 @@
+#if defined(_WIN32) && !defined(__CYGWIN__)
+/* Avoid confusing windows w/o cygwin w/ cygwin */
+#define LOSE32
+#endif
+
+#ifndef LOSE32
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <termios.h>
 #else
 #include <stdint.h>
 #endif
+#endif
+
+#ifdef LOSE32
+#include <windows.h>
+#include <stdint.h>
+#endif
 
 /* C implementation of the mote serial protocol. See
    net.tinyos.packet.Packetizer for more details */
@@ -28,12 +40,14 @@ typedef int bool;
 
 enum {
 #ifndef __CYGWIN__
+#ifndef LOSE32
   FALSE = 0,
   TRUE = 1,
+#endif
 #endif
   BUFSIZE = 256,
   MTU = 256,
-  ACK_TIMEOUT = 1000000, /* in us */
+  ACK_TIMEOUT = 100000, /* in us */
   SYNC_BYTE = SERIAL_HDLC_FLAG_BYTE,
   ESCAPE_BYTE = SERIAL_HDLC_CTLESC_BYTE,
 
@@ -50,8 +64,12 @@ struct packet_list
   struct packet_list *next;
 };
 
-struct serial_source {
+struct serial_source_t {
+#ifndef LOSE32
   int fd;
+#else
+  HANDLE hComm;
+#endif
   bool non_blocking;
   void (*message)(serial_source_msg problem);
 
@@ -72,6 +90,7 @@ struct serial_source {
   } send;
 };
 
+#ifndef LOSE32
 static tcflag_t parse_baudrate(int requested)
 {
   int baudrate;
@@ -173,6 +192,7 @@ static tcflag_t parse_baudrate(int requested)
     }
   return baudrate;
 }
+#endif
 
 #ifdef DEBUG
 static void dump(const char *msg, unsigned char *packet, int len)
@@ -194,6 +214,7 @@ static void message(serial_source src, serial_source_msg msg)
 
 static int serial_read(serial_source src, int non_blocking, void *buffer, int n)
 {
+#ifndef LOSE32
   fd_set fds;
   int cnt;
 
@@ -225,6 +246,30 @@ static int serial_read(serial_source src, int non_blocking, void *buffer, int n)
        if (cnt != 0)
          return cnt;
       }
+#else // LOSE32
+  int cnt;
+
+  if (non_blocking) {
+    ReadFile(src->hComm, buffer, n, &cnt, NULL);
+
+    return cnt;
+
+  } else {
+      for (;;) {
+          DWORD eventMask;
+          SetCommMask(src->hComm, EV_RXCHAR);
+          if (!WaitCommEvent(src->hComm, &eventMask, NULL)) {
+              return -1;
+          }
+
+          ReadFile(src->hComm, buffer, n, &cnt, NULL);
+
+          if (cnt != 0) {
+            return cnt;
+          }
+      }
+  }
+#endif
 }
 
 serial_source open_serial_source(const char *device, int baud_rate,
@@ -237,6 +282,7 @@ serial_source open_serial_source(const char *device, int baud_rate,
      NULL for failure (bad device or bad baud rate)
  */
 {
+#ifndef LOSE32
   struct termios newtio;
   int fd;
   tcflag_t baudflag = parse_baudrate(baud_rate);
@@ -288,8 +334,52 @@ serial_source open_serial_source(const char *device, int baud_rate,
   close(fd);
 
   return NULL;
+#else // LOSE32
+       LPCTSTR       ComName = (LPCTSTR)device;
+    HANDLE        hComm;
+       DCB           dcb;
+    serial_source src;
+
+       int buflen = MultiByteToWideChar(CP_ACP,0,(PCSTR)device,-1,(LPWSTR)ComName,0);
+       MultiByteToWideChar(CP_ACP,0,(PCSTR)device,-1,(LPWSTR)ComName,buflen);
+       
+       //syncronize
+       hComm = CreateFile(ComName,  GENERIC_READ | GENERIC_WRITE,  0,  NULL,  OPEN_EXISTING,
+                                       FILE_ATTRIBUTE_NORMAL, NULL);
+
+    if (hComm == INVALID_HANDLE_VALUE) {
+        return NULL;
+    }
+
+    PurgeComm(hComm, PURGE_RXCLEAR);
+
+       GetCommState(hComm, &dcb); 
+       dcb.BaudRate = baud_rate;
+       dcb.ByteSize = 8;
+       dcb.Parity = NOPARITY;
+       dcb.fParity = FALSE;
+       dcb.StopBits = ONESTOPBIT;
+    if (SetCommState(hComm, &dcb) == 0) {
+        return NULL;
+    }
+
+    src = malloc(sizeof *src);
+
+    if (src) {
+         memset(src, 0, sizeof *src);
+         src->hComm = hComm;
+         src->non_blocking = non_blocking;
+         src->message = message;
+         src->send.seqno = 37;
+
+       }
+
+       return src;
+
+#endif // LOSE32
 }
 
+#ifndef LOSE32
 int serial_source_fd(serial_source src)
 /* Returns: the file descriptor used by serial source src (useful when
      non-blocking reads were requested)
@@ -297,6 +387,17 @@ int serial_source_fd(serial_source src)
 {
   return src->fd;
 }
+#endif
+
+#ifdef LOSE32
+HANDLE serial_source_handle(serial_source src)
+/* Returns: the file descriptor used by serial source src (useful when
+     non-blocking reads were requested)
+*/
+{
+  return src->hComm;
+}
+#endif
 
 int close_serial_source(serial_source src)
 /* Effects: closes serial source src
@@ -304,7 +405,11 @@ int close_serial_source(serial_source src)
      considered closed anyway)
  */
 {
+#ifndef LOSE32
   int ok = close(src->fd);
+#else
+  int ok = CloseHandle(src->hComm);
+#endif
 
   free(src);
 
@@ -317,6 +422,7 @@ static int source_wait(serial_source src, struct timeval *deadline)
    Returns: 0 if data is available, -1 if the deadline expires
 */
 {
+#ifndef LOSE32
   struct timeval tv;
   fd_set fds;
   int cnt;
@@ -354,10 +460,23 @@ static int source_wait(serial_source src, struct timeval *deadline)
        return -1;
       return 0;
     }
+#else // LOSE32
+    // FIXME: the deadline is ignored here
+
+    DWORD eventMask;
+    SetCommMask(src->hComm, EV_RXCHAR);
+    if (!WaitCommEvent(src->hComm, &eventMask, NULL)) {
+        return -1;
+    }
+
+    return 0;
+
+#endif
 }
 
 static int source_write(serial_source src, const void *buffer, int count)
 {
+#ifndef LOSE32
   int actual = 0;
 
   if (fcntl(src->fd, F_SETFL, 0) < 0)
@@ -388,6 +507,25 @@ static int source_write(serial_source src, const void *buffer, int count)
       /* We're in trouble, but there's no obvious fix. */
     }
   return actual;
+#else // LOSE32
+    int actual = 0;
+    int n;
+    const unsigned char * b = buffer;
+
+    while (count > 0) {
+      if (!WriteFile(src->hComm, b, count, &n, NULL)) {
+             message(src, msg_unix_error);
+          actual = -1;
+          break;
+      }
+
+      count  -= n;
+      actual += n;
+      b      += n;
+    }
+
+    return actual;
+#endif
 }
 
 static void push_protocol_packet(serial_source src,
@@ -494,11 +632,13 @@ static int read_byte(serial_source src, int non_blocking)
              src->recv.bufused = n;
              break;
            }
+#ifndef LOSE32
          if (errno == EAGAIN)
            return -1;
          if (errno != EINTR)
            message(src, msg_unix_error);
-       }
+#endif
+    }
     }
   //printf("in %02x\n", src->recv.buffer[src->recv.bufpos]);
   return src->recv.buffer[src->recv.bufpos++];
@@ -758,8 +898,13 @@ int write_serial_packet(serial_source src, const void *packet, int len)
   if (write_framed_packet(src, P_PACKET_ACK, src->send.seqno, packet, len) < 0)
     return -1;
 
+  // FIXME: the WIN32 implementation of source_wait()
+  //        disregards the deadline parameter anyway
+#ifndef LOSE32
   gettimeofday(&deadline, NULL);
   add_timeval(&deadline, ACK_TIMEOUT);
+#endif
+
   for (;;) 
     {
       struct packet_list *entry;
index 28ba5bdc6ccfde284a82729d3e835b1b790754be..8fa232bd071a961c2431d99a840cf45eb44a7264 100644 (file)
@@ -1,11 +1,15 @@
 #ifndef SERIALSOURCE_H
 #define SERIALSOURCE_H
 
+#ifdef _WIN32
+#include <windows.h>
+#endif
+
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-typedef struct serial_source *serial_source;
+typedef struct serial_source_t *serial_source;
 
 typedef enum {
   msg_unknown_packet_type,     /* packet of unknown type received */
@@ -32,10 +36,19 @@ serial_source open_serial_source(const char *device, int baud_rate,
      NULL for failure
  */
 
+#ifndef _WIN32
 int serial_source_fd(serial_source src);
 /* Returns: the file descriptor used by serial source src (useful when
      non-blocking reads were requested)
 */
+#endif
+
+#ifdef _WIN32
+HANDLE serial_source_handle(serial_source src);
+/* Returns: the file descriptor used by serial source src (useful when
+     non-blocking reads were requested)
+*/
+#endif
 
 int serial_source_empty(serial_source src);
 /* Returns: true if serial source does not contain any pending data, i.e.,
index ada9bc5b4613ba2eec63f5742d452f1fe54c9f2b..f26fe8100298b800e684398581a074d7db9db5ae 100644 (file)
@@ -1,5 +1,6 @@
 #include <sys/types.h>
 #include <sys/socket.h>
+#include <sys/select.h>
 #include <netinet/in.h>
 #include <netdb.h>
 #include <errno.h>
index 24df9603acc33581dea43bc61c3e60a2169a29c3..ecde05c65bbb0e65c4b043f6e414e7ed578700d8 100644 (file)
@@ -70,7 +70,7 @@ int open_sf_source(const char *host, int port)
     }      
 
   addr.sin_family = entry->h_addrtype;
-  memcpy(&addr.sin_addr, entry->h_addr, entry->h_length);
+  memcpy(&addr.sin_addr, entry->h_addr_list[0], entry->h_length);
   addr.sin_port = htons(port);
   if (connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0)
     {
index 4479e18f6ebdb16a0c65681d9c8c2592094c94f5..a5869f1c6a0cd99dfedaf5076fdab60d02f96c07 100644 (file)
@@ -35,6 +35,7 @@
 
 #include <ctime>
 #include <cstdlib>
+#include <cstring>
 #include <iostream>
 #include <fcntl.h>
 #include <termios.h>
@@ -42,6 +43,7 @@
 #include <sstream>
 #include <sys/time.h>
 #include <errno.h>
+#include <stdint.h>
 
 using namespace std;
 
@@ -275,11 +277,11 @@ SerialComm::SerialComm(const char* pDevice, int pBaudrate, PacketBuffer &pReadBu
     newtio.c_oflag = 0;
 
     if ((tcflush(serialReadFD, TCIFLUSH) >= 0 && tcsetattr(serialReadFD, TCSANOW, &newtio) >= 0)
-            && (tcflush(serialWriteFD, TCIFLUSH) >= 0 && tcsetattr(serialWriteFD, TCSANOW, &newtio) >= 0)
-            && !errorReported)
+        && (tcflush(serialWriteFD, TCIFLUSH) >= 0 && tcsetattr(serialWriteFD, TCSANOW, &newtio) >= 0)
+        && !errorReported)
     {
         DEBUG("SerialComm::SerialComm : opened device "<< pDevice << " with baudrate = " << pBaudrate)
-    }
+            }
     else
     {
         close(serialReadFD);
@@ -337,12 +339,12 @@ int SerialComm::writeFD(int fd, const char *buffer, int count, int *err)
 {
     int cnt = 0;
     /*
-    FD_SET(serialWriteFD, &wfds);
-    if(select(serialWriteFD + 1, NULL, &wfds, NULL, NULL) < 0) {
-        return -1;
-    }
-    FD_CLR(serialWriteFD, &wfds);
-     */
+      FD_SET(serialWriteFD, &wfds);
+      if(select(serialWriteFD + 1, NULL, &wfds, NULL, NULL) < 0) {
+      return -1;
+      }
+      FD_CLR(serialWriteFD, &wfds);
+    */
     int tmpCnt = BaseComm::writeFD(fd, buffer, count, err);
     if (tmpCnt < 0) {
         *err = errno;
@@ -414,145 +416,91 @@ char SerialComm::nextRaw() {
 /* reads packet */
 bool SerialComm::readPacket(SFPacket &pPacket)
 {
-    bool sync = false;
-    bool escape = false;
-    bool completePacket = false;
+    uint8_t buffer[maxMTU + 10];
     int count = 0;
-    uint16_t crc = 0;
-    char buffer[maxMTU];
-    while(!completePacket)
-    {
-        buffer[count] = nextRaw();
-
-        if(sync && (count == 1) && (buffer[count] == SYNC_BYTE)) {
-            DEBUG("SerialComm::readPacket double sync byte");
-            sync = false;
-            escape = false;
-            count = 1;
-            crc = 0;
-            buffer[0] = SYNC_BYTE;
-        }
-        
-        if (!sync)
-        {
-            // wait for sync
-            if (buffer[0] == SYNC_BYTE)
-            {
-                sync = true;
-                escape = false;
-                count = 1;
-                crc = 0;
+    rx_states_t state = WAIT_FOR_SYNC;
+    for(;;) {
+        uint8_t nextByte = nextRaw();
+        if(state == WAIT_FOR_SYNC) {
+            if(nextByte == SYNC_BYTE) {
+                count = 0;
+                state = IN_SYNC;
             }
         }
-        else if (count >= maxMTU)
-        {
-            DEBUG("SerialComm::readPacket : frame too long - size = " << count << " : resynchronising")
-            sync = false;
-            escape = false;
-            count = crc = 0;
-           badPacketCount++;
-        }
-        else if (escape)
-        {
-            if (buffer[count] == SYNC_BYTE)
-            {
-                DEBUG("SerialComm::readPacket : resynchronising")
-                sync = false;
-                escape = false;
-                count = crc = 0;
-               badPacketCount++;
-            }
-            else
-            {
-                buffer[count] ^= 0x20;
-                if (count > 3)
-                {
-                    crc = SerialComm::byteCRC(buffer[count-3], crc);
+        else if(state == IN_SYNC) {
+            if(nextByte == SYNC_BYTE) {
+                if(count < minMTU) {
+                    DEBUG("SerialComm::readPacket : frame too short - size = " << count << " : resynchronising ");
+                    badPacketCount++; 
+                    count = 0;
+                }
+                else {
+                    bool dobreak = true;
+                    DEBUG("SerialComm::readPacket : frame size = " << count);
+                    if(checkCrc(buffer, count)) {
+                        pPacket.setType(buffer[typeOffset]);
+                        pPacket.setSeqno(buffer[seqnoOffset]);
+                        switch (buffer[typeOffset]) {
+                        case SF_ACK:
+                            break;
+                        case SF_PACKET_NO_ACK:
+                            pPacket.setPayload((char *)(&buffer[payloadOffset]-1), count+1+1 - serialHeaderBytes);
+                            break;
+                        case SF_PACKET_ACK:
+                            pPacket.setPayload((char *)(&buffer[payloadOffset]), count+1 - serialHeaderBytes);
+                            break;
+                        default:
+                            dobreak = false;
+                            DEBUG("SerialComm::readPacket : unknown packet type = " \
+                                  << static_cast<uint16_t>(buffer[typeOffset] & 0xff));
+                            break;
+                        }
+                        if(dobreak) break; // leave loop
+                    }
+                    else {
+                        DEBUG("SerialComm::readPacket : bad crc");
+                        count = 0;
+                        badPacketCount++;
+                    }
                 }
-                ++count;
-                escape = false;
             }
-        }
-        else if (buffer[count] == ESCAPE_BYTE)
-        {
-            // next byte is escaped
-            escape = true;
-        }
-        else if (buffer[count] == SYNC_BYTE)
-        {
-            // calculate last crc byte
-            if (count > 3)
-            {
-                crc = SerialComm::byteCRC(buffer[count-3], crc);
+            else if(nextByte == ESCAPE_BYTE) {
+                state = ESCAPED;
             }
-            uint16_t packetCRC = (buffer[count - 2] & 0xff) | ((buffer[count - 1] << 8) & 0xff00);
-            if (count < minMTU)
-            {
-                DEBUG("SerialComm::readPacket : frame too short - size = " << count << " : resynchronising ")
-                sync = false;
-                escape = false;
-                count = crc = 0;
-               badPacketCount++;
+            else {
+                buffer[count++] = nextByte;
+                if(count >= maxMTU) {
+                    DEBUG("SerialComm::readPacket : packet too long, resynchronizing");
+                    count = 0;
+                    badPacketCount++;
+                    state = WAIT_FOR_SYNC;
+                }
             }
-            else if (crc != packetCRC)
-            {
-                DEBUG("SerialComm::readPacket : bad crc - calculated crc = " << crc << " packet crc = " << packetCRC << " : resynchronising " )
-                sync = false;
-                escape = false;
-                count = crc = 0;
-               badPacketCount++;
+        }
+        else if(state == ESCAPED) {
+            if(nextByte == SYNC_BYTE) {
+                DEBUG("SerialComm::readPacket : state ESCAPED, packet got sync byte, resynchronizing");
+                count = 0;
+                badPacketCount++;
+                state = IN_SYNC;
             }
-            else
-            {
-                pPacket.setType(buffer[typeOffset]);
-                pPacket.setSeqno(buffer[seqnoOffset]);
-                switch (buffer[typeOffset])
-                {
-                case SF_ACK:
-                    break;
-                case SF_PACKET_NO_ACK:
-                case SF_PACKET_ACK:
-                    // buffer / payload
-                    // FIXME: strange packet format!? because seqno is not really defined - missing :(
-                    pPacket.setPayload(&buffer[payloadOffset]-1, count+1+1 - serialHeaderBytes);
-                    break;
-                default:
-                    DEBUG("SerialComm::readPacket : unknown packet type = " << static_cast<uint16_t>(buffer[typeOffset] & 0xff))
-                    ;
+            else {
+                buffer[count++] = nextByte ^ 0x20;
+                if(count >= maxMTU) {
+                    DEBUG("SerialComm::readPacket : state ESCAPED, packet too long, resynchronizing");
+                    count = 0;
+                    badPacketCount++;
+                    state = WAIT_FOR_SYNC;
                 }
-                completePacket = true;
-#ifdef DEBUG_RAW_SERIALCOMM
-
-                DEBUG("SerialComm::readPacket : raw data >>")
-                for (int j=0; j <= count; j++)
-                {
-                    cout << std::hex << static_cast<uint16_t>(buffer[j] & 0xff) << " " << std::dec;
-                }
-                cout << endl;
-                cout << "as payload >> " << endl;
-                const char* ptr = pPacket.getPayload();
-                for (int j=0; j < pPacket.getLength(); j++)
-                {
-                    cout << std::hex << static_cast<uint16_t>(ptr[j] & 0xff) << " " << std::dec;
+                else {
+                    state = IN_SYNC;
                 }
-                cout << endl;
-#endif
-
             }
         }
-        else
-        {
-            if (count > 3)
-            {
-                crc = SerialComm::byteCRC(buffer[count-3], crc);
-            }
-            ++count;
-        }
     }
     return true;
 }
 
-
 /* writes packet */
 bool SerialComm::writePacket(SFPacket &pPacket)
 {
@@ -643,37 +591,37 @@ void SerialComm::readSerial()
         SFPacket packet;
         readPacket(packet);
         switch (packet.getType())
-        {
-        case SF_ACK:
+       {
+       case SF_ACK:
             // successful delivery
             // FIXME: seqnos are not implemented on the node !
             pthread_cond_signal(&ack.received);
             break;
-        case SF_PACKET_ACK:
-            {
-                // put ack in front of queue
-                SFPacket ack(SF_ACK, packet.getSeqno());
-                writeBuffer.enqueueFront(ack);
-            }
-        case SF_PACKET_NO_ACK:
+       case SF_PACKET_ACK:
+        {
+           // put ack in front of queue
+           SFPacket ack(SF_ACK, packet.getSeqno());
+           writeBuffer.enqueueFront(ack);
+        }
+       case SF_PACKET_NO_ACK:
             // do nothing - fall through
-        default:
+       default:
             if (!readBuffer.isFull())
-            {
+           {
                 ++readPacketCount;
                 // put silently into buffer...
                 readBuffer.enqueueBack(packet);
-            }
+           }
             else
-            {
+           {
                 while(readBuffer.isFull()) {
                     readBuffer.dequeue();
                     ++droppedReadPacketCount;
                 }
                 readBuffer.enqueueBack(packet);
                 // DEBUG("SerialComm::readSerial : dropped packet")
-            }
-        }
+           }
+       }
     }
 }
 
@@ -695,33 +643,34 @@ void SerialComm::writeSerial()
     while (true)
     {
         if (!retry)
-        {
+       {
+            cerr << " serial deqeue packet, empty: " << writeBuffer.isEmpty() << endl;
             packet = writeBuffer.dequeue();
-        }
+       }
         switch (packet.getType())
-        {
-        case SF_ACK:
+       {
+       case SF_ACK:
             // successful delivery
             if (!writePacket(packet))
-            {
+           {
                 DEBUG("SerialComm::writeSerial : writePacket failed (SF_ACK)")
-                reportError("SerialComm::writeSerial : writePacket(SF_ACK)", -1);
-            }
+                    reportError("SerialComm::writeSerial : writePacket(SF_ACK)", -1);
+           }
             break;
-        case SF_PACKET_ACK:
+       case SF_PACKET_ACK:
             // do nothing - fall through
-        case SF_PACKET_NO_ACK:
+       case SF_PACKET_NO_ACK:
             // do nothing - fall through
-        default:
+       default:
             if (!retry)
                 ++writtenPacketCount;
             // FIXME: this is the only currently supported type by the mote
             packet.setType(SF_PACKET_ACK);
             if (!writePacket(packet))
-            {
+           {
                 DEBUG("SerialComm::writeSerial : writePacket failed (SF_PACKET)")
-                reportError("SerialComm::writeSerial : writeFD(SF_PACKET)", -1);
-            }
+                    reportError("SerialComm::writeSerial : writeFD(SF_PACKET)", -1);
+           }
             // wait for ack...
             struct timeval currentTime;
             struct timespec ackTime;
@@ -734,24 +683,24 @@ void SerialComm::writeSerial()
             ackTime.tv_sec = currentTime.tv_sec;
             ackTime.tv_nsec = currentTime.tv_usec * 1000;
 
-           ackTime.tv_sec  +=  timeout / (1000*1000*1000);
-           ackTime.tv_nsec += timeout % (1000*1000*1000);
+            ackTime.tv_sec  +=  timeout / (1000*1000*1000);
+            ackTime.tv_nsec += timeout % (1000*1000*1000);
 
             pthread_cleanup_push((void(*)(void*)) pthread_mutex_unlock, (void *) &ack.lock);
             int retval = pthread_cond_timedwait(&ack.received, &ack.lock, &ackTime);
             if (!((retryCount < maxRetries) && (retval == ETIMEDOUT)))
-            {
-               if (retryCount >= maxRetries) ++droppedWritePacketCount;
+           {
+                if (retryCount >= maxRetries) ++droppedWritePacketCount;
                 retry = false;
                 retryCount = 0;
-            }
+           }
             else
-            {
+           {
                 ++retryCount;
                 retry = true;
                 DEBUG("SerialComm::writeSerial : packet retryCount = " << retryCount);
-               ++sumRetries;
-            }
+                ++sumRetries;
+           }
             // removes the cleanup handler and executes it (unlock mutex)
             pthread_cleanup_pop(1);         }
     }
@@ -764,51 +713,51 @@ void SerialComm::cancel()
     if(readerThreadRunning && pthread_equal(callingThread, readerThread))
     {
         DEBUG("SerialComm::cancel : by readerThread")
-        pthread_detach(readerThread);
+            pthread_detach(readerThread);
         if (writerThreadRunning)
-        {
+       {
             pthread_cancel(writerThread);
             DEBUG("SerialComm::cancel : writerThread canceled, joining")
-            pthread_join(writerThread, NULL);
+                pthread_join(writerThread, NULL);
             writerThreadRunning = false;
-        }
+       }
         readerThreadRunning = false;
-       pthread_cond_signal(&control.cancel);
+        pthread_cond_signal(&control.cancel);
         pthread_exit(NULL);
     }
     else if(writerThreadRunning && pthread_equal(callingThread, writerThread))
     {
         DEBUG("SerialComm::cancel : by writerThread")
-        pthread_detach(writerThread);
+            pthread_detach(writerThread);
         if (readerThreadRunning)
-        {
+       {
             pthread_cancel(readerThread);
             DEBUG("SerialComm::cancel : readerThread canceled, joining")
-            pthread_join(readerThread, NULL);
+                pthread_join(readerThread, NULL);
             readerThreadRunning = false;
-        }
+       }
         writerThreadRunning = false;
-       pthread_cond_signal(&control.cancel);
+        pthread_cond_signal(&control.cancel);
         pthread_exit(NULL);
     }
     else
     {
         DEBUG("SerialComm::cancel : by other thread")
-        if (readerThreadRunning)
-        {
-            pthread_cancel(readerThread);
-            DEBUG("SerialComm::cancel : readerThread canceled, joining")
-            pthread_join(readerThread, NULL);
-            readerThreadRunning = false;
-        }
+            if (readerThreadRunning)
+            {
+                pthread_cancel(readerThread);
+                DEBUG("SerialComm::cancel : readerThread canceled, joining")
+                    pthread_join(readerThread, NULL);
+                readerThreadRunning = false;
+            }
         if (writerThreadRunning)
-        {
+       {
             pthread_cancel(writerThread);
             DEBUG("SerialComm::cancel : writerThread canceled, joining")
-            pthread_join(writerThread, NULL);
+                pthread_join(writerThread, NULL);
             writerThreadRunning = false;
-        }
-       pthread_cond_signal(&control.cancel);
+       }
+        pthread_cond_signal(&control.cancel);
     }
 }
 
@@ -818,10 +767,10 @@ int SerialComm::reportError(const char *msg, int result)
     if ((result < 0) && (!errorReported))
     {
         errorMsg << "error : SF-Server ( SerialComm on device = " << device << " ) : "
-        << msg << " ( result = " << result << " )" << endl
-        << "error-description : " << strerror(errno) << endl;
+                 << msg << " ( result = " << result << " )" << endl
+                 << "error-description : " << strerror(errno) << endl;
 
-       cerr << errorMsg.str();
+        cerr << errorMsg.str();
         errorReported = true;
         cancel();
     }
index 974984775d031369031d66190970a37242c32fc9..af2a57cf64c2aae51c91702b7e438a809e242b55 100644 (file)
@@ -38,6 +38,7 @@
 #include "packetbuffer.h"
 #include "sharedinfo.h"
 
+#include <sys/select.h>
 #include <pthread.h>
 #include <termios.h>
 #include <string>
@@ -66,13 +67,13 @@ protected:
     // min serial MTU
     static const int minMTU = 4;
     // byte count of serial header
-    static const int serialHeaderBytes = 6;
+    static const int serialHeaderBytes = 5;
     // byte offset of type field
-    static const int typeOffset = 1;
+    static const int typeOffset = 0;
     // byte offset of sequence number field
-    static const int seqnoOffset = 2;
+    static const int seqnoOffset = 1;
     // byte offset of payload field
-    static const int payloadOffset = 3;
+    static const int payloadOffset = 2;
     // timeout for acks in s
     static const int ackTimeout = 1000 * 1000 * 200;
     // max. reties for packets from pc to node
@@ -80,6 +81,12 @@ protected:
 
     // how many bytes do we attempt to read from the serial line in one go?
     static const int rawReadBytes = 20;
+
+    enum rx_states_t {
+        WAIT_FOR_SYNC,
+        IN_SYNC,
+        ESCAPED
+    };
     
     /** Member vars */
 protected:
@@ -189,6 +196,24 @@ protected:
         crc ^= (crc & 0xff) << 5;
         return crc;
     }
+    
+    inline static uint16_t calcCRC(uint8_t *bytes, uint16_t len) {
+        uint16_t crc = 0;
+        for(unsigned i = 0; i < len; i++) {
+            crc = SerialComm::byteCRC(bytes[i], crc);
+        }
+        return crc;
+    }
+
+    inline static uint16_t checkCrc(uint8_t *bytes, uint16_t count) {
+        bool crcOk = false;
+        if(count > 2) {
+            uint16_t crc = calcCRC(bytes, count - 2);
+            uint16_t packetCrc = (bytes[count-1] << 8) | bytes[count-2];
+            if(crc == packetCrc) crcOk = true;
+        }
+        return crcOk;
+    }
 
     /* HDLC encode (byte stuff) count bytes from buffer from into buffer to.
      * to must be at least count * 2 bytes large. Returns the number of bytes
index 4cfeac4bf2ca9cd9ac5fb3455fc434487a1de338..8489d0b2d5f743052280a0dede6bdd9e446e9aff 100644 (file)
@@ -42,6 +42,8 @@
 #include <fcntl.h>
 
 #include <string>
+#include <cstdlib>
+#include <cstring>
 #include <iostream>
 #include <sstream>
 #include <fstream>
index c43059c600e8739dc147dad37bb1c55d0aaa89f8..0b066c8e1eea62bffeb027644bd8ff159e13a1a1 100644 (file)
@@ -31,6 +31,7 @@
  */
 
 #include "sfpacket.h"
+#include <cstring>
 
 SFPacket::SFPacket(int pType, int pSeqno) {
     length = 0;
index 27231a6202995e98778a9a5c56e1bde5dd3cbeca..2e77a22cfca9efcf0b636fbe1f6856dcc5f7be9b 100644 (file)
@@ -38,6 +38,7 @@
 #include <iostream>
 #include <set>
 
+#include <cstring>
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
@@ -582,7 +583,7 @@ void TCPComm::reportStatus(ostream& os)
 void TCPComm::stuffPipe() 
 {
     char info = 'n';
-    write(pipeWriteFD, &info, 1);
+    if(write(pipeWriteFD, &info, 1) != 1) DEBUG("TCPComm::stuffPipe : lokal pipe is broken");
 }
 
 void TCPComm::clearPipe() {
diff --git a/support/sdk/java/net/tinyos/tools/.cvsignore b/support/sdk/java/net/tinyos/tools/.cvsignore
new file mode 100644 (file)
index 0000000..933f8f4
--- /dev/null
@@ -0,0 +1 @@
+PrintfMsg.java
index 7aaf760c99629cb3b44fc6b76e15a02541587c93..dee4de43af77364e5d3abbcfeb4d61ce6222d280 100644 (file)
 # @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
 # @author David Purdy <david@radioretail.co.za>
 
-"""A library that implements the T2 serial communication.
+"""
+A library that implements the T2 serial communication.
 
 This library has two parts: one that deals with sending and receiving
 packets using the serial format from T2 (TEP113) and a second one that
 tries to simplifies the work with arbitrary packets.
-
 """
 
-import sys, struct, time, serial, socket, operator, thread
-from Queue import Queue
-from threading import Lock, Condition
+import sys, struct, time, socket, operator, os
+import traceback
+
+try: 
+    import serial
+except ImportError, e: 
+    print "Please install PySerial first."
+    sys.exit(1)
 
 __version__ = "$Id$"
 
@@ -40,124 +45,135 @@ __all__ = ['Serial', 'AM',
            'AckFrame', 'DataFrame', 'NoAckDataFrame',
            'ActiveMessage']
 
-ACK_WAIT = 0.2 # Maximum amount of time to wait for an ack
-ACK_WARN = 0.2 # Warn if acks take longer than this to arrive
-
-def list2hex(v):
-    return " ".join(["%02x" % p for p in v])
-
-
-class Error(Exception):
-    """Base error class for this module"""
-    pass
-
-
-class TimeoutError(Error):
-    """Thrown when a serial operation times out"""
-    pass
-
+HDLC_FLAG_BYTE = 0x7e
+HDLC_CTLESC_BYTE = 0x7d
 
-class ReadError(Error):
-    """Base class for read error exceptions"""
-    pass
-
-
-class WriteError(Error):
-    """Base class for write error exceptions"""
-    pass
-
-
-class ReadTimeoutError(TimeoutError, ReadError):
-    """Thrown when a serial read operation times out"""
-    pass
+TOS_SERIAL_ACTIVE_MESSAGE_ID = 0
+TOS_SERIAL_CC1000_ID = 1
+TOS_SERIAL_802_15_4_ID = 2
+TOS_SERIAL_UNKNOWN_ID = 255
 
+SERIAL_PROTO_ACK = 67
+SERIAL_PROTO_PACKET_ACK = 68
+SERIAL_PROTO_PACKET_NOACK = 69
+SERIAL_PROTO_PACKET_UNKNOWN = 255
 
-class ReadCRCError(ReadError):
-    """Thrown when a read packet fails a CRC check"""
-    pass
-
-
-class BadAckSeqnoError(ReadError):
-    """Thrown if an ack packet has an unexpected sequenc number"""
-    pass
-
+def list2hex(v):
+    return " ".join(["%02x" % p for p in v])
 
-class WriteTimeoutError(TimeoutError, WriteError):
-    """Thrown when a serial write operation times out"""
+class Timeout(Exception):
     pass
 
+def getSource(comm):
+    source = comm.split('@')
+    params = source[1].split(':')
+    debug = '--debug' in sys.argv
+    if source[0] == 'serial':
+        try:
+            return Serial(params[0], int(params[1]), flush=True, debug=debug)
+        except:
+            print "ERROR: Unable to initialize a serial connection to", comm
+            raise Exception
+    elif source[0] == 'network':
+        try:
+            return SerialMIB600(params[0], int(params[1]), debug=debug)
+        except:
+            print "ERROR: Unable to initialize a network connection to", comm
+            print "ERROR:", traceback.format_exc()
+            raise Exception
+    raise Exception
 
-class SimpleSerial:
-    """
-    A SimpleSerial object offers a way to send and data using a HDLC-like
-    formating.
-
-    Use SimpleSerial objects for basic low-level serial communications. Use
-    Serial objects for higher level logic (retry sends, log printfs, etc).
-    """
-
-    HDLC_FLAG_BYTE = 0x7e
-    HDLC_CTLESC_BYTE = 0x7d
-
-    TOS_SERIAL_ACTIVE_MESSAGE_ID = 0
-    TOS_SERIAL_CC1000_ID = 1
-    TOS_SERIAL_802_15_4_ID = 2
-    TOS_SERIAL_UNKNOWN_ID = 255
-
-    SERIAL_PROTO_ACK = 67
-    SERIAL_PROTO_PACKET_ACK = 68
-    SERIAL_PROTO_PACKET_NOACK = 69
-    SERIAL_PROTO_PACKET_UNKNOWN = 255
-
-    def __init__(self, port, baudrate, flush=False, debug=False, qsize=10,
-                 timeout=None):
-        self._debug = debug
-        self._in_queue = []
-        self._qsize = qsize
-        self._ack = None
-        self._write_counter = 0
-        self._write_counter_failures = 0
-        self._read_counter = 0
+class Serial:
+    def __init__(self, port, baudrate, flush=False, debug=False, readTimeout=None, ackTimeout=0.02):
+        self.debug = debug
+        self.readTimeout = readTimeout
+        self.ackTimeout = ackTimeout
         self._ts = None
-        self.timeout = timeout # Public attribute
-        self._received_packet_filters = [] # filter functions for received packets
 
-        # Remember sent (and unacknowledged) seqno numbers for 15 seconds:
-        self._unacked_seqnos = SeqTracker(15.0)
+        if port.startswith('COM') or port.startswith('com'):
+            port = int(port[3:]) - 1
+        elif port.isdigit():
+            port = int(port) - 1
 
-        self._s = serial.Serial(port, baudrate, rtscts=0, timeout=0.5)
+        self._s = serial.Serial(port, int(baudrate), rtscts=0, timeout=0.5)
         self._s.flushInput()
         if flush:
             print >>sys.stdout, "Flushing the serial port",
             endtime = time.time() + 1
             while time.time() < endtime:
-                try:
-                    self._read()
-                except ReadError:
-                    pass
+                self._s.read()
                 sys.stdout.write(".")
-            if not self._debug:
+            if not self.debug:
                 sys.stdout.write("\n")
         self._s.close()
-        self._s = serial.Serial(port, baudrate, rtscts=0, timeout=timeout)
+        self._s = serial.Serial(port, baudrate, rtscts=0, timeout=readTimeout)
 
-        # Add a filter for received 'write ack' packets
-        self.add_received_packet_filter(self._write_ack_filter)
+    def getByte(self):
+        c = self._s.read()
+        if c == '':
+            raise Timeout
+        #print 'Serial:getByte: 0x%02x' % ord(c)
+        return ord(c)
 
-    # Returns the next incoming serial packet
-    def _read(self, timeout=None):
-        """Wait for a packet and return it as a RawPacket.
+    def putBytes(self, data):
+        #print "DEBUG: putBytes:", data
+        for b in data:
+            self._s.write(struct.pack('B', b))
+            time.sleep(0.000001)
 
-        Throws:
-         - ReadCRCError if a CRC check fails
-         - ReadTimeoutError if the timeout expires.
+    def getTimeout(self):
+        return self._s.timeout
 
-        """
+    def setTimeout(self, timeout):
+        self._s.timeout = timeout
+
+class SerialMIB600:
+    def __init__(self, host, port=10002, debug=False, readTimeout=None, ackTimeout=0.5):
+        self.debug = debug
+        self.readTimeout = readTimeout
+        self.ackTimeout = ackTimeout
+        self._ts = None
+        self._s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        self._s.connect((host, port))
+        print "Connected"
+
+    def getByte(self):
+        try:
+            c = self._s.recv(1)
+        except socket.timeout:
+            c = ''
+        if c == '':
+            raise Timeout
+        #print 'Serial:getByte: 0x%02x' % ord(c)
+        return ord(c)
+
+    def putBytes(self, data):
+        #print "DEBUG: putBytes:", data
+        for b in data:
+            self._s.send(struct.pack('B', b))
+
+    def getTimeout(self):
+        return self._s.gettimeout()
+
+    def setTimeout(self, timeout):
+        self._s.settimeout(timeout)
+
+class HDLC:
+    """
+    An HDLC object offers a way to send and receive data on a byte
+    source using a HDLC-like formating.
+    """
+    def __init__(self, source):
+        self._s = source
+
+    # Returns the next incoming serial packet
+    def read(self, timeout=None):
+        """Wait for a packet and return it as a RawPacket."""
 
         # Developer notes:
         #
-        # Packet data read from Serial is in this format:
-        # [HDLC_FLAG_BYTE][Escaped data][HDLC_FLAG_BYTE]
+        # Packet data read is in this format:
+        #     [HDLC_FLAG_BYTE][Escaped data][HDLC_FLAG_BYTE]
         #
         # [Escaped data] is encoded so that [HDLC_FLAG_BYTE] byte
         # values cannot occur within it. When [Escaped data] has been
@@ -167,57 +183,72 @@ class SimpleSerial:
         #
         # It's also possible that the serial device was half-way
         # through transmitting a packet when this function was called
-        # (app was just started). So we also neeed to handle this case:
+        # (app was just started). So we also neeed to handle this
+        # case:
         #
-        # [Incomplete escaped data][HDLC_FLAG_BYTE][HDLC_FLAG_BYTE][Escaped data][HDLC_FLAG_BYTE]
+        #     [Incomplete escaped data][HDLC_FLAG_BYTE][HDLC_FLAG_BYTE][Escaped data][HDLC_FLAG_BYTE]
         #
         # In this case we skip over the first (incomplete) packet.
         #
 
-        if self._s.timeout != timeout and timeout != None:
-            if self._debug:
-                print "Set the timeout to %s, previous one was %s" % (timeout, self._s.timeout)
-            self._s.timeout = timeout
+        if self._s.getTimeout() != timeout and timeout != None:
+            self.log("Set the timeout to %s, previous one was %s" % (timeout, self._s.getTimeout()))
+            self._s.setTimeout(timeout)
+
+        #    +--- FLAG -----+
+        #    |              |  ___________
+        #    v              | /           |
+        #  >(1)-- !FLAG -->(2)<-- !FLAG --+
+        #    |
+        #   FLAG
+        #    |  ___________
+        #    v /           |
+        #   (3)<-- FLAG ---+
+        #    |
+        #  !FLAG
+        #    |  ___________
+        #    v /           |
+        #   (4)<-- !FLAG --+
+        #    |
+        #   FLAG
+        #    |
+        #    v
+        #   (5)
 
         try:
             # Read bytes until we get to a HDLC_FLAG_BYTE value
             # (either the end of a packet, or the start of a new one)
-            d = self._get_byte(timeout)
+            d = self._s.getByte()
             ts = time.time()
-            if self._debug and d != self.HDLC_FLAG_BYTE:
-                print "Skipping incomplete packet"
-            while d != self.HDLC_FLAG_BYTE:
-                d = self._get_byte(timeout)
-                ts = time.time()
+            if d != HDLC_FLAG_BYTE:
+                self.log("Skipping byte %d" % d)
+                while d != HDLC_FLAG_BYTE:
+                    d = self._s.getByte()
+                    self.log("Skipping byte %d" % d)
+                    ts = time.time()
 
             # Store HDLC_FLAG_BYTE at the start of the retrieved packet
             # data:
             packet = [d]
 
             # Is the next byte also HDLC_FLAG_BYTE?
-            d = self._get_byte(timeout)
-            if d == self.HDLC_FLAG_BYTE:
-                # Yes. This means that the previous byte was for
-                # the end of the previous packet, and this byte is for
-                # the start of the next packet.
-
-                # Get the 2nd byte of the new packet:
-                d = self._get_byte(timeout)
+            d = self._s.getByte()
+            while d == HDLC_FLAG_BYTE:
+                d = self._s.getByte()
                 ts = time.time()
 
             # We are now on the 2nd byte of the packet. Add it to
             # our retrieved packet data:
             packet.append(d)
 
-            # Read bytes from serial until we read another
-            # HDLC_FLAG_BYTE value (end of the current packet):
-            while d != self.HDLC_FLAG_BYTE:
-                d = self._get_byte(timeout)
+            # Read bytes from serial until we read another HDLC_FLAG_BYTE
+            # value (end of the current packet):
+            while d != HDLC_FLAG_BYTE:
+                d = self._s.getByte()
                 packet.append(d)
 
             # Done reading a whole packet from serial
-            if self._debug:
-                print "SimpleSerial:_read: unescaped", packet
+            self.log("SimpleSerial:_read: unescaped %s" % packet)
 
             # Decode the packet, and check CRC:
             packet = self._unescape(packet)
@@ -227,137 +258,32 @@ class SimpleSerial:
 
             if crc != packet_crc:
                 print "Warning: wrong CRC! %x != %x %s" % (crc, packet_crc, ["%2x" % i for i in packet])
-                raise ReadCRCError
-            if self._debug:
-                if self._ts == None:
-                    self._ts = ts
-                else:
-                    print "Serial:_read: %.4f (%.4f) Recv:" % (ts, ts - self._ts), self._format_packet(packet[1:-3])
-                self._ts = ts
+            if not self._s._ts:
+                self._s._ts = ts
+            self.log("Serial:_read: %.4f (%.4f) Recv: %s" % (ts, ts - self._s._ts, self._format(packet[1:-3])))
+            self._ts = ts
 
             # Packet was successfully retrieved, so return it in a
-            # RawPacket wrapper object (but leave out the
-            # HDLC_FLAG_BYTE and CRC bytes)
+            # RawPacket wrapper object (but leave out the HDLC_FLAG_BYTE
+            # and CRC bytes)
             return RawPacket(ts, packet[1:-3])
-        except socket.timeout:
-            raise ReadTimeoutError
-
-    def _write_ack_filter(self, packet):
-        """Filter for recieved write acknowledgement packets"""
-        ack = AckFrame(packet.data)
-        if ack.protocol == self.SERIAL_PROTO_ACK:
-            if self._debug:
-                print "_filter_read: got an ack:", ack
-            self._ack = ack
-            packet = None # No further processing of received ack packet
-        return packet
-
-    def _filter_read(self, timeout=None):
-        """Read a packet from the serial device, perform filtering, and return
-        the packet if it hasn't been processed yet.
-
-        """
-        p = self._read(timeout)
-        self._read_counter += 1
-        if self._debug:
-            print "_filter_read: got a packet(%d): %s" % (self._read_counter, p)
-
-        # Pass the received packet through the filter functions:
-        if p is not None:
-            for filter_func in self._received_packet_filters:
-                p = filter_func(p)
-                # Stop now if the packet doesn't need further processing:
-                if p is None:
-                    break
-
-        # Return the packet (if there was no timeout and it wasn't filtered)
-        return p
-
-    def _get_ack(self, timeout, expected_seqno):
-        """Get the next ack packet
-
-        Read packets from the serial device until we get the next ack (which
-        then gets stored in self._ack), or the timeout expires. non-ack packets
-        are buffered.
-
-        Throws:
-         - ReadTimeoutError if the timeout expires.
-         - BadAckSeqnoError if an ack with a bad sequence number is received
-
-        """
-        endtime = time.time() + timeout
-        while time.time() < endtime:
-            # Read the a packet over serial
-            self._ack = None
-            remaining = endtime - time.time()
-            p = self._filter_read(timeout)
-
-            # Was the packet filtered?
-            if p:
-                # Got an unfiltered packet
-                if len(self._in_queue) >= self._qsize:
-                    print "Warning: Buffer overflow"
-                    self._in_queue.pop(0)
-                self._in_queue.append(p)
-            else:
-                # Packet was filtered. Was it an ack?
-                if self._ack is not None:
-                    # The packet was an ack, so remove it from our
-                    # 'unacknowledged seqnos' list (or raise a BadAckSeqnoError
-                    # error if it isn't in the list)
-                    self._unacked_seqnos.seqno_acked(self._ack.seqno)
-
-                    # Stop reading packets if it's the ack we are waiting for:
-                    if self._ack.seqno == expected_seqno:
-                        return
-
-        # Timed out
-        raise ReadTimeoutError
-
-    def close(self):
-        """Close the serial device"""
-        self._s.close()
-
-    def read(self, timeout=None):
-        """Read a packet, either from the input buffer or from the serial
-        device.
-
-        Returns a RawPacket object, otherwise None if the packet was filtered
-        (by eg: Serial's printf-filtering function)
-
-        Does not retry reads if the first one fails. Use Serial.read() for
-        that.
-
-        """
-        if self._in_queue:
-            return self._in_queue.pop(0)
-        else:
-            return self._filter_read(timeout)
+        except Timeout:
+            return None
 
-    def write(self, payload, seqno, timeout=0.2):
+    def write(self, payload, seqno):
         """
         Write a packet. If the payload argument is a list, it is
         assumed to be exactly the payload. Otherwise the payload is
         assume to be a Packet and the real payload is obtain by
         calling the .payload().
-
-        Only attempts to write once, and times out if an ack packet is not
-        received within [timeout] seconds. Use Serial.write() if you want
-        automatic write retries.
-
-        seqno should be an integer between 0 and 99 which changes each time you
-        send a new packet. The value should remain the same when you are
-        retrying a packet write that just failed.
-
-        Raises WriteTimeoutError if the write times out (ack packet doesn't
-        arrive within [timeout] seconds).
-
         """
-        if type(payload) != type([]):
-            # Assume this will be derived from Packet
+
+        if isinstance(payload, Packet):
             payload = payload.payload()
+
         packet = DataFrame();
-        packet.protocol = self.SERIAL_PROTO_PACKET_ACK
+        # We need to always request for acks
+        packet.protocol = SERIAL_PROTO_PACKET_ACK
         packet.seqno = seqno
         packet.dispatch = 0
         packet.data = payload
@@ -365,59 +291,14 @@ class SimpleSerial:
         crc = self._crc16(0, packet)
         packet.append(crc & 0xff)
         packet.append((crc >> 8) & 0xff)
-        packet = [self.HDLC_FLAG_BYTE] + self._escape(packet) + [self.HDLC_FLAG_BYTE]
-
-        # Write the packet:
-        self._unacked_seqnos.seqno_sent(seqno) # Keep track of sent seqno's
-        self._put_bytes(packet)
-        self._write_counter += 1
-
-        # Wait for an ack packet:
-        if self._debug:
-            print "Send(%d/%d): %s" % (self._write_counter, self._write_counter_failures, packet)
-            print "Wait for ack %d ..." % (seqno)
-
-        try:
-            self._get_ack(timeout, seqno)
-        except ReadTimeoutError:
-            # Re-raise read timeouts (of ack packets) as write timeouts (of
-            # the write operation)
-            self._write_counter_failures += 1
-            raise WriteTimeoutError
-
-        # Received an ack packet, with the expected sequence number
-        if self._debug:
-            print "Wait for ack %d done. Latest ack:" % (seqno), self._ack
-            print "The packet was acked."
-            print "Returning from SimpleSerial.write..."
-
-    def add_received_packet_filter(self, filter_func):
-        """Register a received packet-filtering callback function
+        packet = [HDLC_FLAG_BYTE] + self._escape(packet) + [HDLC_FLAG_BYTE]
 
-        _filter_read() calls all of the registered filter functions for each
-        packet received over serial. Registered filter functions are called in
-        the order they were registered.
+        self.log("Serial: write %s" % packet)
+        self._s.putBytes(packet)
 
-        Filter functions are called like this: filter_func(packet)
-
-        When a filter function recognises and handles a received packet it
-        should return a None value to indicate that no further processing
-        is required for the packet.
-
-        When a filter function skips a packet (or for some reason you want
-        further processing to happen on a packet you've just processed), the
-        function should return the packet that was passed to it as an argument.
-
-        """
-        self._received_packet_filters.append(filter_func)
-
-    def remove_received_packet_filter(self, filter_func):
-        """Remove a filter function added with add_received_packet_filter()"""
-        self._received_packet_filters.remove(filter_func)
-
-    def _format_packet(self, payload):
+    def _format(self, payload):
         f = NoAckDataFrame(payload)
-        if f.protocol == self.SERIAL_PROTO_ACK:
+        if f.protocol == SERIAL_PROTO_ACK:
             rpacket = AckFrame(payload)
             return "Ack seqno: %d" % (rpacket.seqno)
         else:
@@ -452,24 +333,6 @@ class SimpleSerial:
             r = (r << 8) + i
         return r
 
-    def _get_byte(self, timeout=None):
-#        old_timeout = self._s.timeout
-#        if timeout is not None:
-#            self._s.timeout = timeout
-        try:
-            r = struct.unpack("B", self._s.read())[0]
-            return r
-        except struct.error:
-            # Serial port read timeout
-            raise socket.timeout
-#        finally:
-#            self._s.timeout = old_timeout
-
-    def _put_bytes(self, data):
-        #print "DEBUG: _put_bytes:", data
-        for b in data:
-            self._s.write(struct.pack('B', b))
-
     def _unescape(self, packet):
         r = []
         esc = False
@@ -477,7 +340,7 @@ class SimpleSerial:
             if esc:
                 r.append(b ^ 0x20)
                 esc = False
-            elif b == self.HDLC_CTLESC_BYTE:
+            elif b == HDLC_CTLESC_BYTE:
                 esc = True
             else:
                 r.append(b)
@@ -486,285 +349,150 @@ class SimpleSerial:
     def _escape(self, packet):
         r = []
         for b in packet:
-            if b == self.HDLC_FLAG_BYTE or b == self.HDLC_CTLESC_BYTE:
-                r.append(self.HDLC_CTLESC_BYTE)
+            if b == HDLC_FLAG_BYTE or b == HDLC_CTLESC_BYTE:
+                r.append(HDLC_CTLESC_BYTE)
                 r.append(b ^ 0x20)
             else:
                 r.append(b)
         return r
 
-    def debug(self, debug):
-        self._debug = debug
-
-
-class SeqTracker:
-    """Class for keeping track of unacknowledged packet sequence numbers.
+    def log(self, s):
+        if self._s.debug:
+            print s
 
-    SeqTracker is used by SimpleSerial to keep track of sequence numbers which
-    have been sent with write packets, but not yet acknowledged by received
-    write ack packets.
+class SimpleAM(object):
+    def __init__(self, source, oobHook=None):
+        self._source = source
+        self._hdlc = HDLC(source)
+        self.seqno = 0
+        self.oobHook = oobHook
 
-    """
-    def __init__(self, keep_for):
-        """Initialise a SeqTracker object.
-
-        args:
-
-         - keep_for is the length of time for which unacknowledged sequence
-           numbers should be remembered. After this period has elapsed, the
-           sequence numbers should be forgotten. If the sequence number is
-           acknowledged later, it will be treated as unkown
-
-        """
-        self._keep_for = keep_for
-        self._queue = []
-
-    def seqno_sent(self, seqno):
-        """Register that a packet with the specified sequence number was just
-           sent."""
-        self._gc()
-        self._queue.append((seqno, time.time()))
-
-    def seqno_acked(self, seqno):
-        """Register that a sequence number was just acknowledged.
-
-        Find the oldest-known occurance of seqno in the queue and remove it. If
-        not found then raise a BadAckSeqnoError to inform applications that
-        the sequence number is not known.
-
-        """
-        self._gc()
-        for item in self._queue:
-            if item[0] == seqno:
-                # Found seqno
-                self._queue.remove(item)
-                return
-        # seqno not found!
-        raise BadAckSeqnoError
-
-    def get_seqno_sent_times(self, seqno):
-        """Return the times when packets with the given sequence number were
-        sent."""
-        self._gc()
-        return [item[1] for item in self._queue if item[0] == seqno]
-
-    def __contains__(self, seqno):
-        """Return True if the seqno was sent recently (and not acknowledged
-        yet)"""
-        self._gc()
-        for item in self._queue:
-            if item[0] == seqno:
+    def read(self, timeout=None):
+        f = self._hdlc.read(timeout)
+        if f:
+            return ActiveMessage(NoAckDataFrame(f))
+        return None
+
+    def write(self, packet, amId, timeout=5, blocking=True, inc=1):
+        self.seqno = (self.seqno + inc) % 256
+        prevTimeout = self._source.getTimeout()
+        ack = None
+        end = None
+        if timeout: end = time.time() + timeout
+        while not end or time.time() < end:
+            self._hdlc.write(ActiveMessage(packet, amId=amId), seqno=self.seqno)
+            if not blocking:
                 return True
-        return False
-
-    def _gc(self):
-        """Remove old items from the queue"""
-        remove_before = time.time() - self._keep_for
-        for item in self._queue:
-            # Time for the sequence to be removed?
-            if item[1] < remove_before:
-                # Sequence data is old, so remove it
-                self._queue.remove(item)
-            else:
-                # Sequence number was added recently, so don't remove it. Also
-                # stop processing the queue because all later items will be
-                # newer
+            start = time.time()
+            f = self._hdlc.read(self._source.ackTimeout)
+            if f == None:
+                #print "Ack Timeout!"
+                continue
+            ack = AckFrame(f)
+            while ack.protocol != SERIAL_PROTO_ACK and (not end or time.time() < end):
+                if self.oobHook:
+                    self.oobHook(ActiveMessage(NoAckDataFrame(f)))
+                else:
+                    print 'SimpleAM:write: skip', ack, f
+                f = self._hdlc.read(self._source.ackTimeout)
+                if f == None:
+                    #print "Ack Timeout!"
+                    break
+                ack = AckFrame(f)
+            if f != None:
                 break
-
-
-class Serial:
-    """
-    Wraps a SimpleSerial object, and provides some higher-level functionality
-    like retrying writes and logging printf packets.
-    """
-    def __init__(self, port, baudrate, flush=False, debug=False, qsize=10,
-                 timeout=None):
-        """Initialise a Serial object"""
-        self._debug = debug
-        self.timeout = timeout # Public attribute
-        self._seqno = 0
-        self._simple_serial = SimpleSerial(port, baudrate, flush, debug, qsize,
-                                           timeout)
-
-        # Setup automatic logging of received printf packets:
-        self._printf_msg = ""
-        self._simple_serial.add_received_packet_filter(self._printf_filter)
-
-    def close(self):
-        """Close the serial device"""
-        self._simple_serial.close()
-
-    def read(self, timeout=None):
-        """Read a packet from the serial port.
-
-        Retries packet reads until the timeout expires.
-
-        Throws ReadTimeoutError if a a packet can't be read within the timeout.
-
-        """
-        if timeout is None:
-            timeout = self.timeout
-        endtime = None
-
-        if timeout is not None:
-            endtime = time.time() + timeout
-
-        while endtime is None or time.time() < endtime:
-            remaining = None
-            if endtime is not None:
-                remaining = endtime - time.time()
+        self._source.setTimeout(prevTimeout)
+        #print 'SimpleAM:write: got an ack:', ack, ack.seqno == self.seqno
+        return (ack != None and ack.seqno == self.seqno)
+
+    def setOobHook(self, oobHook):
+        self.oobHook = oobHook
+
+def printfHook(packet):
+    if packet == None:
+        return
+    if packet.type == 100:
+        s = "".join([chr(i) for i in packet.data]).strip('\0')
+        lines = s.split('\n')
+        for line in lines:
+            if line: print "PRINTF:", line
+        packet = None # No further processing for the printf packet
+    return packet    
+
+class AM(SimpleAM):
+    def __init__(self, s=None, oobHook=None):
+        if s == None:
             try:
-                p = self._simple_serial.read(remaining)
-            except ReadError:
-                if self._debug:
-                    print "Packet read failed. Try again."
-            else:
-                # Was the packet filtered?
-                if p is not None:
-                    # Not filtered, so return it.
-                    # In the current TinyOS the packets from the mote are
-                    # always NoAckDataFrame
-                    return NoAckDataFrame(p.data)
-
-        # Read timeout expired
-        raise ReadTimeoutError
-
-    def write(self, payload, timeout=None):
-        """Write a packet to the serial port
-
-        Keeps retrying endlessly, unless a timeout is set. If the timeout
-        expires then WriteTimeoutError is thrown.
-
-        """
-        if timeout is None:
-            timeout = self.timeout
-
-        endtime = None
-        if timeout is not None:
-            endtime = time.time() + timeout
-
-        # Generate the next sequence number:
-        self._seqno = (self._seqno + 1) % 100
-
-        while endtime is None or time.time() < endtime:
-            try:
-                ackwait = ACK_WAIT
-                if endtime is not None:
-                    remaining = endtime - time.time()
-                    ackwait = min(ACK_WAIT, remaining)
-
-                before = time.time()
-                self._simple_serial.write(payload, self._seqno, ackwait)
-                length = time.time() - before
-
-                if length >= ACK_WARN:
-                    print "Warning: Packet write took %.3fs!" % (length)
-                return True
-            except Error:
-                if self._debug:
-                    print "The packet was not acked. Try again."
-
-        # Write operation timed out
-        raise WriteTimeoutError
-
-    def _printf_filter(self, packet):
-        """Filter for recieved printf packets"""
-        ampkt = ActiveMessage(NoAckDataFrame(packet.data).data)
-        if ampkt.type == 100:
-            self._printf_msg += "".join([chr(i) for i in ampkt.data]).strip('\0')
-            # Split printf data on newline character:
-            # (last string in the split list doesn't have a newline after
-            # it, so we keep it until next time)
-            lines = self._printf_msg.split('\n')
-            for line in lines[:-1]:
-                print "PRINTF:", line
-            self._printf_msg = lines[-1]
-            packet = None # No further processing for the printf packet
-        return packet
-
-class SFClient:
-    def __init__(self, host, port, qsize=10):
-        self._in_queue = Queue(qsize)
-        self._s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-        self._s.connect((host, port))
-        data = self._s.recv(2)
-        if data != 'U ':
-            print "Wrong handshake"
-        self._s.send("U ")
-        print "Connected"
-        thread.start_new_thread(self.run, ())
-
-    def run(self):
-        while True:
-            length = ord(self._s.recv(1))
-            data = self._s.recv(length)
-            data = [ord(c) for c in data][1:]
-            #print "Recv %d bytes" % (length), ActiveMessage(data)
-            if self._in_queue.full():
-                print "Warning: Buffer overflow"
-                self._in_queue.get()
-            p = RawPacket()
-            p.data = data
-            self._in_queue.put(p, block=False)
-
-    def read(self, timeout=0):
-        return self._in_queue.get()
-
-    def write(self, payload):
-        print "SFClient: write:", payload
-        if type(payload) != type([]):
-            # Assume this will be derived from Packet
-            payload = payload.payload()
-        payload = [0] + payload
-        self._s.send(chr(len(payload)))
-        self._s.send(''.join([chr(c) for c in payload]))
-        return True
-
-class AM:
-    def __init__(self, s):
-        self._s = s
+                s = getSource(sys.argv[1])
+            except:
+                try:
+                    for (i, j) in zip(sys.argv[1::2], sys.argv[2::2]):
+                        if i == '-comm':
+                            s = getSource(j)
+                    if s == None:
+                        raise Exception
+                except:
+                    try:
+                        s = getSource(os.environ['MOTECOM'])
+                    except:
+                        print "ERROR: Please indicate a way to connect to the mote"
+                        sys.exit(-1)
+        if oobHook == None:
+            oobHook = printfHook
+        super(AM, self).__init__(s, oobHook)
 
     def read(self, timeout=None):
-        return ActiveMessage(self._s.read(timeout).data)
-
-    def write(self, packet, amid, timeout=None):
-        return self._s.write(ActiveMessage(packet, amid=amid), timeout=timeout)
-
-
-class SimpleSerialAM(SimpleSerial):
-    """A derived class of SimpleSerial so that apps can read and write using
-    higher-level packet structures.
-
-    Serves a simalar purpose to the AM class, but for SimpleSerial objects
-    instead instead of Serial.
-
-    """
-
-    def read_am(self, timeout=None):
-        """Read a RawPacket object (or None), convert it to ActiveMessage
-        (or None), and return to the caller"""
-
-        # Get a tos.Rawpacket (or None, if filtered) object
-        p = self.read(timeout)
-        if p is not None:
-            assert isinstance(p, RawPacket)
-            # Convert tos.RawPacket object into an ActiveMessage:
-            p = NoAckDataFrame(p.data)
-            p = ActiveMessage(p.data)
-
-        # Return the ActiveMessage (or None) packet:
-        return p
-
-    def write_am(self, packet, amid, seqno, timeout=2.0):
-        """Convert app packet format to ActiveMessage, and write the
-        ActiveMessage packet to serial"""
-
-        # Convert from app-specific packet to ActiveMessage:
-        p = ActiveMessage(packet, amid=amid)
+        return self.oobHook(super(AM, self).read(timeout))
+
+    def write(self, packet, amId, timeout=None, blocking=True):
+        r = super(AM, self).write(packet, amId, timeout, blocking)
+        while not r:
+            r = super(AM, self).write(packet, amId, timeout, blocking, inc=0)
+            if timeout and not r:
+               raise Timeout
+        return True
 
-        # Write to the serial device
-        self.write(p, seqno, timeout)
 
+# class SFClient:
+#     def __init__(self, host, port, qsize=10):
+#         self._in_queue = Queue(qsize)
+#         self._s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+#         self._s.connect((host, port))
+#         data = self._s.recv(2)
+#         if data != 'U ':
+#             print "Wrong handshake"
+#         self._s.send("U ")
+#         print "Connected"
+#         thread.start_new_thread(self.run, ())
+
+#     def run(self):
+#         while True:
+#             length = ord(self._s.recv(1))
+#             data = self._s.recv(length)
+#             data = [ord(c) for c in data][1:]
+#             #print "Recv %d bytes" % (length), ActiveMessage(data)
+#             if self._in_queue.full():
+#                 print "Warning: Buffer overflow"
+#                 self._in_queue.get()
+#             p = RawPacket()
+#             p.data = data
+#             self._in_queue.put(p, block=False)
+
+#     def read(self, timeout=0):
+#         return self._in_queue.get()
+
+#     def write(self, payload):
+#         print "SFClient: write:", payload
+#         if type(payload) != type([]):
+#             # Assume this will be derived from Packet
+#             payload = payload.payload()
+#         payload = [0] + payload
+#         self._s.send(chr(len(payload)))
+#         self._s.send(''.join([chr(c) for c in payload]))
+#         return True
+
+
+################################################################################
 
 class Packet:
     """
@@ -786,6 +514,11 @@ class Packet:
         output.reverse()
         return output
 
+    def _sign(self, val, dim):
+        if val > (1 << (dim * 8 - 1)):
+            return val - (1 << (dim * 8))
+        return val
+
     def __init__(self, desc, packet = None):
         offset = 0
         boffset = 0
@@ -805,6 +538,9 @@ class Packet:
                 if t == 'int':
                     self._values.append(self._decode(packet[offset:offset + s]))
                     offset += s
+                elif t == 'sint':
+                    self._values.append(self._sign(self._decode(packet[offset:offset + s]), s))
+                    offset += s
                 elif t == 'bint':
                     doffset = 8 - (boffset + s)
                     self._values.append((packet[offset] >> doffset) & ((1<<s) - 1))
@@ -842,27 +578,9 @@ class Packet:
         for i in range(len(self._names), len(self._values)):
             r += "%s" % self._values[i]
         return r
-#        return self._values.__str__()
-
-    # Implement the map behavior
-    def __getitem__(self, key):
-        return self.__getattr__(key)
-
-    def __setitem__(self, key, value):
-        self.__setattr__(key, value)
-
-    def __len__(self):
-        return len(self._values)
-
-    def keys(self):
-        return self._names
-
-    def values(self):
-        return self._names
 
     # Implement the struct behavior
     def __getattr__(self, name):
-        #print "DEBUG: __getattr__", name
         if type(name) == type(0):
             return self._names[name]
         else:
@@ -889,7 +607,23 @@ class Packet:
     def __nonzero__(self):
         return True;
 
-    # Custom
+    # Implement the map behavior
+    def __getitem__(self, key):
+        return self.__getattr__(key)
+
+    def __setitem__(self, key, value):
+        self.__setattr__(key, value)
+
+    def __len__(self):
+        return len(self._values)
+
+    def keys(self):
+        return self._names
+
+    def values(self):
+        return self._values
+
+    # Custom functions
     def names(self):
         return self._names
 
@@ -931,6 +665,11 @@ class RawPacket(Packet):
 
 class AckFrame(Packet):
     def __init__(self, payload = None):
+        if isinstance(payload, Packet):
+            if isinstance(payload, RawPacket):
+                payload = payload.data
+            else:
+                payload = payload.payload()
         Packet.__init__(self,
                         [('protocol', 'int', 1),
                          ('seqno',    'int', 1)],
@@ -938,9 +677,11 @@ class AckFrame(Packet):
 
 class DataFrame(Packet):
     def __init__(self, payload = None):
-        if payload != None and type(payload) != type([]):
-            # Assume is a Packet
-            payload = payload.payload()
+        if isinstance(payload, Packet):
+            if isinstance(payload, RawPacket):
+                payload = payload.data
+            else:
+                payload = payload.payload()
         Packet.__init__(self,
                         [('protocol',  'int', 1),
                          ('seqno',     'int', 1),
@@ -950,9 +691,11 @@ class DataFrame(Packet):
 
 class NoAckDataFrame(Packet):
     def __init__(self, payload = None):
-        if payload != None and type(payload) != type([]):
-            # Assume is a Packet
-            payload = payload.payload()
+        if isinstance(payload, Packet):
+            if isinstance(payload, RawPacket):
+                payload = payload.data
+            else:
+                payload = payload.payload()
         Packet.__init__(self,
                         [('protocol',  'int', 1),
                          ('dispatch',  'int', 1),
@@ -960,27 +703,29 @@ class NoAckDataFrame(Packet):
                         payload)
 
 class ActiveMessage(Packet):
-    def __init__(self, gpacket = None, amid = 0x00, dest = 0xFFFF):
-        if type(gpacket) == type([]):
-            payload = gpacket
-        else:
-            # Assume this will be derived from Packet
-            payload = None
+    def __init__(self, packet = None, amId = 0x00, dest = 0xFFFF):
+        payload = None
+        if type(packet) == type([]):
+            payload = packet
+        elif isinstance(packet, NoAckDataFrame):
+            payload = packet.data
+            packet = None
+
         Packet.__init__(self,
                         [('destination', 'int', 2),
-                         ('source',   'int', 2),
-                         ('length',   'int', 1),
-                         ('group',    'int', 1),
-                         ('type',     'int', 1),
-                         ('data',     'blob', None)],
+                         ('source',      'int', 2),
+                         ('length',      'int', 1),
+                         ('group',       'int', 1),
+                         ('type',        'int', 1),
+                         ('data',        'blob', None)],
                         payload)
         if payload == None:
             self.destination = dest
             self.source = 0x0000
             self.group = 0x00
-            self.type = amid
+            self.type = amId
             self.data = []
-            if gpacket:
-                self.data = gpacket.payload()
+            if isinstance(packet, Packet):
+                self.data = packet.payload()
             self.length = len(self.data)
 
index a41c7e53cc263101d96660a28d99b0023e460178..6886286bd8dc2a4edf4e1d8a8c15a46400105246 100644 (file)
--- a/tinyos.sh
+++ b/tinyos.sh
@@ -20,7 +20,7 @@ gettosroot()
     fi
 }
 
-# Update CLASSPATH by replacing the element value in $1 with the element value 
+# Update CLASSPATH by replacing the element value in $1 with the element value
 # in $2.  An empty $2 removes element $1, if present.  An empty $1, or $1 not
 # present, adds $2.
 updclasspath()
index acc2e7b2183b2ca4c9e11fe9e657877acdf41c38..992d2a659825f28a76f0c2000b58d0fe5640be34 100644 (file)
@@ -106,7 +106,7 @@ AC_MSG_RESULT($JDK)
 
 function jnimap {
   for v in $JNIVERSIONS; do
-    echo -n "${JNIPREFIX}$1$v$JNISUFFIX "
+    /bin/echo -n "${JNIPREFIX}$1$v$JNISUFFIX "
   done
 }
 
index 620af5c658b1ab906b2d85853db1c1c76eb592e4..eb862d93ba0ea0e5f3f04ba88271f2e2a8f7a8e3 100644 (file)
@@ -1,8 +1,8 @@
-# Makefile.in generated by automake 1.8.3 from Makefile.am.
+# Makefile.in generated by automake 1.10.1 from Makefile.am.
 # @configure_input@
 
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008  Free Software Foundation, Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
 # PARTICULAR PURPOSE.
 
 @SET_MAKE@
-srcdir = @srcdir@
-top_srcdir = @top_srcdir@
 VPATH = @srcdir@
 pkgdatadir = $(datadir)/@PACKAGE@
 pkglibdir = $(libdir)/@PACKAGE@
 pkgincludedir = $(includedir)/@PACKAGE@
-top_builddir = .
 am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-INSTALL = @INSTALL@
 install_sh_DATA = $(install_sh) -c -m 644
 install_sh_PROGRAM = $(install_sh) -c
 install_sh_SCRIPT = $(install_sh) -c
@@ -42,18 +38,21 @@ am__aclocal_m4_deps = $(top_srcdir)/configure.in
 am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
        $(ACLOCAL_M4)
 am__CONFIG_DISTCLEAN_FILES = config.status config.cache config.log \
- configure.lineno configure.status.lineno
-mkinstalldirs = $(mkdir_p)
+ configure.lineno config.status.lineno
+mkinstalldirs = $(install_sh) -d
 CONFIG_HEADER = config.h
 CONFIG_CLEAN_FILES =
 SOURCES =
 DIST_SOURCES =
 RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \
        html-recursive info-recursive install-data-recursive \
-       install-exec-recursive install-info-recursive \
-       install-recursive installcheck-recursive installdirs-recursive \
-       pdf-recursive ps-recursive uninstall-info-recursive \
-       uninstall-recursive
+       install-dvi-recursive install-exec-recursive \
+       install-html-recursive install-info-recursive \
+       install-pdf-recursive install-ps-recursive install-recursive \
+       installcheck-recursive installdirs-recursive pdf-recursive \
+       ps-recursive uninstall-recursive
+RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive        \
+  distclean-recursive maintainer-clean-recursive
 ETAGS = etags
 CTAGS = ctags
 DIST_SUBDIRS = $(SUBDIRS)
@@ -69,8 +68,6 @@ GZIP_ENV = --best
 distuninstallcheck_listfiles = find . -type f -print
 distcleancheck_listfiles = find . -type f -print
 ACLOCAL = @ACLOCAL@
-AMDEP_FALSE = @AMDEP_FALSE@
-AMDEP_TRUE = @AMDEP_TRUE@
 AMTAR = @AMTAR@
 AUTOCONF = @AUTOCONF@
 AUTOHEADER = @AUTOHEADER@
@@ -92,6 +89,8 @@ ECHO_N = @ECHO_N@
 ECHO_T = @ECHO_T@
 EGREP = @EGREP@
 EXEEXT = @EXEEXT@
+GREP = @GREP@
+INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
 INSTALL_SCRIPT = @INSTALL_SCRIPT@
@@ -101,6 +100,7 @@ LIBOBJS = @LIBOBJS@
 LIBS = @LIBS@
 LTLIBOBJS = @LTLIBOBJS@
 MAKEINFO = @MAKEINFO@
+MKDIR_P = @MKDIR_P@
 OBJEXT = @OBJEXT@
 PACKAGE = @PACKAGE@
 PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
@@ -113,36 +113,48 @@ SET_MAKE = @SET_MAKE@
 SHELL = @SHELL@
 STRIP = @STRIP@
 VERSION = @VERSION@
+abs_builddir = @abs_builddir@
+abs_srcdir = @abs_srcdir@
+abs_top_builddir = @abs_top_builddir@
+abs_top_srcdir = @abs_top_srcdir@
 ac_ct_CC = @ac_ct_CC@
 ac_ct_CXX = @ac_ct_CXX@
-ac_ct_STRIP = @ac_ct_STRIP@
-am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
-am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
-am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
-am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
 am__include = @am__include@
 am__leading_dot = @am__leading_dot@
 am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
 bindir = @bindir@
 build_alias = @build_alias@
+builddir = @builddir@
 datadir = @datadir@
+datarootdir = @datarootdir@
+docdir = @docdir@
+dvidir = @dvidir@
 exec_prefix = @exec_prefix@
 host_alias = @host_alias@
+htmldir = @htmldir@
 includedir = @includedir@
 infodir = @infodir@
 install_sh = @install_sh@
 libdir = @libdir@
 libexecdir = @libexecdir@
+localedir = @localedir@
 localstatedir = @localstatedir@
 mandir = @mandir@
 mkdir_p = @mkdir_p@
 oldincludedir = @oldincludedir@
+pdfdir = @pdfdir@
 prefix = @prefix@
 program_transform_name = @program_transform_name@
+psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
+srcdir = @srcdir@
 sysconfdir = @sysconfdir@
 target_alias = @target_alias@
+top_builddir = @top_builddir@
+top_srcdir = @top_srcdir@
 MAINTAINERCLEANFILES = aclocal.m4 config.h.in configure Makefile.in *~
 SUBDIRS = config src . #   
 all: config.h
@@ -186,7 +198,7 @@ $(ACLOCAL_M4):  $(am__aclocal_m4_deps)
 config.h: stamp-h1
        @if test ! -f $@; then \
          rm -f stamp-h1; \
-         $(MAKE) stamp-h1; \
+         $(MAKE) $(AM_MAKEFLAGS) stamp-h1; \
        else :; fi
 
 stamp-h1: $(srcdir)/config.h.in $(top_builddir)/config.status
@@ -199,7 +211,6 @@ $(srcdir)/config.h.in:  $(am__configure_deps)
 
 distclean-hdr:
        -rm -f config.h stamp-h1
-uninstall-info-am:
 
 # This directory's subdirectories are mostly independent; you can cd
 # into them and run `make' without going through this Makefile.
@@ -208,7 +219,13 @@ uninstall-info-am:
 #     (which will cause the Makefiles to be regenerated when you run `make');
 # (2) otherwise, pass the desired values on the `make' command line.
 $(RECURSIVE_TARGETS):
-       @set fnord $$MAKEFLAGS; amf=$$2; \
+       @failcom='exit 1'; \
+       for f in x $$MAKEFLAGS; do \
+         case $$f in \
+           *=* | --[!k]*);; \
+           *k*) failcom='fail=yes';; \
+         esac; \
+       done; \
        dot_seen=no; \
        target=`echo $@ | sed s/-recursive//`; \
        list='$(SUBDIRS)'; for subdir in $$list; do \
@@ -220,15 +237,20 @@ $(RECURSIVE_TARGETS):
            local_target="$$target"; \
          fi; \
          (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-          || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \
+         || eval $$failcom; \
        done; \
        if test "$$dot_seen" = "no"; then \
          $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
        fi; test -z "$$fail"
 
-mostlyclean-recursive clean-recursive distclean-recursive \
-maintainer-clean-recursive:
-       @set fnord $$MAKEFLAGS; amf=$$2; \
+$(RECURSIVE_CLEAN_TARGETS):
+       @failcom='exit 1'; \
+       for f in x $$MAKEFLAGS; do \
+         case $$f in \
+           *=* | --[!k]*);; \
+           *k*) failcom='fail=yes';; \
+         esac; \
+       done; \
        dot_seen=no; \
        case "$@" in \
          distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
@@ -249,7 +271,7 @@ maintainer-clean-recursive:
            local_target="$$target"; \
          fi; \
          (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
-          || case "$$amf" in *=*) exit 1;; *k*) fail=yes;; *) exit 1;; esac; \
+         || eval $$failcom; \
        done && test -z "$$fail"
 tags-recursive:
        list='$(SUBDIRS)'; for subdir in $$list; do \
@@ -265,8 +287,8 @@ ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
        unique=`for i in $$list; do \
            if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
          done | \
-         $(AWK) '    { files[$$0] = 1; } \
-              END { for (i in files) print i; }'`; \
+         $(AWK) '{ files[$$0] = 1; nonemtpy = 1; } \
+             END { if (nonempty) { for (i in files) print i; }; }'`; \
        mkid -fID $$unique
 tags: TAGS
 
@@ -274,14 +296,16 @@ TAGS: tags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \
                $(TAGS_FILES) $(LISP)
        tags=; \
        here=`pwd`; \
-       if (etags --etags-include --version) >/dev/null 2>&1; then \
+       if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
          include_option=--etags-include; \
+         empty_fix=.; \
        else \
          include_option=--include; \
+         empty_fix=; \
        fi; \
        list='$(SUBDIRS)'; for subdir in $$list; do \
          if test "$$subdir" = .; then :; else \
-           test -f $$subdir/TAGS && \
+           test ! -f $$subdir/TAGS || \
              tags="$$tags $$include_option=$$here/$$subdir/TAGS"; \
          fi; \
        done; \
@@ -289,22 +313,23 @@ TAGS: tags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \
        unique=`for i in $$list; do \
            if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
          done | \
-         $(AWK) '    { files[$$0] = 1; } \
-              END { for (i in files) print i; }'`; \
-       test -z "$(ETAGS_ARGS)$$tags$$unique" \
-         || $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-            $$tags $$unique
+         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
+             END { if (nonempty) { for (i in files) print i; }; }'`; \
+       if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+         test -n "$$unique" || unique=$$empty_fix; \
+         $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+           $$tags $$unique; \
+       fi
 ctags: CTAGS
 CTAGS: ctags-recursive $(HEADERS) $(SOURCES) config.h.in $(TAGS_DEPENDENCIES) \
                $(TAGS_FILES) $(LISP)
        tags=; \
-       here=`pwd`; \
        list='$(SOURCES) $(HEADERS) config.h.in $(LISP) $(TAGS_FILES)'; \
        unique=`for i in $$list; do \
            if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
          done | \
-         $(AWK) '    { files[$$0] = 1; } \
-              END { for (i in files) print i; }'`; \
+         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
+             END { if (nonempty) { for (i in files) print i; }; }'`; \
        test -z "$(CTAGS_ARGS)$$tags$$unique" \
          || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
             $$tags $$unique
@@ -319,23 +344,22 @@ distclean-tags:
 
 distdir: $(DISTFILES)
        $(am__remove_distdir)
-       mkdir $(distdir)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
-       list='$(DISTFILES)'; for file in $$list; do \
-         case $$file in \
-           $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
-           $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
-         esac; \
+       test -d $(distdir) || mkdir $(distdir)
+       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
+       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
+       list='$(DISTFILES)'; \
+         dist_files=`for file in $$list; do echo $$file; done | \
+         sed -e "s|^$$srcdirstrip/||;t" \
+             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
+       case $$dist_files in \
+         */*) $(MKDIR_P) `echo "$$dist_files" | \
+                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
+                          sort -u` ;; \
+       esac; \
+       for file in $$dist_files; do \
          if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
-         if test "$$dir" != "$$file" && test "$$dir" != "."; then \
-           dir="/$$dir"; \
-           $(mkdir_p) "$(distdir)$$dir"; \
-         else \
-           dir=''; \
-         fi; \
          if test -d $$d/$$file; then \
+           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
            if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
              cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
            fi; \
@@ -346,15 +370,19 @@ distdir: $(DISTFILES)
            || exit 1; \
          fi; \
        done
-       list='$(SUBDIRS)'; for subdir in $$list; do \
+       list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
          if test "$$subdir" = .; then :; else \
            test -d "$(distdir)/$$subdir" \
-           || mkdir "$(distdir)/$$subdir" \
+           || $(MKDIR_P) "$(distdir)/$$subdir" \
            || exit 1; \
+           distdir=`$(am__cd) $(distdir) && pwd`; \
+           top_distdir=`$(am__cd) $(top_distdir) && pwd`; \
            (cd $$subdir && \
              $(MAKE) $(AM_MAKEFLAGS) \
-               top_distdir="../$(top_distdir)" \
-               distdir="../$(distdir)/$$subdir" \
+               top_distdir="$$top_distdir" \
+               distdir="$$distdir/$$subdir" \
+               am__remove_distdir=: \
+               am__skip_length_check=: \
                distdir) \
              || exit 1; \
          fi; \
@@ -362,18 +390,22 @@ distdir: $(DISTFILES)
        -find $(distdir) -type d ! -perm -777 -exec chmod a+rwx {} \; -o \
          ! -type d ! -perm -444 -links 1 -exec chmod a+r {} \; -o \
          ! -type d ! -perm -400 -exec chmod a+r {} \; -o \
-         ! -type d ! -perm -444 -exec $(SHELL) $(install_sh) -c -m a+r {} {} \; \
+         ! -type d ! -perm -444 -exec $(install_sh) -c -m a+r {} {} \; \
        || chmod -R a+r $(distdir)
 dist-gzip: distdir
-       $(AMTAR) chof - $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
+       tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
        $(am__remove_distdir)
 
 dist-bzip2: distdir
-       $(AMTAR) chof - $(distdir) | bzip2 -9 -c >$(distdir).tar.bz2
+       tardir=$(distdir) && $(am__tar) | bzip2 -9 -c >$(distdir).tar.bz2
+       $(am__remove_distdir)
+
+dist-lzma: distdir
+       tardir=$(distdir) && $(am__tar) | lzma -9 -c >$(distdir).tar.lzma
        $(am__remove_distdir)
 
 dist-tarZ: distdir
-       $(AMTAR) chof - $(distdir) | compress -c >$(distdir).tar.Z
+       tardir=$(distdir) && $(am__tar) | compress -c >$(distdir).tar.Z
        $(am__remove_distdir)
 
 dist-shar: distdir
@@ -386,7 +418,7 @@ dist-zip: distdir
        $(am__remove_distdir)
 
 dist dist-all: distdir
-       $(AMTAR) chof - $(distdir) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
+       tardir=$(distdir) && $(am__tar) | GZIP=$(GZIP_ENV) gzip -c >$(distdir).tar.gz
        $(am__remove_distdir)
 
 # This target untars the dist file and tries a VPATH configuration.  Then
@@ -395,13 +427,15 @@ dist dist-all: distdir
 distcheck: dist
        case '$(DIST_ARCHIVES)' in \
        *.tar.gz*) \
-         GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(AMTAR) xf - ;;\
+         GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | $(am__untar) ;;\
        *.tar.bz2*) \
-         bunzip2 -c $(distdir).tar.bz2 | $(AMTAR) xf - ;;\
+         bunzip2 -c $(distdir).tar.bz2 | $(am__untar) ;;\
+       *.tar.lzma*) \
+         unlzma -c $(distdir).tar.lzma | $(am__untar) ;;\
        *.tar.Z*) \
-         uncompress -c $(distdir).tar.Z | $(AMTAR) xf - ;;\
+         uncompress -c $(distdir).tar.Z | $(am__untar) ;;\
        *.shar.gz*) \
-         GZIP=$(GZIP_ENV) gunzip -c $(distdir).tar.gz | unshar ;;\
+         GZIP=$(GZIP_ENV) gunzip -c $(distdir).shar.gz | unshar ;;\
        *.zip*) \
          unzip $(distdir).zip ;;\
        esac
@@ -437,7 +471,7 @@ distcheck: dist
        $(am__remove_distdir)
        @(echo "$(distdir) archives ready for distribution: "; \
          list='$(DIST_ARCHIVES)'; for i in $$list; do echo $$i; done) | \
-         sed -e '1{h;s/./=/g;p;x;}' -e '$${p;x;}'
+         sed -e 1h -e 1s/./=/g -e 1p -e 1x -e '$$p' -e '$$x'
 distuninstallcheck:
        @cd $(distuninstallcheck_dir) \
        && test `$(distuninstallcheck_listfiles) | wc -l` -le 1 \
@@ -480,7 +514,7 @@ mostlyclean-generic:
 clean-generic:
 
 distclean-generic:
-       -rm -f $(CONFIG_CLEAN_FILES)
+       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
 
 maintainer-clean-generic:
        @echo "This command is intended for maintainers to use"
@@ -507,12 +541,20 @@ info-am:
 
 install-data-am:
 
+install-dvi: install-dvi-recursive
+
 install-exec-am:
 
+install-html: install-html-recursive
+
 install-info: install-info-recursive
 
 install-man:
 
+install-pdf: install-pdf-recursive
+
+install-ps: install-ps-recursive
+
 installcheck-am:
 
 maintainer-clean: maintainer-clean-recursive
@@ -533,24 +575,25 @@ ps: ps-recursive
 
 ps-am:
 
-uninstall-am: uninstall-info-am
-
-uninstall-info: uninstall-info-recursive
-
-.PHONY: $(RECURSIVE_TARGETS) CTAGS GTAGS all all-am am--refresh check \
-       check-am clean clean-generic clean-recursive ctags \
-       ctags-recursive dist dist-all dist-bzip2 dist-gzip dist-shar \
-       dist-tarZ dist-zip distcheck distclean distclean-generic \
-       distclean-hdr distclean-recursive distclean-tags \
-       distcleancheck distdir distuninstallcheck dvi dvi-am html \
-       html-am info info-am install install-am install-data \
-       install-data-am install-exec install-exec-am install-info \
-       install-info-am install-man install-strip installcheck \
-       installcheck-am installdirs installdirs-am maintainer-clean \
-       maintainer-clean-generic maintainer-clean-recursive \
-       mostlyclean mostlyclean-generic mostlyclean-recursive pdf \
-       pdf-am ps ps-am tags tags-recursive uninstall uninstall-am \
-       uninstall-info-am
+uninstall-am:
+
+.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) install-am \
+       install-strip
+
+.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \
+       all all-am am--refresh check check-am clean clean-generic \
+       ctags ctags-recursive dist dist-all dist-bzip2 dist-gzip \
+       dist-lzma dist-shar dist-tarZ dist-zip distcheck distclean \
+       distclean-generic distclean-hdr distclean-tags distcleancheck \
+       distdir distuninstallcheck dvi dvi-am html html-am info \
+       info-am install install-am install-data install-data-am \
+       install-dvi install-dvi-am install-exec install-exec-am \
+       install-html install-html-am install-info install-info-am \
+       install-man install-pdf install-pdf-am install-ps \
+       install-ps-am install-strip installcheck installcheck-am \
+       installdirs installdirs-am maintainer-clean \
+       maintainer-clean-generic mostlyclean mostlyclean-generic pdf \
+       pdf-am ps ps-am tags tags-recursive uninstall uninstall-am
 
 #bin_PROGRAMS=mobfwtest
 #mobfwtest_SOURCES=
index c5d6715d1e26be5cf36b4f25f255795b9e80b81d..d57c8f6f964504b16b388749422efdb7ac790d6b 100644 (file)
@@ -1,7 +1,7 @@
-# generated automatically by aclocal 1.8.3 -*- Autoconf -*-
+# generated automatically by aclocal 1.10.1 -*- Autoconf -*-
 
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
-# Free Software Foundation, Inc.
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+# 2005, 2006, 2007, 2008  Free Software Foundation, Inc.
 # This file is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
 # even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 # PARTICULAR PURPOSE.
 
-#                                                        -*- Autoconf -*-
-# Copyright (C) 2002, 2003  Free Software Foundation, Inc.
-# Generated from amversion.in; do not edit by hand.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
+m4_ifndef([AC_AUTOCONF_VERSION],
+  [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
+m4_if(AC_AUTOCONF_VERSION, [2.61],,
+[m4_warning([this file was generated for autoconf 2.61.
+You have another version of autoconf.  It may work, but is not guaranteed to.
+If you have problems, you may need to regenerate the build system entirely.
+To do so, use the procedure documented by the package, typically `autoreconf'.])])
 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+# Copyright (C) 2002, 2003, 2005, 2006, 2007  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
 # AM_AUTOMAKE_VERSION(VERSION)
 # ----------------------------
 # Automake X.Y traces this macro to ensure aclocal.m4 has been
 # generated from the m4 files accompanying Automake X.Y.
-AC_DEFUN([AM_AUTOMAKE_VERSION], [am__api_version="1.8"])
+# (This private macro should not be called outside this file.)
+AC_DEFUN([AM_AUTOMAKE_VERSION],
+[am__api_version='1.10'
+dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to
+dnl require some minimum version.  Point them to the right macro.
+m4_if([$1], [1.10.1], [],
+      [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl
+])
+
+# _AM_AUTOCONF_VERSION(VERSION)
+# -----------------------------
+# aclocal traces this macro to find the Autoconf version.
+# This is a private macro too.  Using m4_define simplifies
+# the logic in aclocal, which can simply ignore this definition.
+m4_define([_AM_AUTOCONF_VERSION], [])
 
 # AM_SET_CURRENT_AUTOMAKE_VERSION
 # -------------------------------
-# Call AM_AUTOMAKE_VERSION so it can be traced.
+# Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced.
 # This function is AC_REQUIREd by AC_INIT_AUTOMAKE.
 AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION],
-        [AM_AUTOMAKE_VERSION([1.8.3])])
-
-# AM_AUX_DIR_EXPAND
+[AM_AUTOMAKE_VERSION([1.10.1])dnl
+m4_ifndef([AC_AUTOCONF_VERSION],
+  [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl
+_AM_AUTOCONF_VERSION(AC_AUTOCONF_VERSION)])
 
-# Copyright (C) 2001, 2003 Free Software Foundation, Inc.
+# AM_AUX_DIR_EXPAND                                         -*- Autoconf -*-
 
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# Copyright (C) 2001, 2003, 2005  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
 # For projects using AC_CONFIG_AUX_DIR([foo]), Autoconf sets
 # $ac_aux_dir to `$srcdir/foo'.  In other projects, it is set to
@@ -106,26 +108,16 @@ AC_PREREQ([2.50])dnl
 am_aux_dir=`cd $ac_aux_dir && pwd`
 ])
 
-# AM_CONDITIONAL                                              -*- Autoconf -*-
-
-# Copyright (C) 1997, 2000, 2001, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
+# AM_CONDITIONAL                                            -*- Autoconf -*-
 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# Copyright (C) 1997, 2000, 2001, 2003, 2004, 2005, 2006
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-# serial 6
+# serial 8
 
 # AM_CONDITIONAL(NAME, SHELL-CONDITION)
 # -------------------------------------
@@ -134,8 +126,10 @@ AC_DEFUN([AM_CONDITIONAL],
 [AC_PREREQ(2.52)dnl
  ifelse([$1], [TRUE],  [AC_FATAL([$0: invalid condition: $1])],
        [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl
-AC_SUBST([$1_TRUE])
-AC_SUBST([$1_FALSE])
+AC_SUBST([$1_TRUE])dnl
+AC_SUBST([$1_FALSE])dnl
+_AM_SUBST_NOTMAKE([$1_TRUE])dnl
+_AM_SUBST_NOTMAKE([$1_FALSE])dnl
 if $2; then
   $1_TRUE=
   $1_FALSE='#'
@@ -145,30 +139,18 @@ else
 fi
 AC_CONFIG_COMMANDS_PRE(
 [if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then
-  AC_MSG_ERROR([conditional "$1" was never defined.
-Usually this means the macro was only invoked conditionally.])
+  AC_MSG_ERROR([[conditional "$1" was never defined.
+Usually this means the macro was only invoked conditionally.]])
 fi])])
 
-# serial 7                                             -*- Autoconf -*-
-
-# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004
+# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
 # Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
-
+# serial 9
 
 # There are a few dirty hacks below to avoid letting `AC_PROG_CC' be
 # written in clear, in which case automake, when reading aclocal.m4,
@@ -177,7 +159,6 @@ fi])])
 # CC etc. in the Makefile, will ask for an AC_PROG_CC use...
 
 
-
 # _AM_DEPENDENCIES(NAME)
 # ----------------------
 # See how the compiler implements dependency checking.
@@ -197,6 +178,7 @@ AC_REQUIRE([AM_DEP_TRACK])dnl
 ifelse([$1], CC,   [depcc="$CC"   am_compiler_list=],
        [$1], CXX,  [depcc="$CXX"  am_compiler_list=],
        [$1], OBJC, [depcc="$OBJC" am_compiler_list='gcc3 gcc'],
+       [$1], UPC,  [depcc="$UPC"  am_compiler_list=],
        [$1], GCJ,  [depcc="$GCJ"  am_compiler_list='gcc3 gcc'],
                    [depcc="$$1"   am_compiler_list=])
 
@@ -262,13 +244,19 @@ AC_CACHE_CHECK([dependency style of $depcc],
        depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
        $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \
          >/dev/null 2>conftest.err &&
+       grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 &&
        grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
        grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 &&
        ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
       # icc doesn't choke on unknown options, it will just issue warnings
-      # (even with -Werror).  So we grep stderr for any message
-      # that says an option was ignored.
-      if grep 'ignoring option' conftest.err >/dev/null 2>&1; then :; else
+      # or remarks (even with -Werror).  So we grep stderr for any message
+      # that says an option was ignored or not supported.
+      # When given -MP, icc 7.0 and 7.1 complain thusly:
+      #   icc: Command line warning: ignoring option '-M'; no argument required
+      # The diagnosis changed in icc 8.0:
+      #   icc: Command line remark: option '-MP' not supported
+      if (grep 'ignoring option' conftest.err ||
+          grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
         am_cv_$1_dependencies_compiler_type=$depmode
         break
       fi
@@ -309,29 +297,20 @@ if test "x$enable_dependency_tracking" != xno; then
   AMDEPBACKSLASH='\'
 fi
 AM_CONDITIONAL([AMDEP], [test "x$enable_dependency_tracking" != xno])
-AC_SUBST([AMDEPBACKSLASH])
+AC_SUBST([AMDEPBACKSLASH])dnl
+_AM_SUBST_NOTMAKE([AMDEPBACKSLASH])dnl
 ])
 
-# Generate code to set up dependency tracking.   -*- Autoconf -*-
-
-# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
+# Generate code to set up dependency tracking.              -*- Autoconf -*-
 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-#serial 2
+#serial 3
 
 # _AM_OUTPUT_DEPENDENCY_COMMANDS
 # ------------------------------
@@ -344,33 +323,28 @@ AC_DEFUN([_AM_OUTPUT_DEPENDENCY_COMMANDS],
   # some people rename them; so instead we look at the file content.
   # Grep'ing the first line is not enough: some people post-process
   # each Makefile.in and add a new line on top of each file to say so.
-  # So let's grep whole file.
-  if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then
+  # Grep'ing the whole file is not good either: AIX grep has a line
+  # limit of 2048, but all sed's we know have understand at least 4000.
+  if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then
     dirpart=`AS_DIRNAME("$mf")`
   else
     continue
   fi
-  grep '^DEP_FILES *= *[[^ @%:@]]' < "$mf" > /dev/null || continue
-  # Extract the definition of DEP_FILES from the Makefile without
-  # running `make'.
+  # Extract the definition of DEPDIR, am__include, and am__quote
+  # from the Makefile without running `make'.
   DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"`
   test -z "$DEPDIR" && continue
+  am__include=`sed -n 's/^am__include = //p' < "$mf"`
+  test -z "am__include" && continue
+  am__quote=`sed -n 's/^am__quote = //p' < "$mf"`
   # When using ansi2knr, U may be empty or an underscore; expand it
   U=`sed -n 's/^U = //p' < "$mf"`
-  test -d "$dirpart/$DEPDIR" || mkdir "$dirpart/$DEPDIR"
-  # We invoke sed twice because it is the simplest approach to
-  # changing $(DEPDIR) to its actual value in the expansion.
-  for file in `sed -n '
-    /^DEP_FILES = .*\\\\$/ {
-      s/^DEP_FILES = //
-      :loop
-       s/\\\\$//
-       p
-       n
-       /\\\\$/ b loop
-      p
-    }
-    /^DEP_FILES = / s/^DEP_FILES = //p' < "$mf" | \
+  # Find all dependency output files, they are included files with
+  # $(DEPDIR) in their names.  We invoke sed twice because it is the
+  # simplest approach to changing $(DEPDIR) to its actual value in the
+  # expansion.
+  for file in `sed -n "
+    s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \
        sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do
     # Make sure the directory exists.
     test -f "$dirpart/$file" && continue
@@ -396,54 +370,31 @@ AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS],
      [AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"])
 ])
 
-# Like AC_CONFIG_HEADER, but automatically create stamp file. -*- Autoconf -*-
-
-# Copyright (C) 1996, 1997, 2000, 2001, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-# serial 7
+# serial 8
 
 # AM_CONFIG_HEADER is obsolete.  It has been replaced by AC_CONFIG_HEADERS.
 AU_DEFUN([AM_CONFIG_HEADER], [AC_CONFIG_HEADERS($@)])
 
-# Do all the work for Automake.                            -*- Autoconf -*-
-
-# This macro actually does too much some checks are only needed if
-# your package does certain things.  But this isn't really a big deal.
-
-# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
-# Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
+# Do all the work for Automake.                             -*- Autoconf -*-
 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
+# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
+# 2005, 2006, 2008 Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# serial 13
 
-# serial 11
+# This macro actually does too much.  Some checks are only needed if
+# your package does certain things.  But this isn't really a big deal.
 
 # AM_INIT_AUTOMAKE(PACKAGE, VERSION, [NO-DEFINE])
 # AM_INIT_AUTOMAKE([OPTIONS])
@@ -457,16 +408,20 @@ AU_DEFUN([AM_CONFIG_HEADER], [AC_CONFIG_HEADERS($@)])
 # arguments mandatory, and then we can depend on a new Autoconf
 # release and drop the old call support.
 AC_DEFUN([AM_INIT_AUTOMAKE],
-[AC_PREREQ([2.58])dnl
+[AC_PREREQ([2.60])dnl
 dnl Autoconf wants to disallow AM_ names.  We explicitly allow
 dnl the ones we care about.
 m4_pattern_allow([^AM_[A-Z]+FLAGS$])dnl
 AC_REQUIRE([AM_SET_CURRENT_AUTOMAKE_VERSION])dnl
 AC_REQUIRE([AC_PROG_INSTALL])dnl
-# test to see if srcdir already configured
-if test "`cd $srcdir && pwd`" != "`pwd`" &&
-   test -f $srcdir/config.status; then
-  AC_MSG_ERROR([source directory already configured; run "make distclean" there first])
+if test "`cd $srcdir && pwd`" != "`pwd`"; then
+  # Use -I$(srcdir) only when $(srcdir) != ., so that make's output
+  # is not polluted with repeated "-I."
+  AC_SUBST([am__isrc], [' -I$(srcdir)'])_AM_SUBST_NOTMAKE([am__isrc])dnl
+  # test to see if srcdir already configured
+  if test -f $srcdir/config.status; then
+    AC_MSG_ERROR([source directory already configured; run "make distclean" there first])
+  fi
 fi
 
 # test whether we have cygpath
@@ -486,6 +441,9 @@ m4_ifval([$2],
  AC_SUBST([PACKAGE], [$1])dnl
  AC_SUBST([VERSION], [$2])],
 [_AM_SET_OPTIONS([$1])dnl
+dnl Diagnose old-style AC_INIT with new-style AM_AUTOMAKE_INIT.
+m4_if(m4_ifdef([AC_PACKAGE_NAME], 1)m4_ifdef([AC_PACKAGE_VERSION], 1), 11,,
+  [m4_fatal([AC_INIT should be called with package and version arguments])])dnl
  AC_SUBST([PACKAGE], ['AC_PACKAGE_TARNAME'])dnl
  AC_SUBST([VERSION], ['AC_PACKAGE_VERSION'])])dnl
 
@@ -501,7 +459,6 @@ AM_MISSING_PROG(AUTOCONF, autoconf)
 AM_MISSING_PROG(AUTOMAKE, automake-${am__api_version})
 AM_MISSING_PROG(AUTOHEADER, autoheader)
 AM_MISSING_PROG(MAKEINFO, makeinfo)
-AM_MISSING_PROG(AMTAR, tar)
 AM_PROG_INSTALL_SH
 AM_PROG_INSTALL_STRIP
 AC_REQUIRE([AM_PROG_MKDIR_P])dnl
@@ -510,7 +467,9 @@ AC_REQUIRE([AM_PROG_MKDIR_P])dnl
 AC_REQUIRE([AC_PROG_AWK])dnl
 AC_REQUIRE([AC_PROG_MAKE_SET])dnl
 AC_REQUIRE([AM_SET_LEADING_DOT])dnl
-
+_AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])],
+              [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])],
+                            [_AM_PROG_TAR([v7])])])
 _AM_IF_OPTION([no-dependencies],,
 [AC_PROVIDE_IFELSE([AC_PROG_CC],
                   [_AM_DEPENDENCIES(CC)],
@@ -520,6 +479,10 @@ AC_PROVIDE_IFELSE([AC_PROG_CXX],
                   [_AM_DEPENDENCIES(CXX)],
                   [define([AC_PROG_CXX],
                           defn([AC_PROG_CXX])[_AM_DEPENDENCIES(CXX)])])dnl
+AC_PROVIDE_IFELSE([AC_PROG_OBJC],
+                  [_AM_DEPENDENCIES(OBJC)],
+                  [define([AC_PROG_OBJC],
+                          defn([AC_PROG_OBJC])[_AM_DEPENDENCIES(OBJC)])])dnl
 ])
 ])
 
@@ -533,62 +496,39 @@ AC_PROVIDE_IFELSE([AC_PROG_CXX],
 # our stamp files there.
 AC_DEFUN([_AC_AM_CONFIG_HEADER_HOOK],
 [# Compute $1's index in $config_headers.
+_am_arg=$1
 _am_stamp_count=1
 for _am_header in $config_headers :; do
   case $_am_header in
-    $1 | $1:* )
+    $_am_arg | $_am_arg:* )
       break ;;
     * )
       _am_stamp_count=`expr $_am_stamp_count + 1` ;;
   esac
 done
-echo "timestamp for $1" >`AS_DIRNAME([$1])`/stamp-h[]$_am_stamp_count])
+echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count])
+
+# Copyright (C) 2001, 2003, 2005  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
 # AM_PROG_INSTALL_SH
 # ------------------
 # Define $install_sh.
-
-# Copyright (C) 2001, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
-
 AC_DEFUN([AM_PROG_INSTALL_SH],
 [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
-install_sh=${install_sh-"$am_aux_dir/install-sh"}
+install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"}
 AC_SUBST(install_sh)])
 
-#                                                          -*- Autoconf -*-
-# Copyright (C) 2003  Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# Copyright (C) 2003, 2005  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-# serial 1
+# serial 2
 
 # Check whether the underlying file-system supports filenames
 # with a leading dot.  For instance MS-DOS doesn't.
@@ -603,26 +543,15 @@ fi
 rmdir .tst 2>/dev/null
 AC_SUBST([am__leading_dot])])
 
-# Check to see how 'make' treats includes.     -*- Autoconf -*-
-
-# Copyright (C) 2001, 2002, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
+# Check to see how 'make' treats includes.                 -*- Autoconf -*-
 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# Copyright (C) 2001, 2002, 2003, 2005  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-# serial 2
+# serial 3
 
 # AM_MAKE_INCLUDE()
 # -----------------
@@ -666,27 +595,16 @@ AC_MSG_RESULT([$_am_result])
 rm -f confinc confmf
 ])
 
-#  -*- Autoconf -*-
+# Fake the existence of programs that GNU maintainers use.  -*- Autoconf -*-
 
+# Copyright (C) 1997, 1999, 2000, 2001, 2003, 2004, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-# Copyright (C) 1997, 1999, 2000, 2001, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
-
-# serial 3
+# serial 5
 
 # AM_MISSING_PROG(NAME, PROGRAM)
 # ------------------------------
@@ -702,6 +620,7 @@ AC_SUBST($1)])
 # If it does, set am_missing_run to use it, otherwise, to nothing.
 AC_DEFUN([AM_MISSING_HAS_RUN],
 [AC_REQUIRE([AM_AUX_DIR_EXPAND])dnl
+AC_REQUIRE_AUX_FILE([missing])dnl
 test x"${MISSING+set}" = xset || MISSING="\${SHELL} $am_aux_dir/missing"
 # Use eval to expand $SHELL
 if eval "$MISSING --run true"; then
@@ -712,92 +631,41 @@ else
 fi
 ])
 
+# Copyright (C) 2003, 2004, 2005, 2006  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
 # AM_PROG_MKDIR_P
 # ---------------
-# Check whether `mkdir -p' is supported, fallback to mkinstalldirs otherwise.
-
-# Copyright (C) 2003, 2004 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
-
-# Automake 1.8 used `mkdir -m 0755 -p --' to ensure that directories
-# created by `make install' are always world readable, even if the
-# installer happens to have an overly restrictive umask (e.g. 077).
-# This was a mistake.  There are at least two reasons why we must not
-# use `-m 0755':
-#   - it causes special bits like SGID to be ignored,
-#   - it may be too restrictive (some setups expect 775 directories).
-#
-# Do not use -m 0755 and let people choose whatever they expect by
-# setting umask.
-#
-# We cannot accept any implementation of `mkdir' that recognizes `-p'.
-# Some implementations (such as Solaris 8's) are not thread-safe: if a
-# parallel make tries to run `mkdir -p a/b' and `mkdir -p a/c'
-# concurrently, both version can detect that a/ is missing, but only
-# one can create it and the other will error out.  Consequently we
-# restrict ourselves to GNU make (using the --version option ensures
-# this.)
+# Check for `mkdir -p'.
 AC_DEFUN([AM_PROG_MKDIR_P],
-[if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then
-  # Keeping the `.' argument allows $(mkdir_p) to be used without
-  # argument.  Indeed, we sometimes output rules like
-  #   $(mkdir_p) $(somedir)
-  # where $(somedir) is conditionally defined.
-  # (`test -n '$(somedir)' && $(mkdir_p) $(somedir)' is a more
-  # expensive solution, as it forces Make to start a sub-shell.)
-  mkdir_p='mkdir -p -- .'
-else
-  # On NextStep and OpenStep, the `mkdir' command does not
-  # recognize any option.  It will interpret all options as
-  # directories to create, and then abort because `.' already
-  # exists.
-  for d in ./-p ./--version;
-  do
-    test -d $d && rmdir $d
-  done
-  # $(mkinstalldirs) is defined by Automake if mkinstalldirs exists.
-  if test -f "$ac_aux_dir/mkinstalldirs"; then
-    mkdir_p='$(mkinstalldirs)'
-  else
-    mkdir_p='$(install_sh) -d'
-  fi
-fi
-AC_SUBST([mkdir_p])])
-
-# Helper functions for option handling.                    -*- Autoconf -*-
-
-# Copyright (C) 2001, 2002, 2003  Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
+[AC_PREREQ([2.60])dnl
+AC_REQUIRE([AC_PROG_MKDIR_P])dnl
+dnl Automake 1.8 to 1.9.6 used to define mkdir_p.  We now use MKDIR_P,
+dnl while keeping a definition of mkdir_p for backward compatibility.
+dnl @MKDIR_P@ is magic: AC_OUTPUT adjusts its value for each Makefile.
+dnl However we cannot define mkdir_p as $(MKDIR_P) for the sake of
+dnl Makefile.ins that do not define MKDIR_P, so we do our own
+dnl adjustment using top_builddir (which is defined more often than
+dnl MKDIR_P).
+AC_SUBST([mkdir_p], ["$MKDIR_P"])dnl
+case $mkdir_p in
+  [[\\/$]]* | ?:[[\\/]]*) ;;
+  */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;;
+esac
+])
 
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
+# Helper functions for option handling.                     -*- Autoconf -*-
 
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# Copyright (C) 2001, 2002, 2003, 2005  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-# serial 2
+# serial 3
 
 # _AM_MANGLE_OPTION(NAME)
 # -----------------------
@@ -822,28 +690,16 @@ AC_DEFUN([_AM_SET_OPTIONS],
 AC_DEFUN([_AM_IF_OPTION],
 [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])])
 
-#
-# Check to make sure that the build environment is sane.
-#
-
-# Copyright (C) 1996, 1997, 2000, 2001, 2003 Free Software Foundation, Inc.
+# Check to make sure that the build environment is sane.    -*- Autoconf -*-
 
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# Copyright (C) 1996, 1997, 2000, 2001, 2003, 2005
+# Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
-# serial 3
+# serial 4
 
 # AM_SANITY_CHECK
 # ---------------
@@ -886,25 +742,14 @@ Check your system clock])
 fi
 AC_MSG_RESULT(yes)])
 
-# AM_PROG_INSTALL_STRIP
-
-# Copyright (C) 2001, 2003 Free Software Foundation, Inc.
-
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 2, or (at your option)
-# any later version.
-
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
-# 02111-1307, USA.
+# Copyright (C) 2001, 2003, 2005  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
 
+# AM_PROG_INSTALL_STRIP
+# ---------------------
 # One issue with vendor `install' (even GNU) is that you can't
 # specify the program used to strip binaries.  This is especially
 # annoying in cross-compiling environments, where the build's strip
@@ -922,6 +767,114 @@ dnl Don't test for $cross_compiling = yes, because it might be `maybe'.
 if test "$cross_compiling" != no; then
   AC_CHECK_TOOL([STRIP], [strip], :)
 fi
-INSTALL_STRIP_PROGRAM="\${SHELL} \$(install_sh) -c -s"
+INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s"
 AC_SUBST([INSTALL_STRIP_PROGRAM])])
 
+# Copyright (C) 2006  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# _AM_SUBST_NOTMAKE(VARIABLE)
+# ---------------------------
+# Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in.
+# This macro is traced by Automake.
+AC_DEFUN([_AM_SUBST_NOTMAKE])
+
+# Check how to create a tarball.                            -*- Autoconf -*-
+
+# Copyright (C) 2004, 2005  Free Software Foundation, Inc.
+#
+# This file is free software; the Free Software Foundation
+# gives unlimited permission to copy and/or distribute it,
+# with or without modifications, as long as this notice is preserved.
+
+# serial 2
+
+# _AM_PROG_TAR(FORMAT)
+# --------------------
+# Check how to create a tarball in format FORMAT.
+# FORMAT should be one of `v7', `ustar', or `pax'.
+#
+# Substitute a variable $(am__tar) that is a command
+# writing to stdout a FORMAT-tarball containing the directory
+# $tardir.
+#     tardir=directory && $(am__tar) > result.tar
+#
+# Substitute a variable $(am__untar) that extract such
+# a tarball read from stdin.
+#     $(am__untar) < result.tar
+AC_DEFUN([_AM_PROG_TAR],
+[# Always define AMTAR for backward compatibility.
+AM_MISSING_PROG([AMTAR], [tar])
+m4_if([$1], [v7],
+     [am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -'],
+     [m4_case([$1], [ustar],, [pax],,
+              [m4_fatal([Unknown tar format])])
+AC_MSG_CHECKING([how to create a $1 tar archive])
+# Loop over all known methods to create a tar archive until one works.
+_am_tools='gnutar m4_if([$1], [ustar], [plaintar]) pax cpio none'
+_am_tools=${am_cv_prog_tar_$1-$_am_tools}
+# Do not fold the above two line into one, because Tru64 sh and
+# Solaris sh will not grok spaces in the rhs of `-'.
+for _am_tool in $_am_tools
+do
+  case $_am_tool in
+  gnutar)
+    for _am_tar in tar gnutar gtar;
+    do
+      AM_RUN_LOG([$_am_tar --version]) && break
+    done
+    am__tar="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$$tardir"'
+    am__tar_="$_am_tar --format=m4_if([$1], [pax], [posix], [$1]) -chf - "'"$tardir"'
+    am__untar="$_am_tar -xf -"
+    ;;
+  plaintar)
+    # Must skip GNU tar: if it does not support --format= it doesn't create
+    # ustar tarball either.
+    (tar --version) >/dev/null 2>&1 && continue
+    am__tar='tar chf - "$$tardir"'
+    am__tar_='tar chf - "$tardir"'
+    am__untar='tar xf -'
+    ;;
+  pax)
+    am__tar='pax -L -x $1 -w "$$tardir"'
+    am__tar_='pax -L -x $1 -w "$tardir"'
+    am__untar='pax -r'
+    ;;
+  cpio)
+    am__tar='find "$$tardir" -print | cpio -o -H $1 -L'
+    am__tar_='find "$tardir" -print | cpio -o -H $1 -L'
+    am__untar='cpio -i -H $1 -d'
+    ;;
+  none)
+    am__tar=false
+    am__tar_=false
+    am__untar=false
+    ;;
+  esac
+
+  # If the value was cached, stop now.  We just wanted to have am__tar
+  # and am__untar set.
+  test -n "${am_cv_prog_tar_$1}" && break
+
+  # tar/untar a dummy directory, and stop if the command works
+  rm -rf conftest.dir
+  mkdir conftest.dir
+  echo GrepMe > conftest.dir/file
+  AM_RUN_LOG([tardir=conftest.dir && eval $am__tar_ >conftest.tar])
+  rm -rf conftest.dir
+  if test -s conftest.tar; then
+    AM_RUN_LOG([$am__untar <conftest.tar])
+    grep GrepMe conftest.dir/file >/dev/null 2>&1 && break
+  fi
+done
+rm -rf conftest.dir
+
+AC_CACHE_VAL([am_cv_prog_tar_$1], [am_cv_prog_tar_$1=$_am_tool])
+AC_MSG_RESULT([$am_cv_prog_tar_$1])])
+AC_SUBST([am__tar])
+AC_SUBST([am__untar])
+]) # _AM_PROG_TAR
+
index 19808a0979fb8f580f8f73866b76240528b059f2..812ccc7de112f96be5f6f4f5e2687393d4f47ac2 100644 (file)
@@ -1,35 +1,71 @@
 /* config.h.in.  Generated from configure.in by autoheader.  */
 
+/* Define to 1 if you have the <fcntl.h> header file. */
+#undef HAVE_FCNTL_H
+
 /* Define to 1 if you have the <inttypes.h> header file. */
 #undef HAVE_INTTYPES_H
 
 /* Define to 1 if you have the `popt' library (-lpopt). */
 #undef HAVE_LIBPOPT
 
+/* Define to 1 if you have the <linux/version.h> header file. */
+#undef HAVE_LINUX_VERSION_H
+
 /* Define to 1 if you have the <memory.h> header file. */
 #undef HAVE_MEMORY_H
 
+/* Define to 1 if you have the <popt.h> header file. */
+#undef HAVE_POPT_H
+
+/* Define to 1 if you have the `select' function. */
+#undef HAVE_SELECT
+
+/* Define to 1 if stdbool.h conforms to C99. */
+#undef HAVE_STDBOOL_H
+
 /* Define to 1 if you have the <stdint.h> header file. */
 #undef HAVE_STDINT_H
 
 /* Define to 1 if you have the <stdlib.h> header file. */
 #undef HAVE_STDLIB_H
 
+/* Define to 1 if you have the `strerror' function. */
+#undef HAVE_STRERROR
+
 /* Define to 1 if you have the <strings.h> header file. */
 #undef HAVE_STRINGS_H
 
 /* Define to 1 if you have the <string.h> header file. */
 #undef HAVE_STRING_H
 
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#undef HAVE_SYS_IOCTL_H
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#undef HAVE_SYS_SELECT_H
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#undef HAVE_SYS_SOCKET_H
+
 /* Define to 1 if you have the <sys/stat.h> header file. */
 #undef HAVE_SYS_STAT_H
 
+/* Define to 1 if you have the <sys/time.h> header file. */
+#undef HAVE_SYS_TIME_H
+
 /* Define to 1 if you have the <sys/types.h> header file. */
 #undef HAVE_SYS_TYPES_H
 
+/* Define to 1 if you have the <termios.h> header file. */
+#undef HAVE_TERMIOS_H
+
 /* Define to 1 if you have the <unistd.h> header file. */
 #undef HAVE_UNISTD_H
 
+/* Define to 1 if the system has the type `_Bool'. */
+#undef HAVE__BOOL
+
 /* Name of package */
 #undef PACKAGE
 
 /* Define to the version of this package. */
 #undef PACKAGE_VERSION
 
+/* Define to the type of arg 1 for `select'. */
+#undef SELECT_TYPE_ARG1
+
+/* Define to the type of args 2, 3 and 4 for `select'. */
+#undef SELECT_TYPE_ARG234
+
+/* Define to the type of arg 5 for `select'. */
+#undef SELECT_TYPE_ARG5
+
 /* Define to 1 if you have the ANSI C header files. */
 #undef STDC_HEADERS
 
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#undef TIME_WITH_SYS_TIME
+
 /* Version number of package */
 #undef VERSION
 
+/* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>,
+   <pthread.h>, or <semaphore.h> is not used. If the typedef was allowed, the
+   #define below would cause a syntax error. */
+#undef _UINT8_T
+
 /* Define to empty if `const' does not conform to ANSI C. */
 #undef const
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+   calls it, or to nothing if 'inline' is not supported under any name.  */
+#ifndef __cplusplus
+#undef inline
+#endif
+
+/* Define to the type of an unsigned integer type of width exactly 16 bits if
+   such a type exists and the standard includes do not define it. */
+#undef uint16_t
+
+/* Define to the type of an unsigned integer type of width exactly 8 bits if
+   such a type exists and the standard includes do not define it. */
+#undef uint8_t
index 2296d49cc582d6f4a5a0ea7f8b7fbd61e53692bc..039cb8cac2923351910fe1c4fa1fc6b0b21a83ca 100644 (file)
@@ -1,8 +1,8 @@
-# Makefile.in generated by automake 1.8.3 from Makefile.am.
+# Makefile.in generated by automake 1.10.1 from Makefile.am.
 # @configure_input@
 
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008  Free Software Foundation, Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
 # PARTICULAR PURPOSE.
 
 @SET_MAKE@
-srcdir = @srcdir@
-top_srcdir = @top_srcdir@
 VPATH = @srcdir@
 pkgdatadir = $(datadir)/@PACKAGE@
 pkglibdir = $(libdir)/@PACKAGE@
 pkgincludedir = $(includedir)/@PACKAGE@
-top_builddir = ..
 am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-INSTALL = @INSTALL@
 install_sh_DATA = $(install_sh) -c -m 644
 install_sh_PROGRAM = $(install_sh) -c
 install_sh_SCRIPT = $(install_sh) -c
@@ -40,15 +36,13 @@ ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/configure.in
 am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
        $(ACLOCAL_M4)
-mkinstalldirs = $(mkdir_p)
+mkinstalldirs = $(install_sh) -d
 CONFIG_HEADER = $(top_builddir)/config.h
 CONFIG_CLEAN_FILES =
 SOURCES =
 DIST_SOURCES =
 DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL = @ACLOCAL@
-AMDEP_FALSE = @AMDEP_FALSE@
-AMDEP_TRUE = @AMDEP_TRUE@
 AMTAR = @AMTAR@
 AUTOCONF = @AUTOCONF@
 AUTOHEADER = @AUTOHEADER@
@@ -70,6 +64,8 @@ ECHO_N = @ECHO_N@
 ECHO_T = @ECHO_T@
 EGREP = @EGREP@
 EXEEXT = @EXEEXT@
+GREP = @GREP@
+INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
 INSTALL_SCRIPT = @INSTALL_SCRIPT@
@@ -79,6 +75,7 @@ LIBOBJS = @LIBOBJS@
 LIBS = @LIBS@
 LTLIBOBJS = @LTLIBOBJS@
 MAKEINFO = @MAKEINFO@
+MKDIR_P = @MKDIR_P@
 OBJEXT = @OBJEXT@
 PACKAGE = @PACKAGE@
 PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
@@ -91,36 +88,48 @@ SET_MAKE = @SET_MAKE@
 SHELL = @SHELL@
 STRIP = @STRIP@
 VERSION = @VERSION@
+abs_builddir = @abs_builddir@
+abs_srcdir = @abs_srcdir@
+abs_top_builddir = @abs_top_builddir@
+abs_top_srcdir = @abs_top_srcdir@
 ac_ct_CC = @ac_ct_CC@
 ac_ct_CXX = @ac_ct_CXX@
-ac_ct_STRIP = @ac_ct_STRIP@
-am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
-am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
-am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
-am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
 am__include = @am__include@
 am__leading_dot = @am__leading_dot@
 am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
 bindir = @bindir@
 build_alias = @build_alias@
+builddir = @builddir@
 datadir = @datadir@
+datarootdir = @datarootdir@
+docdir = @docdir@
+dvidir = @dvidir@
 exec_prefix = @exec_prefix@
 host_alias = @host_alias@
+htmldir = @htmldir@
 includedir = @includedir@
 infodir = @infodir@
 install_sh = @install_sh@
 libdir = @libdir@
 libexecdir = @libexecdir@
+localedir = @localedir@
 localstatedir = @localstatedir@
 mandir = @mandir@
 mkdir_p = @mkdir_p@
 oldincludedir = @oldincludedir@
+pdfdir = @pdfdir@
 prefix = @prefix@
 program_transform_name = @program_transform_name@
+psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
+srcdir = @srcdir@
 sysconfdir = @sysconfdir@
 target_alias = @target_alias@
+top_builddir = @top_builddir@
+top_srcdir = @top_srcdir@
 MAINTAINERCLEANFILES = Makefile.in config.guess config.sub depcomp \
                          install-sh ltmain.sh missing \
                        mkinstalldirs *~
@@ -157,7 +166,6 @@ $(top_srcdir)/configure:  $(am__configure_deps)
        cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 $(ACLOCAL_M4):  $(am__aclocal_m4_deps)
        cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
-uninstall-info-am:
 tags: TAGS
 TAGS:
 
@@ -166,22 +174,21 @@ CTAGS:
 
 
 distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
-       list='$(DISTFILES)'; for file in $$list; do \
-         case $$file in \
-           $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
-           $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
-         esac; \
+       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
+       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
+       list='$(DISTFILES)'; \
+         dist_files=`for file in $$list; do echo $$file; done | \
+         sed -e "s|^$$srcdirstrip/||;t" \
+             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
+       case $$dist_files in \
+         */*) $(MKDIR_P) `echo "$$dist_files" | \
+                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
+                          sort -u` ;; \
+       esac; \
+       for file in $$dist_files; do \
          if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
-         if test "$$dir" != "$$file" && test "$$dir" != "."; then \
-           dir="/$$dir"; \
-           $(mkdir_p) "$(distdir)$$dir"; \
-         else \
-           dir=''; \
-         fi; \
          if test -d $$d/$$file; then \
+           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
            if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
              cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
            fi; \
@@ -215,7 +222,7 @@ mostlyclean-generic:
 clean-generic:
 
 distclean-generic:
-       -rm -f $(CONFIG_CLEAN_FILES)
+       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
 
 maintainer-clean-generic:
        @echo "This command is intended for maintainers to use"
@@ -241,12 +248,20 @@ info-am:
 
 install-data-am:
 
+install-dvi: install-dvi-am
+
 install-exec-am:
 
+install-html: install-html-am
+
 install-info: install-info-am
 
 install-man:
 
+install-pdf: install-pdf-am
+
+install-ps: install-ps-am
+
 installcheck-am:
 
 maintainer-clean: maintainer-clean-am
@@ -265,16 +280,19 @@ ps: ps-am
 
 ps-am:
 
-uninstall-am: uninstall-info-am
+uninstall-am:
+
+.MAKE: install-am install-strip
 
 .PHONY: all all-am check check-am clean clean-generic distclean \
        distclean-generic distdir dvi dvi-am html html-am info info-am \
-       install install-am install-data install-data-am install-exec \
-       install-exec-am install-info install-info-am install-man \
+       install install-am install-data install-data-am install-dvi \
+       install-dvi-am install-exec install-exec-am install-html \
+       install-html-am install-info install-info-am install-man \
+       install-pdf install-pdf-am install-ps install-ps-am \
        install-strip installcheck installcheck-am installdirs \
        maintainer-clean maintainer-clean-generic mostlyclean \
-       mostlyclean-generic pdf pdf-am ps ps-am uninstall uninstall-am \
-       uninstall-info-am
+       mostlyclean-generic pdf pdf-am ps ps-am uninstall uninstall-am
 
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
index 7ef6bab143555ea987b8af65d3ccafef875441b0..4cf4ea2c2d944d62f370c285ed61cfce5cede851 100755 (executable)
@@ -1,27 +1,56 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.59 for cppbsl 0.1.
+# Generated by GNU Autoconf 2.61 for cppbsl 0.1.
 #
 # Report bugs to <koepke@tkn.tu-berlin.de>.
 #
-# Copyright (C) 2003 Free Software Foundation, Inc.
+# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
 # This configure script is free software; the Free Software Foundation
 # gives unlimited permission to copy, distribute and modify it.
 ## --------------------- ##
 ## M4sh Initialization.  ##
 ## --------------------- ##
 
-# Be Bourne compatible
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
 if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
   emulate sh
   NULLCMD=:
   # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
   # is contrary to our usage.  Disable this feature.
   alias -g '${1+"$@"}'='"$@"'
-elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
-  set -o posix
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
 fi
-DUALCASE=1; export DUALCASE # for MKS sh
 
 # Support unset when possible.
 if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
@@ -31,8 +60,43 @@ else
 fi
 
 
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""       $as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
 # Work around bugs in pre-3.0 UWIN ksh.
-$as_unset ENV MAIL MAILPATH
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
 PS1='$ '
 PS2='> '
 PS4='+ '
@@ -46,18 +110,19 @@ do
   if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
     eval $as_var=C; export $as_var
   else
-    $as_unset $as_var
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
   fi
 done
 
 # Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1; then
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
   as_expr=expr
 else
   as_expr=false
 fi
 
-if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
   as_basename=basename
 else
   as_basename=false
@@ -65,157 +130,388 @@ fi
 
 
 # Name of the executable.
-as_me=`$as_basename "$0" ||
+as_me=`$as_basename -- "$0" ||
 $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
         X"$0" : 'X\(//\)$' \| \
-        X"$0" : 'X\(/\)$' \| \
-        .     : '\(.\)' 2>/dev/null ||
+        X"$0" : 'X\(/\)' \| . 2>/dev/null ||
 echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
-         /^X\/\(\/\/\)$/{ s//\1/; q; }
-         /^X\/\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+           s//\1/
+           q
+         }
+         /^X\/\(\/\/\)$/{
+           s//\1/
+           q
+         }
+         /^X\/\(\/\).*/{
+           s//\1/
+           q
+         }
+         s/.*/./; q'`
 
+# CDPATH.
+$as_unset CDPATH
 
-# PATH needs CR, and LINENO needs CR and PATH.
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
 
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
+if test "x$CONFIG_SHELL" = x; then
+  if (eval ":") 2>/dev/null; then
+  as_have_required=yes
+else
+  as_have_required=no
 fi
 
+  if test $as_have_required = yes &&    (eval ":
+(as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
 
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2"  || {
-  # Find who we are.  Look in the path if we contain no path at all
-  # relative or not.
-  case $0 in
-    *[\\/]* ) as_myself=$0 ;;
-    *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-done
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
 
-       ;;
-  esac
-  # We did not find ourselves, most probably we were run as `sh COMMAND'
-  # in which case we are not to be found in the path.
-  if test "x$as_myself" = x; then
-    as_myself=$0
-  fi
-  if test ! -f "$as_myself"; then
-    { echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2
-   { (exit 1); exit 1; }; }
-  fi
-  case $CONFIG_SHELL in
-  '')
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0) || { (exit 1); exit 1; }
+
+(
+  as_lineno_1=\$LINENO
+  as_lineno_2=\$LINENO
+  test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" &&
+  test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; }
+") 2> /dev/null; then
+  :
+else
+  as_candidate_shells=
     as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
 for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
 do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
-  for as_base in sh bash ksh sh5; do
-        case $as_dir in
+  case $as_dir in
         /*)
-          if ("$as_dir/$as_base" -c '
+          for as_base in sh bash ksh sh5; do
+            as_candidate_shells="$as_candidate_shells $as_dir/$as_base"
+          done;;
+       esac
+done
+IFS=$as_save_IFS
+
+
+      for as_shell in $as_candidate_shells $SHELL; do
+        # Try only shells that exist, to save several forks.
+        if { test -f "$as_shell" || test -f "$as_shell.exe"; } &&
+               { ("$as_shell") 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+_ASEOF
+}; then
+  CONFIG_SHELL=$as_shell
+              as_have_required=yes
+              if { "$as_shell" 2> /dev/null <<\_ASEOF
+if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
+  emulate sh
+  NULLCMD=:
+  # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
+  # is contrary to our usage.  Disable this feature.
+  alias -g '${1+"$@"}'='"$@"'
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+:
+(as_func_return () {
+  (exit $1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = "$1" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test $exitcode = 0) || { (exit 1); exit 1; }
+
+(
   as_lineno_1=$LINENO
   as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
   test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2" ') 2>/dev/null; then
-            $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
-            $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
-            CONFIG_SHELL=$as_dir/$as_base
-            export CONFIG_SHELL
-            exec "$CONFIG_SHELL" "$0" ${1+"$@"}
-          fi;;
-        esac
-       done
-done
-;;
-  esac
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; }
+
+_ASEOF
+}; then
+  break
+fi
+
+fi
+
+      done
+
+      if test "x$CONFIG_SHELL" != x; then
+  for as_var in BASH_ENV ENV
+        do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+        done
+        export CONFIG_SHELL
+        exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+fi
+
+
+    if test $as_have_required = no; then
+  echo This script requires a shell more modern than all the
+      echo shells that I found on your system.  Please install a
+      echo modern shell, or manually run the script under such a
+      echo shell if you do have one.
+      { (exit 1); exit 1; }
+fi
+
+
+fi
+
+fi
+
+
+
+(eval "as_func_return () {
+  (exit \$1)
+}
+as_func_success () {
+  as_func_return 0
+}
+as_func_failure () {
+  as_func_return 1
+}
+as_func_ret_success () {
+  return 0
+}
+as_func_ret_failure () {
+  return 1
+}
+
+exitcode=0
+if as_func_success; then
+  :
+else
+  exitcode=1
+  echo as_func_success failed.
+fi
+
+if as_func_failure; then
+  exitcode=1
+  echo as_func_failure succeeded.
+fi
+
+if as_func_ret_success; then
+  :
+else
+  exitcode=1
+  echo as_func_ret_success failed.
+fi
+
+if as_func_ret_failure; then
+  exitcode=1
+  echo as_func_ret_failure succeeded.
+fi
+
+if ( set x; as_func_ret_success y && test x = \"\$1\" ); then
+  :
+else
+  exitcode=1
+  echo positional parameters were not saved.
+fi
+
+test \$exitcode = 0") || {
+  echo No shell found that supports shell functions.
+  echo Please tell autoconf@gnu.org about your system,
+  echo including any error possibly output before this
+  echo message
+}
+
+
+
+  as_lineno_1=$LINENO
+  as_lineno_2=$LINENO
+  test "x$as_lineno_1" != "x$as_lineno_2" &&
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
 
   # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
   # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line before each line; the second 'sed' does the real
-  # work.  The second script uses 'N' to pair each line-number line
-  # with the numbered line, and appends trailing '-' during
-  # substitution so that $LINENO is not a special case at line end.
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
   # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # second 'sed' script.  Blame Lee E. McMahon for sed's syntax.  :-)
-  sed '=' <$as_myself |
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
     sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
       N
-      s,$,-,
-      : loop
-      s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
       t loop
-      s,-$,,
-      s,^['$as_cr_digits']*\n,,
+      s/-\n.*//
     ' >$as_me.lineno &&
-  chmod +x $as_me.lineno ||
+  chmod +x "$as_me.lineno" ||
     { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
    { (exit 1); exit 1; }; }
 
   # Don't try to exec as it changes $[0], causing all sort of problems
   # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensible to this).
-  . ./$as_me.lineno
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
   # Exit status is that of the last command.
   exit
 }
 
 
-case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
-  *c*,-n*) ECHO_N= ECHO_C='
-' ECHO_T='     ' ;;
-  *c*,*  ) ECHO_N=-n ECHO_C= ECHO_T= ;;
-  *)       ECHO_N= ECHO_C='\c' ECHO_T= ;;
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='        ';;     # ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
 esac
 
-if expr a : '\(a\)' >/dev/null 2>&1; then
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
   as_expr=expr
 else
   as_expr=false
 fi
 
 rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
 echo >conf$$.file
 if ln -s conf$$.file conf$$ 2>/dev/null; then
-  # We could just check for DJGPP; but this test a) works b) is more generic
-  # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
-  if test -f conf$$.exe; then
-    # Don't use ln at all; we don't have any links
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
     as_ln_s='cp -p'
-  else
-    as_ln_s='ln -s'
-  fi
 elif ln conf$$.file conf$$ 2>/dev/null; then
   as_ln_s=ln
 else
   as_ln_s='cp -p'
 fi
-rm -f conf$$ conf$$.exe conf$$.file
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
 
 if mkdir -p . 2>/dev/null; then
   as_mkdir_p=:
@@ -224,7 +520,28 @@ else
   as_mkdir_p=false
 fi
 
-as_executable_p="test -f"
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+       case $1 in
+        -*)set "./$1";;
+       esac;
+       case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+       ???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
 
 # Sed expression to map a string onto a valid CPP name.
 as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
@@ -233,39 +550,27 @@ as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
 as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
 
 
-# IFS
-# We need space, tab and new line, in precisely that order.
-as_nl='
-'
-IFS="  $as_nl"
-
-# CDPATH.
-$as_unset CDPATH
 
+exec 7<&0 </dev/null 6>&1
 
 # Name of the host.
 # hostname on some systems (SVR3.2, Linux) returns a bogus exit status,
 # so uname gets run too.
 ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q`
 
-exec 6>&1
-
 #
 # Initializations.
 #
 ac_default_prefix=/usr/local
+ac_clean_files=
 ac_config_libobj_dir=.
+LIBOBJS=
 cross_compiling=no
 subdirs=
 MFLAGS=
 MAKEFLAGS=
 SHELL=${CONFIG_SHELL-/bin/sh}
 
-# Maximum number of lines to put in a shell here document.
-# This variable seems obsolete.  It should probably be removed, and
-# only ac_max_sed_lines should be used.
-: ${ac_max_here_lines=38}
-
 # Identity of this package.
 PACKAGE_NAME='cppbsl'
 PACKAGE_TARNAME='cppbsl'
@@ -277,42 +582,139 @@ ac_unique_file="src"
 # Factoring default headers for most tests.
 ac_includes_default="\
 #include <stdio.h>
-#if HAVE_SYS_TYPES_H
+#ifdef HAVE_SYS_TYPES_H
 # include <sys/types.h>
 #endif
-#if HAVE_SYS_STAT_H
+#ifdef HAVE_SYS_STAT_H
 # include <sys/stat.h>
 #endif
-#if STDC_HEADERS
+#ifdef STDC_HEADERS
 # include <stdlib.h>
 # include <stddef.h>
 #else
-# if HAVE_STDLIB_H
+# ifdef HAVE_STDLIB_H
 #  include <stdlib.h>
 # endif
 #endif
-#if HAVE_STRING_H
-# if !STDC_HEADERS && HAVE_MEMORY_H
+#ifdef HAVE_STRING_H
+# if !defined STDC_HEADERS && defined HAVE_MEMORY_H
 #  include <memory.h>
 # endif
 # include <string.h>
 #endif
-#if HAVE_STRINGS_H
+#ifdef HAVE_STRINGS_H
 # include <strings.h>
 #endif
-#if HAVE_INTTYPES_H
+#ifdef HAVE_INTTYPES_H
 # include <inttypes.h>
-#else
-# if HAVE_STDINT_H
-#  include <stdint.h>
-# endif
 #endif
-#if HAVE_UNISTD_H
+#ifdef HAVE_STDINT_H
+# include <stdint.h>
+#endif
+#ifdef HAVE_UNISTD_H
 # include <unistd.h>
 #endif"
 
-ac_subst_vars='SHELL PATH_SEPARATOR PACKAGE_NAME PACKAGE_TARNAME PACKAGE_VERSION PACKAGE_STRING PACKAGE_BUGREPORT exec_prefix prefix program_transform_name bindir sbindir libexecdir datadir sysconfdir sharedstatedir localstatedir libdir includedir oldincludedir infodir mandir build_alias host_alias target_alias DEFS ECHO_C ECHO_N ECHO_T LIBS INSTALL_PROGRAM INSTALL_SCRIPT INSTALL_DATA CYGPATH_W PACKAGE VERSION ACLOCAL AUTOCONF AUTOMAKE AUTOHEADER MAKEINFO AMTAR install_sh STRIP ac_ct_STRIP INSTALL_STRIP_PROGRAM mkdir_p AWK SET_MAKE am__leading_dot CC CFLAGS LDFLAGS CPPFLAGS ac_ct_CC EXEEXT OBJEXT DEPDIR am__include am__quote AMDEP_TRUE AMDEP_FALSE AMDEPBACKSLASH CCDEPMODE am__fastdepCC_TRUE am__fastdepCC_FALSE CPP CXX CXXFLAGS ac_ct_CXX CXXDEPMODE am__fastdepCXX_TRUE am__fastdepCXX_FALSE EGREP LIBOBJS LTLIBOBJS'
+ac_subst_vars='SHELL
+PATH_SEPARATOR
+PACKAGE_NAME
+PACKAGE_TARNAME
+PACKAGE_VERSION
+PACKAGE_STRING
+PACKAGE_BUGREPORT
+exec_prefix
+prefix
+program_transform_name
+bindir
+sbindir
+libexecdir
+datarootdir
+datadir
+sysconfdir
+sharedstatedir
+localstatedir
+includedir
+oldincludedir
+docdir
+infodir
+htmldir
+dvidir
+pdfdir
+psdir
+libdir
+localedir
+mandir
+DEFS
+ECHO_C
+ECHO_N
+ECHO_T
+LIBS
+build_alias
+host_alias
+target_alias
+INSTALL_PROGRAM
+INSTALL_SCRIPT
+INSTALL_DATA
+am__isrc
+CYGPATH_W
+PACKAGE
+VERSION
+ACLOCAL
+AUTOCONF
+AUTOMAKE
+AUTOHEADER
+MAKEINFO
+install_sh
+STRIP
+INSTALL_STRIP_PROGRAM
+mkdir_p
+AWK
+SET_MAKE
+am__leading_dot
+AMTAR
+am__tar
+am__untar
+CC
+CFLAGS
+LDFLAGS
+CPPFLAGS
+ac_ct_CC
+EXEEXT
+OBJEXT
+DEPDIR
+am__include
+am__quote
+AMDEP_TRUE
+AMDEP_FALSE
+AMDEPBACKSLASH
+CCDEPMODE
+am__fastdepCC_TRUE
+am__fastdepCC_FALSE
+CPP
+CXX
+CXXFLAGS
+ac_ct_CXX
+CXXDEPMODE
+am__fastdepCXX_TRUE
+am__fastdepCXX_FALSE
+GREP
+EGREP
+LIBOBJS
+LTLIBOBJS'
 ac_subst_files=''
+      ac_precious_vars='build_alias
+host_alias
+target_alias
+CC
+CFLAGS
+LDFLAGS
+LIBS
+CPPFLAGS
+CPP
+CXX
+CXXFLAGS
+CCC'
+
 
 # Initialize some variables set by options.
 ac_init_help=
@@ -339,34 +741,48 @@ x_libraries=NONE
 # and all the variables that are supposed to be based on exec_prefix
 # by default will actually change.
 # Use braces instead of parens because sh, perl, etc. also accept them.
+# (The list follows the same order as the GNU Coding Standards.)
 bindir='${exec_prefix}/bin'
 sbindir='${exec_prefix}/sbin'
 libexecdir='${exec_prefix}/libexec'
-datadir='${prefix}/share'
+datarootdir='${prefix}/share'
+datadir='${datarootdir}'
 sysconfdir='${prefix}/etc'
 sharedstatedir='${prefix}/com'
 localstatedir='${prefix}/var'
-libdir='${exec_prefix}/lib'
 includedir='${prefix}/include'
 oldincludedir='/usr/include'
-infodir='${prefix}/info'
-mandir='${prefix}/man'
+docdir='${datarootdir}/doc/${PACKAGE_TARNAME}'
+infodir='${datarootdir}/info'
+htmldir='${docdir}'
+dvidir='${docdir}'
+pdfdir='${docdir}'
+psdir='${docdir}'
+libdir='${exec_prefix}/lib'
+localedir='${datarootdir}/locale'
+mandir='${datarootdir}/man'
 
 ac_prev=
+ac_dashdash=
 for ac_option
 do
   # If the previous option needs an argument, assign it.
   if test -n "$ac_prev"; then
-    eval "$ac_prev=\$ac_option"
+    eval $ac_prev=\$ac_option
     ac_prev=
     continue
   fi
 
-  ac_optarg=`expr "x$ac_option" : 'x[^=]*=\(.*\)'`
+  case $ac_option in
+  *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;;
+  *)   ac_optarg=yes ;;
+  esac
 
   # Accept the important Cygnus configure options, so we can diagnose typos.
 
-  case $ac_option in
+  case $ac_dashdash$ac_option in
+  --)
+    ac_dashdash=yes ;;
 
   -bindir | --bindir | --bindi | --bind | --bin | --bi)
     ac_prev=bindir ;;
@@ -388,33 +804,45 @@ do
   --config-cache | -C)
     cache_file=config.cache ;;
 
-  -datadir | --datadir | --datadi | --datad | --data | --dat | --da)
+  -datadir | --datadir | --datadi | --datad)
     ac_prev=datadir ;;
-  -datadir=* | --datadir=* | --datadi=* | --datad=* | --data=* | --dat=* \
-  | --da=*)
+  -datadir=* | --datadir=* | --datadi=* | --datad=*)
     datadir=$ac_optarg ;;
 
+  -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \
+  | --dataroo | --dataro | --datar)
+    ac_prev=datarootdir ;;
+  -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \
+  | --dataroot=* | --dataroo=* | --dataro=* | --datar=*)
+    datarootdir=$ac_optarg ;;
+
   -disable-* | --disable-*)
     ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid feature name: $ac_feature" >&2
    { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/-/_/g'`
-    eval "enable_$ac_feature=no" ;;
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=no ;;
+
+  -docdir | --docdir | --docdi | --doc | --do)
+    ac_prev=docdir ;;
+  -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*)
+    docdir=$ac_optarg ;;
+
+  -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv)
+    ac_prev=dvidir ;;
+  -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*)
+    dvidir=$ac_optarg ;;
 
   -enable-* | --enable-*)
     ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_feature" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+    expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid feature name: $ac_feature" >&2
    { (exit 1); exit 1; }; }
-    ac_feature=`echo $ac_feature | sed 's/-/_/g'`
-    case $ac_option in
-      *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "enable_$ac_feature='$ac_optarg'" ;;
+    ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'`
+    eval enable_$ac_feature=\$ac_optarg ;;
 
   -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \
   | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \
@@ -441,6 +869,12 @@ do
   -host=* | --host=* | --hos=* | --ho=*)
     host_alias=$ac_optarg ;;
 
+  -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht)
+    ac_prev=htmldir ;;
+  -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \
+  | --ht=*)
+    htmldir=$ac_optarg ;;
+
   -includedir | --includedir | --includedi | --included | --include \
   | --includ | --inclu | --incl | --inc)
     ac_prev=includedir ;;
@@ -465,13 +899,16 @@ do
   | --libexe=* | --libex=* | --libe=*)
     libexecdir=$ac_optarg ;;
 
+  -localedir | --localedir | --localedi | --localed | --locale)
+    ac_prev=localedir ;;
+  -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*)
+    localedir=$ac_optarg ;;
+
   -localstatedir | --localstatedir | --localstatedi | --localstated \
-  | --localstate | --localstat | --localsta | --localst \
-  | --locals | --local | --loca | --loc | --lo)
+  | --localstate | --localstat | --localsta | --localst | --locals)
     ac_prev=localstatedir ;;
   -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \
-  | --localstate=* | --localstat=* | --localsta=* | --localst=* \
-  | --locals=* | --local=* | --loca=* | --loc=* | --lo=*)
+  | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*)
     localstatedir=$ac_optarg ;;
 
   -mandir | --mandir | --mandi | --mand | --man | --ma | --m)
@@ -536,6 +973,16 @@ do
   | --progr-tra=* | --program-tr=* | --program-t=*)
     program_transform_name=$ac_optarg ;;
 
+  -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd)
+    ac_prev=pdfdir ;;
+  -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*)
+    pdfdir=$ac_optarg ;;
+
+  -psdir | --psdir | --psdi | --psd | --ps)
+    ac_prev=psdir ;;
+  -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*)
+    psdir=$ac_optarg ;;
+
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil)
     silent=yes ;;
@@ -588,24 +1035,20 @@ do
   -with-* | --with-*)
     ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid package name: $ac_package" >&2
    { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package| sed 's/-/_/g'`
-    case $ac_option in
-      *=*) ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`;;
-      *) ac_optarg=yes ;;
-    esac
-    eval "with_$ac_package='$ac_optarg'" ;;
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=\$ac_optarg ;;
 
   -without-* | --without-*)
     ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'`
     # Reject names that are not valid shell variable names.
-    expr "x$ac_package" : ".*[^-_$as_cr_alnum]" >/dev/null &&
+    expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid package name: $ac_package" >&2
    { (exit 1); exit 1; }; }
-    ac_package=`echo $ac_package | sed 's/-/_/g'`
-    eval "with_$ac_package=no" ;;
+    ac_package=`echo $ac_package | sed 's/[-.]/_/g'`
+    eval with_$ac_package=no ;;
 
   --x)
     # Obsolete; use --with-x.
@@ -636,8 +1079,7 @@ Try \`$0 --help' for more information." >&2
     expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null &&
       { echo "$as_me: error: invalid variable name: $ac_envvar" >&2
    { (exit 1); exit 1; }; }
-    ac_optarg=`echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"`
-    eval "$ac_envvar='$ac_optarg'"
+    eval $ac_envvar=\$ac_optarg
     export $ac_envvar ;;
 
   *)
@@ -657,27 +1099,19 @@ if test -n "$ac_prev"; then
    { (exit 1); exit 1; }; }
 fi
 
-# Be sure to have absolute paths.
-for ac_var in exec_prefix prefix
-do
-  eval ac_val=$`echo $ac_var`
-  case $ac_val in
-    [\\/$]* | ?:[\\/]* | NONE | '' ) ;;
-    *)  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
-   { (exit 1); exit 1; }; };;
-  esac
-done
-
-# Be sure to have absolute paths.
-for ac_var in bindir sbindir libexecdir datadir sysconfdir sharedstatedir \
-             localstatedir libdir includedir oldincludedir infodir mandir
+# Be sure to have absolute directory names.
+for ac_var in  exec_prefix prefix bindir sbindir libexecdir datarootdir \
+               datadir sysconfdir sharedstatedir localstatedir includedir \
+               oldincludedir docdir infodir htmldir dvidir pdfdir psdir \
+               libdir localedir mandir
 do
-  eval ac_val=$`echo $ac_var`
+  eval ac_val=\$$ac_var
   case $ac_val in
-    [\\/$]* | ?:[\\/]* ) ;;
-    *)  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
-   { (exit 1); exit 1; }; };;
+    [\\/$]* | ?:[\\/]* )  continue;;
+    NONE | '' ) case $ac_var in *prefix ) continue;; esac;;
   esac
+  { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2
+   { (exit 1); exit 1; }; }
 done
 
 # There might be people who depend on the old broken behavior: `$host'
@@ -704,82 +1138,76 @@ test -n "$host_alias" && ac_tool_prefix=$host_alias-
 test "$silent" = yes && exec 6>/dev/null
 
 
-# Find the source files, if location was not specified.
-if test -z "$srcdir"; then
+ac_pwd=`pwd` && test -n "$ac_pwd" &&
+ac_ls_di=`ls -di .` &&
+ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` ||
+  { echo "$as_me: error: Working directory cannot be determined" >&2
+   { (exit 1); exit 1; }; }
+test "X$ac_ls_di" = "X$ac_pwd_ls_di" ||
+  { echo "$as_me: error: pwd does not report name of working directory" >&2
+   { (exit 1); exit 1; }; }
+
+
+# Find the source files, if location was not specified.
+if test -z "$srcdir"; then
   ac_srcdir_defaulted=yes
-  # Try the directory containing this script, then its parent.
-  ac_confdir=`(dirname "$0") 2>/dev/null ||
+  # Try the directory containing this script, then the parent directory.
+  ac_confdir=`$as_dirname -- "$0" ||
 $as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$0" : 'X\(//\)[^/]' \| \
         X"$0" : 'X\(//\)$' \| \
-        X"$0" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
+        X"$0" : 'X\(/\)' \| . 2>/dev/null ||
 echo X"$0" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)[^/].*/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\).*/{
+           s//\1/
+           q
+         }
+         s/.*/./; q'`
   srcdir=$ac_confdir
-  if test ! -r $srcdir/$ac_unique_file; then
+  if test ! -r "$srcdir/$ac_unique_file"; then
     srcdir=..
   fi
 else
   ac_srcdir_defaulted=no
 fi
-if test ! -r $srcdir/$ac_unique_file; then
-  if test "$ac_srcdir_defaulted" = yes; then
-    { echo "$as_me: error: cannot find sources ($ac_unique_file) in $ac_confdir or .." >&2
-   { (exit 1); exit 1; }; }
-  else
-    { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
+if test ! -r "$srcdir/$ac_unique_file"; then
+  test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .."
+  { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2
    { (exit 1); exit 1; }; }
-  fi
 fi
-(cd $srcdir && test -r ./$ac_unique_file) 2>/dev/null ||
-  { echo "$as_me: error: sources are in $srcdir, but \`cd $srcdir' does not work" >&2
+ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work"
+ac_abs_confdir=`(
+       cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2
    { (exit 1); exit 1; }; }
-srcdir=`echo "$srcdir" | sed 's%\([^\\/]\)[\\/]*$%\1%'`
-ac_env_build_alias_set=${build_alias+set}
-ac_env_build_alias_value=$build_alias
-ac_cv_env_build_alias_set=${build_alias+set}
-ac_cv_env_build_alias_value=$build_alias
-ac_env_host_alias_set=${host_alias+set}
-ac_env_host_alias_value=$host_alias
-ac_cv_env_host_alias_set=${host_alias+set}
-ac_cv_env_host_alias_value=$host_alias
-ac_env_target_alias_set=${target_alias+set}
-ac_env_target_alias_value=$target_alias
-ac_cv_env_target_alias_set=${target_alias+set}
-ac_cv_env_target_alias_value=$target_alias
-ac_env_CC_set=${CC+set}
-ac_env_CC_value=$CC
-ac_cv_env_CC_set=${CC+set}
-ac_cv_env_CC_value=$CC
-ac_env_CFLAGS_set=${CFLAGS+set}
-ac_env_CFLAGS_value=$CFLAGS
-ac_cv_env_CFLAGS_set=${CFLAGS+set}
-ac_cv_env_CFLAGS_value=$CFLAGS
-ac_env_LDFLAGS_set=${LDFLAGS+set}
-ac_env_LDFLAGS_value=$LDFLAGS
-ac_cv_env_LDFLAGS_set=${LDFLAGS+set}
-ac_cv_env_LDFLAGS_value=$LDFLAGS
-ac_env_CPPFLAGS_set=${CPPFLAGS+set}
-ac_env_CPPFLAGS_value=$CPPFLAGS
-ac_cv_env_CPPFLAGS_set=${CPPFLAGS+set}
-ac_cv_env_CPPFLAGS_value=$CPPFLAGS
-ac_env_CPP_set=${CPP+set}
-ac_env_CPP_value=$CPP
-ac_cv_env_CPP_set=${CPP+set}
-ac_cv_env_CPP_value=$CPP
-ac_env_CXX_set=${CXX+set}
-ac_env_CXX_value=$CXX
-ac_cv_env_CXX_set=${CXX+set}
-ac_cv_env_CXX_value=$CXX
-ac_env_CXXFLAGS_set=${CXXFLAGS+set}
-ac_env_CXXFLAGS_value=$CXXFLAGS
-ac_cv_env_CXXFLAGS_set=${CXXFLAGS+set}
-ac_cv_env_CXXFLAGS_value=$CXXFLAGS
+       pwd)`
+# When building in place, set srcdir=.
+if test "$ac_abs_confdir" = "$ac_pwd"; then
+  srcdir=.
+fi
+# Remove unnecessary trailing slashes from srcdir.
+# Double slashes in file names in object file debugging info
+# mess up M-x gdb in Emacs.
+case $srcdir in
+*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;;
+esac
+for ac_var in $ac_precious_vars; do
+  eval ac_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_env_${ac_var}_value=\$${ac_var}
+  eval ac_cv_env_${ac_var}_set=\${${ac_var}+set}
+  eval ac_cv_env_${ac_var}_value=\$${ac_var}
+done
 
 #
 # Report the --help message.
@@ -808,9 +1236,6 @@ Configuration:
   -n, --no-create         do not create output files
       --srcdir=DIR        find the sources in DIR [configure dir or \`..']
 
-_ACEOF
-
-  cat <<_ACEOF
 Installation directories:
   --prefix=PREFIX         install architecture-independent files in PREFIX
                          [$ac_default_prefix]
@@ -828,15 +1253,22 @@ Fine tuning of the installation directories:
   --bindir=DIR           user executables [EPREFIX/bin]
   --sbindir=DIR          system admin executables [EPREFIX/sbin]
   --libexecdir=DIR       program executables [EPREFIX/libexec]
-  --datadir=DIR          read-only architecture-independent data [PREFIX/share]
   --sysconfdir=DIR       read-only single-machine data [PREFIX/etc]
   --sharedstatedir=DIR   modifiable architecture-independent data [PREFIX/com]
   --localstatedir=DIR    modifiable single-machine data [PREFIX/var]
   --libdir=DIR           object code libraries [EPREFIX/lib]
   --includedir=DIR       C header files [PREFIX/include]
   --oldincludedir=DIR    C header files for non-gcc [/usr/include]
-  --infodir=DIR          info documentation [PREFIX/info]
-  --mandir=DIR           man documentation [PREFIX/man]
+  --datarootdir=DIR      read-only arch.-independent data root [PREFIX/share]
+  --datadir=DIR          read-only architecture-independent data [DATAROOTDIR]
+  --infodir=DIR          info documentation [DATAROOTDIR/info]
+  --localedir=DIR        locale-dependent data [DATAROOTDIR/locale]
+  --mandir=DIR           man documentation [DATAROOTDIR/man]
+  --docdir=DIR           documentation root [DATAROOTDIR/doc/cppbsl]
+  --htmldir=DIR          html documentation [DOCDIR]
+  --dvidir=DIR           dvi documentation [DOCDIR]
+  --pdfdir=DIR           pdf documentation [DOCDIR]
+  --psdir=DIR            ps documentation [DOCDIR]
 _ACEOF
 
   cat <<\_ACEOF
@@ -869,8 +1301,9 @@ Some influential environment variables:
   CFLAGS      C compiler flags
   LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
               nonstandard directory <lib dir>
-  CPPFLAGS    C/C++ preprocessor flags, e.g. -I<include dir> if you have
-              headers in a nonstandard directory <include dir>
+  LIBS        libraries to pass to the linker, e.g. -l<library>
+  CPPFLAGS    C/C++/Objective C preprocessor flags, e.g. -I<include dir> if
+              you have headers in a nonstandard directory <include dir>
   CPP         C preprocessor
   CXX         C++ compiler command
   CXXFLAGS    C++ compiler flags
@@ -880,120 +1313,86 @@ it to find libraries and programs with nonstandard names/locations.
 
 Report bugs to <koepke@tkn.tu-berlin.de>.
 _ACEOF
+ac_status=$?
 fi
 
 if test "$ac_init_help" = "recursive"; then
   # If there are subdirs, report their specific --help.
-  ac_popdir=`pwd`
   for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue
-    test -d $ac_dir || continue
+    test -d "$ac_dir" || continue
     ac_builddir=.
 
-if test "$ac_dir" != .; then
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
   ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A "../" for each directory in $ac_dir_suffix.
-  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
-else
-  ac_dir_suffix= ac_top_builddir=
-fi
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
 
 case $srcdir in
-  .)  # No --srcdir option.  We are building in place.
+  .)  # We are building in place.
     ac_srcdir=.
-    if test -z "$ac_top_builddir"; then
-       ac_top_srcdir=.
-    else
-       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
-    fi ;;
-  [\\/]* | ?:[\\/]* )  # Absolute path.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
     ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir ;;
-  *) # Relative path.
-    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_builddir$srcdir ;;
-esac
-
-# Do not use `cd foo && pwd` to compute absolute paths, because
-# the directories may not exist.
-case `pwd` in
-.) ac_abs_builddir="$ac_dir";;
-*)
-  case "$ac_dir" in
-  .) ac_abs_builddir=`pwd`;;
-  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
-  *) ac_abs_builddir=`pwd`/"$ac_dir";;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_builddir=${ac_top_builddir}.;;
-*)
-  case ${ac_top_builddir}. in
-  .) ac_abs_top_builddir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
-  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_srcdir=$ac_srcdir;;
-*)
-  case $ac_srcdir in
-  .) ac_abs_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
-  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_srcdir=$ac_top_srcdir;;
-*)
-  case $ac_top_srcdir in
-  .) ac_abs_top_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
-  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
-  esac;;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
 esac
-
-    cd $ac_dir
-    # Check for guested configure; otherwise get Cygnus style configure.
-    if test -f $ac_srcdir/configure.gnu; then
-      echo
-      $SHELL $ac_srcdir/configure.gnu  --help=recursive
-    elif test -f $ac_srcdir/configure; then
-      echo
-      $SHELL $ac_srcdir/configure  --help=recursive
-    elif test -f $ac_srcdir/configure.ac ||
-          test -f $ac_srcdir/configure.in; then
-      echo
-      $ac_configure --help
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
+
+    cd "$ac_dir" || { ac_status=$?; continue; }
+    # Check for guested configure.
+    if test -f "$ac_srcdir/configure.gnu"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure.gnu" --help=recursive
+    elif test -f "$ac_srcdir/configure"; then
+      echo &&
+      $SHELL "$ac_srcdir/configure" --help=recursive
     else
       echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2
-    fi
-    cd $ac_popdir
+    fi || ac_status=$?
+    cd "$ac_pwd" || { ac_status=$?; break; }
   done
 fi
 
-test -n "$ac_init_help" && exit 0
+test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
 cppbsl configure 0.1
-generated by GNU Autoconf 2.59
+generated by GNU Autoconf 2.61
 
-Copyright (C) 2003 Free Software Foundation, Inc.
+Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
+2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
 This configure script is free software; the Free Software Foundation
 gives unlimited permission to copy, distribute and modify it.
 _ACEOF
-  exit 0
+  exit
 fi
-exec 5>config.log
-cat >&5 <<_ACEOF
+cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
 It was created by cppbsl $as_me 0.1, which was
-generated by GNU Autoconf 2.59.  Invocation command line was
+generated by GNU Autoconf 2.61.  Invocation command line was
 
   $ $0 $@
 
 _ACEOF
+exec 5>>config.log
 {
 cat <<_ASUNAME
 ## --------- ##
@@ -1012,7 +1411,7 @@ uname -v = `(uname -v) 2>/dev/null || echo unknown`
 /bin/arch              = `(/bin/arch) 2>/dev/null              || echo unknown`
 /usr/bin/arch -k       = `(/usr/bin/arch -k) 2>/dev/null       || echo unknown`
 /usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown`
-hostinfo               = `(hostinfo) 2>/dev/null               || echo unknown`
+/usr/bin/hostinfo      = `(/usr/bin/hostinfo) 2>/dev/null      || echo unknown`
 /bin/machine           = `(/bin/machine) 2>/dev/null           || echo unknown`
 /usr/bin/oslevel       = `(/usr/bin/oslevel) 2>/dev/null       || echo unknown`
 /bin/universe          = `(/bin/universe) 2>/dev/null          || echo unknown`
@@ -1026,6 +1425,7 @@ do
   test -z "$as_dir" && as_dir=.
   echo "PATH: $as_dir"
 done
+IFS=$as_save_IFS
 
 } >&5
 
@@ -1047,7 +1447,6 @@ _ACEOF
 ac_configure_args=
 ac_configure_args0=
 ac_configure_args1=
-ac_sep=
 ac_must_keep_next=false
 for ac_pass in 1 2
 do
@@ -1058,7 +1457,7 @@ do
     -q | -quiet | --quiet | --quie | --qui | --qu | --q \
     | -silent | --silent | --silen | --sile | --sil)
       continue ;;
-    *" "*|*"   "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
+    *\'*)
       ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;;
     esac
     case $ac_pass in
@@ -1080,9 +1479,7 @@ do
          -* ) ac_must_keep_next=true ;;
        esac
       fi
-      ac_configure_args="$ac_configure_args$ac_sep'$ac_arg'"
-      # Get rid of the leading space.
-      ac_sep=" "
+      ac_configure_args="$ac_configure_args '$ac_arg'"
       ;;
     esac
   done
@@ -1093,8 +1490,8 @@ $as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_
 # When interrupted or exit'd, cleanup temporary files, and complete
 # config.log.  We remove comments because anyway the quotes in there
 # would cause problems or look ugly.
-# WARNING: Be sure not to use single quotes in there, as some shells,
-# such as our DU 5.0 friend, will then `close' the trap.
+# WARNING: Use '\'' to represent an apostrophe within the trap.
+# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug.
 trap 'exit_status=$?
   # Save into config.log some information that might help in debugging.
   {
@@ -1107,20 +1504,34 @@ trap 'exit_status=$?
 _ASBOX
     echo
     # The following way of writing the cache mishandles newlines in values,
-{
+(
+  for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
   (set) 2>&1 |
-    case `(ac_space='"'"' '"'"'; set | grep ac_space) 2>&1` in
-    *ac_space=\ *)
+    case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
       sed -n \
-       "s/'"'"'/'"'"'\\\\'"'"''"'"'/g;
-         s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='"'"'\\2'"'"'/p"
-      ;;
+       "s/'\''/'\''\\\\'\'''\''/g;
+         s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p"
+      ;; #(
     *)
-      sed -n \
-       "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
       ;;
-    esac;
-}
+    esac |
+    sort
+)
     echo
 
     cat <<\_ASBOX
@@ -1131,22 +1542,28 @@ _ASBOX
     echo
     for ac_var in $ac_subst_vars
     do
-      eval ac_val=$`echo $ac_var`
-      echo "$ac_var='"'"'$ac_val'"'"'"
+      eval ac_val=\$$ac_var
+      case $ac_val in
+      *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+      esac
+      echo "$ac_var='\''$ac_val'\''"
     done | sort
     echo
 
     if test -n "$ac_subst_files"; then
       cat <<\_ASBOX
-## ------------- ##
-## Output files. ##
-## ------------- ##
+## ------------------- ##
+## File substitutions. ##
+## ------------------- ##
 _ASBOX
       echo
       for ac_var in $ac_subst_files
       do
-       eval ac_val=$`echo $ac_var`
-       echo "$ac_var='"'"'$ac_val'"'"'"
+       eval ac_val=\$$ac_var
+       case $ac_val in
+       *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;;
+       esac
+       echo "$ac_var='\''$ac_val'\''"
       done | sort
       echo
     fi
@@ -1158,26 +1575,24 @@ _ASBOX
 ## ----------- ##
 _ASBOX
       echo
-      sed "/^$/d" confdefs.h | sort
+      cat confdefs.h
       echo
     fi
     test "$ac_signal" != 0 &&
       echo "$as_me: caught signal $ac_signal"
     echo "$as_me: exit $exit_status"
   } >&5
-  rm -f core *.core &&
-  rm -rf conftest* confdefs* conf$$* $ac_clean_files &&
+  rm -f core *.core core.conftest.* &&
+    rm -f -r conftest* confdefs* conf$$* $ac_clean_files &&
     exit $exit_status
-     ' 0
+' 0
 for ac_signal in 1 2 13 15; do
   trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal
 done
 ac_signal=0
 
 # confdefs.h avoids OS command line length limits that DEFS can exceed.
-rm -rf conftest* confdefs.h
-# AIX cpp loses on an empty file, so make sure it contains at least a newline.
-echo >confdefs.h
+rm -f -r conftest* confdefs.h
 
 # Predefined preprocessor variables.
 
@@ -1208,14 +1623,17 @@ _ACEOF
 
 # Let the site file select an alternate cache file if it wants to.
 # Prefer explicitly selected file to automatically selected ones.
-if test -z "$CONFIG_SITE"; then
-  if test "x$prefix" != xNONE; then
-    CONFIG_SITE="$prefix/share/config.site $prefix/etc/config.site"
-  else
-    CONFIG_SITE="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site"
-  fi
+if test -n "$CONFIG_SITE"; then
+  set x "$CONFIG_SITE"
+elif test "x$prefix" != xNONE; then
+  set x "$prefix/share/config.site" "$prefix/etc/config.site"
+else
+  set x "$ac_default_prefix/share/config.site" \
+       "$ac_default_prefix/etc/config.site"
 fi
-for ac_site_file in $CONFIG_SITE; do
+shift
+for ac_site_file
+do
   if test -r "$ac_site_file"; then
     { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5
 echo "$as_me: loading site script $ac_site_file" >&6;}
@@ -1231,8 +1649,8 @@ if test -r "$cache_file"; then
     { echo "$as_me:$LINENO: loading cache $cache_file" >&5
 echo "$as_me: loading cache $cache_file" >&6;}
     case $cache_file in
-      [\\/]* | ?:[\\/]* ) . $cache_file;;
-      *)                      . ./$cache_file;;
+      [\\/]* | ?:[\\/]* ) . "$cache_file";;
+      *)                      . "./$cache_file";;
     esac
   fi
 else
@@ -1244,12 +1662,11 @@ fi
 # Check that the precious variables saved in the cache have kept the same
 # value.
 ac_cache_corrupted=false
-for ac_var in `(set) 2>&1 |
-              sed -n 's/^ac_env_\([a-zA-Z_0-9]*\)_set=.*/\1/p'`; do
+for ac_var in $ac_precious_vars; do
   eval ac_old_set=\$ac_cv_env_${ac_var}_set
   eval ac_new_set=\$ac_env_${ac_var}_set
-  eval ac_old_val="\$ac_cv_env_${ac_var}_value"
-  eval ac_new_val="\$ac_env_${ac_var}_value"
+  eval ac_old_val=\$ac_cv_env_${ac_var}_value
+  eval ac_new_val=\$ac_env_${ac_var}_value
   case $ac_old_set,$ac_new_set in
     set,)
       { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5
@@ -1274,8 +1691,7 @@ echo "$as_me:   current value: $ac_new_val" >&2;}
   # Pass precious variables to config.status.
   if test "$ac_new_set" = set; then
     case $ac_new_val in
-    *" "*|*"   "*|*[\[\]\~\#\$\^\&\*\(\)\{\}\\\|\;\<\>\?\"\']*)
-      ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
+    *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;;
     *) ac_arg=$ac_var=$ac_new_val ;;
     esac
     case " $ac_configure_args " in
@@ -1292,12 +1708,6 @@ echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start ov
    { (exit 1); exit 1; }; }
 fi
 
-ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
 
 
 
@@ -1322,37 +1732,49 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
 
+ac_ext=c
+ac_cpp='$CPP $CPPFLAGS'
+ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
+ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
+ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
 ac_aux_dir=
-for ac_dir in config $srcdir/config; do
-  if test -f $ac_dir/install-sh; then
+for ac_dir in config "$srcdir"/config; do
+  if test -f "$ac_dir/install-sh"; then
     ac_aux_dir=$ac_dir
     ac_install_sh="$ac_aux_dir/install-sh -c"
     break
-  elif test -f $ac_dir/install.sh; then
+  elif test -f "$ac_dir/install.sh"; then
     ac_aux_dir=$ac_dir
     ac_install_sh="$ac_aux_dir/install.sh -c"
     break
-  elif test -f $ac_dir/shtool; then
+  elif test -f "$ac_dir/shtool"; then
     ac_aux_dir=$ac_dir
     ac_install_sh="$ac_aux_dir/shtool install -c"
     break
   fi
 done
 if test -z "$ac_aux_dir"; then
-  { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in config $srcdir/config" >&5
-echo "$as_me: error: cannot find install-sh or install.sh in config $srcdir/config" >&2;}
+  { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in config \"$srcdir\"/config" >&5
+echo "$as_me: error: cannot find install-sh or install.sh in config \"$srcdir\"/config" >&2;}
    { (exit 1); exit 1; }; }
 fi
-ac_config_guess="$SHELL $ac_aux_dir/config.guess"
-ac_config_sub="$SHELL $ac_aux_dir/config.sub"
-ac_configure="$SHELL $ac_aux_dir/configure" # This should be Cygnus configure.
 
-          ac_config_headers="$ac_config_headers config.h"
+# These three variables are undocumented and unsupported,
+# and are intended to be withdrawn in a future Autoconf release.
+# They can cause serious problems if a builder's source tree is in a directory
+# whose full name contains unusual characters.
+ac_config_guess="$SHELL $ac_aux_dir/config.guess"  # Please don't use this var.
+ac_config_sub="$SHELL $ac_aux_dir/config.sub"  # Please don't use this var.
+ac_configure="$SHELL $ac_aux_dir/configure"  # Please don't use this var.
+
+
+ac_config_headers="$ac_config_headers config.h"
+
 
+am__api_version='1.10'
 
-am__api_version="1.8"
 # Find a good install program.  We prefer a C program (faster),
 # so one script is as good as another.  But avoid the broken or
 # incompatible versions:
@@ -1366,8 +1788,8 @@ am__api_version="1.8"
 # SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff"
 # OS/2's system install, which has a completely different semantic
 # ./install, which can be erroneously created by make from ./install.sh.
-echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5
-echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5
+echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; }
 if test -z "$INSTALL"; then
 if test "${ac_cv_path_install+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
@@ -1389,7 +1811,7 @@ case $as_dir/ in
     # by default.
     for ac_prog in ginstall scoinst install; do
       for ac_exec_ext in '' $ac_executable_extensions; do
-       if $as_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then
+       if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then
          if test $ac_prog = install &&
            grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then
            # AIX install.  It has an incompatible calling convention.
@@ -1408,21 +1830,22 @@ case $as_dir/ in
     ;;
 esac
 done
+IFS=$as_save_IFS
 
 
 fi
   if test "${ac_cv_path_install+set}" = set; then
     INSTALL=$ac_cv_path_install
   else
-    # As a last resort, use the slow shell script.  We don't cache a
-    # path for INSTALL within a source directory, because that will
+    # As a last resort, use the slow shell script.  Don't cache a
+    # value for INSTALL within a source directory, because that will
     # break other packages using the cache if that directory is
-    # removed, or if the path is relative.
+    # removed, or if the value is a relative name.
     INSTALL=$ac_install_sh
   fi
 fi
-echo "$as_me:$LINENO: result: $INSTALL" >&5
-echo "${ECHO_T}$INSTALL" >&6
+echo "$as_me:$LINENO: result: $INSTALL" >&5
+echo "${ECHO_T}$INSTALL" >&6; }
 
 # Use test -z because SunOS4 sh mishandles braces in ${var-val}.
 # It thinks the first close brace ends the variable substitution.
@@ -1432,8 +1855,8 @@ test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}'
 
 test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644'
 
-echo "$as_me:$LINENO: checking whether build environment is sane" >&5
-echo $ECHO_N "checking whether build environment is sane... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking whether build environment is sane" >&5
+echo $ECHO_N "checking whether build environment is sane... $ECHO_C" >&6; }
 # Just in case
 sleep 1
 echo timestamp > conftest.file
@@ -1475,20 +1898,20 @@ echo "$as_me: error: newly created file is older than distributed files!
 Check your system clock" >&2;}
    { (exit 1); exit 1; }; }
 fi
-echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
+echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
 test "$program_prefix" != NONE &&
-  program_transform_name="s,^,$program_prefix,;$program_transform_name"
+  program_transform_name="s&^&$program_prefix&;$program_transform_name"
 # Use a double $ so make ignores it.
 test "$program_suffix" != NONE &&
-  program_transform_name="s,\$,$program_suffix,;$program_transform_name"
+  program_transform_name="s&\$&$program_suffix&;$program_transform_name"
 # Double any \ or $.  echo might interpret backslashes.
 # By default was `s,x,x', remove it if useless.
 cat <<\_ACEOF >conftest.sed
 s/[\\$]/&&/g;s/;s,x,x,$//
 _ACEOF
 program_transform_name=`echo $program_transform_name | sed -f conftest.sed`
-rm conftest.sed
+rm -f conftest.sed
 
 # expand $ac_aux_dir to an absolute path
 am_aux_dir=`cd $ac_aux_dir && pwd`
@@ -1503,37 +1926,60 @@ else
 echo "$as_me: WARNING: \`missing' script is too old or missing" >&2;}
 fi
 
-if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then
-  # Keeping the `.' argument allows $(mkdir_p) to be used without
-  # argument.  Indeed, we sometimes output rules like
-  #   $(mkdir_p) $(somedir)
-  # where $(somedir) is conditionally defined.
-  # (`test -n '$(somedir)' && $(mkdir_p) $(somedir)' is a more
-  # expensive solution, as it forces Make to start a sub-shell.)
-  mkdir_p='mkdir -p -- .'
-else
-  # On NextStep and OpenStep, the `mkdir' command does not
-  # recognize any option.  It will interpret all options as
-  # directories to create, and then abort because `.' already
-  # exists.
-  for d in ./-p ./--version;
-  do
-    test -d $d && rmdir $d
-  done
-  # $(mkinstalldirs) is defined by Automake if mkinstalldirs exists.
-  if test -f "$ac_aux_dir/mkinstalldirs"; then
-    mkdir_p='$(mkinstalldirs)'
+{ echo "$as_me:$LINENO: checking for a thread-safe mkdir -p" >&5
+echo $ECHO_N "checking for a thread-safe mkdir -p... $ECHO_C" >&6; }
+if test -z "$MKDIR_P"; then
+  if test "${ac_cv_path_mkdir+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_prog in mkdir gmkdir; do
+        for ac_exec_ext in '' $ac_executable_extensions; do
+          { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; } || continue
+          case `"$as_dir/$ac_prog$ac_exec_ext" --version 2>&1` in #(
+            'mkdir (GNU coreutils) '* | \
+            'mkdir (coreutils) '* | \
+            'mkdir (fileutils) '4.1*)
+              ac_cv_path_mkdir=$as_dir/$ac_prog$ac_exec_ext
+              break 3;;
+          esac
+        done
+       done
+done
+IFS=$as_save_IFS
+
+fi
+
+  if test "${ac_cv_path_mkdir+set}" = set; then
+    MKDIR_P="$ac_cv_path_mkdir -p"
   else
-    mkdir_p='$(install_sh) -d'
+    # As a last resort, use the slow shell script.  Don't cache a
+    # value for MKDIR_P within a source directory, because that will
+    # break other packages using the cache if that directory is
+    # removed, or if the value is a relative name.
+    test -d ./--version && rmdir ./--version
+    MKDIR_P="$ac_install_sh -d"
   fi
 fi
+{ echo "$as_me:$LINENO: result: $MKDIR_P" >&5
+echo "${ECHO_T}$MKDIR_P" >&6; }
+
+mkdir_p="$MKDIR_P"
+case $mkdir_p in
+  [\\/$]* | ?:[\\/]*) ;;
+  */*) mkdir_p="\$(top_builddir)/$mkdir_p" ;;
+esac
 
 for ac_prog in gawk mawk nawk awk
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
 set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_AWK+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -1546,54 +1992,57 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_AWK="$ac_prog"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
 fi
 fi
 AWK=$ac_cv_prog_AWK
 if test -n "$AWK"; then
-  echo "$as_me:$LINENO: result: $AWK" >&5
-echo "${ECHO_T}$AWK" >&6
+  echo "$as_me:$LINENO: result: $AWK" >&5
+echo "${ECHO_T}$AWK" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
   test -n "$AWK" && break
 done
 
-echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5
-echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6
-set dummy ${MAKE-make}; ac_make=`echo "$2" | sed 'y,:./+-,___p_,'`
-if eval "test \"\${ac_cv_prog_make_${ac_make}_set+set}\" = set"; then
+echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5
+echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6; }
+set x ${MAKE-make}; ac_make=`echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'`
+if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   cat >conftest.make <<\_ACEOF
+SHELL = /bin/sh
 all:
-       @echo 'ac_maketemp="$(MAKE)"'
+       @echo '@@@%%%=$(MAKE)=@@@%%%'
 _ACEOF
 # GNU make sometimes prints "make[1]: Entering...", which would confuse us.
-eval `${MAKE-make} -f conftest.make 2>/dev/null | grep temp=`
-if test -n "$ac_maketemp"; then
-  eval ac_cv_prog_make_${ac_make}_set=yes
-else
-  eval ac_cv_prog_make_${ac_make}_set=no
-fi
+case `${MAKE-make} -f conftest.make 2>/dev/null` in
+  *@@@%%%=?*=@@@%%%*)
+    eval ac_cv_prog_make_${ac_make}_set=yes;;
+  *)
+    eval ac_cv_prog_make_${ac_make}_set=no;;
+esac
 rm -f conftest.make
 fi
-if eval "test \"`echo '$ac_cv_prog_make_'${ac_make}_set`\" = yes"; then
-  echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
+if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then
+  echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
   SET_MAKE=
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
   SET_MAKE="MAKE=${MAKE-make}"
 fi
 
@@ -1606,12 +2055,16 @@ else
 fi
 rmdir .tst 2>/dev/null
 
-# test to see if srcdir already configured
-if test "`cd $srcdir && pwd`" != "`pwd`" &&
-   test -f $srcdir/config.status; then
-  { { echo "$as_me:$LINENO: error: source directory already configured; run \"make distclean\" there first" >&5
+if test "`cd $srcdir && pwd`" != "`pwd`"; then
+  # Use -I$(srcdir) only when $(srcdir) != ., so that make's output
+  # is not polluted with repeated "-I."
+  am__isrc=' -I$(srcdir)'
+  # test to see if srcdir already configured
+  if test -f $srcdir/config.status; then
+    { { echo "$as_me:$LINENO: error: source directory already configured; run \"make distclean\" there first" >&5
 echo "$as_me: error: source directory already configured; run \"make distclean\" there first" >&2;}
    { (exit 1); exit 1; }; }
+  fi
 fi
 
 # test whether we have cygpath
@@ -1654,10 +2107,7 @@ AUTOHEADER=${AUTOHEADER-"${am_missing_run}autoheader"}
 
 MAKEINFO=${MAKEINFO-"${am_missing_run}makeinfo"}
 
-
-AMTAR=${AMTAR-"${am_missing_run}tar"}
-
-install_sh=${install_sh-"$am_aux_dir/install-sh"}
+install_sh=${install_sh-"\$(SHELL) $am_aux_dir/install-sh"}
 
 # Installed binaries are usually stripped using `strip' when the user
 # run `make install-strip'.  However `strip' might not be the right
@@ -1667,8 +2117,8 @@ if test "$cross_compiling" != no; then
   if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}strip", so it can be a program name with args.
 set dummy ${ac_tool_prefix}strip; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_STRIP+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -1681,32 +2131,34 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_STRIP="${ac_tool_prefix}strip"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
 fi
 fi
 STRIP=$ac_cv_prog_STRIP
 if test -n "$STRIP"; then
-  echo "$as_me:$LINENO: result: $STRIP" >&5
-echo "${ECHO_T}$STRIP" >&6
+  echo "$as_me:$LINENO: result: $STRIP" >&5
+echo "${ECHO_T}$STRIP" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
 fi
 if test -z "$ac_cv_prog_STRIP"; then
   ac_ct_STRIP=$STRIP
   # Extract the first word of "strip", so it can be a program name with args.
 set dummy strip; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -1719,36 +2171,57 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_ac_ct_STRIP="strip"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
-  test -z "$ac_cv_prog_ac_ct_STRIP" && ac_cv_prog_ac_ct_STRIP=":"
 fi
 fi
 ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP
 if test -n "$ac_ct_STRIP"; then
-  echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5
-echo "${ECHO_T}$ac_ct_STRIP" >&6
+  echo "$as_me:$LINENO: result: $ac_ct_STRIP" >&5
+echo "${ECHO_T}$ac_ct_STRIP" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
-  STRIP=$ac_ct_STRIP
+  if test "x$ac_ct_STRIP" = x; then
+    STRIP=":"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    STRIP=$ac_ct_STRIP
+  fi
 else
   STRIP="$ac_cv_prog_STRIP"
 fi
 
 fi
-INSTALL_STRIP_PROGRAM="\${SHELL} \$(install_sh) -c -s"
+INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s"
 
 # We need awk for the "check" target.  The system "awk" is bad on
 # some platforms.
+# Always define AMTAR for backward compatibility.
+
+AMTAR=${AMTAR-"${am_missing_run}tar"}
+
+am__tar='${AMTAR} chof - "$$tardir"'; am__untar='${AMTAR} xf -'
+
+
 
 
 
@@ -1762,8 +2235,8 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 if test -n "$ac_tool_prefix"; then
   # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args.
 set dummy ${ac_tool_prefix}gcc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -1776,32 +2249,34 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_CC="${ac_tool_prefix}gcc"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
 fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
+  echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
 fi
 if test -z "$ac_cv_prog_CC"; then
   ac_ct_CC=$CC
   # Extract the first word of "gcc", so it can be a program name with args.
 set dummy gcc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -1814,36 +2289,51 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_ac_ct_CC="gcc"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
 fi
 fi
 ac_ct_CC=$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6
+  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
-  CC=$ac_ct_CC
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
 else
   CC="$ac_cv_prog_CC"
 fi
 
 if test -z "$CC"; then
-  if test -n "$ac_tool_prefix"; then
-  # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
+          if test -n "$ac_tool_prefix"; then
+    # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args.
 set dummy ${ac_tool_prefix}cc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -1856,74 +2346,34 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_CC="${ac_tool_prefix}cc"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
 fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
-else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
-fi
-
-fi
-if test -z "$ac_cv_prog_CC"; then
-  ac_ct_CC=$CC
-  # Extract the first word of "cc", so it can be a program name with args.
-set dummy cc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
-if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  if test -n "$ac_ct_CC"; then
-  ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test.
-else
-as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
-    ac_cv_prog_ac_ct_CC="cc"
-    echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
-    break 2
-  fi
-done
-done
-
-fi
-fi
-ac_ct_CC=$ac_cv_prog_ac_ct_CC
-if test -n "$ac_ct_CC"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6
+  { echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
-  CC=$ac_ct_CC
-else
-  CC="$ac_cv_prog_CC"
-fi
 
+  fi
 fi
 if test -z "$CC"; then
   # Extract the first word of "cc", so it can be a program name with args.
 set dummy cc; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -1937,7 +2387,7 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
        ac_prog_rejected=yes
        continue
@@ -1948,6 +2398,7 @@ do
   fi
 done
 done
+IFS=$as_save_IFS
 
 if test $ac_prog_rejected = yes; then
   # We found a bogon in the path, so make sure we never use it.
@@ -1965,22 +2416,23 @@ fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
+  echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
 fi
 if test -z "$CC"; then
   if test -n "$ac_tool_prefix"; then
-  for ac_prog in cl
+  for ac_prog in cl.exe
   do
     # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
 set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -1993,36 +2445,38 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
 fi
 fi
 CC=$ac_cv_prog_CC
 if test -n "$CC"; then
-  echo "$as_me:$LINENO: result: $CC" >&5
-echo "${ECHO_T}$CC" >&6
+  echo "$as_me:$LINENO: result: $CC" >&5
+echo "${ECHO_T}$CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
     test -n "$CC" && break
   done
 fi
 if test -z "$CC"; then
   ac_ct_CC=$CC
-  for ac_prog in cl
+  for ac_prog in cl.exe
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
 set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_ac_ct_CC+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2035,29 +2489,45 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_ac_ct_CC="$ac_prog"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
 fi
 fi
 ac_ct_CC=$ac_cv_prog_ac_ct_CC
 if test -n "$ac_ct_CC"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
-echo "${ECHO_T}$ac_ct_CC" >&6
+  echo "$as_me:$LINENO: result: $ac_ct_CC" >&5
+echo "${ECHO_T}$ac_ct_CC" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
   test -n "$ac_ct_CC" && break
 done
 
-  CC=$ac_ct_CC
+  if test "x$ac_ct_CC" = x; then
+    CC=""
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    CC=$ac_ct_CC
+  fi
 fi
 
 fi
@@ -2070,21 +2540,35 @@ See \`config.log' for more details." >&2;}
    { (exit 1); exit 1; }; }
 
 # Provide some information about the compiler.
-echo "$as_me:$LINENO:" \
-     "checking for C compiler version" >&5
+echo "$as_me:$LINENO: checking for C compiler version" >&5
 ac_compiler=`set X $ac_compile; echo $2`
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
-  (eval $ac_compiler --version </dev/null >&5) 2>&5
+{ (ac_try="$ac_compiler --version >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler --version >&5") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
-  (eval $ac_compiler -v </dev/null >&5) 2>&5
+{ (ac_try="$ac_compiler -v >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -v >&5") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
-  (eval $ac_compiler -V </dev/null >&5) 2>&5
+{ (ac_try="$ac_compiler -V >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -V >&5") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
@@ -2109,47 +2593,77 @@ ac_clean_files="$ac_clean_files a.out a.exe b.out"
 # Try to create an executable without -o first, disregard a.out.
 # It will help us diagnose broken compilers, and finding out an intuition
 # of exeext.
-echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
-echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for C compiler default output file name" >&5
+echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; }
 ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'`
-if { (eval echo "$as_me:$LINENO: \"$ac_link_default\"") >&5
-  (eval $ac_link_default) 2>&5
+#
+# List of possible output files, starting from the most likely.
+# The algorithm is not robust to junk in `.', hence go to wildcards (a.*)
+# only as a last resort.  b.out is created by i960 compilers.
+ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out'
+#
+# The IRIX 6 linker writes into existing files which may not be
+# executable, retaining their permissions.  Remove them first so a
+# subsequent execution test works.
+ac_rmfiles=
+for ac_file in $ac_files
+do
+  case $ac_file in
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;;
+    * ) ac_rmfiles="$ac_rmfiles $ac_file";;
+  esac
+done
+rm -f $ac_rmfiles
+
+if { (ac_try="$ac_link_default"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link_default") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; then
-  # Find the output, starting from the most likely.  This scheme is
-# not robust to junk in `.', hence go to wildcards (a.*) only as a last
-# resort.
-
-# Be careful to initialize this variable, since it used to be cached.
-# Otherwise an old cache value of `no' led to `EXEEXT = no' in a Makefile.
-ac_cv_exeext=
-# b.out is created by i960 compilers.
-for ac_file in a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out
+  # Autoconf-2.13 could set the ac_cv_exeext variable to `no'.
+# So ignore a value of `no', otherwise this would lead to `EXEEXT = no'
+# in a Makefile.  We should not override ac_cv_exeext if it was cached,
+# so that the user can short-circuit this test for compilers unknown to
+# Autoconf.
+for ac_file in $ac_files ''
 do
   test -f "$ac_file" || continue
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj )
-       ;;
-    conftest.$ac_ext )
-       # This is the source file.
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj )
        ;;
     [ab].out )
        # We found the default executable, but exeext='' is most
        # certainly right.
        break;;
     *.* )
-       ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-       # FIXME: I believe we export ac_cv_exeext for Libtool,
-       # but it would be cool to find out if it's true.  Does anybody
-       # maintain Libtool? --akim.
-       export ac_cv_exeext
+        if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no;
+       then :; else
+          ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
+       fi
+       # We set ac_cv_exeext here because the later test for it is not
+       # safe: cross compilers may not add the suffix if given an `-o'
+       # argument, so we may need to know it at that point already.
+       # Even if this section looks crufty: it has the advantage of
+       # actually working.
        break;;
     * )
        break;;
   esac
 done
+test "$ac_cv_exeext" = no && ac_cv_exeext=
+
 else
+  ac_file=''
+fi
+
+{ echo "$as_me:$LINENO: result: $ac_file" >&5
+echo "${ECHO_T}$ac_file" >&6; }
+if test -z "$ac_file"; then
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
@@ -2161,19 +2675,21 @@ See \`config.log' for more details." >&2;}
 fi
 
 ac_exeext=$ac_cv_exeext
-echo "$as_me:$LINENO: result: $ac_file" >&5
-echo "${ECHO_T}$ac_file" >&6
 
-# Check the compiler produces executables we can run.  If not, either
+# Check that the compiler produces executables we can run.  If not, either
 # the compiler is broken, or we cross compile.
-echo "$as_me:$LINENO: checking whether the C compiler works" >&5
-echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking whether the C compiler works" >&5
+echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; }
 # FIXME: These cross compiler hacks should be removed for Autoconf 3.0
 # If not cross compiling, check that we can run a simple program.
 if test "$cross_compiling" != yes; then
   if { ac_try='./$ac_file'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; }; then
@@ -2192,22 +2708,27 @@ See \`config.log' for more details." >&2;}
     fi
   fi
 fi
-echo "$as_me:$LINENO: result: yes" >&5
-echo "${ECHO_T}yes" >&6
+echo "$as_me:$LINENO: result: yes" >&5
+echo "${ECHO_T}yes" >&6; }
 
 rm -f a.out a.exe conftest$ac_cv_exeext b.out
 ac_clean_files=$ac_clean_files_save
-# Check the compiler produces executables we can run.  If not, either
+# Check that the compiler produces executables we can run.  If not, either
 # the compiler is broken, or we cross compile.
-echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
-echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6
-echo "$as_me:$LINENO: result: $cross_compiling" >&5
-echo "${ECHO_T}$cross_compiling" >&6
-
-echo "$as_me:$LINENO: checking for suffix of executables" >&5
-echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>&5
+{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5
+echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; }
+{ echo "$as_me:$LINENO: result: $cross_compiling" >&5
+echo "${ECHO_T}$cross_compiling" >&6; }
+
+{ echo "$as_me:$LINENO: checking for suffix of executables" >&5
+echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; }
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; then
@@ -2218,9 +2739,8 @@ if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
 for ac_file in conftest.exe conftest conftest.*; do
   test -f "$ac_file" || continue
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.o | *.obj ) ;;
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;;
     *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'`
-         export ac_cv_exeext
          break;;
     * ) break;;
   esac
@@ -2234,14 +2754,14 @@ See \`config.log' for more details." >&2;}
 fi
 
 rm -f conftest$ac_cv_exeext
-echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
-echo "${ECHO_T}$ac_cv_exeext" >&6
+echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5
+echo "${ECHO_T}$ac_cv_exeext" >&6; }
 
 rm -f conftest.$ac_ext
 EXEEXT=$ac_cv_exeext
 ac_exeext=$EXEEXT
-echo "$as_me:$LINENO: checking for suffix of object files" >&5
-echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for suffix of object files" >&5
+echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; }
 if test "${ac_cv_objext+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2261,14 +2781,20 @@ main ()
 }
 _ACEOF
 rm -f conftest.o conftest.obj
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>&5
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; then
-  for ac_file in `(ls conftest.o conftest.obj; ls conftest.*) 2>/dev/null`; do
+  for ac_file in conftest.o conftest.obj conftest.*; do
+  test -f "$ac_file" || continue;
   case $ac_file in
-    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg ) ;;
+    *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;;
     *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'`
        break;;
   esac
@@ -2286,12 +2812,12 @@ fi
 
 rm -f conftest.$ac_cv_objext conftest.$ac_ext
 fi
-echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
-echo "${ECHO_T}$ac_cv_objext" >&6
+echo "$as_me:$LINENO: result: $ac_cv_objext" >&5
+echo "${ECHO_T}$ac_cv_objext" >&6; }
 OBJEXT=$ac_cv_objext
 ac_objext=$OBJEXT
-echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
-echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; }
 if test "${ac_cv_c_compiler_gnu+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2314,50 +2840,49 @@ main ()
 }
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   ac_compiler_gnu=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_compiler_gnu=no
+       ac_compiler_gnu=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 ac_cv_c_compiler_gnu=$ac_compiler_gnu
 
 fi
-echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6
+echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; }
 GCC=`test $ac_compiler_gnu = yes && echo yes`
 ac_test_CFLAGS=${CFLAGS+set}
 ac_save_CFLAGS=$CFLAGS
-CFLAGS="-g"
-echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
-echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6
+{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5
+echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; }
 if test "${ac_cv_prog_cc_g+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat >conftest.$ac_ext <<_ACEOF
+  ac_save_c_werror_flag=$ac_c_werror_flag
+   ac_c_werror_flag=yes
+   ac_cv_prog_cc_g=no
+   CFLAGS="-g"
+   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
@@ -2373,38 +2898,118 @@ main ()
 }
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_prog_cc_g=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       CFLAGS=""
+      cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  :
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_c_werror_flag=$ac_save_c_werror_flag
+        CFLAGS="-g"
+        cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   ac_cv_prog_cc_g=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_prog_cc_g=no
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_c_werror_flag=$ac_save_c_werror_flag
 fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_g" >&6
+echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; }
 if test "$ac_test_CFLAGS" = set; then
   CFLAGS=$ac_save_CFLAGS
 elif test $ac_cv_prog_cc_g = yes; then
@@ -2420,12 +3025,12 @@ else
     CFLAGS=
   fi
 fi
-echo "$as_me:$LINENO: checking for $CC option to accept ANSI C" >&5
-echo $ECHO_N "checking for $CC option to accept ANSI C... $ECHO_C" >&6
-if test "${ac_cv_prog_cc_stdc+set}" = set; then
+{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5
+echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; }
+if test "${ac_cv_prog_cc_c89+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_cv_prog_cc_stdc=no
+  ac_cv_prog_cc_c89=no
 ac_save_CC=$CC
 cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -2459,12 +3064,17 @@ static char *f (char * (*g) (char **, int), char **p, ...)
 /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default.  It has
    function prototypes and stuff, but not '\xHH' hex character constants.
    These don't provoke an error unfortunately, instead are silently treated
-   as 'x'.  The following induces an error, until -std1 is added to get
+   as 'x'.  The following induces an error, until -std is added to get
    proper ANSI mode.  Curiously '\x00'!='x' always comes out true, for an
    array size at least.  It's necessary to write '\x00'==0 to get something
-   that's true only with -std1.  */
+   that's true only with -std.  */
 int osf4_cc_array ['\x00' == 0 ? 1 : -1];
 
+/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters
+   inside strings and character constants.  */
+#define FOO(x) 'x'
+int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1];
+
 int test (int i, double x);
 struct s1 {int (*f) (int a);};
 struct s2 {int (*f) (double a);};
@@ -2479,205 +3089,57 @@ return f (e, argv, 0) != argv[0]  ||  f (e, argv, 1) != argv[1];
   return 0;
 }
 _ACEOF
-# Don't try gcc -ansi; that turns off useful extensions and
-# breaks some systems' header files.
-# AIX                  -qlanglvl=ansi
-# Ultrix and OSF/1     -std1
-# HP-UX 10.20 and later        -Ae
-# HP-UX older versions -Aa -D_HPUX_SOURCE
-# SVR4                 -Xc -D__EXTENSIONS__
-for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
+for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \
+       -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__"
 do
   CC="$ac_save_CC $ac_arg"
   rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_prog_cc_stdc=$ac_arg
-break
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_prog_cc_c89=$ac_arg
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
+
 fi
-rm -f conftest.err conftest.$ac_objext
+
+rm -f core conftest.err conftest.$ac_objext
+  test "x$ac_cv_prog_cc_c89" != "xno" && break
 done
-rm -f conftest.$ac_ext conftest.$ac_objext
+rm -f conftest.$ac_ext
 CC=$ac_save_CC
 
 fi
-
-case "x$ac_cv_prog_cc_stdc" in
-  x|xno)
-    echo "$as_me:$LINENO: result: none needed" >&5
-echo "${ECHO_T}none needed" >&6 ;;
+# AC_CACHE_VAL
+case "x$ac_cv_prog_cc_c89" in
+  x)
+    { echo "$as_me:$LINENO: result: none needed" >&5
+echo "${ECHO_T}none needed" >&6; } ;;
+  xno)
+    { echo "$as_me:$LINENO: result: unsupported" >&5
+echo "${ECHO_T}unsupported" >&6; } ;;
   *)
-    echo "$as_me:$LINENO: result: $ac_cv_prog_cc_stdc" >&5
-echo "${ECHO_T}$ac_cv_prog_cc_stdc" >&6
-    CC="$CC $ac_cv_prog_cc_stdc" ;;
+    CC="$CC $ac_cv_prog_cc_c89"
+    { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5
+echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;;
 esac
 
-# Some people use a C++ compiler to compile C.  Since we use `exit',
-# in C++ we need to declare it.  In case someone uses the same compiler
-# for both compiling C and C++ we need to have the C++ compiler decide
-# the declaration of exit, since it's the most demanding environment.
-cat >conftest.$ac_ext <<_ACEOF
-#ifndef __cplusplus
-  choke me
-#endif
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  for ac_declaration in \
-   '' \
-   'extern "C" void std::exit (int) throw (); using std::exit;' \
-   'extern "C" void std::exit (int); using std::exit;' \
-   'extern "C" void exit (int) throw ();' \
-   'extern "C" void exit (int);' \
-   'void exit (int);'
-do
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_declaration
-#include <stdlib.h>
-int
-main ()
-{
-exit (42);
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  :
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-continue
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-$ac_declaration
-int
-main ()
-{
-exit (42);
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  break
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-done
-rm -f conftest*
-if test -n "$ac_declaration"; then
-  echo '#ifdef __cplusplus' >>confdefs.h
-  echo $ac_declaration      >>confdefs.h
-  echo '#endif'             >>confdefs.h
-fi
-
-else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
 
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
@@ -2685,7 +3147,7 @@ ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 DEPDIR="${am__leading_dot}deps"
 
-          ac_config_commands="$ac_config_commands depfiles"
+ac_config_commands="$ac_config_commands depfiles"
 
 
 am_make=${MAKE-make}
@@ -2695,8 +3157,8 @@ am__doit:
 .PHONY: am__doit
 END
 # If we don't find an include directive, just comment out the code.
-echo "$as_me:$LINENO: checking for style of include used by $am_make" >&5
-echo $ECHO_N "checking for style of include used by $am_make... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for style of include used by $am_make" >&5
+echo $ECHO_N "checking for style of include used by $am_make... $ECHO_C" >&6; }
 am__include="#"
 am__quote=
 _am_result=none
@@ -2723,22 +3185,20 @@ if test "$am__include" = "#"; then
 fi
 
 
-echo "$as_me:$LINENO: result: $_am_result" >&5
-echo "${ECHO_T}$_am_result" >&6
+echo "$as_me:$LINENO: result: $_am_result" >&5
+echo "${ECHO_T}$_am_result" >&6; }
 rm -f confinc confmf
 
-# Check whether --enable-dependency-tracking or --disable-dependency-tracking was given.
+# Check whether --enable-dependency-tracking was given.
 if test "${enable_dependency_tracking+set}" = set; then
-  enableval="$enable_dependency_tracking"
+  enableval=$enable_dependency_tracking;
+fi
 
-fi;
 if test "x$enable_dependency_tracking" != xno; then
   am_depcomp="$ac_aux_dir/depcomp"
   AMDEPBACKSLASH='\'
 fi
-
-
-if test "x$enable_dependency_tracking" != xno; then
+ if test "x$enable_dependency_tracking" != xno; then
   AMDEP_TRUE=
   AMDEP_FALSE='#'
 else
@@ -2748,11 +3208,10 @@ fi
 
 
 
-
 depcc="$CC"   am_compiler_list=
 
-echo "$as_me:$LINENO: checking dependency style of $depcc" >&5
-echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking dependency style of $depcc" >&5
+echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6; }
 if test "${am_cv_CC_dependencies_compiler_type+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -2816,13 +3275,19 @@ else
        depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
        $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \
          >/dev/null 2>conftest.err &&
+       grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 &&
        grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
        grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 &&
        ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
       # icc doesn't choke on unknown options, it will just issue warnings
-      # (even with -Werror).  So we grep stderr for any message
-      # that says an option was ignored.
-      if grep 'ignoring option' conftest.err >/dev/null 2>&1; then :; else
+      # or remarks (even with -Werror).  So we grep stderr for any message
+      # that says an option was ignored or not supported.
+      # When given -MP, icc 7.0 and 7.1 complain thusly:
+      #   icc: Command line warning: ignoring option '-M'; no argument required
+      # The diagnosis changed in icc 8.0:
+      #   icc: Command line remark: option '-MP' not supported
+      if (grep 'ignoring option' conftest.err ||
+          grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
         am_cv_CC_dependencies_compiler_type=$depmode
         break
       fi
@@ -2836,13 +3301,11 @@ else
 fi
 
 fi
-echo "$as_me:$LINENO: result: $am_cv_CC_dependencies_compiler_type" >&5
-echo "${ECHO_T}$am_cv_CC_dependencies_compiler_type" >&6
+echo "$as_me:$LINENO: result: $am_cv_CC_dependencies_compiler_type" >&5
+echo "${ECHO_T}$am_cv_CC_dependencies_compiler_type" >&6; }
 CCDEPMODE=depmode=$am_cv_CC_dependencies_compiler_type
 
-
-
-if
+ if
   test "x$enable_dependency_tracking" != xno \
   && test "$am_cv_CC_dependencies_compiler_type" = gcc3; then
   am__fastdepCC_TRUE=
@@ -2858,8 +3321,8 @@ ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
-echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5
-echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5
+echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; }
 # On Suns, sometimes $CPP names a directory.
 if test -n "$CPP" && test -d "$CPP"; then
   CPP=
@@ -2893,24 +3356,22 @@ cat >>conftest.$ac_ext <<_ACEOF
 #endif
                     Syntax error
 _ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
+  (exit $ac_status); } >/dev/null && {
+        test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       }; then
   :
 else
   echo "$as_me: failed program was:" >&5
@@ -2919,9 +3380,10 @@ sed 's/^/| /' conftest.$ac_ext >&5
   # Broken: fails on valid input.
 continue
 fi
+
 rm -f conftest.err conftest.$ac_ext
 
-  # OK, works on sane cases.  Now check whether non-existent headers
+  # OK, works on sane cases.  Now check whether nonexistent headers
   # can be detected and how.
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -2931,24 +3393,22 @@ cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
+  (exit $ac_status); } >/dev/null && {
+        test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       }; then
   # Broken: success on invalid input.
 continue
 else
@@ -2959,6 +3419,7 @@ sed 's/^/| /' conftest.$ac_ext >&5
 ac_preproc_ok=:
 break
 fi
+
 rm -f conftest.err conftest.$ac_ext
 
 done
@@ -2976,8 +3437,8 @@ fi
 else
   ac_cv_prog_CPP=$CPP
 fi
-echo "$as_me:$LINENO: result: $CPP" >&5
-echo "${ECHO_T}$CPP" >&6
+echo "$as_me:$LINENO: result: $CPP" >&5
+echo "${ECHO_T}$CPP" >&6; }
 ac_preproc_ok=false
 for ac_c_preproc_warn_flag in '' yes
 do
@@ -3000,24 +3461,22 @@ cat >>conftest.$ac_ext <<_ACEOF
 #endif
                     Syntax error
 _ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
+  (exit $ac_status); } >/dev/null && {
+        test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       }; then
   :
 else
   echo "$as_me: failed program was:" >&5
@@ -3026,9 +3485,10 @@ sed 's/^/| /' conftest.$ac_ext >&5
   # Broken: fails on valid input.
 continue
 fi
+
 rm -f conftest.err conftest.$ac_ext
 
-  # OK, works on sane cases.  Now check whether non-existent headers
+  # OK, works on sane cases.  Now check whether nonexistent headers
   # can be detected and how.
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -3038,24 +3498,22 @@ cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 #include <ac_nonexistent.h>
 _ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
+  (exit $ac_status); } >/dev/null && {
+        test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       }; then
   # Broken: success on invalid input.
 continue
 else
@@ -3066,6 +3524,7 @@ sed 's/^/| /' conftest.$ac_ext >&5
 ac_preproc_ok=:
 break
 fi
+
 rm -f conftest.err conftest.$ac_ext
 
 done
@@ -3087,18 +3546,22 @@ ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
-ac_ext=cc
+ac_ext=cpp
 ac_cpp='$CXXCPP $CPPFLAGS'
 ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
 ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
 ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-if test -n "$ac_tool_prefix"; then
-  for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC
+if test -z "$CXX"; then
+  if test -n "$CCC"; then
+    CXX=$CCC
+  else
+    if test -n "$ac_tool_prefix"; then
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
   do
     # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args.
 set dummy $ac_tool_prefix$ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_CXX+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3111,36 +3574,38 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_CXX="$ac_tool_prefix$ac_prog"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
 fi
 fi
 CXX=$ac_cv_prog_CXX
 if test -n "$CXX"; then
-  echo "$as_me:$LINENO: result: $CXX" >&5
-echo "${ECHO_T}$CXX" >&6
+  echo "$as_me:$LINENO: result: $CXX" >&5
+echo "${ECHO_T}$CXX" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
     test -n "$CXX" && break
   done
 fi
 if test -z "$CXX"; then
   ac_ct_CXX=$CXX
-  for ac_prog in $CCC g++ c++ gpp aCC CC cxx cc++ cl FCC KCC RCC xlC_r xlC
+  for ac_prog in g++ c++ gpp aCC CC cxx cc++ cl.exe FCC KCC RCC xlC_r xlC
 do
   # Extract the first word of "$ac_prog", so it can be a program name with args.
 set dummy $ac_prog; ac_word=$2
-echo "$as_me:$LINENO: checking for $ac_word" >&5
-echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking for $ac_word" >&5
+echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; }
 if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3153,55 +3618,85 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
   for ac_exec_ext in '' $ac_executable_extensions; do
-  if $as_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
+  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
     ac_cv_prog_ac_ct_CXX="$ac_prog"
     echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
   fi
 done
 done
+IFS=$as_save_IFS
 
 fi
 fi
 ac_ct_CXX=$ac_cv_prog_ac_ct_CXX
 if test -n "$ac_ct_CXX"; then
-  echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
-echo "${ECHO_T}$ac_ct_CXX" >&6
+  echo "$as_me:$LINENO: result: $ac_ct_CXX" >&5
+echo "${ECHO_T}$ac_ct_CXX" >&6; }
 else
-  echo "$as_me:$LINENO: result: no" >&5
-echo "${ECHO_T}no" >&6
+  echo "$as_me:$LINENO: result: no" >&5
+echo "${ECHO_T}no" >&6; }
 fi
 
+
   test -n "$ac_ct_CXX" && break
 done
-test -n "$ac_ct_CXX" || ac_ct_CXX="g++"
 
-  CXX=$ac_ct_CXX
+  if test "x$ac_ct_CXX" = x; then
+    CXX="g++"
+  else
+    case $cross_compiling:$ac_tool_warned in
+yes:)
+{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&5
+echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools
+whose name does not start with the host triplet.  If you think this
+configuration is useful to you, please write to autoconf@gnu.org." >&2;}
+ac_tool_warned=yes ;;
+esac
+    CXX=$ac_ct_CXX
+  fi
 fi
 
-
+  fi
+fi
 # Provide some information about the compiler.
-echo "$as_me:$LINENO:" \
-     "checking for C++ compiler version" >&5
+echo "$as_me:$LINENO: checking for C++ compiler version" >&5
 ac_compiler=`set X $ac_compile; echo $2`
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler --version </dev/null >&5\"") >&5
-  (eval $ac_compiler --version </dev/null >&5) 2>&5
+{ (ac_try="$ac_compiler --version >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler --version >&5") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -v </dev/null >&5\"") >&5
-  (eval $ac_compiler -v </dev/null >&5) 2>&5
+{ (ac_try="$ac_compiler -v >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -v >&5") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
-{ (eval echo "$as_me:$LINENO: \"$ac_compiler -V </dev/null >&5\"") >&5
-  (eval $ac_compiler -V </dev/null >&5) 2>&5
+{ (ac_try="$ac_compiler -V >&5"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compiler -V >&5") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }
 
-echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5
-echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking whether we are using the GNU C++ compiler" >&5
+echo $ECHO_N "checking whether we are using the GNU C++ compiler... $ECHO_C" >&6; }
 if test "${ac_cv_cxx_compiler_gnu+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3224,50 +3719,49 @@ main ()
 }
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_cxx_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+  (exit $ac_status); } && {
+        test -z "$ac_cxx_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   ac_compiler_gnu=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_compiler_gnu=no
+       ac_compiler_gnu=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 ac_cv_cxx_compiler_gnu=$ac_compiler_gnu
 
 fi
-echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
-echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6
+echo "$as_me:$LINENO: result: $ac_cv_cxx_compiler_gnu" >&5
+echo "${ECHO_T}$ac_cv_cxx_compiler_gnu" >&6; }
 GXX=`test $ac_compiler_gnu = yes && echo yes`
 ac_test_CXXFLAGS=${CXXFLAGS+set}
 ac_save_CXXFLAGS=$CXXFLAGS
-CXXFLAGS="-g"
-echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
-echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6
+{ echo "$as_me:$LINENO: checking whether $CXX accepts -g" >&5
+echo $ECHO_N "checking whether $CXX accepts -g... $ECHO_C" >&6; }
 if test "${ac_cv_prog_cxx_g+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  cat >conftest.$ac_ext <<_ACEOF
+  ac_save_cxx_werror_flag=$ac_cxx_werror_flag
+   ac_cxx_werror_flag=yes
+   ac_cv_prog_cxx_g=no
+   CXXFLAGS="-g"
+   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
@@ -3283,159 +3777,133 @@ main ()
 }
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_cxx_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+  (exit $ac_status); } && {
+        test -z "$ac_cxx_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   ac_cv_prog_cxx_g=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_prog_cxx_g=no
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
-echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6
-if test "$ac_test_CXXFLAGS" = set; then
-  CXXFLAGS=$ac_save_CXXFLAGS
-elif test $ac_cv_prog_cxx_g = yes; then
-  if test "$GXX" = yes; then
-    CXXFLAGS="-g -O2"
-  else
-    CXXFLAGS="-g"
-  fi
-else
-  if test "$GXX" = yes; then
-    CXXFLAGS="-O2"
-  else
-    CXXFLAGS=
-  fi
-fi
-for ac_declaration in \
-   '' \
-   'extern "C" void std::exit (int) throw (); using std::exit;' \
-   'extern "C" void std::exit (int); using std::exit;' \
-   'extern "C" void exit (int) throw ();' \
-   'extern "C" void exit (int);' \
-   'void exit (int);'
-do
-  cat >conftest.$ac_ext <<_ACEOF
+       CXXFLAGS=""
+      cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-$ac_declaration
-#include <stdlib.h>
+
 int
 main ()
 {
-exit (42);
+
   ;
   return 0;
 }
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_cxx_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+  (exit $ac_status); } && {
+        test -z "$ac_cxx_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   :
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-continue
-fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-  cat >conftest.$ac_ext <<_ACEOF
+       ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+        CXXFLAGS="-g"
+        cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-$ac_declaration
+
 int
 main ()
 {
-exit (42);
+
   ;
   return 0;
 }
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_cxx_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  break
+  (exit $ac_status); } && {
+        test -z "$ac_cxx_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_prog_cxx_g=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
+
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-done
-rm -f conftest*
-if test -n "$ac_declaration"; then
-  echo '#ifdef __cplusplus' >>confdefs.h
-  echo $ac_declaration      >>confdefs.h
-  echo '#endif'             >>confdefs.h
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
 
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+   ac_cxx_werror_flag=$ac_save_cxx_werror_flag
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_prog_cxx_g" >&5
+echo "${ECHO_T}$ac_cv_prog_cxx_g" >&6; }
+if test "$ac_test_CXXFLAGS" = set; then
+  CXXFLAGS=$ac_save_CXXFLAGS
+elif test $ac_cv_prog_cxx_g = yes; then
+  if test "$GXX" = yes; then
+    CXXFLAGS="-g -O2"
+  else
+    CXXFLAGS="-g"
+  fi
+else
+  if test "$GXX" = yes; then
+    CXXFLAGS="-O2"
+  else
+    CXXFLAGS=
+  fi
+fi
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
 ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
@@ -3444,8 +3912,8 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 depcc="$CXX"  am_compiler_list=
 
-echo "$as_me:$LINENO: checking dependency style of $depcc" >&5
-echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6
+echo "$as_me:$LINENO: checking dependency style of $depcc" >&5
+echo $ECHO_N "checking dependency style of $depcc... $ECHO_C" >&6; }
 if test "${am_cv_CXX_dependencies_compiler_type+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -3509,13 +3977,19 @@ else
        depfile=sub/conftest.Po tmpdepfile=sub/conftest.TPo \
        $SHELL ./depcomp $depcc -c -o sub/conftest.${OBJEXT-o} sub/conftest.c \
          >/dev/null 2>conftest.err &&
+       grep sub/conftst1.h sub/conftest.Po > /dev/null 2>&1 &&
        grep sub/conftst6.h sub/conftest.Po > /dev/null 2>&1 &&
        grep sub/conftest.${OBJEXT-o} sub/conftest.Po > /dev/null 2>&1 &&
        ${MAKE-make} -s -f confmf > /dev/null 2>&1; then
       # icc doesn't choke on unknown options, it will just issue warnings
-      # (even with -Werror).  So we grep stderr for any message
-      # that says an option was ignored.
-      if grep 'ignoring option' conftest.err >/dev/null 2>&1; then :; else
+      # or remarks (even with -Werror).  So we grep stderr for any message
+      # that says an option was ignored or not supported.
+      # When given -MP, icc 7.0 and 7.1 complain thusly:
+      #   icc: Command line warning: ignoring option '-M'; no argument required
+      # The diagnosis changed in icc 8.0:
+      #   icc: Command line remark: option '-MP' not supported
+      if (grep 'ignoring option' conftest.err ||
+          grep 'not supported' conftest.err) >/dev/null 2>&1; then :; else
         am_cv_CXX_dependencies_compiler_type=$depmode
         break
       fi
@@ -3529,13 +4003,11 @@ else
 fi
 
 fi
-echo "$as_me:$LINENO: result: $am_cv_CXX_dependencies_compiler_type" >&5
-echo "${ECHO_T}$am_cv_CXX_dependencies_compiler_type" >&6
+echo "$as_me:$LINENO: result: $am_cv_CXX_dependencies_compiler_type" >&5
+echo "${ECHO_T}$am_cv_CXX_dependencies_compiler_type" >&6; }
 CXXDEPMODE=depmode=$am_cv_CXX_dependencies_compiler_type
 
-
-
-if
+ if
   test "x$enable_dependency_tracking" != xno \
   && test "$am_cv_CXX_dependencies_compiler_type" = gcc3; then
   am__fastdepCXX_TRUE=
 
 
 
-
-echo "$as_me:$LINENO: checking for egrep" >&5
-echo $ECHO_N "checking for egrep... $ECHO_C" >&6
-if test "${ac_cv_prog_egrep+set}" = set; then
+{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5
+echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; }
+if test "${ac_cv_path_GREP+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  # Extract the first word of "grep ggrep" to use in msg output
+if test -z "$GREP"; then
+set dummy grep ggrep; ac_prog_name=$2
+if test "${ac_cv_path_GREP+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  if echo a | (grep -E '(a|b)') >/dev/null 2>&1
-    then ac_cv_prog_egrep='grep -E'
-    else ac_cv_prog_egrep='egrep'
+  ac_path_GREP_found=false
+# Loop through the user's path and test for each of PROGNAME-LIST
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_prog in grep ggrep; do
+  for ac_exec_ext in '' $ac_executable_extensions; do
+    ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
+    { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue
+    # Check for GNU ac_path_GREP and select it if it is found.
+  # Check for GNU $ac_path_GREP
+case `"$ac_path_GREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;;
+*)
+  ac_count=0
+  echo $ECHO_N "0123456789$ECHO_C" >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    echo 'GREP' >> "conftest.nl"
+    "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    ac_count=`expr $ac_count + 1`
+    if test $ac_count -gt ${ac_path_GREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_GREP="$ac_path_GREP"
+      ac_path_GREP_max=$ac_count
     fi
-fi
-echo "$as_me:$LINENO: result: $ac_cv_prog_egrep" >&5
-echo "${ECHO_T}$ac_cv_prog_egrep" >&6
- EGREP=$ac_cv_prog_egrep
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
 
 
-echo "$as_me:$LINENO: checking for ANSI C header files" >&5
-echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6
-if test "${ac_cv_header_stdc+set}" = set; then
-  echo $ECHO_N "(cached) $ECHO_C" >&6
-else
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
+    $ac_path_GREP_found && break 3
+  done
+done
 
-int
-main ()
-{
+done
+IFS=$as_save_IFS
+
+
+fi
+
+GREP="$ac_cv_path_GREP"
+if test -z "$GREP"; then
+  { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5
+echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;}
+   { (exit 1); exit 1; }; }
+fi
 
-  ;
-  return 0;
-}
-_ACEOF
-rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
-  ac_status=$?
-  grep -v '^ *+' conftest.er1 >conftest.err
-  rm -f conftest.er1
-  cat conftest.err >&5
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_header_stdc=yes
 else
-  echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
+  ac_cv_path_GREP=$GREP
+fi
+
 
-ac_cv_header_stdc=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5
+echo "${ECHO_T}$ac_cv_path_GREP" >&6; }
+ GREP="$ac_cv_path_GREP"
 
-if test $ac_cv_header_stdc = yes; then
+
+{ echo "$as_me:$LINENO: checking for egrep" >&5
+echo $ECHO_N "checking for egrep... $ECHO_C" >&6; }
+if test "${ac_cv_path_EGREP+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
+   then ac_cv_path_EGREP="$GREP -E"
+   else
+     # Extract the first word of "egrep" to use in msg output
+if test -z "$EGREP"; then
+set dummy egrep; ac_prog_name=$2
+if test "${ac_cv_path_EGREP+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_path_EGREP_found=false
+# Loop through the user's path and test for each of PROGNAME-LIST
+as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  for ac_prog in egrep; do
+  for ac_exec_ext in '' $ac_executable_extensions; do
+    ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
+    { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue
+    # Check for GNU ac_path_EGREP and select it if it is found.
+  # Check for GNU $ac_path_EGREP
+case `"$ac_path_EGREP" --version 2>&1` in
+*GNU*)
+  ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;;
+*)
+  ac_count=0
+  echo $ECHO_N "0123456789$ECHO_C" >"conftest.in"
+  while :
+  do
+    cat "conftest.in" "conftest.in" >"conftest.tmp"
+    mv "conftest.tmp" "conftest.in"
+    cp "conftest.in" "conftest.nl"
+    echo 'EGREP' >> "conftest.nl"
+    "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break
+    diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break
+    ac_count=`expr $ac_count + 1`
+    if test $ac_count -gt ${ac_path_EGREP_max-0}; then
+      # Best one so far, save it but keep looking for a better one
+      ac_cv_path_EGREP="$ac_path_EGREP"
+      ac_path_EGREP_max=$ac_count
+    fi
+    # 10*(2^10) chars as input seems more than enough
+    test $ac_count -gt 10 && break
+  done
+  rm -f conftest.in conftest.tmp conftest.nl conftest.out;;
+esac
+
+
+    $ac_path_EGREP_found && break 3
+  done
+done
+
+done
+IFS=$as_save_IFS
+
+
+fi
+
+EGREP="$ac_cv_path_EGREP"
+if test -z "$EGREP"; then
+  { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5
+echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;}
+   { (exit 1); exit 1; }; }
+fi
+
+else
+  ac_cv_path_EGREP=$EGREP
+fi
+
+
+   fi
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5
+echo "${ECHO_T}$ac_cv_path_EGREP" >&6; }
+ EGREP="$ac_cv_path_EGREP"
+
+
+if test $ac_cv_c_compiler_gnu = yes; then
+    { echo "$as_me:$LINENO: checking whether $CC needs -traditional" >&5
+echo $ECHO_N "checking whether $CC needs -traditional... $ECHO_C" >&6; }
+if test "${ac_cv_prog_gcc_traditional+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+    ac_pattern="Autoconf.*'x'"
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <sgtty.h>
+Autoconf TIOCGETP
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "$ac_pattern" >/dev/null 2>&1; then
+  ac_cv_prog_gcc_traditional=yes
+else
+  ac_cv_prog_gcc_traditional=no
+fi
+rm -f conftest*
+
+
+  if test $ac_cv_prog_gcc_traditional = no; then
+    cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <termio.h>
+Autoconf TCGETA
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "$ac_pattern" >/dev/null 2>&1; then
+  ac_cv_prog_gcc_traditional=yes
+fi
+rm -f conftest*
+
+  fi
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_prog_gcc_traditional" >&5
+echo "${ECHO_T}$ac_cv_prog_gcc_traditional" >&6; }
+  if test $ac_cv_prog_gcc_traditional = yes; then
+    CC="$CC -traditional"
+  fi
+fi
+
+
+{ echo "$as_me:$LINENO: checking for error_at_line" >&5
+echo $ECHO_N "checking for error_at_line... $ECHO_C" >&6; }
+if test "${ac_cv_lib_error_at_line+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <error.h>
+int
+main ()
+{
+error_at_line (0, 0, "", 0, "an error occurred");
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest$ac_exeext &&
+       $as_test_x conftest$ac_exeext; then
+  ac_cv_lib_error_at_line=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_cv_lib_error_at_line=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+      conftest$ac_exeext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_error_at_line" >&5
+echo "${ECHO_T}$ac_cv_lib_error_at_line" >&6; }
+if test $ac_cv_lib_error_at_line = no; then
+  case " $LIBOBJS " in
+  *" error.$ac_objext "* ) ;;
+  *) LIBOBJS="$LIBOBJS error.$ac_objext"
+ ;;
+esac
+
+fi
+
+{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5
+echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; }
+if test "${ac_cv_header_stdc+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_header_stdc=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_cv_header_stdc=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
   # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
@@ -3673,6 +4398,7 @@ cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 #include <ctype.h>
+#include <stdlib.h>
 #if ((' ' & 0x0FF) == 0x020)
 # define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
 # define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
@@ -3692,18 +4418,27 @@ main ()
   for (i = 0; i < 256; i++)
     if (XOR (islower (i), ISLOWER (i))
        || toupper (i) != TOUPPER (i))
-      exit(2);
-  exit (0);
+      return 2;
+  return 0;
 }
 _ACEOF
 rm -f conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>&5
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
+  { (case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_try") 2>&5
   ac_status=$?
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
   (exit $ac_status); }; }; then
@@ -3716,12 +4451,14 @@ sed 's/^/| /' conftest.$ac_ext >&5
 ( exit $ac_status )
 ac_cv_header_stdc=no
 fi
-rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
 fi
+
+
 fi
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
-echo "${ECHO_T}$ac_cv_header_stdc" >&6
+echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
+echo "${ECHO_T}$ac_cv_header_stdc" >&6; }
 if test $ac_cv_header_stdc = yes; then
 
 cat >>confdefs.h <<\_ACEOF
@@ -3744,9 +4481,9 @@ for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \
                  inttypes.h stdint.h unistd.h
 do
 as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
-echo "$as_me:$LINENO: checking for $ac_header" >&5
-echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6
-if eval "test \"\${$as_ac_Header+set}\" = set"; then
+echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   cat >conftest.$ac_ext <<_ACEOF
@@ -3760,38 +4497,35 @@ $ac_includes_default
 #include <$ac_header>
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   eval "$as_ac_Header=yes"
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-eval "$as_ac_Header=no"
+       eval "$as_ac_Header=no"
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-echo "$as_me:$LINENO: result: `eval echo '${'$as_ac_Header'}'`" >&5
-echo "${ECHO_T}`eval echo '${'$as_ac_Header'}'`" >&6
+ac_res=`eval echo '${'$as_ac_Header'}'`
+              { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
 if test `eval echo '${'$as_ac_Header'}'` = yes; then
   cat >>confdefs.h <<_ACEOF
 #define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
@@ -3802,9 +4536,9 @@ fi
 done
 
 
-echo "$as_me:$LINENO: checking for error_at_line" >&5
-echo $ECHO_N "checking for error_at_line... $ECHO_C" >&6
-if test "${ac_cv_lib_error_at_line+set}" = set; then
+{ echo "$as_me:$LINENO: checking for stdbool.h that conforms to C99" >&5
+echo $ECHO_N "checking for stdbool.h that conforms to C99... $ECHO_C" >&6; }
+if test "${ac_cv_header_stdbool_h+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   cat >conftest.$ac_ext <<_ACEOF
@@ -3813,63 +4547,114 @@ _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-$ac_includes_default
+
+#include <stdbool.h>
+#ifndef bool
+ "error: bool is not defined"
+#endif
+#ifndef false
+ "error: false is not defined"
+#endif
+#if false
+ "error: false is not 0"
+#endif
+#ifndef true
+ "error: true is not defined"
+#endif
+#if true != 1
+ "error: true is not 1"
+#endif
+#ifndef __bool_true_false_are_defined
+ "error: __bool_true_false_are_defined is not defined"
+#endif
+
+       struct s { _Bool s: 1; _Bool t; } s;
+
+       char a[true == 1 ? 1 : -1];
+       char b[false == 0 ? 1 : -1];
+       char c[__bool_true_false_are_defined == 1 ? 1 : -1];
+       char d[(bool) 0.5 == true ? 1 : -1];
+       bool e = &s;
+       char f[(_Bool) 0.0 == false ? 1 : -1];
+       char g[true];
+       char h[sizeof (_Bool)];
+       char i[sizeof s.t];
+       enum { j = false, k = true, l = false * true, m = true * 256 };
+       _Bool n[m];
+       char o[sizeof n == m * sizeof n[0] ? 1 : -1];
+       char p[-1 - (_Bool) 0 < 0 && -1 - (bool) 0 < 0 ? 1 : -1];
+#      if defined __xlc__ || defined __GNUC__
+        /* Catch a bug in IBM AIX xlc compiler version 6.0.0.0
+           reported by James Lemley on 2005-10-05; see
+           http://lists.gnu.org/archive/html/bug-coreutils/2005-10/msg00086.html
+           This test is not quite right, since xlc is allowed to
+           reject this program, as the initializer for xlcbug is
+           not one of the forms that C requires support for.
+           However, doing the test right would require a runtime
+           test, and that would make cross-compilation harder.
+           Let us hope that IBM fixes the xlc bug, and also adds
+           support for this kind of constant expression.  In the
+           meantime, this test will reject xlc, which is OK, since
+           our stdbool.h substitute should suffice.  We also test
+           this with GCC, where it should work, to detect more
+           quickly whether someone messes up the test in the
+           future.  */
+        char digs[] = "0123456789";
+        int xlcbug = 1 / (&(digs + 5)[-2 + (bool) 1] == &digs[4] ? 1 : -1);
+#      endif
+       /* Catch a bug in an HP-UX C compiler.  See
+          http://gcc.gnu.org/ml/gcc-patches/2003-12/msg02303.html
+          http://lists.gnu.org/archive/html/bug-coreutils/2005-11/msg00161.html
+        */
+       _Bool q = true;
+       _Bool *pq = &q;
+
 int
 main ()
 {
-error_at_line (0, 0, "", 0, "");
+
+       *pq |= q;
+       *pq |= ! q;
+       /* Refer to every declared value, to avoid compiler optimizations.  */
+       return (!a + !b + !c + !d + !e + !f + !g + !h + !i + !!j + !k + !!l
+               + !m + !n + !o + !p + !q + !pq);
+
   ;
   return 0;
 }
 _ACEOF
-rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_error_at_line=yes
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_header_stdbool_h=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_error_at_line=no
-fi
-rm -f conftest.err conftest.$ac_objext \
-      conftest$ac_exeext conftest.$ac_ext
+       ac_cv_header_stdbool_h=no
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_error_at_line" >&5
-echo "${ECHO_T}$ac_cv_lib_error_at_line" >&6
-if test $ac_cv_lib_error_at_line = no; then
-  case $LIBOBJS in
-    "error.$ac_objext"   | \
-  *" error.$ac_objext"   | \
-    "error.$ac_objext "* | \
-  *" error.$ac_objext "* ) ;;
-  *) LIBOBJS="$LIBOBJS error.$ac_objext" ;;
-esac
 
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
-
-echo "$as_me:$LINENO: checking for ANSI C header files" >&5
-echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6
-if test "${ac_cv_header_stdc+set}" = set; then
+{ echo "$as_me:$LINENO: result: $ac_cv_header_stdbool_h" >&5
+echo "${ECHO_T}$ac_cv_header_stdbool_h" >&6; }
+{ echo "$as_me:$LINENO: checking for _Bool" >&5
+echo $ECHO_N "checking for _Bool... $ECHO_C" >&6; }
+if test "${ac_cv_type__Bool+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
   cat >conftest.$ac_ext <<_ACEOF
@@ -3878,163 +4663,356 @@ _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <float.h>
-
+$ac_includes_default
+typedef _Bool ac__type_new_;
 int
 main ()
 {
-
+if ((ac__type_new_ *) 0)
+  return 0;
+if (sizeof (ac__type_new_))
+  return 0;
   ;
   return 0;
 }
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_header_stdc=yes
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_type__Bool=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_header_stdc=no
+       ac_cv_type__Bool=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
 
-if test $ac_cv_header_stdc = yes; then
-  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
-  cat >conftest.$ac_ext <<_ACEOF
-/* confdefs.h.  */
-_ACEOF
-cat confdefs.h >>conftest.$ac_ext
-cat >>conftest.$ac_ext <<_ACEOF
-/* end confdefs.h.  */
-#include <string.h>
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_type__Bool" >&5
+echo "${ECHO_T}$ac_cv_type__Bool" >&6; }
+if test $ac_cv_type__Bool = yes; then
 
+cat >>confdefs.h <<_ACEOF
+#define HAVE__BOOL 1
 _ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "memchr" >/dev/null 2>&1; then
-  :
-else
-  ac_cv_header_stdc=no
+
+
 fi
-rm -f conftest*
+
+if test $ac_cv_header_stdbool_h = yes; then
+
+cat >>confdefs.h <<\_ACEOF
+#define HAVE_STDBOOL_H 1
+_ACEOF
 
 fi
 
-if test $ac_cv_header_stdc = yes; then
-  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+{ echo "$as_me:$LINENO: checking whether time.h and sys/time.h may both be included" >&5
+echo $ECHO_N "checking whether time.h and sys/time.h may both be included... $ECHO_C" >&6; }
+if test "${ac_cv_header_time+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
   cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/time.h>
+#include <time.h>
 
+int
+main ()
+{
+if ((struct tm *) 0)
+return 0;
+  ;
+  return 0;
+}
 _ACEOF
-if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
-  $EGREP "free" >/dev/null 2>&1; then
-  :
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_header_time=yes
 else
-  ac_cv_header_stdc=no
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_cv_header_time=no
 fi
-rm -f conftest*
 
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 fi
+{ echo "$as_me:$LINENO: result: $ac_cv_header_time" >&5
+echo "${ECHO_T}$ac_cv_header_time" >&6; }
+if test $ac_cv_header_time = yes; then
 
-if test $ac_cv_header_stdc = yes; then
-  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
-  if test "$cross_compiling" = yes; then
-  :
+cat >>confdefs.h <<\_ACEOF
+#define TIME_WITH_SYS_TIME 1
+_ACEOF
+
+fi
+
+
+#checks for header files and libraries
+
+
+
+
+
+
+
+
+
+for ac_header in linux/version.h popt.h fcntl.h inttypes.h stdlib.h sys/ioctl.h sys/time.h termios.h unistd.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+  { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+              { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
 else
-  cat >conftest.$ac_ext <<_ACEOF
+  # Is the header compilable?
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-#include <ctype.h>
-#if ((' ' & 0x0FF) == 0x020)
-# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
-# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
-#else
-# define ISLOWER(c) \
-                  (('a' <= (c) && (c) <= 'i') \
-                    || ('j' <= (c) && (c) <= 'r') \
-                    || ('s' <= (c) && (c) <= 'z'))
-# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
-#endif
-
-#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
-int
-main ()
-{
-  int i;
-  for (i = 0; i < 256; i++)
-    if (XOR (islower (i), ISLOWER (i))
-       || toupper (i) != TOUPPER (i))
-      exit(2);
-  exit (0);
-}
+$ac_includes_default
+#include <$ac_header>
 _ACEOF
-rm -f conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>&5
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } && { ac_try='./conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_header_compiler=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_header_compiler=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
+
+# Is the header present?
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#include <$ac_header>
+_ACEOF
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
   ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  :
+  (exit $ac_status); } >/dev/null && {
+        test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       }; then
+  ac_header_preproc=yes
 else
-  echo "$as_me: program exited with status $ac_status" >&5
-echo "$as_me: failed program was:" >&5
+  echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-( exit $ac_status )
-ac_cv_header_stdc=no
+  ac_header_preproc=no
 fi
-rm -f core *.core gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext
+
+rm -f conftest.err conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
+
+# So?  What about this header?
+case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
+  yes:no: )
+    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
+    ac_header_preproc=yes
+    ;;
+  no:yes:* )
+    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header:     check for missing prerequisite headers?" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+    ( cat <<\_ASBOX
+## -------------------------------------- ##
+## Report this to koepke@tkn.tu-berlin.de ##
+## -------------------------------------- ##
+_ASBOX
+     ) | sed "s/^/$as_me: WARNING:     /" >&2
+    ;;
+esac
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  eval "$as_ac_Header=\$ac_header_preproc"
 fi
+ac_res=`eval echo '${'$as_ac_Header'}'`
+              { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+
 fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+  cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
+
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5
-echo "${ECHO_T}$ac_cv_header_stdc" >&6
-if test $ac_cv_header_stdc = yes; then
 
-cat >>confdefs.h <<\_ACEOF
-#define STDC_HEADERS 1
+done
+
+
+{ echo "$as_me:$LINENO: checking for poptGetNextOpt in -lpopt" >&5
+echo $ECHO_N "checking for poptGetNextOpt in -lpopt... $ECHO_C" >&6; }
+if test "${ac_cv_lib_popt_poptGetNextOpt+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lpopt  $LIBS"
+cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
 _ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
 
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char poptGetNextOpt ();
+int
+main ()
+{
+return poptGetNextOpt ();
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext conftest$ac_exeext
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest$ac_exeext &&
+       $as_test_x conftest$ac_exeext; then
+  ac_cv_lib_popt_poptGetNextOpt=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_cv_lib_popt_poptGetNextOpt=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
+      conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
 fi
+{ echo "$as_me:$LINENO: result: $ac_cv_lib_popt_poptGetNextOpt" >&5
+echo "${ECHO_T}$ac_cv_lib_popt_poptGetNextOpt" >&6; }
+if test $ac_cv_lib_popt_poptGetNextOpt = yes; then
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBPOPT 1
+_ACEOF
+
+  LIBS="-lpopt $LIBS"
 
-echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5
-echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6
+fi
+
+
+# Checks for typedefs, structures, and compiler characteristics.
+{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5
+echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; }
 if test "${ac_cv_c_const+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
@@ -4052,10 +5030,10 @@ main ()
 #ifndef __cplusplus
   /* Ultrix mips cc rejects this.  */
   typedef int charset[2];
-  const charset x;
+  const charset cs;
   /* SunOS 4.1.1 cc rejects this.  */
-  char const *const *ccp;
-  char **p;
+  char const *const *pcpcc;
+  char **ppc;
   /* NEC SVR4.0.2 mips cc rejects this.  */
   struct point {int x, y;};
   static struct point const zero = {0,0};
@@ -4064,16 +5042,17 @@ main ()
      an arm of an if-expression whose if-part is not a constant
      expression */
   const char *g = "string";
-  ccp = &g + (g ? g-g : 0);
+  pcpcc = &g + (g ? g-g : 0);
   /* HPUX 7.0 cc rejects these. */
-  ++ccp;
-  p = (char**) ccp;
-  ccp = (char const *const *) p;
+  ++pcpcc;
+  ppc = (char**) pcpcc;
+  pcpcc = (char const *const *) ppc;
   { /* SCO 3.2v4 cc rejects this.  */
     char *t;
     char const *s = 0 ? (char *) 0 : (char const *) 0;
 
     *t++ = 0;
+    if (s) return 0;
   }
   { /* Someone thinks the Sun supposedly-ANSI compiler will reject this.  */
     int x[] = {25, 17};
@@ -4092,70 +5071,288 @@ main ()
   }
   { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
     const int foo = 10;
+    if (!foo) return 0;
   }
+  return !cs[0] && !zero.x;
+#endif
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_c_const=yes
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_cv_c_const=no
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5
+echo "${ECHO_T}$ac_cv_c_const" >&6; }
+if test $ac_cv_c_const = no; then
+
+cat >>confdefs.h <<\_ACEOF
+#define const
+_ACEOF
+
+fi
+
+{ echo "$as_me:$LINENO: checking for inline" >&5
+echo $ECHO_N "checking for inline... $ECHO_C" >&6; }
+if test "${ac_cv_c_inline+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_cv_c_inline=no
+for ac_kw in inline __inline__ __inline; do
+  cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+#ifndef __cplusplus
+typedef int foo_t;
+static $ac_kw foo_t static_foo () {return 0; }
+$ac_kw foo_t foo () {return 0; }
 #endif
 
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_c_inline=$ac_kw
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  test "$ac_cv_c_inline" != no && break
+done
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_c_inline" >&5
+echo "${ECHO_T}$ac_cv_c_inline" >&6; }
+
+
+case $ac_cv_c_inline in
+  inline | yes) ;;
+  *)
+    case $ac_cv_c_inline in
+      no) ac_val=;;
+      *) ac_val=$ac_cv_c_inline;;
+    esac
+    cat >>confdefs.h <<_ACEOF
+#ifndef __cplusplus
+#define inline $ac_val
+#endif
+_ACEOF
+    ;;
+esac
+
+
+  { echo "$as_me:$LINENO: checking for uint16_t" >&5
+echo $ECHO_N "checking for uint16_t... $ECHO_C" >&6; }
+if test "${ac_cv_c_uint16_t+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_cv_c_uint16_t=no
+     for ac_type in 'uint16_t' 'unsigned int' 'unsigned long int' \
+        'unsigned long long int' 'unsigned short int' 'unsigned char'; do
+       cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+int
+main ()
+{
+static int test_array [1 - 2 * !(($ac_type) -1 >> (16 - 1) == 1)];
+test_array [0] = 0
+
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  case $ac_type in
+  uint16_t) ac_cv_c_uint16_t=yes ;;
+  *) ac_cv_c_uint16_t=$ac_type ;;
+esac
+
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+       test "$ac_cv_c_uint16_t" != no && break
+     done
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_c_uint16_t" >&5
+echo "${ECHO_T}$ac_cv_c_uint16_t" >&6; }
+  case $ac_cv_c_uint16_t in #(
+  no|yes) ;; #(
+  *)
+
+
+cat >>confdefs.h <<_ACEOF
+#define uint16_t $ac_cv_c_uint16_t
+_ACEOF
+;;
+  esac
+
+
+  { echo "$as_me:$LINENO: checking for uint8_t" >&5
+echo $ECHO_N "checking for uint8_t... $ECHO_C" >&6; }
+if test "${ac_cv_c_uint8_t+set}" = set; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  ac_cv_c_uint8_t=no
+     for ac_type in 'uint8_t' 'unsigned int' 'unsigned long int' \
+        'unsigned long long int' 'unsigned short int' 'unsigned char'; do
+       cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+int
+main ()
+{
+static int test_array [1 - 2 * !(($ac_type) -1 >> (8 - 1) == 1)];
+test_array [0] = 0
+
   ;
   return 0;
 }
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_c_const=yes
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  case $ac_type in
+  uint8_t) ac_cv_c_uint8_t=yes ;;
+  *) ac_cv_c_uint8_t=$ac_type ;;
+esac
+
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_c_const=no
+
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+       test "$ac_cv_c_uint8_t" != no && break
+     done
 fi
-echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5
-echo "${ECHO_T}$ac_cv_c_const" >&6
-if test $ac_cv_c_const = no; then
+{ echo "$as_me:$LINENO: result: $ac_cv_c_uint8_t" >&5
+echo "${ECHO_T}$ac_cv_c_uint8_t" >&6; }
+  case $ac_cv_c_uint8_t in #(
+  no|yes) ;; #(
+  *)
 
 cat >>confdefs.h <<\_ACEOF
-#define const
+#define _UINT8_T 1
 _ACEOF
 
-fi
+
+cat >>confdefs.h <<_ACEOF
+#define uint8_t $ac_cv_c_uint8_t
+_ACEOF
+;;
+  esac
 
 
-#checks for header files and libraries
-#AC_CHECK_HEADER(readline.h)
-#AC_CHECK_LIB(readline, rl_initialize)
-if test "${ac_cv_header_popt_h+set}" = set; then
-  echo "$as_me:$LINENO: checking for popt.h" >&5
-echo $ECHO_N "checking for popt.h... $ECHO_C" >&6
-if test "${ac_cv_header_popt_h+set}" = set; then
+
+
+for ac_header in sys/select.h sys/socket.h
+do
+as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh`
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
+  { echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_popt_h" >&5
-echo "${ECHO_T}$ac_cv_header_popt_h" >&6
+ac_res=`eval echo '${'$as_ac_Header'}'`
+              { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
 else
   # Is the header compilable?
-echo "$as_me:$LINENO: checking popt.h usability" >&5
-echo $ECHO_N "checking popt.h usability... $ECHO_C" >&6
+{ echo "$as_me:$LINENO: checking $ac_header usability" >&5
+echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; }
 cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
@@ -4163,70 +5360,64 @@ cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
 $ac_includes_default
-#include <popt.h>
+#include <$ac_header>
 _ACEOF
 rm -f conftest.$ac_objext
-if { (eval echo "$as_me:$LINENO: \"$ac_compile\"") >&5
-  (eval $ac_compile) 2>conftest.er1
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest.$ac_objext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
   ac_header_compiler=yes
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_header_compiler=no
+       ac_header_compiler=no
 fi
-rm -f conftest.err conftest.$ac_objext conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
-echo "${ECHO_T}$ac_header_compiler" >&6
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5
+echo "${ECHO_T}$ac_header_compiler" >&6; }
 
 # Is the header present?
-echo "$as_me:$LINENO: checking popt.h presence" >&5
-echo $ECHO_N "checking popt.h presence... $ECHO_C" >&6
+{ echo "$as_me:$LINENO: checking $ac_header presence" >&5
+echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; }
 cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
-#include <popt.h>
+#include <$ac_header>
 _ACEOF
-if { (eval echo "$as_me:$LINENO: \"$ac_cpp conftest.$ac_ext\"") >&5
-  (eval $ac_cpp conftest.$ac_ext) 2>conftest.er1
+if { (ac_try="$ac_cpp conftest.$ac_ext"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } >/dev/null; then
-  if test -s conftest.err; then
-    ac_cpp_err=$ac_c_preproc_warn_flag
-    ac_cpp_err=$ac_cpp_err$ac_c_werror_flag
-  else
-    ac_cpp_err=
-  fi
-else
-  ac_cpp_err=yes
-fi
-if test -z "$ac_cpp_err"; then
+  (exit $ac_status); } >/dev/null && {
+        test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       }; then
   ac_header_preproc=yes
 else
   echo "$as_me: failed program was:" >&5
@@ -4234,133 +5425,245 @@ sed 's/^/| /' conftest.$ac_ext >&5
 
   ac_header_preproc=no
 fi
+
 rm -f conftest.err conftest.$ac_ext
-echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
-echo "${ECHO_T}$ac_header_preproc" >&6
+echo "$as_me:$LINENO: result: $ac_header_preproc" >&5
+echo "${ECHO_T}$ac_header_preproc" >&6; }
 
 # So?  What about this header?
 case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in
   yes:no: )
-    { echo "$as_me:$LINENO: WARNING: popt.h: accepted by the compiler, rejected by the preprocessor!" >&5
-echo "$as_me: WARNING: popt.h: accepted by the compiler, rejected by the preprocessor!" >&2;}
-    { echo "$as_me:$LINENO: WARNING: popt.h: proceeding with the compiler's result" >&5
-echo "$as_me: WARNING: popt.h: proceeding with the compiler's result" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5
+echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;}
     ac_header_preproc=yes
     ;;
   no:yes:* )
-    { echo "$as_me:$LINENO: WARNING: popt.h: present but cannot be compiled" >&5
-echo "$as_me: WARNING: popt.h: present but cannot be compiled" >&2;}
-    { echo "$as_me:$LINENO: WARNING: popt.h:     check for missing prerequisite headers?" >&5
-echo "$as_me: WARNING: popt.h:     check for missing prerequisite headers?" >&2;}
-    { echo "$as_me:$LINENO: WARNING: popt.h: see the Autoconf documentation" >&5
-echo "$as_me: WARNING: popt.h: see the Autoconf documentation" >&2;}
-    { echo "$as_me:$LINENO: WARNING: popt.h:     section \"Present But Cannot Be Compiled\"" >&5
-echo "$as_me: WARNING: popt.h:     section \"Present But Cannot Be Compiled\"" >&2;}
-    { echo "$as_me:$LINENO: WARNING: popt.h: proceeding with the preprocessor's result" >&5
-echo "$as_me: WARNING: popt.h: proceeding with the preprocessor's result" >&2;}
-    { echo "$as_me:$LINENO: WARNING: popt.h: in the future, the compiler will take precedence" >&5
-echo "$as_me: WARNING: popt.h: in the future, the compiler will take precedence" >&2;}
-    (
-      cat <<\_ASBOX
+    { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5
+echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header:     check for missing prerequisite headers?" >&5
+echo "$as_me: WARNING: $ac_header:     check for missing prerequisite headers?" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5
+echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&5
+echo "$as_me: WARNING: $ac_header:     section \"Present But Cannot Be Compiled\"" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5
+echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;}
+    { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5
+echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;}
+    ( cat <<\_ASBOX
 ## -------------------------------------- ##
 ## Report this to koepke@tkn.tu-berlin.de ##
 ## -------------------------------------- ##
 _ASBOX
-    ) |
-      sed "s/^/$as_me: WARNING:     /" >&2
+     ) | sed "s/^/$as_me: WARNING:     /" >&2
     ;;
 esac
-echo "$as_me:$LINENO: checking for popt.h" >&5
-echo $ECHO_N "checking for popt.h... $ECHO_C" >&6
-if test "${ac_cv_header_popt_h+set}" = set; then
+{ echo "$as_me:$LINENO: checking for $ac_header" >&5
+echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; }
+if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_cv_header_popt_h=$ac_header_preproc
+  eval "$as_ac_Header=\$ac_header_preproc"
 fi
-echo "$as_me:$LINENO: result: $ac_cv_header_popt_h" >&5
-echo "${ECHO_T}$ac_cv_header_popt_h" >&6
+ac_res=`eval echo '${'$as_ac_Header'}'`
+              { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
 
 fi
+if test `eval echo '${'$as_ac_Header'}'` = yes; then
+  cat >>confdefs.h <<_ACEOF
+#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1
+_ACEOF
 
+fi
 
+done
 
-echo "$as_me:$LINENO: checking for poptGetNextOpt in -lpopt" >&5
-echo $ECHO_N "checking for poptGetNextOpt in -lpopt... $ECHO_C" >&6
-if test "${ac_cv_lib_popt_poptGetNextOpt+set}" = set; then
+{ echo "$as_me:$LINENO: checking types of arguments for select" >&5
+echo $ECHO_N "checking types of arguments for select... $ECHO_C" >&6; }
+if test "${ac_cv_func_select_args+set}" = set; then
   echo $ECHO_N "(cached) $ECHO_C" >&6
 else
-  ac_check_lib_save_LIBS=$LIBS
-LIBS="-lpopt  $LIBS"
-cat >conftest.$ac_ext <<_ACEOF
+  for ac_arg234 in 'fd_set *' 'int *' 'void *'; do
+ for ac_arg1 in 'int' 'size_t' 'unsigned long int' 'unsigned int'; do
+  for ac_arg5 in 'struct timeval *' 'const struct timeval *'; do
+   cat >conftest.$ac_ext <<_ACEOF
+/* confdefs.h.  */
+_ACEOF
+cat confdefs.h >>conftest.$ac_ext
+cat >>conftest.$ac_ext <<_ACEOF
+/* end confdefs.h.  */
+$ac_includes_default
+#ifdef HAVE_SYS_SELECT_H
+# include <sys/select.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+# include <sys/socket.h>
+#endif
+
+int
+main ()
+{
+extern int select ($ac_arg1,
+                                           $ac_arg234, $ac_arg234, $ac_arg234,
+                                           $ac_arg5);
+  ;
+  return 0;
+}
+_ACEOF
+rm -f conftest.$ac_objext
+if { (ac_try="$ac_compile"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_compile") 2>conftest.er1
+  ac_status=$?
+  grep -v '^ *+' conftest.er1 >conftest.err
+  rm -f conftest.er1
+  cat conftest.err >&5
+  echo "$as_me:$LINENO: \$? = $ac_status" >&5
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest.$ac_objext; then
+  ac_cv_func_select_args="$ac_arg1,$ac_arg234,$ac_arg5"; break 3
+else
+  echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+
+fi
+
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+  done
+ done
+done
+# Provide a safe default value.
+: ${ac_cv_func_select_args='int,int *,struct timeval *'}
+
+fi
+{ echo "$as_me:$LINENO: result: $ac_cv_func_select_args" >&5
+echo "${ECHO_T}$ac_cv_func_select_args" >&6; }
+ac_save_IFS=$IFS; IFS=','
+set dummy `echo "$ac_cv_func_select_args" | sed 's/\*/\*/g'`
+IFS=$ac_save_IFS
+shift
+
+cat >>confdefs.h <<_ACEOF
+#define SELECT_TYPE_ARG1 $1
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define SELECT_TYPE_ARG234 ($2)
+_ACEOF
+
+
+cat >>confdefs.h <<_ACEOF
+#define SELECT_TYPE_ARG5 ($3)
+_ACEOF
+
+rm -f conftest*
+
+
+
+for ac_func in select strerror
+do
+as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh`
+{ echo "$as_me:$LINENO: checking for $ac_func" >&5
+echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; }
+if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then
+  echo $ECHO_N "(cached) $ECHO_C" >&6
+else
+  cat >conftest.$ac_ext <<_ACEOF
 /* confdefs.h.  */
 _ACEOF
 cat confdefs.h >>conftest.$ac_ext
 cat >>conftest.$ac_ext <<_ACEOF
 /* end confdefs.h.  */
+/* Define $ac_func to an innocuous variant, in case <limits.h> declares $ac_func.
+   For example, HP-UX 11i <limits.h> declares gettimeofday.  */
+#define $ac_func innocuous_$ac_func
+
+/* System header to define __stub macros and hopefully few prototypes,
+    which can conflict with char $ac_func (); below.
+    Prefer <limits.h> to <assert.h> if __STDC__ is defined, since
+    <limits.h> exists even on freestanding compilers.  */
+
+#ifdef __STDC__
+# include <limits.h>
+#else
+# include <assert.h>
+#endif
+
+#undef $ac_func
 
-/* Override any gcc2 internal prototype to avoid an error.  */
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
 #ifdef __cplusplus
 extern "C"
 #endif
-/* We use char because int might match the return type of a gcc2
-   builtin and then its argument prototype would still apply.  */
-char poptGetNextOpt ();
+char $ac_func ();
+/* The GNU C library defines this for functions which it implements
+    to always fail with ENOSYS.  Some functions are actually named
+    something starting with __ and the normal name is an alias.  */
+#if defined __stub_$ac_func || defined __stub___$ac_func
+choke me
+#endif
+
 int
 main ()
 {
-poptGetNextOpt ();
+return $ac_func ();
   ;
   return 0;
 }
 _ACEOF
 rm -f conftest.$ac_objext conftest$ac_exeext
-if { (eval echo "$as_me:$LINENO: \"$ac_link\"") >&5
-  (eval $ac_link) 2>conftest.er1
+if { (ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5
+  (eval "$ac_link") 2>conftest.er1
   ac_status=$?
   grep -v '^ *+' conftest.er1 >conftest.err
   rm -f conftest.er1
   cat conftest.err >&5
   echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); } &&
-        { ac_try='test -z "$ac_c_werror_flag"
-                        || test ! -s conftest.err'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; } &&
-        { ac_try='test -s conftest$ac_exeext'
-  { (eval echo "$as_me:$LINENO: \"$ac_try\"") >&5
-  (eval $ac_try) 2>&5
-  ac_status=$?
-  echo "$as_me:$LINENO: \$? = $ac_status" >&5
-  (exit $ac_status); }; }; then
-  ac_cv_lib_popt_poptGetNextOpt=yes
+  (exit $ac_status); } && {
+        test -z "$ac_c_werror_flag" ||
+        test ! -s conftest.err
+       } && test -s conftest$ac_exeext &&
+       $as_test_x conftest$ac_exeext; then
+  eval "$as_ac_var=yes"
 else
   echo "$as_me: failed program was:" >&5
 sed 's/^/| /' conftest.$ac_ext >&5
 
-ac_cv_lib_popt_poptGetNextOpt=no
+       eval "$as_ac_var=no"
 fi
-rm -f conftest.err conftest.$ac_objext \
+
+rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \
       conftest$ac_exeext conftest.$ac_ext
-LIBS=$ac_check_lib_save_LIBS
 fi
-echo "$as_me:$LINENO: result: $ac_cv_lib_popt_poptGetNextOpt" >&5
-echo "${ECHO_T}$ac_cv_lib_popt_poptGetNextOpt" >&6
-if test $ac_cv_lib_popt_poptGetNextOpt = yes; then
+ac_res=`eval echo '${'$as_ac_var'}'`
+              { echo "$as_me:$LINENO: result: $ac_res" >&5
+echo "${ECHO_T}$ac_res" >&6; }
+if test `eval echo '${'$as_ac_var'}'` = yes; then
   cat >>confdefs.h <<_ACEOF
-#define HAVE_LIBPOPT 1
+#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1
 _ACEOF
 
-  LIBS="-lpopt $LIBS"
-
 fi
+done
 
-#AC_CHECK_HEADER(pthread.h)
-
-# Checks for typedefs, structures, and compiler characteristics.
-# AC_HEADER_STDBOOL
 
 
 
@@ -4368,11 +5671,11 @@ fi
 
 # optimization features
 DEFDEBUG="no"
-# Check whether --enable-debug or --disable-debug was given.
+# Check whether --enable-debug was given.
 if test "${enable_debug+set}" = set; then
-  enableval="$enable_debug"
-  DEFDEBUG=$enableval
-fi;
+  enableval=$enable_debug; DEFDEBUG=$enableval
+fi
+
 if test "$DEFDEBUG" = "yes"; then
    CFLAGS=`echo $CFLAGS | sed -e 's/-O2//g' | sed -e 's/-g//g'`
    CFLAGS="$CFLAGS -ggdb3"
@@ -4381,11 +5684,11 @@ if test "$DEFDEBUG" = "yes"; then
 fi
 
 DEFOPTIMIZE="no"
-# Check whether --enable-optimize or --disable-optimize was given.
+# Check whether --enable-optimize was given.
 if test "${enable_optimize+set}" = set; then
-  enableval="$enable_optimize"
-  DEFOPTIMIZE=$enableval
-fi;
+  enableval=$enable_optimize; DEFOPTIMIZE=$enableval
+fi
+
 if test "$DEFOPTIMIZE" = "yes"; then
    CFLAGS=`echo $CFLAGS | sed -e 's/-O2//g' | sed -e 's/-g//g'`
    CFLAGS="$CFLAGS -O3 -ggdb3 "
@@ -4394,11 +5697,11 @@ if test "$DEFOPTIMIZE" = "yes"; then
 fi
 
 DEFPROF="no"
-# Check whether --enable-prof or --disable-prof was given.
+# Check whether --enable-prof was given.
 if test "${enable_prof+set}" = set; then
-  enableval="$enable_prof"
-  DEFPROF=$enableval
-fi;
+  enableval=$enable_prof; DEFPROF=$enableval
+fi
+
 if test "$DEFPROF" = "yes"; then
    CFLAGS=`echo $CFLAGS | sed -e 's/-O2//g' | sed -e 's/-g//g'`
    CFLAGS="$CFLAGS -O1 -pg"
@@ -4415,7 +5718,7 @@ CXXFLAGS="$CXXFLAGS $PTHREAD_CFLAGS"
 CC="$PTHREAD_CC"
 # CXX="$CXX $PTHREAD_CFLAGS $LIBS"
 
-                              ac_config_files="$ac_config_files Makefile config/Makefile src/Makefile"
+ac_config_files="$ac_config_files Makefile config/Makefile src/Makefile"
 
 cat >confcache <<\_ACEOF
 # This file is a shell script that caches the results of configure
@@ -4435,39 +5738,58 @@ _ACEOF
 
 # The following way of writing the cache mishandles newlines in values,
 # but we know of no workaround that is simple, portable, and efficient.
-# So, don't put newlines in cache variables' values.
+# So, we kill variables containing newlines.
 # Ultrix sh set writes to stderr and can't be redirected directly,
 # and sets the high bit in the cache file unless we assign to the vars.
-{
+(
+  for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do
+    eval ac_val=\$$ac_var
+    case $ac_val in #(
+    *${as_nl}*)
+      case $ac_var in #(
+      *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5
+echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;;
+      esac
+      case $ac_var in #(
+      _ | IFS | as_nl) ;; #(
+      *) $as_unset $ac_var ;;
+      esac ;;
+    esac
+  done
+
   (set) 2>&1 |
-    case `(ac_space=' '; set | grep ac_space) 2>&1` in
-    *ac_space=\ *)
+    case $as_nl`(ac_space=' '; set) 2>&1` in #(
+    *${as_nl}ac_space=\ *)
       # `set' does not quote correctly, so add quotes (double-quote
       # substitution turns \\\\ into \\, and sed turns \\ into \).
       sed -n \
        "s/'/'\\\\''/g;
          s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p"
-      ;;
+      ;; #(
     *)
       # `set' quotes correctly as required by POSIX, so do not add quotes.
-      sed -n \
-       "s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1=\\2/p"
+      sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p"
       ;;
-    esac;
-} |
+    esac |
+    sort
+) |
   sed '
+     /^ac_cv_env_/b end
      t clear
-     : clear
+     :clear
      s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/
      t end
-     /^ac_cv_env/!s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
-     : end' >>confcache
-if diff $cache_file confcache >/dev/null 2>&1; then :; else
-  if test -w $cache_file; then
-    test "x$cache_file" != "x/dev/null" && echo "updating cache $cache_file"
+     s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/
+     :end' >>confcache
+if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
+  if test -w "$cache_file"; then
+    test "x$cache_file" != "x/dev/null" &&
+      { echo "$as_me:$LINENO: updating cache $cache_file" >&5
+echo "$as_me: updating cache $cache_file" >&6;}
     cat confcache >$cache_file
   else
-    echo "not updating unwritable cache $cache_file"
+    { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5
+echo "$as_me: not updating unwritable cache $cache_file" >&6;}
   fi
 fi
 rm -f confcache
@@ -4476,32 +5798,18 @@ test "x$prefix" = xNONE && prefix=$ac_default_prefix
 # Let make expand exec_prefix.
 test "x$exec_prefix" = xNONE && exec_prefix='${prefix}'
 
-# VPATH may cause trouble with some makes, so we remove $(srcdir),
-# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
-# trailing colons and then remove the whole line if VPATH becomes empty
-# (actually we leave an empty line to preserve line numbers).
-if test "x$srcdir" = x.; then
-  ac_vpsub='/^[         ]*VPATH[        ]*=/{
-s/:*\$(srcdir):*/:/;
-s/:*\${srcdir}:*/:/;
-s/:*@srcdir@:*/:/;
-s/^\([^=]*=[    ]*\):*/\1/;
-s/:*$//;
-s/^[^=]*=[      ]*$//;
-}'
-fi
-
 DEFS=-DHAVE_CONFIG_H
 
 ac_libobjs=
 ac_ltlibobjs=
 for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue
   # 1. Remove the extension, and $U if already installed.
-  ac_i=`echo "$ac_i" |
-        sed 's/\$U\././;s/\.o$//;s/\.obj$//'`
-  # 2. Add them.
-  ac_libobjs="$ac_libobjs $ac_i\$U.$ac_objext"
-  ac_ltlibobjs="$ac_ltlibobjs $ac_i"'$U.lo'
+  ac_script='s/\$U\././;s/\.o$//;s/\.obj$//'
+  ac_i=`echo "$ac_i" | sed "$ac_script"`
+  # 2. Prepend LIBOBJDIR.  When used with automake>=1.10 LIBOBJDIR
+  #    will be set to the directory where LIBOBJS objects are built.
+  ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext"
+  ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo'
 done
 LIBOBJS=$ac_libobjs
 
@@ -4553,17 +5861,45 @@ cat >>$CONFIG_STATUS <<\_ACEOF
 ## M4sh Initialization.  ##
 ## --------------------- ##
 
-# Be Bourne compatible
+# Be more Bourne compatible
+DUALCASE=1; export DUALCASE # for MKS sh
 if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then
   emulate sh
   NULLCMD=:
   # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which
   # is contrary to our usage.  Disable this feature.
   alias -g '${1+"$@"}'='"$@"'
-elif test -n "${BASH_VERSION+set}" && (set -o posix) >/dev/null 2>&1; then
-  set -o posix
+  setopt NO_GLOB_SUBST
+else
+  case `(set -o) 2>/dev/null` in
+  *posix*) set -o posix ;;
+esac
+
+fi
+
+
+
+
+# PATH needs CR
+# Avoid depending upon Character Ranges.
+as_cr_letters='abcdefghijklmnopqrstuvwxyz'
+as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+as_cr_Letters=$as_cr_letters$as_cr_LETTERS
+as_cr_digits='0123456789'
+as_cr_alnum=$as_cr_Letters$as_cr_digits
+
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+  echo "#! /bin/sh" >conf$$.sh
+  echo  "exit 0"   >>conf$$.sh
+  chmod +x conf$$.sh
+  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+    PATH_SEPARATOR=';'
+  else
+    PATH_SEPARATOR=:
+  fi
+  rm -f conf$$.sh
 fi
-DUALCASE=1; export DUALCASE # for MKS sh
 
 # Support unset when possible.
 if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then
@@ -4573,8 +5909,43 @@ else
 fi
 
 
+# IFS
+# We need space, tab and new line, in precisely that order.  Quoting is
+# there to prevent editors from complaining about space-tab.
+# (If _AS_PATH_WALK were called with IFS unset, it would disable word
+# splitting by setting IFS to empty value.)
+as_nl='
+'
+IFS=" ""       $as_nl"
+
+# Find who we are.  Look in the path if we contain no directory separator.
+case $0 in
+  *[\\/]* ) as_myself=$0 ;;
+  *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
+for as_dir in $PATH
+do
+  IFS=$as_save_IFS
+  test -z "$as_dir" && as_dir=.
+  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
+done
+IFS=$as_save_IFS
+
+     ;;
+esac
+# We did not find ourselves, most probably we were run as `sh COMMAND'
+# in which case we are not to be found in the path.
+if test "x$as_myself" = x; then
+  as_myself=$0
+fi
+if test ! -f "$as_myself"; then
+  echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2
+  { (exit 1); exit 1; }
+fi
+
 # Work around bugs in pre-3.0 UWIN ksh.
-$as_unset ENV MAIL MAILPATH
+for as_var in ENV MAIL MAILPATH
+do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
+done
 PS1='$ '
 PS2='> '
 PS4='+ '
@@ -4588,18 +5959,19 @@ do
   if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then
     eval $as_var=C; export $as_var
   else
-    $as_unset $as_var
+    ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var
   fi
 done
 
 # Required to use basename.
-if expr a : '\(a\)' >/dev/null 2>&1; then
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
   as_expr=expr
 else
   as_expr=false
 fi
 
-if (basename /) >/dev/null 2>&1 && test "X`basename / 2>&1`" = "X/"; then
+if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then
   as_basename=basename
 else
   as_basename=false
 
 
 # Name of the executable.
-as_me=`$as_basename "$0" ||
+as_me=`$as_basename -- "$0" ||
 $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \
         X"$0" : 'X\(//\)$' \| \
-        X"$0" : 'X\(/\)$' \| \
-        .     : '\(.\)' 2>/dev/null ||
+        X"$0" : 'X\(/\)' \| . 2>/dev/null ||
 echo X/"$0" |
-    sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/; q; }
-         /^X\/\(\/\/\)$/{ s//\1/; q; }
-         /^X\/\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
-
-
-# PATH needs CR, and LINENO needs CR and PATH.
-# Avoid depending upon Character Ranges.
-as_cr_letters='abcdefghijklmnopqrstuvwxyz'
-as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-as_cr_Letters=$as_cr_letters$as_cr_LETTERS
-as_cr_digits='0123456789'
-as_cr_alnum=$as_cr_Letters$as_cr_digits
+    sed '/^.*\/\([^/][^/]*\)\/*$/{
+           s//\1/
+           q
+         }
+         /^X\/\(\/\/\)$/{
+           s//\1/
+           q
+         }
+         /^X\/\(\/\).*/{
+           s//\1/
+           q
+         }
+         s/.*/./; q'`
 
-# The user is always right.
-if test "${PATH_SEPARATOR+set}" != set; then
-  echo "#! /bin/sh" >conf$$.sh
-  echo  "exit 0"   >>conf$$.sh
-  chmod +x conf$$.sh
-  if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
-    PATH_SEPARATOR=';'
-  else
-    PATH_SEPARATOR=:
-  fi
-  rm -f conf$$.sh
-fi
+# CDPATH.
+$as_unset CDPATH
 
 
-  as_lineno_1=$LINENO
-  as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
-  test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2"  || {
-  # Find who we are.  Look in the path if we contain no path at all
-  # relative or not.
-  case $0 in
-    *[\\/]* ) as_myself=$0 ;;
-    *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in $PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break
-done
 
-       ;;
-  esac
-  # We did not find ourselves, most probably we were run as `sh COMMAND'
-  # in which case we are not to be found in the path.
-  if test "x$as_myself" = x; then
-    as_myself=$0
-  fi
-  if test ! -f "$as_myself"; then
-    { { echo "$as_me:$LINENO: error: cannot find myself; rerun with an absolute path" >&5
-echo "$as_me: error: cannot find myself; rerun with an absolute path" >&2;}
-   { (exit 1); exit 1; }; }
-  fi
-  case $CONFIG_SHELL in
-  '')
-    as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
-for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH
-do
-  IFS=$as_save_IFS
-  test -z "$as_dir" && as_dir=.
-  for as_base in sh bash ksh sh5; do
-        case $as_dir in
-        /*)
-          if ("$as_dir/$as_base" -c '
   as_lineno_1=$LINENO
   as_lineno_2=$LINENO
-  as_lineno_3=`(expr $as_lineno_1 + 1) 2>/dev/null`
   test "x$as_lineno_1" != "x$as_lineno_2" &&
-  test "x$as_lineno_3"  = "x$as_lineno_2" ') 2>/dev/null; then
-            $as_unset BASH_ENV || test "${BASH_ENV+set}" != set || { BASH_ENV=; export BASH_ENV; }
-            $as_unset ENV || test "${ENV+set}" != set || { ENV=; export ENV; }
-            CONFIG_SHELL=$as_dir/$as_base
-            export CONFIG_SHELL
-            exec "$CONFIG_SHELL" "$0" ${1+"$@"}
-          fi;;
-        esac
-       done
-done
-;;
-  esac
+  test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || {
 
   # Create $as_me.lineno as a copy of $as_myself, but with $LINENO
   # uniformly replaced by the line number.  The first 'sed' inserts a
-  # line-number line before each line; the second 'sed' does the real
-  # work.  The second script uses 'N' to pair each line-number line
-  # with the numbered line, and appends trailing '-' during
-  # substitution so that $LINENO is not a special case at line end.
+  # line-number line after each line using $LINENO; the second 'sed'
+  # does the real work.  The second script uses 'N' to pair each
+  # line-number line with the line containing $LINENO, and appends
+  # trailing '-' during substitution so that $LINENO is not a special
+  # case at line end.
   # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the
-  # second 'sed' script.  Blame Lee E. McMahon for sed's syntax.  :-)
-  sed '=' <$as_myself |
+  # scripts with optimization help from Paolo Bonzini.  Blame Lee
+  # E. McMahon (1931-1989) for sed's syntax.  :-)
+  sed -n '
+    p
+    /[$]LINENO/=
+  ' <$as_myself |
     sed '
+      s/[$]LINENO.*/&-/
+      t lineno
+      b
+      :lineno
       N
-      s,$,-,
-      : loop
-      s,^\(['$as_cr_digits']*\)\(.*\)[$]LINENO\([^'$as_cr_alnum'_]\),\1\2\1\3,
+      :loop
+      s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/
       t loop
-      s,-$,,
-      s,^['$as_cr_digits']*\n,,
+      s/-\n.*//
     ' >$as_me.lineno &&
-  chmod +x $as_me.lineno ||
-    { { echo "$as_me:$LINENO: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&5
-echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2;}
+  chmod +x "$as_me.lineno" ||
+    { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2
    { (exit 1); exit 1; }; }
 
   # Don't try to exec as it changes $[0], causing all sort of problems
   # (the dirname of $[0] is not the place where we might find the
-  # original and so on.  Autoconf is especially sensible to this).
-  . ./$as_me.lineno
+  # original and so on.  Autoconf is especially sensitive to this).
+  . "./$as_me.lineno"
   # Exit status is that of the last command.
   exit
 }
 
 
-case `echo "testing\c"; echo 1,2,3`,`echo -n testing; echo 1,2,3` in
-  *c*,-n*) ECHO_N= ECHO_C='
-' ECHO_T='     ' ;;
-  *c*,*  ) ECHO_N=-n ECHO_C= ECHO_T= ;;
-  *)       ECHO_N= ECHO_C='\c' ECHO_T= ;;
+if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then
+  as_dirname=dirname
+else
+  as_dirname=false
+fi
+
+ECHO_C= ECHO_N= ECHO_T=
+case `echo -n x` in
+-n*)
+  case `echo 'x\c'` in
+  *c*) ECHO_T='        ';;     # ECHO_T is single tab character.
+  *)   ECHO_C='\c';;
+  esac;;
+*)
+  ECHO_N='-n';;
 esac
 
-if expr a : '\(a\)' >/dev/null 2>&1; then
+if expr a : '\(a\)' >/dev/null 2>&1 &&
+   test "X`expr 00001 : '.*\(...\)'`" = X001; then
   as_expr=expr
 else
   as_expr=false
 fi
 
 rm -f conf$$ conf$$.exe conf$$.file
+if test -d conf$$.dir; then
+  rm -f conf$$.dir/conf$$.file
+else
+  rm -f conf$$.dir
+  mkdir conf$$.dir
+fi
 echo >conf$$.file
 if ln -s conf$$.file conf$$ 2>/dev/null; then
-  # We could just check for DJGPP; but this test a) works b) is more generic
-  # and c) will remain valid once DJGPP supports symlinks (DJGPP 2.04).
-  if test -f conf$$.exe; then
-    # Don't use ln at all; we don't have any links
+  as_ln_s='ln -s'
+  # ... but there are two gotchas:
+  # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
+  # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
+  # In both cases, we have to default to `cp -p'.
+  ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
     as_ln_s='cp -p'
-  else
-    as_ln_s='ln -s'
-  fi
 elif ln conf$$.file conf$$ 2>/dev/null; then
   as_ln_s=ln
 else
   as_ln_s='cp -p'
 fi
-rm -f conf$$ conf$$.exe conf$$.file
+rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
+rmdir conf$$.dir 2>/dev/null
 
 if mkdir -p . 2>/dev/null; then
   as_mkdir_p=:
@@ -4768,7 +6101,28 @@ else
   as_mkdir_p=false
 fi
 
-as_executable_p="test -f"
+if test -x / >/dev/null 2>&1; then
+  as_test_x='test -x'
+else
+  if ls -dL / >/dev/null 2>&1; then
+    as_ls_L_option=L
+  else
+    as_ls_L_option=
+  fi
+  as_test_x='
+    eval sh -c '\''
+      if test -d "$1"; then
+        test -d "$1/.";
+      else
+       case $1 in
+        -*)set "./$1";;
+       esac;
+       case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in
+       ???[sx]*):;;*)false;;esac;fi
+    '\'' sh
+  '
+fi
+as_executable_p=$as_test_x
 
 # Sed expression to map a string onto a valid CPP name.
 as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
@@ -4777,31 +6131,14 @@ as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
 as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'"
 
 
-# IFS
-# We need space, tab and new line, in precisely that order.
-as_nl='
-'
-IFS="  $as_nl"
-
-# CDPATH.
-$as_unset CDPATH
-
 exec 6>&1
 
-# Open the log real soon, to keep \$[0] and so on meaningful, and to
+# Save the log message, to keep $[0] and so on meaningful, and to
 # report actual input values of CONFIG_FILES etc. instead of their
-# values after options handling.  Logging --version etc. is OK.
-exec 5>>config.log
-{
-  echo
-  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
-## Running $as_me. ##
-_ASBOX
-} >&5
-cat >&5 <<_CSEOF
-
+# values after options handling.
+ac_log="
 This file was extended by cppbsl $as_me 0.1, which was
-generated by GNU Autoconf 2.59.  Invocation command line was
+generated by GNU Autoconf 2.61.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
   CONFIG_HEADERS  = $CONFIG_HEADERS
@@ -4809,30 +6146,20 @@ generated by GNU Autoconf 2.59.  Invocation command line was
   CONFIG_COMMANDS = $CONFIG_COMMANDS
   $ $0 $@
 
-_CSEOF
-echo "on `(hostname || uname -n) 2>/dev/null | sed 1q`" >&5
-echo >&5
+on `(hostname || uname -n) 2>/dev/null | sed 1q`
+"
+
 _ACEOF
 
+cat >>$CONFIG_STATUS <<_ACEOF
 # Files that config.status was made for.
-if test -n "$ac_config_files"; then
-  echo "config_files=\"$ac_config_files\"" >>$CONFIG_STATUS
-fi
-
-if test -n "$ac_config_headers"; then
-  echo "config_headers=\"$ac_config_headers\"" >>$CONFIG_STATUS
-fi
-
-if test -n "$ac_config_links"; then
-  echo "config_links=\"$ac_config_links\"" >>$CONFIG_STATUS
-fi
+config_files="$ac_config_files"
+config_headers="$ac_config_headers"
+config_commands="$ac_config_commands"
 
-if test -n "$ac_config_commands"; then
-  echo "config_commands=\"$ac_config_commands\"" >>$CONFIG_STATUS
-fi
+_ACEOF
 
 cat >>$CONFIG_STATUS <<\_ACEOF
-
 ac_cs_usage="\
 \`$as_me' instantiates files from templates according to the
 current configuration.
@@ -4840,7 +6167,7 @@ current configuration.
 Usage: $0 [OPTIONS] [FILE]...
 
   -h, --help       print this help, then exit
-  -V, --version    print version number, then exit
+  -V, --version    print version number and configuration settings, then exit
   -q, --quiet      do not print progress messages
   -d, --debug      don't remove temporary files
       --recheck    update $as_me by reconfiguring in the same conditions
@@ -4859,19 +6186,22 @@ Configuration commands:
 $config_commands
 
 Report bugs to <bug-autoconf@gnu.org>."
-_ACEOF
 
+_ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF
 ac_cs_version="\\
 cppbsl config.status 0.1
-configured by $0, generated by GNU Autoconf 2.59,
-  with options \\"`echo "$ac_configure_args" | sed 's/[\\""\`\$]/\\\\&/g'`\\"
+configured by $0, generated by GNU Autoconf 2.61,
+  with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\"
 
-Copyright (C) 2003 Free Software Foundation, Inc.
+Copyright (C) 2006 Free Software Foundation, Inc.
 This config.status script is free software; the Free Software Foundation
 gives unlimited permission to copy, distribute and modify it."
-srcdir=$srcdir
-INSTALL="$INSTALL"
+
+ac_pwd='$ac_pwd'
+srcdir='$srcdir'
+INSTALL='$INSTALL'
+MKDIR_P='$MKDIR_P'
 _ACEOF
 
 cat >>$CONFIG_STATUS <<\_ACEOF
@@ -4882,39 +6212,24 @@ while test $# != 0
 do
   case $1 in
   --*=*)
-    ac_option=`expr "x$1" : 'x\([^=]*\)='`
-    ac_optarg=`expr "x$1" : 'x[^=]*=\(.*\)'`
+    ac_option=`expr "X$1" : 'X\([^=]*\)='`
+    ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'`
     ac_shift=:
     ;;
-  -*)
+  *)
     ac_option=$1
     ac_optarg=$2
     ac_shift=shift
     ;;
-  *) # This is not an option, so the user has probably given explicit
-     # arguments.
-     ac_option=$1
-     ac_need_defaults=false;;
   esac
 
   case $ac_option in
   # Handling of the options.
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
   -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r)
     ac_cs_recheck=: ;;
-  --version | --vers* | -V )
-    echo "$ac_cs_version"; exit 0 ;;
-  --he | --h)
-    # Conflict between --help and --header
-    { { echo "$as_me:$LINENO: error: ambiguous option: $1
-Try \`$0 --help' for more information." >&5
-echo "$as_me: error: ambiguous option: $1
-Try \`$0 --help' for more information." >&2;}
-   { (exit 1); exit 1; }; };;
-  --help | --hel | -h )
-    echo "$ac_cs_usage"; exit 0 ;;
-  --debug | --d* | -d )
+  --version | --versio | --versi | --vers | --ver | --ve | --v | -V )
+    echo "$ac_cs_version"; exit ;;
+  --debug | --debu | --deb | --de | --d | -d )
     debug=: ;;
   --file | --fil | --fi | --f )
     $ac_shift
@@ -4924,18 +6239,24 @@ Try \`$0 --help' for more information." >&2;}
     $ac_shift
     CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg"
     ac_need_defaults=false;;
+  --he | --h)
+    # Conflict between --help and --header
+    { echo "$as_me: error: ambiguous option: $1
+Try \`$0 --help' for more information." >&2
+   { (exit 1); exit 1; }; };;
+  --help | --hel | -h )
+    echo "$ac_cs_usage"; exit ;;
   -q | -quiet | --quiet | --quie | --qui | --qu | --q \
   | -silent | --silent | --silen | --sile | --sil | --si | --s)
     ac_cs_silent=: ;;
 
   # This is an error.
-  -*) { { echo "$as_me:$LINENO: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&5
-echo "$as_me: error: unrecognized option: $1
-Try \`$0 --help' for more information." >&2;}
+  -*) { echo "$as_me: error: unrecognized option: $1
+Try \`$0 --help' for more information." >&2
    { (exit 1); exit 1; }; } ;;
 
-  *) ac_config_targets="$ac_config_targets $1" ;;
+  *) ac_config_targets="$ac_config_targets $1"
+     ac_need_defaults=false ;;
 
   esac
   shift
@@ -4951,39 +6272,51 @@ fi
 _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF
 if \$ac_cs_recheck; then
-  echo "running $SHELL $0 " $ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
-  exec $SHELL $0 $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+  echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6
+  CONFIG_SHELL=$SHELL
+  export CONFIG_SHELL
+  exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
 fi
 
 _ACEOF
+cat >>$CONFIG_STATUS <<\_ACEOF
+exec 5>>config.log
+{
+  echo
+  sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX
+## Running $as_me. ##
+_ASBOX
+  echo "$ac_log"
+} >&5
 
+_ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF
 #
-# INIT-COMMANDS section.
+# INIT-COMMANDS
 #
-
 AMDEP_TRUE="$AMDEP_TRUE" ac_aux_dir="$ac_aux_dir"
 
 _ACEOF
 
-
-
 cat >>$CONFIG_STATUS <<\_ACEOF
+
+# Handling of arguments.
 for ac_config_target in $ac_config_targets
 do
-  case "$ac_config_target" in
-  # Handling of arguments.
-  "Makefile" ) CONFIG_FILES="$CONFIG_FILES Makefile" ;;
-  "config/Makefile" ) CONFIG_FILES="$CONFIG_FILES config/Makefile" ;;
-  "src/Makefile" ) CONFIG_FILES="$CONFIG_FILES src/Makefile" ;;
-  "depfiles" ) CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;;
-  "config.h" ) CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
+  case $ac_config_target in
+    "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
+    "depfiles") CONFIG_COMMANDS="$CONFIG_COMMANDS depfiles" ;;
+    "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+    "config/Makefile") CONFIG_FILES="$CONFIG_FILES config/Makefile" ;;
+    "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;;
+
   *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5
 echo "$as_me: error: invalid argument: $ac_config_target" >&2;}
    { (exit 1); exit 1; }; };;
   esac
 done
 
+
 # If the user did not use the arguments to specify the items to instantiate,
 # then the envvar interface is used.  Set only those that are not.
 # We use the long form for the default assignment because of an extremely
@@ -4995,330 +6328,405 @@ if $ac_need_defaults; then
 fi
 
 # Have a temporary directory for convenience.  Make it in the build tree
-# simply because there is no reason to put it here, and in addition,
+# simply because there is no reason against having it here, and in addition,
 # creating and moving files from /tmp can sometimes cause problems.
-# Create a temporary directory, and hook for its removal unless debugging.
+# Hook for its removal unless debugging.
+# Note that there is a small window in which the directory will not be cleaned:
+# after its creation but before its name has been assigned to `$tmp'.
 $debug ||
 {
-  trap 'exit_status=$?; rm -rf $tmp && exit $exit_status' 0
+  tmp=
+  trap 'exit_status=$?
+  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+' 0
   trap '{ (exit 1); exit 1; }' 1 2 13 15
 }
-
 # Create a (secure) tmp directory for tmp files.
 
 {
-  tmp=`(umask 077 && mktemp -d -q "./confstatXXXXXX") 2>/dev/null` &&
+  tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
   test -n "$tmp" && test -d "$tmp"
 }  ||
 {
-  tmp=./confstat$$-$RANDOM
-  (umask 077 && mkdir $tmp)
+  tmp=./conf$$-$RANDOM
+  (umask 077 && mkdir "$tmp")
 } ||
 {
    echo "$me: cannot create a temporary directory in ." >&2
    { (exit 1); exit 1; }
 }
 
-_ACEOF
-
-cat >>$CONFIG_STATUS <<_ACEOF
-
 #
-# CONFIG_FILES section.
+# Set up the sed scripts for CONFIG_FILES section.
 #
 
 # No need to generate the scripts if there are no CONFIG_FILES.
 # This happens for instance when ./config.status config.h
-if test -n "\$CONFIG_FILES"; then
-  # Protect against being on the right side of a sed subst in config.status.
-  sed 's/,@/@@/; s/@,/@@/; s/,;t t\$/@;t t/; /@;t t\$/s/[\\\\&,]/\\\\&/g;
-   s/@@/,@/; s/@@/@,/; s/@;t t\$/,;t t/' >\$tmp/subs.sed <<\\CEOF
-s,@SHELL@,$SHELL,;t t
-s,@PATH_SEPARATOR@,$PATH_SEPARATOR,;t t
-s,@PACKAGE_NAME@,$PACKAGE_NAME,;t t
-s,@PACKAGE_TARNAME@,$PACKAGE_TARNAME,;t t
-s,@PACKAGE_VERSION@,$PACKAGE_VERSION,;t t
-s,@PACKAGE_STRING@,$PACKAGE_STRING,;t t
-s,@PACKAGE_BUGREPORT@,$PACKAGE_BUGREPORT,;t t
-s,@exec_prefix@,$exec_prefix,;t t
-s,@prefix@,$prefix,;t t
-s,@program_transform_name@,$program_transform_name,;t t
-s,@bindir@,$bindir,;t t
-s,@sbindir@,$sbindir,;t t
-s,@libexecdir@,$libexecdir,;t t
-s,@datadir@,$datadir,;t t
-s,@sysconfdir@,$sysconfdir,;t t
-s,@sharedstatedir@,$sharedstatedir,;t t
-s,@localstatedir@,$localstatedir,;t t
-s,@libdir@,$libdir,;t t
-s,@includedir@,$includedir,;t t
-s,@oldincludedir@,$oldincludedir,;t t
-s,@infodir@,$infodir,;t t
-s,@mandir@,$mandir,;t t
-s,@build_alias@,$build_alias,;t t
-s,@host_alias@,$host_alias,;t t
-s,@target_alias@,$target_alias,;t t
-s,@DEFS@,$DEFS,;t t
-s,@ECHO_C@,$ECHO_C,;t t
-s,@ECHO_N@,$ECHO_N,;t t
-s,@ECHO_T@,$ECHO_T,;t t
-s,@LIBS@,$LIBS,;t t
-s,@INSTALL_PROGRAM@,$INSTALL_PROGRAM,;t t
-s,@INSTALL_SCRIPT@,$INSTALL_SCRIPT,;t t
-s,@INSTALL_DATA@,$INSTALL_DATA,;t t
-s,@CYGPATH_W@,$CYGPATH_W,;t t
-s,@PACKAGE@,$PACKAGE,;t t
-s,@VERSION@,$VERSION,;t t
-s,@ACLOCAL@,$ACLOCAL,;t t
-s,@AUTOCONF@,$AUTOCONF,;t t
-s,@AUTOMAKE@,$AUTOMAKE,;t t
-s,@AUTOHEADER@,$AUTOHEADER,;t t
-s,@MAKEINFO@,$MAKEINFO,;t t
-s,@AMTAR@,$AMTAR,;t t
-s,@install_sh@,$install_sh,;t t
-s,@STRIP@,$STRIP,;t t
-s,@ac_ct_STRIP@,$ac_ct_STRIP,;t t
-s,@INSTALL_STRIP_PROGRAM@,$INSTALL_STRIP_PROGRAM,;t t
-s,@mkdir_p@,$mkdir_p,;t t
-s,@AWK@,$AWK,;t t
-s,@SET_MAKE@,$SET_MAKE,;t t
-s,@am__leading_dot@,$am__leading_dot,;t t
-s,@CC@,$CC,;t t
-s,@CFLAGS@,$CFLAGS,;t t
-s,@LDFLAGS@,$LDFLAGS,;t t
-s,@CPPFLAGS@,$CPPFLAGS,;t t
-s,@ac_ct_CC@,$ac_ct_CC,;t t
-s,@EXEEXT@,$EXEEXT,;t t
-s,@OBJEXT@,$OBJEXT,;t t
-s,@DEPDIR@,$DEPDIR,;t t
-s,@am__include@,$am__include,;t t
-s,@am__quote@,$am__quote,;t t
-s,@AMDEP_TRUE@,$AMDEP_TRUE,;t t
-s,@AMDEP_FALSE@,$AMDEP_FALSE,;t t
-s,@AMDEPBACKSLASH@,$AMDEPBACKSLASH,;t t
-s,@CCDEPMODE@,$CCDEPMODE,;t t
-s,@am__fastdepCC_TRUE@,$am__fastdepCC_TRUE,;t t
-s,@am__fastdepCC_FALSE@,$am__fastdepCC_FALSE,;t t
-s,@CPP@,$CPP,;t t
-s,@CXX@,$CXX,;t t
-s,@CXXFLAGS@,$CXXFLAGS,;t t
-s,@ac_ct_CXX@,$ac_ct_CXX,;t t
-s,@CXXDEPMODE@,$CXXDEPMODE,;t t
-s,@am__fastdepCXX_TRUE@,$am__fastdepCXX_TRUE,;t t
-s,@am__fastdepCXX_FALSE@,$am__fastdepCXX_FALSE,;t t
-s,@EGREP@,$EGREP,;t t
-s,@LIBOBJS@,$LIBOBJS,;t t
-s,@LTLIBOBJS@,$LTLIBOBJS,;t t
-CEOF
+if test -n "$CONFIG_FILES"; then
 
 _ACEOF
 
-  cat >>$CONFIG_STATUS <<\_ACEOF
-  # Split the substitutions into bite-sized pieces for seds with
-  # small command number limits, like on Digital OSF/1 and HP-UX.
-  ac_max_sed_lines=48
-  ac_sed_frag=1 # Number of current file.
-  ac_beg=1 # First line for current file.
-  ac_end=$ac_max_sed_lines # Line after last line for current file.
-  ac_more_lines=:
-  ac_sed_cmds=
-  while $ac_more_lines; do
-    if test $ac_beg -gt 1; then
-      sed "1,${ac_beg}d; ${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
-    else
-      sed "${ac_end}q" $tmp/subs.sed >$tmp/subs.frag
-    fi
-    if test ! -s $tmp/subs.frag; then
-      ac_more_lines=false
-    else
-      # The purpose of the label and of the branching condition is to
-      # speed up the sed processing (if there are no `@' at all, there
-      # is no need to browse any of the substitutions).
-      # These are the two extra sed commands mentioned above.
-      (echo ':t
-  /@[a-zA-Z_][a-zA-Z_0-9]*@/!b' && cat $tmp/subs.frag) >$tmp/subs-$ac_sed_frag.sed
-      if test -z "$ac_sed_cmds"; then
-       ac_sed_cmds="sed -f $tmp/subs-$ac_sed_frag.sed"
-      else
-       ac_sed_cmds="$ac_sed_cmds | sed -f $tmp/subs-$ac_sed_frag.sed"
-      fi
-      ac_sed_frag=`expr $ac_sed_frag + 1`
-      ac_beg=$ac_end
-      ac_end=`expr $ac_end + $ac_max_sed_lines`
-    fi
-  done
-  if test -z "$ac_sed_cmds"; then
-    ac_sed_cmds=cat
+
+
+ac_delim='%!_!# '
+for ac_last_try in false false false false false :; do
+  cat >conf$$subs.sed <<_ACEOF
+SHELL!$SHELL$ac_delim
+PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim
+PACKAGE_NAME!$PACKAGE_NAME$ac_delim
+PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim
+PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim
+PACKAGE_STRING!$PACKAGE_STRING$ac_delim
+PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim
+exec_prefix!$exec_prefix$ac_delim
+prefix!$prefix$ac_delim
+program_transform_name!$program_transform_name$ac_delim
+bindir!$bindir$ac_delim
+sbindir!$sbindir$ac_delim
+libexecdir!$libexecdir$ac_delim
+datarootdir!$datarootdir$ac_delim
+datadir!$datadir$ac_delim
+sysconfdir!$sysconfdir$ac_delim
+sharedstatedir!$sharedstatedir$ac_delim
+localstatedir!$localstatedir$ac_delim
+includedir!$includedir$ac_delim
+oldincludedir!$oldincludedir$ac_delim
+docdir!$docdir$ac_delim
+infodir!$infodir$ac_delim
+htmldir!$htmldir$ac_delim
+dvidir!$dvidir$ac_delim
+pdfdir!$pdfdir$ac_delim
+psdir!$psdir$ac_delim
+libdir!$libdir$ac_delim
+localedir!$localedir$ac_delim
+mandir!$mandir$ac_delim
+DEFS!$DEFS$ac_delim
+ECHO_C!$ECHO_C$ac_delim
+ECHO_N!$ECHO_N$ac_delim
+ECHO_T!$ECHO_T$ac_delim
+LIBS!$LIBS$ac_delim
+build_alias!$build_alias$ac_delim
+host_alias!$host_alias$ac_delim
+target_alias!$target_alias$ac_delim
+INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim
+INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim
+INSTALL_DATA!$INSTALL_DATA$ac_delim
+am__isrc!$am__isrc$ac_delim
+CYGPATH_W!$CYGPATH_W$ac_delim
+PACKAGE!$PACKAGE$ac_delim
+VERSION!$VERSION$ac_delim
+ACLOCAL!$ACLOCAL$ac_delim
+AUTOCONF!$AUTOCONF$ac_delim
+AUTOMAKE!$AUTOMAKE$ac_delim
+AUTOHEADER!$AUTOHEADER$ac_delim
+MAKEINFO!$MAKEINFO$ac_delim
+install_sh!$install_sh$ac_delim
+STRIP!$STRIP$ac_delim
+INSTALL_STRIP_PROGRAM!$INSTALL_STRIP_PROGRAM$ac_delim
+mkdir_p!$mkdir_p$ac_delim
+AWK!$AWK$ac_delim
+SET_MAKE!$SET_MAKE$ac_delim
+am__leading_dot!$am__leading_dot$ac_delim
+AMTAR!$AMTAR$ac_delim
+am__tar!$am__tar$ac_delim
+am__untar!$am__untar$ac_delim
+CC!$CC$ac_delim
+CFLAGS!$CFLAGS$ac_delim
+LDFLAGS!$LDFLAGS$ac_delim
+CPPFLAGS!$CPPFLAGS$ac_delim
+ac_ct_CC!$ac_ct_CC$ac_delim
+EXEEXT!$EXEEXT$ac_delim
+OBJEXT!$OBJEXT$ac_delim
+DEPDIR!$DEPDIR$ac_delim
+am__include!$am__include$ac_delim
+am__quote!$am__quote$ac_delim
+AMDEP_TRUE!$AMDEP_TRUE$ac_delim
+AMDEP_FALSE!$AMDEP_FALSE$ac_delim
+AMDEPBACKSLASH!$AMDEPBACKSLASH$ac_delim
+CCDEPMODE!$CCDEPMODE$ac_delim
+am__fastdepCC_TRUE!$am__fastdepCC_TRUE$ac_delim
+am__fastdepCC_FALSE!$am__fastdepCC_FALSE$ac_delim
+CPP!$CPP$ac_delim
+CXX!$CXX$ac_delim
+CXXFLAGS!$CXXFLAGS$ac_delim
+ac_ct_CXX!$ac_ct_CXX$ac_delim
+CXXDEPMODE!$CXXDEPMODE$ac_delim
+am__fastdepCXX_TRUE!$am__fastdepCXX_TRUE$ac_delim
+am__fastdepCXX_FALSE!$am__fastdepCXX_FALSE$ac_delim
+GREP!$GREP$ac_delim
+EGREP!$EGREP$ac_delim
+LIBOBJS!$LIBOBJS$ac_delim
+LTLIBOBJS!$LTLIBOBJS$ac_delim
+_ACEOF
+
+  if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 86; then
+    break
+  elif $ac_last_try; then
+    { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5
+echo "$as_me: error: could not make $CONFIG_STATUS" >&2;}
+   { (exit 1); exit 1; }; }
+  else
+    ac_delim="$ac_delim!$ac_delim _$ac_delim!! "
   fi
-fi # test -n "$CONFIG_FILES"
+done
+
+ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed`
+if test -n "$ac_eof"; then
+  ac_eof=`echo "$ac_eof" | sort -nru | sed 1q`
+  ac_eof=`expr $ac_eof + 1`
+fi
 
+cat >>$CONFIG_STATUS <<_ACEOF
+cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof
+/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end
+_ACEOF
+sed '
+s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g
+s/^/s,@/; s/!/@,|#_!!_#|/
+:n
+t n
+s/'"$ac_delim"'$/,g/; t
+s/$/\\/; p
+N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n
+' >>$CONFIG_STATUS <conf$$subs.sed
+rm -f conf$$subs.sed
+cat >>$CONFIG_STATUS <<_ACEOF
+:end
+s/|#_!!_#|//g
+CEOF$ac_eof
 _ACEOF
+
+
+# VPATH may cause trouble with some makes, so we remove $(srcdir),
+# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and
+# trailing colons and then remove the whole line if VPATH becomes empty
+# (actually we leave an empty line to preserve line numbers).
+if test "x$srcdir" = x.; then
+  ac_vpsub='/^[         ]*VPATH[        ]*=/{
+s/:*\$(srcdir):*/:/
+s/:*\${srcdir}:*/:/
+s/:*@srcdir@:*/:/
+s/^\([^=]*=[    ]*\):*/\1/
+s/:*$//
+s/^[^=]*=[      ]*$//
+}'
+fi
+
 cat >>$CONFIG_STATUS <<\_ACEOF
-for ac_file in : $CONFIG_FILES; do test "x$ac_file" = x: && continue
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
-  case $ac_file in
-  - | *:- | *:-:* ) # input from stdin
-       cat >$tmp/stdin
-       ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-       ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-       ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  * )   ac_file_in=$ac_file.in ;;
+fi # test -n "$CONFIG_FILES"
+
+
+for ac_tag in  :F $CONFIG_FILES  :H $CONFIG_HEADERS    :C $CONFIG_COMMANDS
+do
+  case $ac_tag in
+  :[FHLC]) ac_mode=$ac_tag; continue;;
+  esac
+  case $ac_mode$ac_tag in
+  :[FHL]*:*);;
+  :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5
+echo "$as_me: error: Invalid tag $ac_tag." >&2;}
+   { (exit 1); exit 1; }; };;
+  :[FH]-) ac_tag=-:-;;
+  :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
+  esac
+  ac_save_IFS=$IFS
+  IFS=:
+  set x $ac_tag
+  IFS=$ac_save_IFS
+  shift
+  ac_file=$1
+  shift
+
+  case $ac_mode in
+  :L) ac_source=$1;;
+  :[FH])
+    ac_file_inputs=
+    for ac_f
+    do
+      case $ac_f in
+      -) ac_f="$tmp/stdin";;
+      *) # Look for the file first in the build tree, then in the source tree
+        # (if the path is not absolute).  The absolute path cannot be DOS-style,
+        # because $ac_f cannot contain `:'.
+        test -f "$ac_f" ||
+          case $ac_f in
+          [\\/$]*) false;;
+          *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
+          esac ||
+          { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5
+echo "$as_me: error: cannot find input file: $ac_f" >&2;}
+   { (exit 1); exit 1; }; };;
+      esac
+      ac_file_inputs="$ac_file_inputs $ac_f"
+    done
+
+    # Let's still pretend it is `configure' which instantiates (i.e., don't
+    # use $as_me), people would be surprised to read:
+    #    /* config.h.  Generated by config.status.  */
+    configure_input="Generated from "`IFS=:
+         echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure."
+    if test x"$ac_file" != x-; then
+      configure_input="$ac_file.  $configure_input"
+      { echo "$as_me:$LINENO: creating $ac_file" >&5
+echo "$as_me: creating $ac_file" >&6;}
+    fi
+
+    case $ac_tag in
+    *:-:* | *:-) cat >"$tmp/stdin";;
+    esac
+    ;;
   esac
 
-  # Compute @srcdir@, @top_srcdir@, and @INSTALL@ for subdirectories.
-  ac_dir=`(dirname "$ac_file") 2>/dev/null ||
+  ac_dir=`$as_dirname -- "$ac_file" ||
 $as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$ac_file" : 'X\(//\)[^/]' \| \
         X"$ac_file" : 'X\(//\)$' \| \
-        X"$ac_file" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
+        X"$ac_file" : 'X\(/\)' \| . 2>/dev/null ||
 echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
-  { if $as_mkdir_p; then
-    mkdir -p "$ac_dir"
-  else
-    as_dir="$ac_dir"
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)[^/].*/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\).*/{
+           s//\1/
+           q
+         }
+         s/.*/./; q'`
+  { as_dir="$ac_dir"
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
     as_dirs=
-    while test ! -d "$as_dir"; do
-      as_dirs="$as_dir $as_dirs"
-      as_dir=`(dirname "$as_dir") 2>/dev/null ||
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
 $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$as_dir" : 'X\(//\)[^/]' \| \
         X"$as_dir" : 'X\(//\)$' \| \
-        X"$as_dir" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
+        X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
 echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)[^/].*/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\).*/{
+           s//\1/
+           q
+         }
+         s/.*/./; q'`
+      test -d "$as_dir" && break
     done
-    test ! -n "$as_dirs" || mkdir $as_dirs
-  fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
-echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
    { (exit 1); exit 1; }; }; }
-
   ac_builddir=.
 
-if test "$ac_dir" != .; then
+case "$ac_dir" in
+.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;;
+*)
   ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A "../" for each directory in $ac_dir_suffix.
-  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
-else
-  ac_dir_suffix= ac_top_builddir=
-fi
+  # A ".." for each directory in $ac_dir_suffix.
+  ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'`
+  case $ac_top_builddir_sub in
+  "") ac_top_builddir_sub=. ac_top_build_prefix= ;;
+  *)  ac_top_build_prefix=$ac_top_builddir_sub/ ;;
+  esac ;;
+esac
+ac_abs_top_builddir=$ac_pwd
+ac_abs_builddir=$ac_pwd$ac_dir_suffix
+# for backward compatibility:
+ac_top_builddir=$ac_top_build_prefix
 
 case $srcdir in
-  .)  # No --srcdir option.  We are building in place.
+  .)  # We are building in place.
     ac_srcdir=.
-    if test -z "$ac_top_builddir"; then
-       ac_top_srcdir=.
-    else
-       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
-    fi ;;
-  [\\/]* | ?:[\\/]* )  # Absolute path.
+    ac_top_srcdir=$ac_top_builddir_sub
+    ac_abs_top_srcdir=$ac_pwd ;;
+  [\\/]* | ?:[\\/]* )  # Absolute name.
     ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir ;;
-  *) # Relative path.
-    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_builddir$srcdir ;;
+    ac_top_srcdir=$srcdir
+    ac_abs_top_srcdir=$srcdir ;;
+  *) # Relative name.
+    ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix
+    ac_top_srcdir=$ac_top_build_prefix$srcdir
+    ac_abs_top_srcdir=$ac_pwd/$srcdir ;;
 esac
+ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix
 
-# Do not use `cd foo && pwd` to compute absolute paths, because
-# the directories may not exist.
-case `pwd` in
-.) ac_abs_builddir="$ac_dir";;
-*)
-  case "$ac_dir" in
-  .) ac_abs_builddir=`pwd`;;
-  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
-  *) ac_abs_builddir=`pwd`/"$ac_dir";;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_builddir=${ac_top_builddir}.;;
-*)
-  case ${ac_top_builddir}. in
-  .) ac_abs_top_builddir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
-  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_srcdir=$ac_srcdir;;
-*)
-  case $ac_srcdir in
-  .) ac_abs_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
-  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_srcdir=$ac_top_srcdir;;
-*)
-  case $ac_top_srcdir in
-  .) ac_abs_top_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
-  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
-  esac;;
-esac
 
+  case $ac_mode in
+  :F)
+  #
+  # CONFIG_FILE
+  #
 
   case $INSTALL in
   [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;;
-  *) ac_INSTALL=$ac_top_builddir$INSTALL ;;
+  *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;;
   esac
+  ac_MKDIR_P=$MKDIR_P
+  case $MKDIR_P in
+  [\\/$]* | ?:[\\/]* ) ;;
+  */*) ac_MKDIR_P=$ac_top_build_prefix$MKDIR_P ;;
+  esac
+_ACEOF
 
-  if test x"$ac_file" != x-; then
-    { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
-    rm -f "$ac_file"
-  fi
-  # Let's still pretend it is `configure' which instantiates (i.e., don't
-  # use $as_me), people would be surprised to read:
-  #    /* config.h.  Generated by config.status.  */
-  if test x"$ac_file" = x-; then
-    configure_input=
-  else
-    configure_input="$ac_file.  "
-  fi
-  configure_input=$configure_input"Generated from `echo $ac_file_in |
-                                    sed 's,.*/,,'` by configure."
-
-  # First look for the input files in the build tree, otherwise in the
-  # src tree.
-  ac_file_inputs=`IFS=:
-    for f in $ac_file_in; do
-      case $f in
-      -) echo $tmp/stdin ;;
-      [\\/$]*)
-        # Absolute (can't be DOS-style, as IFS=:)
-        test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-        echo "$f";;
-      *) # Relative
-        if test -f "$f"; then
-          # Build tree
-          echo "$f"
-        elif test -f "$srcdir/$f"; then
-          # Source tree
-          echo "$srcdir/$f"
-        else
-          # /dev/null tree
-          { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-        fi;;
-      esac
-    done` || { (exit 1); exit 1; }
+cat >>$CONFIG_STATUS <<\_ACEOF
+# If the template does not know about datarootdir, expand it.
+# FIXME: This hack should be removed a few years after 2.60.
+ac_datarootdir_hack=; ac_datarootdir_seen=
+
+case `sed -n '/datarootdir/ {
+  p
+  q
+}
+/@datadir@/p
+/@docdir@/p
+/@infodir@/p
+/@localedir@/p
+/@mandir@/p
+' $ac_file_inputs` in
+*datarootdir*) ac_datarootdir_seen=yes;;
+*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*)
+  { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5
+echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;}
+_ACEOF
+cat >>$CONFIG_STATUS <<_ACEOF
+  ac_datarootdir_hack='
+  s&@datadir@&$datadir&g
+  s&@docdir@&$docdir&g
+  s&@infodir@&$infodir&g
+  s&@localedir@&$localedir&g
+  s&@mandir@&$mandir&g
+    s&\\\${datarootdir}&$datarootdir&g' ;;
+esac
 _ACEOF
+
+# Neutralize VPATH when `$srcdir' = `.'.
+# Shell code in configure.ac might set extrasub.
+# FIXME: do we really want to maintain this feature?
 cat >>$CONFIG_STATUS <<_ACEOF
   sed "$ac_vpsub
 $extrasub
@@ -5326,387 +6734,175 @@ _ACEOF
 cat >>$CONFIG_STATUS <<\_ACEOF
 :t
 /@[a-zA-Z_][a-zA-Z_0-9]*@/!b
-s,@configure_input@,$configure_input,;t t
-s,@srcdir@,$ac_srcdir,;t t
-s,@abs_srcdir@,$ac_abs_srcdir,;t t
-s,@top_srcdir@,$ac_top_srcdir,;t t
-s,@abs_top_srcdir@,$ac_abs_top_srcdir,;t t
-s,@builddir@,$ac_builddir,;t t
-s,@abs_builddir@,$ac_abs_builddir,;t t
-s,@top_builddir@,$ac_top_builddir,;t t
-s,@abs_top_builddir@,$ac_abs_top_builddir,;t t
-s,@INSTALL@,$ac_INSTALL,;t t
-" $ac_file_inputs | (eval "$ac_sed_cmds") >$tmp/out
-  rm -f $tmp/stdin
-  if test x"$ac_file" != x-; then
-    mv $tmp/out $ac_file
-  else
-    cat $tmp/out
-    rm -f $tmp/out
-  fi
-
-done
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-
-#
-# CONFIG_HEADER section.
-#
-
-# These sed commands are passed to sed as "A NAME B NAME C VALUE D", where
-# NAME is the cpp macro being defined and VALUE is the value it is being given.
-#
-# ac_d sets the value in "#define NAME VALUE" lines.
-ac_dA='s,^\([   ]*\)#\([        ]*define[       ][      ]*\)'
-ac_dB='[        ].*$,\1#\2'
-ac_dC=' '
-ac_dD=',;t'
-# ac_u turns "#undef NAME" without trailing blanks into "#define NAME VALUE".
-ac_uA='s,^\([   ]*\)#\([        ]*\)undef\([    ][      ]*\)'
-ac_uB='$,\1#\2define\3'
-ac_uC=' '
-ac_uD=',;t'
-
-for ac_file in : $CONFIG_HEADERS; do test "x$ac_file" = x: && continue
-  # Support "outfile[:infile[:infile...]]", defaulting infile="outfile.in".
+s&@configure_input@&$configure_input&;t t
+s&@top_builddir@&$ac_top_builddir_sub&;t t
+s&@srcdir@&$ac_srcdir&;t t
+s&@abs_srcdir@&$ac_abs_srcdir&;t t
+s&@top_srcdir@&$ac_top_srcdir&;t t
+s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t
+s&@builddir@&$ac_builddir&;t t
+s&@abs_builddir@&$ac_abs_builddir&;t t
+s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
+s&@INSTALL@&$ac_INSTALL&;t t
+s&@MKDIR_P@&$ac_MKDIR_P&;t t
+$ac_datarootdir_hack
+" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out
+
+test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[         ]*datarootdir[  ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+  { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&5
+echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
+which seems to be undefined.  Please make sure it is defined." >&2;}
+
+  rm -f "$tmp/stdin"
   case $ac_file in
-  - | *:- | *:-:* ) # input from stdin
-       cat >$tmp/stdin
-       ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-       ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  *:* ) ac_file_in=`echo "$ac_file" | sed 's,[^:]*:,,'`
-       ac_file=`echo "$ac_file" | sed 's,:.*,,'` ;;
-  * )   ac_file_in=$ac_file.in ;;
+  -) cat "$tmp/out"; rm -f "$tmp/out";;
+  *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;;
   esac
-
-  test x"$ac_file" != x- && { echo "$as_me:$LINENO: creating $ac_file" >&5
-echo "$as_me: creating $ac_file" >&6;}
-
-  # First look for the input files in the build tree, otherwise in the
-  # src tree.
-  ac_file_inputs=`IFS=:
-    for f in $ac_file_in; do
-      case $f in
-      -) echo $tmp/stdin ;;
-      [\\/$]*)
-        # Absolute (can't be DOS-style, as IFS=:)
-        test -f "$f" || { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-        # Do quote $f, to prevent DOS paths from being IFS'd.
-        echo "$f";;
-      *) # Relative
-        if test -f "$f"; then
-          # Build tree
-          echo "$f"
-        elif test -f "$srcdir/$f"; then
-          # Source tree
-          echo "$srcdir/$f"
-        else
-          # /dev/null tree
-          { { echo "$as_me:$LINENO: error: cannot find input file: $f" >&5
-echo "$as_me: error: cannot find input file: $f" >&2;}
-   { (exit 1); exit 1; }; }
-        fi;;
-      esac
-    done` || { (exit 1); exit 1; }
-  # Remove the trailing spaces.
-  sed 's/[      ]*$//' $ac_file_inputs >$tmp/in
-
+ ;;
+  :H)
+  #
+  # CONFIG_HEADER
+  #
 _ACEOF
 
-# Transform confdefs.h into two sed scripts, `conftest.defines' and
-# `conftest.undefs', that substitutes the proper values into
-# config.h.in to produce config.h.  The first handles `#define'
-# templates, and the second `#undef' templates.
-# And first: Protect against being on the right side of a sed subst in
-# config.status.  Protect against being in an unquoted here document
-# in config.status.
-rm -f conftest.defines conftest.undefs
-# Using a here document instead of a string reduces the quoting nightmare.
-# Putting comments in sed scripts is not portable.
-#
-# `end' is used to avoid that the second main sed command (meant for
-# 0-ary CPP macros) applies to n-ary macro definitions.
-# See the Autoconf documentation for `clear'.
-cat >confdef2sed.sed <<\_ACEOF
-s/[\\&,]/\\&/g
-s,[\\$`],\\&,g
-t clear
-: clear
-s,^[    ]*#[    ]*define[       ][      ]*\([^  (][^    (]*\)\(([^)]*)\)[       ]*\(.*\)$,${ac_dA}\1${ac_dB}\1\2${ac_dC}\3${ac_dD},gp
-t end
-s,^[    ]*#[    ]*define[       ][      ]*\([^  ][^     ]*\)[   ]*\(.*\)$,${ac_dA}\1${ac_dB}\1${ac_dC}\2${ac_dD},gp
-: end
-_ACEOF
-# If some macros were called several times there might be several times
-# the same #defines, which is useless.  Nevertheless, we may not want to
-# sort them, since we want the *last* AC-DEFINE to be honored.
-uniq confdefs.h | sed -n -f confdef2sed.sed >conftest.defines
-sed 's/ac_d/ac_u/g' conftest.defines >conftest.undefs
-rm -f confdef2sed.sed
-
-# This sed command replaces #undef with comments.  This is necessary, for
+# Transform confdefs.h into a sed script `conftest.defines', that
+# substitutes the proper values into config.h.in to produce config.h.
+rm -f conftest.defines conftest.tail
+# First, append a space to every undef/define line, to ease matching.
+echo 's/$/ /' >conftest.defines
+# Then, protect against being on the right side of a sed subst, or in
+# an unquoted here document, in config.status.  If some macros were
+# called several times there might be several #defines for the same
+# symbol, which is useless.  But do not sort them, since the last
+# AC_DEFINE must be honored.
+ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]*
+# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where
+# NAME is the cpp macro being defined, VALUE is the value it is being given.
+# PARAMS is the parameter list in the macro definition--in most cases, it's
+# just an empty string.
+ac_dA='s,^\\([  #]*\\)[^        ]*\\([  ]*'
+ac_dB='\\)[     (].*,\\1define\\2'
+ac_dC=' '
+ac_dD=' ,'
+
+uniq confdefs.h |
+  sed -n '
+       t rset
+       :rset
+       s/^[     ]*#[    ]*define[       ][      ]*//
+       t ok
+       d
+       :ok
+       s/[\\&,]/\\&/g
+       s/^\('"$ac_word_re"'\)\(([^()]*)\)[      ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p
+       s/^\('"$ac_word_re"'\)[  ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p
+  ' >>conftest.defines
+
+# Remove the space that was appended to ease matching.
+# Then replace #undef with comments.  This is necessary, for
 # example, in the case of _POSIX_SOURCE, which is predefined and required
 # on some systems where configure will not decide to define it.
-cat >>conftest.undefs <<\_ACEOF
-s,^[    ]*#[    ]*undef[        ][      ]*[a-zA-Z_][a-zA-Z_0-9]*,/* & */,
-_ACEOF
-
-# Break up conftest.defines because some shells have a limit on the size
-# of here documents, and old seds have small limits too (100 cmds).
-echo '  # Handle all the #define templates only if necessary.' >>$CONFIG_STATUS
-echo '  if grep "^[     ]*#[    ]*define" $tmp/in >/dev/null; then' >>$CONFIG_STATUS
-echo '  # If there are no defines, we may have an empty if/fi' >>$CONFIG_STATUS
-echo '  :' >>$CONFIG_STATUS
-rm -f conftest.tail
-while grep . conftest.defines >/dev/null
+# (The regexp can be short, since the line contains either #define or #undef.)
+echo 's/ $//
+s,^[    #]*u.*,/* & */,' >>conftest.defines
+
+# Break up conftest.defines:
+ac_max_sed_lines=50
+
+# First sed command is:         sed -f defines.sed $ac_file_inputs >"$tmp/out1"
+# Second one is:        sed -f defines.sed "$tmp/out1" >"$tmp/out2"
+# Third one will be:    sed -f defines.sed "$tmp/out2" >"$tmp/out1"
+# et cetera.
+ac_in='$ac_file_inputs'
+ac_out='"$tmp/out1"'
+ac_nxt='"$tmp/out2"'
+
+while :
 do
-  # Write a limited-size here document to $tmp/defines.sed.
-  echo '  cat >$tmp/defines.sed <<CEOF' >>$CONFIG_STATUS
-  # Speed up: don't consider the non `#define' lines.
-  echo '/^[     ]*#[    ]*define/!b' >>$CONFIG_STATUS
-  # Work around the forget-to-reset-the-flag bug.
-  echo 't clr' >>$CONFIG_STATUS
-  echo ': clr' >>$CONFIG_STATUS
-  sed ${ac_max_here_lines}q conftest.defines >>$CONFIG_STATUS
+  # Write a here document:
+    cat >>$CONFIG_STATUS <<_ACEOF
+    # First, check the format of the line:
+    cat >"\$tmp/defines.sed" <<\\CEOF
+/^[     ]*#[    ]*undef[        ][      ]*$ac_word_re[  ]*\$/b def
+/^[     ]*#[    ]*define[       ][      ]*$ac_word_re[(         ]/b def
+b
+:def
+_ACEOF
+  sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS
   echo 'CEOF
-  sed -f $tmp/defines.sed $tmp/in >$tmp/out
-  rm -f $tmp/in
-  mv $tmp/out $tmp/in
-' >>$CONFIG_STATUS
-  sed 1,${ac_max_here_lines}d conftest.defines >conftest.tail
+    sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS
+  ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in
+  sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail
+  grep . conftest.tail >/dev/null || break
   rm -f conftest.defines
   mv conftest.tail conftest.defines
 done
-rm -f conftest.defines
-echo '  fi # grep' >>$CONFIG_STATUS
-echo >>$CONFIG_STATUS
-
-# Break up conftest.undefs because some shells have a limit on the size
-# of here documents, and old seds have small limits too (100 cmds).
-echo '  # Handle all the #undef templates' >>$CONFIG_STATUS
-rm -f conftest.tail
-while grep . conftest.undefs >/dev/null
-do
-  # Write a limited-size here document to $tmp/undefs.sed.
-  echo '  cat >$tmp/undefs.sed <<CEOF' >>$CONFIG_STATUS
-  # Speed up: don't consider the non `#undef'
-  echo '/^[     ]*#[    ]*undef/!b' >>$CONFIG_STATUS
-  # Work around the forget-to-reset-the-flag bug.
-  echo 't clr' >>$CONFIG_STATUS
-  echo ': clr' >>$CONFIG_STATUS
-  sed ${ac_max_here_lines}q conftest.undefs >>$CONFIG_STATUS
-  echo 'CEOF
-  sed -f $tmp/undefs.sed $tmp/in >$tmp/out
-  rm -f $tmp/in
-  mv $tmp/out $tmp/in
-' >>$CONFIG_STATUS
-  sed 1,${ac_max_here_lines}d conftest.undefs >conftest.tail
-  rm -f conftest.undefs
-  mv conftest.tail conftest.undefs
-done
-rm -f conftest.undefs
+rm -f conftest.defines conftest.tail
 
+echo "ac_result=$ac_in" >>$CONFIG_STATUS
 cat >>$CONFIG_STATUS <<\_ACEOF
-  # Let's still pretend it is `configure' which instantiates (i.e., don't
-  # use $as_me), people would be surprised to read:
-  #    /* config.h.  Generated by config.status.  */
-  if test x"$ac_file" = x-; then
-    echo "/* Generated by configure.  */" >$tmp/config.h
-  else
-    echo "/* $ac_file.  Generated by configure.  */" >$tmp/config.h
-  fi
-  cat $tmp/in >>$tmp/config.h
-  rm -f $tmp/in
   if test x"$ac_file" != x-; then
-    if diff $ac_file $tmp/config.h >/dev/null 2>&1; then
+    echo "/* $configure_input  */" >"$tmp/config.h"
+    cat "$ac_result" >>"$tmp/config.h"
+    if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then
       { echo "$as_me:$LINENO: $ac_file is unchanged" >&5
 echo "$as_me: $ac_file is unchanged" >&6;}
     else
-      ac_dir=`(dirname "$ac_file") 2>/dev/null ||
-$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$ac_file" : 'X\(//\)[^/]' \| \
-        X"$ac_file" : 'X\(//\)$' \| \
-        X"$ac_file" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
-echo X"$ac_file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
-      { if $as_mkdir_p; then
-    mkdir -p "$ac_dir"
-  else
-    as_dir="$ac_dir"
-    as_dirs=
-    while test ! -d "$as_dir"; do
-      as_dirs="$as_dir $as_dirs"
-      as_dir=`(dirname "$as_dir") 2>/dev/null ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$as_dir" : 'X\(//\)[^/]' \| \
-        X"$as_dir" : 'X\(//\)$' \| \
-        X"$as_dir" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
-echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
-    done
-    test ! -n "$as_dirs" || mkdir $as_dirs
-  fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
-echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
-   { (exit 1); exit 1; }; }; }
-
       rm -f $ac_file
-      mv $tmp/config.h $ac_file
+      mv "$tmp/config.h" $ac_file
     fi
   else
-    cat $tmp/config.h
-    rm -f $tmp/config.h
+    echo "/* $configure_input  */"
+    cat "$ac_result"
   fi
+  rm -f "$tmp/out12"
 # Compute $ac_file's index in $config_headers.
+_am_arg=$ac_file
 _am_stamp_count=1
 for _am_header in $config_headers :; do
   case $_am_header in
-    $ac_file | $ac_file:* )
+    $_am_arg | $_am_arg:* )
       break ;;
     * )
       _am_stamp_count=`expr $_am_stamp_count + 1` ;;
   esac
 done
-echo "timestamp for $ac_file" >`(dirname $ac_file) 2>/dev/null ||
-$as_expr X$ac_file : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X$ac_file : 'X\(//\)[^/]' \| \
-        X$ac_file : 'X\(//\)$' \| \
-        X$ac_file : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
-echo X$ac_file |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`/stamp-h$_am_stamp_count
-done
-_ACEOF
-cat >>$CONFIG_STATUS <<\_ACEOF
-
-#
-# CONFIG_COMMANDS section.
-#
-for ac_file in : $CONFIG_COMMANDS; do test "x$ac_file" = x: && continue
-  ac_dest=`echo "$ac_file" | sed 's,:.*,,'`
-  ac_source=`echo "$ac_file" | sed 's,[^:]*:,,'`
-  ac_dir=`(dirname "$ac_dest") 2>/dev/null ||
-$as_expr X"$ac_dest" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$ac_dest" : 'X\(//\)[^/]' \| \
-        X"$ac_dest" : 'X\(//\)$' \| \
-        X"$ac_dest" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
-echo X"$ac_dest" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
-  { if $as_mkdir_p; then
-    mkdir -p "$ac_dir"
-  else
-    as_dir="$ac_dir"
-    as_dirs=
-    while test ! -d "$as_dir"; do
-      as_dirs="$as_dir $as_dirs"
-      as_dir=`(dirname "$as_dir") 2>/dev/null ||
-$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
-        X"$as_dir" : 'X\(//\)[^/]' \| \
-        X"$as_dir" : 'X\(//\)$' \| \
-        X"$as_dir" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
-echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
-    done
-    test ! -n "$as_dirs" || mkdir $as_dirs
-  fi || { { echo "$as_me:$LINENO: error: cannot create directory \"$ac_dir\"" >&5
-echo "$as_me: error: cannot create directory \"$ac_dir\"" >&2;}
-   { (exit 1); exit 1; }; }; }
-
-  ac_builddir=.
-
-if test "$ac_dir" != .; then
-  ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'`
-  # A "../" for each directory in $ac_dir_suffix.
-  ac_top_builddir=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,../,g'`
-else
-  ac_dir_suffix= ac_top_builddir=
-fi
-
-case $srcdir in
-  .)  # No --srcdir option.  We are building in place.
-    ac_srcdir=.
-    if test -z "$ac_top_builddir"; then
-       ac_top_srcdir=.
-    else
-       ac_top_srcdir=`echo $ac_top_builddir | sed 's,/$,,'`
-    fi ;;
-  [\\/]* | ?:[\\/]* )  # Absolute path.
-    ac_srcdir=$srcdir$ac_dir_suffix;
-    ac_top_srcdir=$srcdir ;;
-  *) # Relative path.
-    ac_srcdir=$ac_top_builddir$srcdir$ac_dir_suffix
-    ac_top_srcdir=$ac_top_builddir$srcdir ;;
-esac
+echo "timestamp for $_am_arg" >`$as_dirname -- "$_am_arg" ||
+$as_expr X"$_am_arg" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
+        X"$_am_arg" : 'X\(//\)[^/]' \| \
+        X"$_am_arg" : 'X\(//\)$' \| \
+        X"$_am_arg" : 'X\(/\)' \| . 2>/dev/null ||
+echo X"$_am_arg" |
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)[^/].*/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\).*/{
+           s//\1/
+           q
+         }
+         s/.*/./; q'`/stamp-h$_am_stamp_count
+ ;;
 
-# Do not use `cd foo && pwd` to compute absolute paths, because
-# the directories may not exist.
-case `pwd` in
-.) ac_abs_builddir="$ac_dir";;
-*)
-  case "$ac_dir" in
-  .) ac_abs_builddir=`pwd`;;
-  [\\/]* | ?:[\\/]* ) ac_abs_builddir="$ac_dir";;
-  *) ac_abs_builddir=`pwd`/"$ac_dir";;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_builddir=${ac_top_builddir}.;;
-*)
-  case ${ac_top_builddir}. in
-  .) ac_abs_top_builddir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_builddir=${ac_top_builddir}.;;
-  *) ac_abs_top_builddir=$ac_abs_builddir/${ac_top_builddir}.;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_srcdir=$ac_srcdir;;
-*)
-  case $ac_srcdir in
-  .) ac_abs_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_srcdir=$ac_srcdir;;
-  *) ac_abs_srcdir=$ac_abs_builddir/$ac_srcdir;;
-  esac;;
-esac
-case $ac_abs_builddir in
-.) ac_abs_top_srcdir=$ac_top_srcdir;;
-*)
-  case $ac_top_srcdir in
-  .) ac_abs_top_srcdir=$ac_abs_builddir;;
-  [\\/]* | ?:[\\/]* ) ac_abs_top_srcdir=$ac_top_srcdir;;
-  *) ac_abs_top_srcdir=$ac_abs_builddir/$ac_top_srcdir;;
-  esac;;
-esac
+  :C)  { echo "$as_me:$LINENO: executing $ac_file commands" >&5
+echo "$as_me: executing $ac_file commands" >&6;}
+ ;;
+  esac
 
 
-  { echo "$as_me:$LINENO: executing $ac_dest commands" >&5
-echo "$as_me: executing $ac_dest commands" >&6;}
-  case $ac_dest in
-    depfiles ) test x"$AMDEP_TRUE" != x"" || for mf in $CONFIG_FILES; do
+  case $ac_file$ac_mode in
+    "depfiles":C) test x"$AMDEP_TRUE" != x"" || for mf in $CONFIG_FILES; do
   # Strip MF so we end up with the name of the file.
   mf=`echo "$mf" | sed -e 's/:.*$//'`
   # Check whether this is an Automake generated Makefile or not.
@@ -5714,94 +6910,126 @@ echo "$as_me: executing $ac_dest commands" >&6;}
   # some people rename them; so instead we look at the file content.
   # Grep'ing the first line is not enough: some people post-process
   # each Makefile.in and add a new line on top of each file to say so.
-  # So let's grep whole file.
-  if grep '^#.*generated by automake' $mf > /dev/null 2>&1; then
-    dirpart=`(dirname "$mf") 2>/dev/null ||
+  # Grep'ing the whole file is not good either: AIX grep has a line
+  # limit of 2048, but all sed's we know have understand at least 4000.
+  if sed -n 's,^#.*generated by automake.*,X,p' "$mf" | grep X >/dev/null 2>&1; then
+    dirpart=`$as_dirname -- "$mf" ||
 $as_expr X"$mf" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$mf" : 'X\(//\)[^/]' \| \
         X"$mf" : 'X\(//\)$' \| \
-        X"$mf" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
+        X"$mf" : 'X\(/\)' \| . 2>/dev/null ||
 echo X"$mf" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)[^/].*/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\).*/{
+           s//\1/
+           q
+         }
+         s/.*/./; q'`
   else
     continue
   fi
-  grep '^DEP_FILES *= *[^ #]' < "$mf" > /dev/null || continue
-  # Extract the definition of DEP_FILES from the Makefile without
-  # running `make'.
+  # Extract the definition of DEPDIR, am__include, and am__quote
+  # from the Makefile without running `make'.
   DEPDIR=`sed -n 's/^DEPDIR = //p' < "$mf"`
   test -z "$DEPDIR" && continue
+  am__include=`sed -n 's/^am__include = //p' < "$mf"`
+  test -z "am__include" && continue
+  am__quote=`sed -n 's/^am__quote = //p' < "$mf"`
   # When using ansi2knr, U may be empty or an underscore; expand it
   U=`sed -n 's/^U = //p' < "$mf"`
-  test -d "$dirpart/$DEPDIR" || mkdir "$dirpart/$DEPDIR"
-  # We invoke sed twice because it is the simplest approach to
-  # changing $(DEPDIR) to its actual value in the expansion.
-  for file in `sed -n '
-    /^DEP_FILES = .*\\\\$/ {
-      s/^DEP_FILES = //
-      :loop
-       s/\\\\$//
-       p
-       n
-       /\\\\$/ b loop
-      p
-    }
-    /^DEP_FILES = / s/^DEP_FILES = //p' < "$mf" | \
+  # Find all dependency output files, they are included files with
+  # $(DEPDIR) in their names.  We invoke sed twice because it is the
+  # simplest approach to changing $(DEPDIR) to its actual value in the
+  # expansion.
+  for file in `sed -n "
+    s/^$am__include $am__quote\(.*(DEPDIR).*\)$am__quote"'$/\1/p' <"$mf" | \
        sed -e 's/\$(DEPDIR)/'"$DEPDIR"'/g' -e 's/\$U/'"$U"'/g'`; do
     # Make sure the directory exists.
     test -f "$dirpart/$file" && continue
-    fdir=`(dirname "$file") 2>/dev/null ||
+    fdir=`$as_dirname -- "$file" ||
 $as_expr X"$file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$file" : 'X\(//\)[^/]' \| \
         X"$file" : 'X\(//\)$' \| \
-        X"$file" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
+        X"$file" : 'X\(/\)' \| . 2>/dev/null ||
 echo X"$file" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
-    { if $as_mkdir_p; then
-    mkdir -p $dirpart/$fdir
-  else
-    as_dir=$dirpart/$fdir
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)[^/].*/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\).*/{
+           s//\1/
+           q
+         }
+         s/.*/./; q'`
+    { as_dir=$dirpart/$fdir
+  case $as_dir in #(
+  -*) as_dir=./$as_dir;;
+  esac
+  test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || {
     as_dirs=
-    while test ! -d "$as_dir"; do
-      as_dirs="$as_dir $as_dirs"
-      as_dir=`(dirname "$as_dir") 2>/dev/null ||
+    while :; do
+      case $as_dir in #(
+      *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #(
+      *) as_qdir=$as_dir;;
+      esac
+      as_dirs="'$as_qdir' $as_dirs"
+      as_dir=`$as_dirname -- "$as_dir" ||
 $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \
         X"$as_dir" : 'X\(//\)[^/]' \| \
         X"$as_dir" : 'X\(//\)$' \| \
-        X"$as_dir" : 'X\(/\)' \| \
-        .     : '\(.\)' 2>/dev/null ||
+        X"$as_dir" : 'X\(/\)' \| . 2>/dev/null ||
 echo X"$as_dir" |
-    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/; q; }
-         /^X\(\/\/\)[^/].*/{ s//\1/; q; }
-         /^X\(\/\/\)$/{ s//\1/; q; }
-         /^X\(\/\).*/{ s//\1/; q; }
-         s/.*/./; q'`
+    sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)[^/].*/{
+           s//\1/
+           q
+         }
+         /^X\(\/\/\)$/{
+           s//\1/
+           q
+         }
+         /^X\(\/\).*/{
+           s//\1/
+           q
+         }
+         s/.*/./; q'`
+      test -d "$as_dir" && break
     done
-    test ! -n "$as_dirs" || mkdir $as_dirs
-  fi || { { echo "$as_me:$LINENO: error: cannot create directory $dirpart/$fdir" >&5
-echo "$as_me: error: cannot create directory $dirpart/$fdir" >&2;}
+    test -z "$as_dirs" || eval "mkdir $as_dirs"
+  } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5
+echo "$as_me: error: cannot create directory $as_dir" >&2;}
    { (exit 1); exit 1; }; }; }
-
     # echo "creating $dirpart/$file"
     echo '# dummy' > "$dirpart/$file"
   done
 done
  ;;
+
   esac
-done
-_ACEOF
+done # for ac_tag
 
-cat >>$CONFIG_STATUS <<\_ACEOF
 
 { (exit 0); exit 0; }
 _ACEOF
index 293ae8b655c0e9ce8a57899cca064e5510dcdb95..4d0cf83d69ad1735a3775a3fe2b1184d011add78 100644 (file)
@@ -12,20 +12,25 @@ AM_INIT_AUTOMAKE
 AC_PROG_CC
 AC_PROG_CPP
 AC_PROG_CXX
+AC_PROG_GCC_TRADITIONAL
 
 AC_FUNC_ERROR_AT_LINE
 AC_HEADER_STDC
-AC_C_CONST
+AC_HEADER_STDBOOL
+AC_HEADER_TIME
 
 #checks for header files and libraries
-#AC_CHECK_HEADER(readline.h)
-#AC_CHECK_LIB(readline, rl_initialize)
-AC_CHECK_HEADER(popt.h)
+AC_CHECK_HEADERS([linux/version.h popt.h fcntl.h inttypes.h stdlib.h sys/ioctl.h sys/time.h termios.h unistd.h])
 AC_CHECK_LIB(popt, poptGetNextOpt)
-#AC_CHECK_HEADER(pthread.h)
 
 # Checks for typedefs, structures, and compiler characteristics.
-# AC_HEADER_STDBOOL
+AC_C_CONST
+AC_C_INLINE
+AC_TYPE_UINT16_T
+AC_TYPE_UINT8_T
+
+AC_FUNC_SELECT_ARGTYPES
+AC_CHECK_FUNCS([select strerror])
 
 AC_DEFUN([ACX_PTHREAD], [
 AC_REQUIRE([AC_CANONICAL_HOST])
index b00ffa5914fd6b1c5972946cee8c0eb9ec162e44..3946e7a567084762a82fa579bc284c0188832391 100644 (file)
@@ -1,8 +1,8 @@
-# Makefile.in generated by automake 1.8.3 from Makefile.am.
+# Makefile.in generated by automake 1.10.1 from Makefile.am.
 # @configure_input@
 
 # Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002,
-# 2003, 2004  Free Software Foundation, Inc.
+# 2003, 2004, 2005, 2006, 2007, 2008  Free Software Foundation, Inc.
 # This Makefile.in is free software; the Free Software Foundation
 # gives unlimited permission to copy and/or distribute it,
 # with or without modifications, as long as this notice is preserved.
 
 @SET_MAKE@
 
-SOURCES = $(cppbsl_SOURCES)
-
-srcdir = @srcdir@
-top_srcdir = @top_srcdir@
 VPATH = @srcdir@
 pkgdatadir = $(datadir)/@PACKAGE@
 pkglibdir = $(libdir)/@PACKAGE@
 pkgincludedir = $(includedir)/@PACKAGE@
-top_builddir = ..
 am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
-INSTALL = @INSTALL@
 install_sh_DATA = $(install_sh) -c -m 644
 install_sh_PROGRAM = $(install_sh) -c
 install_sh_SCRIPT = $(install_sh) -c
@@ -43,7 +37,7 @@ ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
 am__aclocal_m4_deps = $(top_srcdir)/configure.in
 am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
        $(ACLOCAL_M4)
-mkinstalldirs = $(mkdir_p)
+mkinstalldirs = $(install_sh) -d
 CONFIG_HEADER = $(top_builddir)/config.h
 CONFIG_CLEAN_FILES =
 am__installdirs = "$(DESTDIR)$(bindir)"
@@ -53,11 +47,9 @@ am_cppbsl_OBJECTS = Parameters.$(OBJEXT) Serial.$(OBJEXT) \
        Bsl.$(OBJEXT) cppbsl.$(OBJEXT)
 cppbsl_OBJECTS = $(am_cppbsl_OBJECTS)
 cppbsl_LDADD = $(LDADD)
-DEFAULT_INCLUDES = -I. -I$(srcdir) -I$(top_builddir)
+DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir)
 depcomp = $(SHELL) $(top_srcdir)/config/depcomp
 am__depfiles_maybe = depfiles
-@AMDEP_TRUE@DEP_FILES = ./$(DEPDIR)/Bsl.Po ./$(DEPDIR)/Parameters.Po \
-@AMDEP_TRUE@   ./$(DEPDIR)/Serial.Po ./$(DEPDIR)/cppbsl.Po
 CXXCOMPILE = $(CXX) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \
        $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CXXFLAGS) $(CXXFLAGS)
 CXXLD = $(CXX)
@@ -73,8 +65,6 @@ ETAGS = etags
 CTAGS = ctags
 DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
 ACLOCAL = @ACLOCAL@
-AMDEP_FALSE = @AMDEP_FALSE@
-AMDEP_TRUE = @AMDEP_TRUE@
 AMTAR = @AMTAR@
 AUTOCONF = @AUTOCONF@
 AUTOHEADER = @AUTOHEADER@
@@ -96,6 +86,8 @@ ECHO_N = @ECHO_N@
 ECHO_T = @ECHO_T@
 EGREP = @EGREP@
 EXEEXT = @EXEEXT@
+GREP = @GREP@
+INSTALL = @INSTALL@
 INSTALL_DATA = @INSTALL_DATA@
 INSTALL_PROGRAM = @INSTALL_PROGRAM@
 INSTALL_SCRIPT = @INSTALL_SCRIPT@
@@ -105,6 +97,7 @@ LIBOBJS = @LIBOBJS@
 LIBS = @LIBS@
 LTLIBOBJS = @LTLIBOBJS@
 MAKEINFO = @MAKEINFO@
+MKDIR_P = @MKDIR_P@
 OBJEXT = @OBJEXT@
 PACKAGE = @PACKAGE@
 PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@
@@ -117,36 +110,48 @@ SET_MAKE = @SET_MAKE@
 SHELL = @SHELL@
 STRIP = @STRIP@
 VERSION = @VERSION@
+abs_builddir = @abs_builddir@
+abs_srcdir = @abs_srcdir@
+abs_top_builddir = @abs_top_builddir@
+abs_top_srcdir = @abs_top_srcdir@
 ac_ct_CC = @ac_ct_CC@
 ac_ct_CXX = @ac_ct_CXX@
-ac_ct_STRIP = @ac_ct_STRIP@
-am__fastdepCC_FALSE = @am__fastdepCC_FALSE@
-am__fastdepCC_TRUE = @am__fastdepCC_TRUE@
-am__fastdepCXX_FALSE = @am__fastdepCXX_FALSE@
-am__fastdepCXX_TRUE = @am__fastdepCXX_TRUE@
 am__include = @am__include@
 am__leading_dot = @am__leading_dot@
 am__quote = @am__quote@
+am__tar = @am__tar@
+am__untar = @am__untar@
 bindir = @bindir@
 build_alias = @build_alias@
+builddir = @builddir@
 datadir = @datadir@
+datarootdir = @datarootdir@
+docdir = @docdir@
+dvidir = @dvidir@
 exec_prefix = @exec_prefix@
 host_alias = @host_alias@
+htmldir = @htmldir@
 includedir = @includedir@
 infodir = @infodir@
 install_sh = @install_sh@
 libdir = @libdir@
 libexecdir = @libexecdir@
+localedir = @localedir@
 localstatedir = @localstatedir@
 mandir = @mandir@
 mkdir_p = @mkdir_p@
 oldincludedir = @oldincludedir@
+pdfdir = @pdfdir@
 prefix = @prefix@
 program_transform_name = @program_transform_name@
+psdir = @psdir@
 sbindir = @sbindir@
 sharedstatedir = @sharedstatedir@
+srcdir = @srcdir@
 sysconfdir = @sysconfdir@
 target_alias = @target_alias@
+top_builddir = @top_builddir@
+top_srcdir = @top_srcdir@
 MAINTAINERCLEANFILES = Makefile.in
 cppbsl_SOURCES = \
        Parameters.h \
@@ -192,7 +197,7 @@ $(ACLOCAL_M4):  $(am__aclocal_m4_deps)
        cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
 install-binPROGRAMS: $(bin_PROGRAMS)
        @$(NORMAL_INSTALL)
-       test -z "$(bindir)" || $(mkdir_p) "$(DESTDIR)$(bindir)"
+       test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)"
        @list='$(bin_PROGRAMS)'; for p in $$list; do \
          p1=`echo $$p|sed 's/$(EXEEXT)$$//'`; \
          if test -f $$p \
@@ -215,7 +220,7 @@ clean-binPROGRAMS:
        -test -z "$(bin_PROGRAMS)" || rm -f $(bin_PROGRAMS)
 cppbsl$(EXEEXT): $(cppbsl_OBJECTS) $(cppbsl_DEPENDENCIES) 
        @rm -f cppbsl$(EXEEXT)
-       $(CXXLINK) $(cppbsl_LDFLAGS) $(cppbsl_OBJECTS) $(cppbsl_LDADD) $(LIBS)
+       $(CXXLINK) $(cppbsl_OBJECTS) $(cppbsl_LDADD) $(LIBS)
 
 mostlyclean-compile:
        -rm -f *.$(OBJEXT)
@@ -229,29 +234,26 @@ distclean-compile:
 @AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cppbsl.Po@am__quote@
 
 .cc.o:
-@am__fastdepCXX_TRUE@  if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ $<; \
-@am__fastdepCXX_TRUE@  then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+@am__fastdepCXX_TRUE@  $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $<
+@am__fastdepCXX_TRUE@  mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
 @AMDEP_TRUE@@am__fastdepCXX_FALSE@     source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCXX_FALSE@     depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCXX_FALSE@     $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+@AMDEP_TRUE@@am__fastdepCXX_FALSE@     DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ $<
 
 .cc.obj:
-@am__fastdepCXX_TRUE@  if $(CXXCOMPILE) -MT $@ -MD -MP -MF "$(DEPDIR)/$*.Tpo" -c -o $@ `$(CYGPATH_W) '$<'`; \
-@am__fastdepCXX_TRUE@  then mv -f "$(DEPDIR)/$*.Tpo" "$(DEPDIR)/$*.Po"; else rm -f "$(DEPDIR)/$*.Tpo"; exit 1; fi
+@am__fastdepCXX_TRUE@  $(CXXCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'`
+@am__fastdepCXX_TRUE@  mv -f $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po
 @AMDEP_TRUE@@am__fastdepCXX_FALSE@     source='$<' object='$@' libtool=no @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCXX_FALSE@     depfile='$(DEPDIR)/$*.Po' tmpdepfile='$(DEPDIR)/$*.TPo' @AMDEPBACKSLASH@
-@AMDEP_TRUE@@am__fastdepCXX_FALSE@     $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
+@AMDEP_TRUE@@am__fastdepCXX_FALSE@     DEPDIR=$(DEPDIR) $(CXXDEPMODE) $(depcomp) @AMDEPBACKSLASH@
 @am__fastdepCXX_FALSE@ $(CXXCOMPILE) -c -o $@ `$(CYGPATH_W) '$<'`
-uninstall-info-am:
 
 ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES)
        list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \
        unique=`for i in $$list; do \
            if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
          done | \
-         $(AWK) '    { files[$$0] = 1; } \
-              END { for (i in files) print i; }'`; \
+         $(AWK) '{ files[$$0] = 1; nonemtpy = 1; } \
+             END { if (nonempty) { for (i in files) print i; }; }'`; \
        mkid -fID $$unique
 tags: TAGS
 
@@ -263,22 +265,23 @@ TAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
        unique=`for i in $$list; do \
            if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
          done | \
-         $(AWK) '    { files[$$0] = 1; } \
-              END { for (i in files) print i; }'`; \
-       test -z "$(ETAGS_ARGS)$$tags$$unique" \
-         || $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
-            $$tags $$unique
+         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
+             END { if (nonempty) { for (i in files) print i; }; }'`; \
+       if test -z "$(ETAGS_ARGS)$$tags$$unique"; then :; else \
+         test -n "$$unique" || unique=$$empty_fix; \
+         $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
+           $$tags $$unique; \
+       fi
 ctags: CTAGS
 CTAGS:  $(HEADERS) $(SOURCES)  $(TAGS_DEPENDENCIES) \
                $(TAGS_FILES) $(LISP)
        tags=; \
-       here=`pwd`; \
        list='$(SOURCES) $(HEADERS)  $(LISP) $(TAGS_FILES)'; \
        unique=`for i in $$list; do \
            if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
          done | \
-         $(AWK) '    { files[$$0] = 1; } \
-              END { for (i in files) print i; }'`; \
+         $(AWK) '{ files[$$0] = 1; nonempty = 1; } \
+             END { if (nonempty) { for (i in files) print i; }; }'`; \
        test -z "$(CTAGS_ARGS)$$tags$$unique" \
          || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
             $$tags $$unique
@@ -292,22 +295,21 @@ distclean-tags:
        -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
 
 distdir: $(DISTFILES)
-       @srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
-       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
-       list='$(DISTFILES)'; for file in $$list; do \
-         case $$file in \
-           $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
-           $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
-         esac; \
+       @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
+       topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
+       list='$(DISTFILES)'; \
+         dist_files=`for file in $$list; do echo $$file; done | \
+         sed -e "s|^$$srcdirstrip/||;t" \
+             -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
+       case $$dist_files in \
+         */*) $(MKDIR_P) `echo "$$dist_files" | \
+                          sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
+                          sort -u` ;; \
+       esac; \
+       for file in $$dist_files; do \
          if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
-         dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
-         if test "$$dir" != "$$file" && test "$$dir" != "."; then \
-           dir="/$$dir"; \
-           $(mkdir_p) "$(distdir)$$dir"; \
-         else \
-           dir=''; \
-         fi; \
          if test -d $$d/$$file; then \
+           dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
            if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
              cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
            fi; \
@@ -323,7 +325,7 @@ check: check-am
 all-am: Makefile $(PROGRAMS)
 installdirs:
        for dir in "$(DESTDIR)$(bindir)"; do \
-         test -z "$$dir" || $(mkdir_p) "$$dir"; \
+         test -z "$$dir" || $(MKDIR_P) "$$dir"; \
        done
 install: install-am
 install-exec: install-exec-am
@@ -344,7 +346,7 @@ mostlyclean-generic:
 clean-generic:
 
 distclean-generic:
-       -rm -f $(CONFIG_CLEAN_FILES)
+       -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
 
 maintainer-clean-generic:
        @echo "This command is intended for maintainers to use"
@@ -372,12 +374,20 @@ info-am:
 
 install-data-am:
 
+install-dvi: install-dvi-am
+
 install-exec-am: install-binPROGRAMS
 
+install-html: install-html-am
+
 install-info: install-info-am
 
 install-man:
 
+install-pdf: install-pdf-am
+
+install-ps: install-ps-am
+
 installcheck-am:
 
 maintainer-clean: maintainer-clean-am
@@ -397,18 +407,22 @@ ps: ps-am
 
 ps-am:
 
-uninstall-am: uninstall-binPROGRAMS uninstall-info-am
+uninstall-am: uninstall-binPROGRAMS
+
+.MAKE: install-am install-strip
 
 .PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \
        clean-generic ctags distclean distclean-compile \
        distclean-generic distclean-tags distdir dvi dvi-am html \
        html-am info info-am install install-am install-binPROGRAMS \
-       install-data install-data-am install-exec install-exec-am \
-       install-info install-info-am install-man install-strip \
+       install-data install-data-am install-dvi install-dvi-am \
+       install-exec install-exec-am install-html install-html-am \
+       install-info install-info-am install-man install-pdf \
+       install-pdf-am install-ps install-ps-am install-strip \
        installcheck installcheck-am installdirs maintainer-clean \
        maintainer-clean-generic mostlyclean mostlyclean-compile \
        mostlyclean-generic pdf pdf-am ps ps-am tags uninstall \
-       uninstall-am uninstall-binPROGRAMS uninstall-info-am
+       uninstall-am uninstall-binPROGRAMS
 
 # Tell versions [3.59,3.63) of GNU make to not export all variables.
 # Otherwise a system limit (for SysV at least) may be exceeded.
index 119323033990563b77443abddf2053929966c863..1f06989c01ec30202886e585184e72401ba512eb 100644 (file)
  */
 #include <stdio.h>
 #include <iostream>
+#include "../config.h"
+#ifdef HAVE_LINUX_VERSION_H
+#include <linux/version.h>
+#else
+#define LINUX_VERSION_CODE 1
+#define KERNEL_VERSION 3
+#endif
 
 #include "Serial.h"
 
@@ -83,6 +90,7 @@ int serial_connect(int* err, const char* dev, int* readFD, int* writeFD, termios
         return -1;
     }
     /* prepare attributes */
+#if defined(HAVE_LINUX_VERSION_H) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
     r = tcgetattr(*writeFD, &my_tios);
     if(r == -1) {
         *err = errno;
@@ -127,7 +135,30 @@ int serial_connect(int* err, const char* dev, int* readFD, int* writeFD, termios
         close(*writeFD);
         return -1;        
     }
-
+#else
+    r = tcgetattr(*writeFD, &my_tios);
+    if(r == -1) {
+        *err = errno;
+        close(*readFD);
+        close(*writeFD);
+        return -1;
+    }
+    *pt = my_tios;
+    cfmakeraw(&my_tios);
+    my_tios.c_iflag |= IGNBRK | INPCK;
+    my_tios.c_cflag |= (CS8 | CLOCAL | CREAD | PARENB);
+    cfsetispeed(&my_tios, B9600);
+    cfsetospeed(&my_tios, B9600);
+    r = tcsetattr(*readFD, TCSANOW, &my_tios);
+    if(r == -1) {
+        *err = errno;
+        r = tcsetattr(*writeFD, TCSANOW, pt);
+        close(*readFD);
+        close(*writeFD);
+        return -1;        
+    }
+#endif
+    
     // clear buffers
     r = tcflush(*writeFD, TCIOFLUSH);
     if(r == -1) {
@@ -344,8 +375,10 @@ int BaseSerial::txrx(int *err, frame_t *txframe, frame_t *rxframe) {
 }
 
 int BaseSerial::highSpeed(int *err) {
+    int r;
+#if defined(HAVE_LINUX_VERSION_H) && (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,24))
     struct serial_struct serinfo;
-    int r = ioctl(serialWriteFD, TIOCGSERIAL, &serinfo);
+    r = ioctl(serialWriteFD, TIOCGSERIAL, &serinfo);
     if(r == -1) {
         *err = errno;
         return -1;
@@ -355,6 +388,19 @@ int BaseSerial::highSpeed(int *err) {
     serinfo.flags &= ~ASYNC_SPD_MASK;
     serinfo.flags |= ASYNC_SPD_CUST;
     r = ioctl(serialWriteFD, TIOCSSERIAL, &serinfo);
+#else
+    struct termios my_tios;
+    r = tcgetattr(serialWriteFD, &my_tios);
+    cfsetispeed(&my_tios, B38400); 
+    cfsetospeed(&my_tios, B38400);
+    r = tcsetattr(serialReadFD, TCSANOW, &my_tios);
+    if(r == -1) {
+        *err = errno;
+    }
+    else {
+        r = tcsetattr(serialWriteFD, TCSANOW, &my_tios);
+    }
+#endif    
     if(r == -1) {
         *err = errno;
         return -1;
index b8c1af35d070a6a8edae3282895ab1198eba445c..adc2df323996659b90f8ae4185c6c1715605f47f 100644 (file)
@@ -6,7 +6,7 @@
 # this is distributed under a free software license, see license.txt
 
 import sys, os, string
-VERSION = string.split("$Revision$")[1]     #extract CVS version
+VERSION = "$Revision$"     #extract CVS version
 
 #chose an implementation, depending on os
 if os.name == 'nt': #sys.platform == 'win32':
index 67b15dec7e059ae66a6d0ece9d17e95d5b2633c1..39239bddd26be1f22e729c5bb10bdb2d705b62c6 100644 (file)
@@ -8,7 +8,7 @@
 import sys, os, string, javax.comm
 import serialutil
 
-VERSION = string.split("$Revision$")[1]     #extract CVS version
+VERSION = "$Revision$"     #extract CVS version
 
 PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = (0,1,2,3,4)
 STOPBITS_ONE, STOPBITS_TWO, STOPBITS_ONE_HALVE = (1, 2, 3)
index 96a284cd8961373b7dac624cf961d5b0db1ed303..50ee86aa2b153562bae5e00f4adf928aafb23c92 100644 (file)
@@ -12,7 +12,7 @@
 import sys, os, fcntl, termios, struct, string, select
 import serialutil
 
-VERSION = string.split("$Revision$")[1]     #extract CVS version
+VERSION = "$Revision$"     #extract CVS version
 
 PARITY_NONE, PARITY_EVEN, PARITY_ODD = range(3)
 STOPBITS_ONE, STOPBITS_TWO = (1, 2)
index ffb3155a352b595c5ec39dbb3e88fd72179fa146..97472c38041c3d32a9e3b6c05af50c6fbd48950e 100644 (file)
@@ -11,7 +11,7 @@ import win32con   # constants.
 import sys, string
 import serialutil
 
-VERSION = string.split("$Revision$")[1]     #extract CVS version
+VERSION = "$Revision$"     #extract CVS version
 
 PARITY_NONE, PARITY_EVEN, PARITY_ODD = range(3)
 STOPBITS_ONE, STOPBITS_TWO = (1, 2)
index 097a96205a41593c1dea0a1a28b93de9148823da..1cdb2c292eda7da96397ae4119200b67c1d42754 100755 (executable)
@@ -1,44 +1,24 @@
 #!/bin/bash
-## NOTE: This is for MY rpm setup. Don't expect it to work for you...
 
-# For linux, change to /usr/src/redhat
-# For my cygwin: /cygdrive/c/rpmsrc
-if [ -z $RPMS ]; then #test to see if RPMS is overridden by the environment
-               RPMS=/usr/src/rpm
-fi             
-TINYOS_VERSION=2.1.0
-TINYOS_TOOLS_VERSION=1.3.0
+RPMS="`rpm --eval=\"%_topdir\"`"
+
+TOS_NAME="tinyos"
+TOS_VERSION=2.1.1
+
+TOS_TOOLS_NAME="tinyos-tools"
+TOS_TOOLS_VERSION=1.4.0
+
+TOS_DEPUTY_NAME="tinyos-deputy"
+TOS_DEPUTY_VERSION=1.1-1
 
 echo "*** Building tarballs"
-#rm ../../../*.tar.gz
-sh tinyos.files
-sh tinyos-tools.files
-#sh contrib/contrib.files
-#sh vm/vm.files
-#sh task-tinydb/task-tinydb.files
-
-HERE=$PWD
-
-echo "*** Removing old srcs and rpms"
-cd $RPMS
-#rm -f $RPMS/SOURCES/*.tar.gz
-#rm -f $RPMS/RPMS/noarch/*.rpm
-#rm -f $RPMS/RPMS/i386/*.rpm
-
-echo "*** Installing new tarballs"
-cd $HERE/../../..
-cp tinyos-$TINYOS_VERSION.tar.gz $RPMS/SOURCES
-cp tinyos-tools-$TINYOS_TOOLS_VERSION.tar.gz $RPMS/SOURCES
-#cp tinyos-vm-$VM_VERSION.tar.gz $RPMS/SOURCES
-#cp tinyos-contrib-$CONTRIB_VERSION.tar.gz $RPMS/SOURCES
-#cp task-tinydb-$TINYDB_VERSION.tar.gz $RPMS/SOURCES
+bash tinyos.files $TOS_NAME $TOS_VERSION $RPMS/SOURCES/$TOS_NAME-$TOS_VERSION.tar.gz
+bash tinyos-tools.files $TOS_TOOLS_NAME $TOS_TOOLS_VERSION $RPMS/SOURCES/$TOS_TOOLS_NAME-$TOS_TOOLS_VERSION.tar.gz
+#sh deputy.files
 
 echo "*** Creating rpms"
-cd $RPMS
-rpmbuild -bb $HERE/tinyos.spec
-rpmbuild -bb $HERE/tinyos-tools.spec
-#rpmbuild -bb $HERE/task-tinydb/task-tinydb.spec
-#rpmbuild -bb $HERE/contrib/contrib.spec
-#rpmbuild -bb $HERE/vm/vm.spec
+rpmbuild -bb tinyos.spec
+rpmbuild -bb tinyos-tools.spec
+#rpmbuild -bb deputy.spec
 
 
diff --git a/tools/release/deputy.files b/tools/release/deputy.files
new file mode 100755 (executable)
index 0000000..f975358
--- /dev/null
@@ -0,0 +1,11 @@
+NAME=tinyos-deputy
+VERSION=1.1
+RELEASE=1
+
+cd ../..
+rm -rf $NAME-$VERSION
+svn checkout svn://hal.cs.berkeley.edu/home/svn/projects/trunk/deputy
+mv deputy $NAME-$VERSION
+tar czvf ../$NAME-$VERSION-$RELEASE.tar.gz $NAME-$VERSION
+wget -O ../$NAME-$VERSION-$RELEASE.patch http://www.cs.utah.edu/~coop/safetinyos/files/deputy.patch
+
diff --git a/tools/release/deputy.spec b/tools/release/deputy.spec
new file mode 100644 (file)
index 0000000..c96f501
--- /dev/null
@@ -0,0 +1,44 @@
+%define deputy_name deputy
+%define tinyos_deputy_version 1.1
+%define tinyos_deputy_release 1
+
+Summary: Deputy compiler for Safe TinyOS.
+Name: tinyos-%{deputy_name}
+Version: %{tinyos_deputy_version}
+Release: %{tinyos_deputy_release}%{dist}
+Source: http://deputy.cs.berkeley.edu/%{name}-%{tinyos_deputy_version}-%{tinyos_deputy_release}.tar.gz
+Patch0: tinyos-%{deputy_name}-%{tinyos_deputy_version}-%{tinyos_deputy_release}.patch
+Vendor: Deputy
+URL: http://deputy.cs.berkeley.edu/
+License: LGPL
+Group: Developement tool
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+This package is the deputy compiler for Safe TinyOS.
+
+%prep
+%setup -q
+%patch0 -p0
+
+%build
+touch configure
+./configure --prefix=/usr
+make
+
+%install
+rm -rf $RPM_BUILD_ROOT
+make DESTDIR=$RPM_BUILD_ROOT install
+rm -rf $RPM_BUILD_ROOT/usr/lib/deputy/bin/deputy.byte.exe
+
+%clean
+rm -rf $RPM_BUILD_ROOT
+
+%files
+%defattr(-,root,root)
+/usr/bin/*
+/usr/lib/*
+/usr/man/man1/*
+
+
+%changelog
diff --git a/tools/release/external-tools/avarice.spec b/tools/release/external-tools/avarice.spec
new file mode 100755 (executable)
index 0000000..74f2d7a
--- /dev/null
@@ -0,0 +1,48 @@
+%define theprefix /usr
+
+Summary: AVaRICE - an interface for Atmel JTAG ICE to GDB
+Name: avarice
+Version: 2.4
+Release: 1
+Packager: kwright, TinyOS Group, UC Berkeley
+License: GNU GPL
+Group: Development/Tools 
+URL: http://sourceforge.net/projects/avarice/
+Source0: avarice-%{version}.tar.bz2
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+AVaRICE compiled for the %{target} platform.
+AVaRICE is a program interfacing the Atmel JTAG ICE to GDB. 
+Users can debug their embedded AVR target via the Atmel JTAG 
+ICE using GDB.
+
+%prep
+%setup -q
+
+%build
+./configure --prefix=/usr
+make
+
+%install
+rm -rf %{buildroot}%{theprefix}
+make prefix=%{buildroot}%{theprefix} install
+
+%clean
+rm -rf $RPM_BUILD_DIR/%(name)-%(version)
+rm -rf $RPM_SOURCE_DIR/%(name)-%(version)
+
+%files
+%defattr(-,root,root,-)
+%{theprefix}
+%doc
+
+%changelog
+* Fri Feb 3 2006 kwright <kwright@cs.berkeley.edu>
+- Update to avarice 2.4; create multi-platform file
+* Tue Mar 1 2005 kwright <kwright@cs.berkeley.edu>
+- Update for TinyOS 1.2 build.
+* Mon Aug 18 2003 kwright <kwright@cs.berkeley.edu>
+- Initial build.
+
+
diff --git a/tools/release/external-tools/avr-gcc.spec b/tools/release/external-tools/avr-gcc.spec
new file mode 100755 (executable)
index 0000000..8dbd323
--- /dev/null
@@ -0,0 +1,65 @@
+# 
+# The source must be in a tgz with the 
+# name %{target}-%{version}-binutils.tgz.
+# When unfolded, the top-level directory 
+# must be %{target}-%{version}.
+# 
+#
+# 03/14/2005 xscale
+# target: xscale-elf
+# version: 3.4.3
+# release: 1
+# 
+
+%define target avr 
+%define version  4.1.2
+%define release  1
+%define name     %{target}-gcc
+%define theprefix /usr
+%define source %{name}-%{version}.tgz
+%define __strip avr-strip
+
+Summary: gcc compiled for the %{target} platform 
+Name: %{name}
+Version: %{version}
+Release: %{release}
+Packager: kwright, TinyOS Group, UC Berkeley
+License: GNU GPL
+Group: Development/Tools
+URL: ftp://ftp.gnu.org/pub/gnu/gcc/gcc-3.4.3/gcc-3.4.3.tar.bz2
+Source0: %{name}-%{version}.tgz
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+gcc compiled for the %{target} platform. The tarfile was renamed 
+to %{target}-gcc* to reflect the purpose. 
+
+%prep
+%setup -q
+
+%build
+./configure --target=%{target} --enable-languages=c --disable-nls --prefix=/usr --disable-libssp
+make
+
+%install
+rm -rf %{buildroot}%{theprefix}
+make prefix=%{buildroot}%{theprefix} install
+cd %{buildroot}%{theprefix}
+rm lib/libiberty.a
+sed -i -e "s|%{buildroot}||g" lib/gcc/avr/*/install-tools/mkheaders.conf
+
+%clean
+rm -rf $RPM_BUILD_DIR/%{name}-%{version}
+rm -rf $RPM_SOURCE_DIR/%{name}-%{version}
+
+%files
+%defattr(-,root,root,-)
+%{theprefix}
+%doc
+
+%changelog
+* Sun Aug 10 2008 pal <pal@cs.stanford.edu> 4.1.2, avr
+* Mon Mar 14 2005 root <kwright@cs.berkeley.edu> 3.4.3
+- Initial build for multi-platform, multi-target
+
+
diff --git a/tools/release/external-tools/avr-insight.spec b/tools/release/external-tools/avr-insight.spec
new file mode 100755 (executable)
index 0000000..458b004
--- /dev/null
@@ -0,0 +1,47 @@
+%define theprefix /usr
+
+Summary: Insight GDB GUI       
+Name: avr-insight
+Version: 6.3
+Release: 1
+Packager: TinyOS Group, UC Berkeley
+License: GNU GPL
+Group: Development/Tools
+URL: httphttp://ftp.gnu.org/gnu/gdb/gdb-6.2.tar.gz 
+Source0: %{name}-%{version}.tar.gz
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+This package includes gdb and insight, a graphical user interface to GDB
+written in Tcl/Tk originally by Red Hat and Cygnus.
+
+%prep
+%setup -q
+
+%build
+./configure --prefix=%{theprefix} --target=avr --with-gnu-ld --with-gnu-as --disable-nls 
+make
+
+%install
+rm -rf %{buildroot}/usr/local
+make prefix=%{buildroot}/usr/local install
+cd %{buildroot}/usr/local
+rm info/bfd.info* info/configure.info* info/dir info/standards.info
+rm lib/libiberty.a
+
+%clean
+rm -rf $RPM_BUILD_DIR/%{name}-%{version}
+rm -rf $RPM_SOURCE_DIR/%{name}-%{version}
+
+%files
+%defattr(-,root,root,-)
+/usr/local
+%doc
+
+%changelog
+* Thu Aug 28 2003 root <kwright@cs.berkeley.edu> pre6.0cvs-1.2
+- Removed last of the file conflicts and changed name to avr-insight
+* Fri Aug 15 2003 root <kwright@cs.berkeley.edu> pre6.0cvs-1
+- Initial build.
+
+
diff --git a/tools/release/external-tools/avr-libc.spec b/tools/release/external-tools/avr-libc.spec
new file mode 100644 (file)
index 0000000..f59ab99
--- /dev/null
@@ -0,0 +1,59 @@
+# 
+# The source must be in a tgz with the 
+# name %{target}-%{version}-binutils.tgz.
+# When unfolded, the top-level directory 
+# must be %{target}-%{version}.
+# 
+
+%define target avr
+%define libname libc
+%define version 1.4.7
+%define release 1
+%define url http://savannah.nongnu.org/download/
+%define name     %{target}-%{libname}
+%define theprefix /usr
+%define source   %{name}-%{version}.tgz
+%define __strip avr-strip
+%define debug_package %{nil}
+
+Summary: C library for the %{target} platform
+Name: %{name}
+Version: %{version}
+Release: %{release}
+Packager: TinyOS Group, UC Berkeley
+License: GNU GPL-compatible
+Group: Development/Tools
+URL: %{url}
+Source0: %{source}
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+C library for the %{target} platform.
+
+%prep
+%setup -q
+
+%build
+./configure --prefix=%{theprefix}  --build=`./config.guess` --host=avr
+make
+
+%install
+rm -rf %{buildroot}%{theprefix}
+make prefix=%{buildroot}%{theprefix} install
+
+%clean
+rm -rf $RPM_BUILD_DIR/%{name}-%{version}
+rm -rf $RPM_SOURCE_DIR/%{name}-%{version}
+
+%files
+%{theprefix}
+%defattr(-,root,root,-)
+%doc
+
+
+%changelog
+* Fri Mar 10 2005 root <kwright@cs.berkeley.edu> 1.2.3-1
+- Initial version for multi-platform, multi-target
+
+
+
diff --git a/tools/release/external-tools/binutils.spec b/tools/release/external-tools/binutils.spec
new file mode 100755 (executable)
index 0000000..d539cbf
--- /dev/null
@@ -0,0 +1,73 @@
+# 
+# The source must be in a tgz with the 
+# name %{target}-%{version}-binutils.tgz.
+# When unfolded, the top-level directory 
+# must be %{target}-%{version}.
+# 
+# 03/14/2005 xscale
+# target: xscale-elf
+# version: 2.15
+# release: 1
+#
+# 03/25/2005 avr
+# target: avr
+# version: 2.15tinyos
+# release: 3
+# 
+
+%define target   avr
+%define version  2.17tinyos
+%define release  3
+%define name     %{target}-binutils
+%define theprefix /usr
+%define source   %{name}-%{version}.tgz
+
+Summary: GNU binutils for the %{target} platform
+Name: %{name}
+Version: %{version}
+Release: %{release}
+Packager: kwright, TinyOS Group, UC Berkeley
+URL: http://ftp.gnu.org/gnu/binutils/
+Source0: %{source}
+License: GNU GPL
+Group: Development/Tools 
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+The GNU Binutils are a collection of binary tools. The main tools are 
+ld and as. This particular collection  contains a patched as for 
+use with TinyOS 1.2+ on the %{target} platform. The patch allows 
+NesC to use the $ character within symbols to separate component
+names and variable names. 
+
+%prep
+%setup -q
+
+%build
+./configure --target=%{target} --prefix=%{theprefix}
+make
+
+%install
+rm -rf %{buildroot}%{theprefix}
+make prefix=%{buildroot}%{theprefix} install
+cd %{buildroot}%{theprefix}
+rm -rf info share 
+rm lib/libiberty.a
+
+%clean
+rm -rf $RPM_BUILD_DIR/%{name}-%{version}
+rm -rf $RPM_SOURCE_DIR/%{name}-%{version}
+
+%files
+%defattr(-,root,root)
+%{theprefix}
+%doc
+
+%changelog
+* Tue Jul 26 2005 kwright <kwright@cs.berkeley.edu>
+- Increase release version for avr; old version did not have the $
+  patch
+* Tue Mar 11 2005 kwright <kwright@cs.berkeley.edu>
+- Initial version for multi-platform, multi-target.
+
+
diff --git a/tools/release/external-tools/msp430-libc.spec b/tools/release/external-tools/msp430-libc.spec
new file mode 100755 (executable)
index 0000000..5cd0c07
--- /dev/null
@@ -0,0 +1,76 @@
+# 
+# The source must be in a tgz with the 
+# name %{target}-%{version}-binutils.tgz.
+# When unfolded, the top-level directory 
+# must be %{target}-%{version}.
+# 
+# avr:
+# target: avr
+# libname: libc
+# version: 1.2.3
+# release: 1
+# url: http://savannah.nongnu.org/download/avr-libc/
+# 
+# xscale-elf:
+# target: xscale-elf
+# libname: newlib
+# version: 1.11tinyos
+# release: 1
+# url: ftp://sources.redhat.com/pub/newlib/newlib-1.11.0.tar.gz
+
+%define target msp430tools 
+%define libname libc
+%define version 20080808
+%define release 1
+%define url http://savannah.nongnu.org/download/
+%define name     %{target}-%{libname}
+%define theprefix /opt
+%define source   %{name}-%{version}.tgz
+%define __strip msp430-strip
+%define debug_package %{nil}
+
+Summary: C library for the %{target} platform
+Name: %{name}
+Version: %{version}
+Release: %{release}
+Packager: TinyOS Group, UC Berkeley
+License: GNU GPL-compatible
+Group: Development/Tools
+URL: %{url}
+Source0: %{source}
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+C library for the %{target} platform.
+
+%prep
+%setup -q
+
+%build
+# doconf can have additional configuration parameters
+cd src
+make
+
+%install
+rm -rf %{buildroot}%{theprefix}
+cd src
+make prefix=%{buildroot}%{theprefix}/msp430 install
+cd %{buildroot}%{theprefix}
+rm -rf info
+
+%clean
+rm -rf $RPM_BUILD_DIR/%{name}-%{version}
+rm -rf $RPM_SOURCE_DIR/%{name}-%{version}
+
+%files
+%{theprefix}
+%defattr(-,root,root,-)
+%doc
+
+
+%changelog
+* Fri Mar 10 2005 root <kwright@cs.berkeley.edu> 1.2.3-1
+- Initial version for multi-platform, multi-target
+
+
+
diff --git a/tools/release/external-tools/xscale-elf.gcc.spec b/tools/release/external-tools/xscale-elf.gcc.spec
new file mode 100755 (executable)
index 0000000..13e9526
--- /dev/null
@@ -0,0 +1,62 @@
+# 
+# The source must be in a tgz with the 
+# name %{target}-%{version}-binutils.tgz.
+# When unfolded, the top-level directory 
+# must be %{target}-%{version}.
+# 
+#
+# 03/14/2005 xscale
+# target: xscale-elf
+# version: 3.4.3
+# release: 1
+# 
+
+%define target xscale-elf
+%define version  3.4.3
+%define release  1
+%define name     %{target}-gcc
+%define theprefix /usr
+%define source %{name}-%{version}.tgz
+
+Summary: gcc compiled for the %{target} platform 
+Name: %{name}
+Version: %{version}
+Release: %{release}
+Packager: kwright, TinyOS Group, UC Berkeley
+License: GNU GPL
+Group: Development/Tools
+URL: ftp://ftp.gnu.org/pub/gnu/gcc/gcc-3.4.3/gcc-3.4.3.tar.bz2
+Source0: %{name}-%{version}.tgz
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+gcc compiled for the %{target} platform. The tarfile was renamed 
+to %{target}-gcc* to reflect the purpose. 
+
+%prep
+%setup -q
+
+%build
+./configure --target=%{target} --enable-languages=c --disable-nls --prefix=/usr
+make
+
+%install
+rm -rf %{buildroot}%{theprefix}
+make prefix=%{buildroot}%{theprefix} install
+cd %{buildroot}%{theprefix}
+rm lib/libiberty.a
+
+%clean
+rm -rf $RPM_BUILD_DIR/%{name}-%{version}
+rm -rf $RPM_SOURCE_DIR/%{name}-%{version}
+
+%files
+%defattr(-,root,root,-)
+%{theprefix}
+%doc
+
+%changelog
+* Mon Mar 14 2005 root <kwright@cs.berkeley.edu> 3.4.3
+- Initial build for multi-platform, multi-target
+
+
index dc9b894f4c74eb792d8d0fe5eed482ed5b8ae449..97679f5bf098910a64a93676681c8d2df37843c0 100755 (executable)
@@ -1,5 +1,6 @@
 #!/usr/bin/perl
 $name = $ARGV[0];
+$file_path = $ARGV[1];
 
 @files = split /\n/, `find .`;
 @result = @files;
@@ -20,7 +21,7 @@ mkdir $name;
 open TAR, "|tar cf - -T - --no-recursion | tar xf - -C $name";
 print TAR join("\n", @result);
 close TAR;
-#print join("\n", @result);
-system("tar cf - $name");
+system("tar cfz $file_path $name");
+system("rm -rf $name");
 
 
diff --git a/tools/release/nesc.spec b/tools/release/nesc.spec
new file mode 100644 (file)
index 0000000..15f065b
--- /dev/null
@@ -0,0 +1,64 @@
+%define version 1.3.0
+%define theprefix /usr
+
+Summary: nesC compiler 
+Name: nesc
+Version: 1.3.0
+Release: 1%{dist}
+License: GNU GPL Version 2
+Packager: TinyOS Group, UC Berkeley
+Group: Development/Tools
+URL: http://sourceforge.net/projects/nescc
+Source0: %{name}-%{version}.tar.gz
+BuildRoot: %{_tmppath}/%{name}-root
+
+%description
+nesC is a compiler for a C-based language designed to support embedded
+systems including TinyOS. nesC provides several advantages for the
+TinyOS compiler infrastructure: improved syntax, support for full type
+safety, abundant error reporting, generic components, and Java-like
+interfaces.
+
+%prep
+%setup -q
+
+%build
+./configure --prefix=%{theprefix}
+make 
+
+%install
+rm -rf %{buildroot}%{theprefix}
+make prefix=%{buildroot}%{theprefix} install
+
+%clean
+rm -rf $RPM_BUILD_DIR/%{name}-%{version}
+
+%files
+%defattr(-,root,root,-)
+%{theprefix}
+%doc
+
+%changelog
+* Wed Aug 6 2008  <david.e.gay@intel.com> 1.3.0
+- Deputy support
+* Tue Jul 3 2007  <david.e.gay@intel.com> 1.2.9
+* Wed Dec 20 2006  <david.e.gay@intel.com> 1.2.8a
+* Fri Dec 1 2006  <david.e.gay@intel.com> 1.2.8
+* Thu Jul 6 2006  <kwright@archrock.com> 1.2.7a
+* Wed Jun 28 2006  <kwright@archrock.com> 1.2.7
+- Version 1.2.7
+* Fri Feb 3 2006  <kwright@cs.berkeley.edu> 1.2.4
+- Version 1.2.4
+* Mon Mar 14 2005  <kwright@cs.berkeley.edu> 1.1.2b
+- Version 1.1.2b; use buildroot
+* Tue Jul 27 2004  <dgay@intel-research.net> 1.1.2-1w
+- Version 1.1.2
+* Fri Sep 26 2003 root <kwright@cs.utah.edu> 1.1-1
+- New source
+* Fri Sep 19 2003 root <kwright@cs.utah.edu> 1.1pre4-2
+- Removed set-mote-id
+* Fri Sep 12 2003 root <kwright@cs.utah.edu> 1.1pre4-1
+- New source
+* Fri Aug 15 2003 root <kwright@cs.utah.edu> 1.1pre2-1
+- Initial build.
+
index d341370d6d1c858677b7e391a5ff287e88da0d89..bda13fa88771be68255951aafc5d2cd1c208649c 100755 (executable)
@@ -1,9 +1,13 @@
-NAME=tinyos-tools
-VERSION=1.3.0
+NAME="$1"
+VERSION="$2"
+OUTPUT_FILE="$3"
 
-cd ../..
-rm -rf $NAME-$VERSION
-tools/release/extractor $NAME-$VERSION <<'EOF' | gzip >../$NAME-$VERSION.tar.gz
+pushd ../../
+./tools/release/extractor $NAME-$VERSION $OUTPUT_FILE <<'EOF'
+!^./tinyos.sh
+!^./tos.mk
+!^./debian
+!^./(patch|configure|build|install)-stamp
 !^./apps
 !^./doc
 !^./support
@@ -13,7 +17,12 @@ tools/release/extractor $NAME-$VERSION <<'EOF' | gzip >../$NAME-$VERSION.tar.gz
 !/.cvsignore
 !/CVS/
 !/CVS$
+!/.svn/
+!/.svn$
+!^./.git
+!^./.gitignore
+!^./.gbp.conf
 !~$
 !#
 EOF
-rm -rf $NAME-$VERSION
+popd
index 8eb60f3b1ceb6eb28758847bf779d97047269b9c..0fe0968f79a017c967b753babf98545847c21525 100644 (file)
@@ -2,8 +2,8 @@
 
 Summary: TinyOS tools 
 Name: tinyos-tools
-Version: 1.3.0
-Release: 1
+Version: 1.4.0
+Release: 1%{dist}
 License: Please see source
 Group: Development/System
 URL: http://www.tinyos.net/
@@ -60,6 +60,7 @@ if [ $? -ne 0 ]; then
 fi
 %ifos linux
 java=`$RPM_INSTALL_PREFIX/bin/tos-locate-jre --java`
+tinyoslibdir=$RPM_INSTALL_PREFIX/lib/tinyos
 bits=32
 if [ $? -ne 0 ]; then
   echo "java command not found - assuming 32 bits"
index 5711669bcacac6d5d5a2030a8a81148633d6d104..13e723b1c9370ab5aa71170350944b84aaa6f0e3 100644 (file)
@@ -1,7 +1,57 @@
-NAME=tinyos
-VERSION=2.1.0
+NAME="$1"
+VERSION="$2"
+OUTPUT_FILE="$3"
 
-cd ../..
-rm -rf $NAME-$VERSION
-tools/release/extractor $NAME-$VERSION < tools/release/tinyos.filter | gzip >../$NAME-$VERSION.tar.gz
-rm -rf $NAME-$VERSION
+pushd ../../
+./tools/release/extractor $NAME-$VERSION $OUTPUT_FILE <<'EOF' 
+!^./tinyos.sh
+!^./tos.mk
+!^./debian
+!^./(patch|configure|build|install)-stamp
+!^./apps/tests/(eyesIFX|mica2|msp430|rf230|mts300|telosb)
+!^./apps/tests/(RadioStress|TestAlarm|TestAM|TestAMOnOff|TestAMService|TestBroadcast|TestCollection|TestLocalTime|TestMultihopLqi|TestOscilloscopeLQI|TestPowerManager|TestPowerup|TestPrintf|TestRadioPM|TestScheduler|TestSerialBandwidth|TestSharedResource|TestSimTimers|TestSleep|TestTimerSync|TestTreeRouting|TestTrickleTimer|TestTymo)
+!^/apps/(BlinkAlarm|BlinkMSP430|BlinkTask|BlinkToRadio|Test|TestADC|TestArbiter|TestCC2420|TestRadio|TestSPI|TestScheduler|TestSchedulerTemp|TestSerial)
+!^./doc
+!^./overall-todo.txt
+!^./support/make/Makelocal
+!^./support/make/btnode3.target
+!^./tests
+!^./tools
+!^./tos/chips/Atmega128
+!^./tos/chips/cc2420_pm
+!^./tos/chips/cc1000_pm
+!^./tos/lib/adc
+!^./tos/lib/ByteRadio
+!^./tos/lib/deluge
+!^./tos/lib/net/collection
+!^./tos/lib/net/zigbee
+!^./tos/lib/net/tymo
+!^./tos/lib/oski
+!^./tos/platforms/btnode3
+!/.cvsignore
+!/CVS/
+!/CVS$
+!/.svn/
+!/.svn$
+!^./.git
+!^./.gitignore
+!^./.gbp.conf
+!~$
+!/build/
+!/build$
+!#
+!.class$
+./RadioSenseToLeds/RadioSenseMsg.class
+./MViz/MVizMsg.class
+./tests/cc2420/TestPacketLink/TestPacketLink.class
+./tests/cc2420/TestPacketLink/PacketLinkMsg.class
+./tests/cc2420/TxThroughput/ThroughputMsg.class
+./tests/cc2420/TxThroughput/TxThroughput.class
+./tests/cc2420/LplBroadcastCountToLeds/RadioCountMsg.class
+./tests/cc2420/RssiToSerial/SpecAnalyzer.class
+./tests/cc2420/RssiToSerial/RssiSerialMsg.class
+./tests/TestSerial/TestSerialMsg.class
+./tests/TestSerial/TestSerial.class
+./RadioCountToLeds/RadioCountMsg.class
+EOF
+popd
diff --git a/tools/release/tinyos.filter b/tools/release/tinyos.filter
deleted file mode 100644 (file)
index e3c8a1e..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-!^./tinyos.sh
-!^./tos.mk
-!^./debian
-!^./(patch|configure|build|install)-stamp
-!^./apps/tests/(eyesIFX|mica2|msp430|rf230|mts300|telosb)
-!^./apps/tests/(RadioStress|TestAlarm|TestAM|TestAMOnOff|TestAMService|TestBroadcast|TestCollection|TestLocalTime|TestMultihopLqi|TestOscilloscopeLQI|TestPowerManager|TestPowerup|TestPrintf|TestRadioPM|TestScheduler|TestSerialBandwidth|TestSharedResource|TestSimTimers|TestSleep|TestTimerSync|TestTreeRouting|TestTrickleTimer|TestTymo)
-!^/apps/(BlinkAlarm|BlinkMSP430|BlinkTask|BlinkToRadio|Test|TestADC|TestArbiter|TestCC2420|TestRadio|TestSPI|TestScheduler|TestSchedulerTemp|TestSerial)
-!^./doc
-!^./overall-todo.txt
-!^./support/make/Makelocal
-!^./support/make/btnode3.target
-!^./tests
-!^./tools
-!^./tos/chips/Atmega128
-!^./tos/chips/cc2420_pm
-!^./tos/chips/cc1000_pm
-!^./tos/lib/adc
-!^./tos/lib/ByteRadio
-!^./tos/lib/deluge
-!^./tos/lib/net/collection
-!^./tos/lib/net/zigbee
-!^./tos/lib/net/tymo
-!^./tos/lib/oski
-!^./tos/platforms/btnode3
-!/.cvsignore
-!/CVS/
-!/CVS$
-!/.svn/
-!/.svn$
-!^./.git
-!^./.gitignore
-!^./.gbp.conf
-!~$
-!/build/
-!/build$
-!#
-!.class$
-./RadioSenseToLeds/RadioSenseMsg.class
-./MViz/MVizMsg.class
-./tests/cc2420/TestPacketLink/TestPacketLink.class
-./tests/cc2420/TestPacketLink/PacketLinkMsg.class
-./tests/cc2420/TxThroughput/ThroughputMsg.class
-./tests/cc2420/TxThroughput/TxThroughput.class
-./tests/cc2420/LplBroadcastCountToLeds/RadioCountMsg.class
-./tests/cc2420/RssiToSerial/SpecAnalyzer.class
-./tests/cc2420/RssiToSerial/RssiSerialMsg.class
-./tests/TestSerial/TestSerialMsg.class
-./tests/TestSerial/TestSerial.class
-./RadioCountToLeds/RadioCountMsg.class
index dfcb111435b083512911484bf8e6898506481720..ca01f7b49d1d90628028c58d4527a34ddb842434 100644 (file)
@@ -1,8 +1,8 @@
 Summary: An event-based operating environment designed for use with embedded networked sensors.
 Name: tinyos
 BuildArchitectures: noarch
-Version: 2.1.0
-Release: 1
+Version: 2.1.1
+Release: 1%{dist}
 License: Please see source
 Packager: TinyOS Group, UC Berkeley
 Group: Development/System
@@ -10,7 +10,7 @@ URL: www.tinyos.net
 Source0: %{name}-%{version}.tar.gz
 BuildRoot: %{_tmppath}/%{name}-root
 Prefix: /opt
-Requires: tinyos-tools >= 1.3, nesc >= 1.3
+Requires: tinyos-tools >= 1.4, nesc >= 1.3
 
 %description
 TinyOS is an event based operating environment designed for use with 
index 2d03f2d513ffd9d3c489f5065af4829cdfd25440..f451e8060464fd54ac6d24f39a965526af770d2d 100644 (file)
@@ -14,12 +14,13 @@ libgetenv_32_so_SOURCES = net_tinyos_util_Env.h net_tinyos_util_Env.c
 libgetenv_64_so_SOURCES = $(libgetenv_32_so_SOURCES)
 
 libgetenv-32.so : net_tinyos_util_Env.h net_tinyos_util_Env.c
-       $(CC) $(SOFLAGS) -m32 net_tinyos_util_Env.c -o$@
+       $(CC) $(SOFLAGS) -m32 net_tinyos_util_Env.c -o$@ || \
+       (echo 32-bit libgetenv.so NOT GENERATED - DO NOT USE THIS RUN TO BUILD AN RPM; echo Press return to continue; read; rm -f $@)
 
 libgetenv-64.so : net_tinyos_util_Env.h net_tinyos_util_Env.c
        @echo $(CC) $(SOFLAGS) -m64 net_tinyos_util_Env.c -o$@
        @$(CC) $(SOFLAGS) -m64 net_tinyos_util_Env.c -o$@ || \
-       (echo 64-bit libgetenv.so NOT GENERATED - DO NOT USE THIS RUN TO BUILD AN RPM; echo Press return to continue; read; rm -f libtoscomm-64.so)
+       (echo 64-bit libgetenv.so NOT GENERATED - DO NOT USE THIS RUN TO BUILD AN RPM; echo Press return to continue; read; rm -f $@)
 
 getenv.dll: net_tinyos_util_Env.h net_tinyos_util_Env.c
        gcc -shared -o$@ -mno-cygwin "-I$(JDK)/include" "-I$(JDK)/include/win32" -D_JNI_IMPLEMENTATION -Wl,--kill-at net_tinyos_util_Env.c
index 88e2ed5cec4df3ed22d83acab8233365c890ef7f..5b63d8b73c30972560ceeb2913d7ea5198ee49ce 100644 (file)
@@ -34,12 +34,13 @@ libtoscomm.jnilib:  $(libtoscomm_jnilib_SOURCES)
         -o $@ NativeSerial_darwin.cpp
 
 libtoscomm-32.so: $(libtoscomm_so_SOURCES)
-       $(CXX) -m32 $(SOFLAGS) -o $@ NativeSerial_linux.cpp
+       $(CXX) -m32 $(SOFLAGS) -o $@ NativeSerial_linux.cpp || \
+       (echo 32-bit libtoscomm.so NOT GENERATED - DO NOT USE THIS RUN TO BUILD AN RPM; echo Press return to continue; read; rm -f $@)
 
 libtoscomm-64.so: $(libtoscomm_so_SOURCES)
        @echo $(CXX) -m64 $(SOFLAGS) -o $@ NativeSerial_linux.cpp
        @$(CXX) -m64 $(SOFLAGS) -o $@ NativeSerial_linux.cpp || \
-       (echo 64-bit libtoscomm.so NOT GENERATED - DO NOT USE THIS RUN TO BUILD AN RPM; echo Press return to continue; read; rm -f libtoscomm-64.so)
+       (echo 64-bit libtoscomm.so NOT GENERATED - DO NOT USE THIS RUN TO BUILD AN RPM; echo Press return to continue; read; rm -f $@)
 
 toscomm.dll: $(toscomm_dll_SOURCES)
        $(CXX) -O2 -s -mno-cygwin -shared "-I$(JDK)/include" "-I$(JDK)/include/win32" -D_JNI_IMPLEMENTATION -Wl,--kill-at \
index 76498bb1cb5ffba95e638544ba5f76d64d43ac13..0fc584d56312aef7bdd9060ac585f826a5ae53c8 100644 (file)
@@ -31,6 +31,7 @@ bin_SCRIPTS = tos-ident-flags \
              tos-storage-at45db \
              tos-storage-pxa27xp30     \
              tos-build-deluge-image \
-             tos-deluge
+             tos-deluge \
+             tos-dump.py
 
 bin_PROGRAMS = tos-serial-debug
index 3095167aeeed9ad4c37b26a5700c52c0c9ec4691..0dddf828cc76d74acf23a145d628e63e7dd99d8c 100755 (executable)
@@ -130,10 +130,11 @@ except:
 all = []
 section = []
 end_addr = None
+offset = 0
 for line in image.split():
     #print "DEBUG:", line
     length = int(line[1:3], 16)
-    addr = int(line[3:7], 16)
+    addr = int(line[3:7], 16) + offset
     rectype = int(line[7:9], 16)
     data = []
     if len(line) > 11:
@@ -155,6 +156,8 @@ for line in image.split():
             start_addr = addr
         section += data
         end_addr = addr + length
+    elif rectype == 0x02:
+        offset = int(line[9:9+4], 16) << 4
     elif rectype == 0x01:
         all.append((start_addr, section))
         section = []
index c1c7777fb86b7c87d483232be7184371f3c19434..21d7727f96a61142d82f6678bfc70ce06d4b7274 100755 (executable)
@@ -39,9 +39,6 @@ PATH_PY_BUILD_IMAGE  = os.path.join(os.path.dirname(sys.argv[0]), 'tos-build-del
 FM_AMID = 0x53
 DM_AMID = 0x54
 SERIAL_DATA_LENGTH = 28 - 1 - 1 - 2 - 2
-BAUDRATES = {'micaz': 57600,
-             'telosb': 115200,
-             'iris': 57600}
 
 # Commands for FlashManager
 FM_CMD_ERASE     = 0
@@ -73,7 +70,7 @@ class FMReqPacket(tos.Packet):
         tos.Packet.__init__(self,
                             [('cmd',    'int',  1),
                              ('imgNum', 'int',  1),
-                             ('offset', 'int',  2),
+                             ('offset', 'int',  4),
                              ('length', 'int',  2),
                              ('data',   'blob', None)],
                             packet)
@@ -188,9 +185,23 @@ def read(imgNum, offset, length):
     return r
 
 def erase(imgNum):
+    # Note: the normal erase doesn't work properly on AT45DB. A
+    # workaround is to do the normal erase (to make happy STM25P)
+    # and then overwrite the metadata (to make happy AT45DB).
+
     sreqpkt = FMReqPacket((FM_CMD_ERASE, imgNum, 0, 0, []))
     success = am.write(sreqpkt, FM_AMID)
-    return handleResponse(success, "ERROR: Unable to erase the flash volume")
+    result = handleResponse(success, "ERROR: Unable to erase the flash volume")
+    if result: return True;
+
+    print 'Attempt the workaround for AT45DB...'
+    sreqpkt = FMReqPacket((FM_CMD_WRITE, imgNum, 0, 0, []))
+    sreqpkt.data = [0xFF] * DELUGE_IDENT_SIZE
+    sreqpkt.length = DELUGE_IDENT_SIZE
+    success = am.write(sreqpkt, FM_AMID)
+    result = handleResponse(success, "ERROR: Unable to erase the flash volume")
+    if not result: return False;
+    return sync(imgNum)
 
 def sync(imgNum):
     sreqpkt = FMReqPacket((FM_CMD_SYNC, imgNum, 0, 0, []))
@@ -370,8 +381,10 @@ def localstop():
     return handleResponse(success, "ERROR: Unable to initiate the local stop")
 
 def print_usage():
-    print "Usage: %s <device_port> <baud_rate> <-p|-i|-r|-d|-e|-s> image_number [options]" % sys.argv[0]
-    print "  <baud_rate>      Either the platform name (micaz or telosv) or a baudrate value"
+    print "Usage: %s <source> <-p|-i|-r|-d|-e|-s> image_number [options]" % sys.argv[0]
+    print "  <source> can be:"
+    print "     serial@PORT:SPEED   Serial ports"
+    print "     network@HOST:PORT   MIB600"
     print "  -p --ping        Provide status of the image in the external flash"
     print "  -i --inject      Inject a compiled TinyOS application"
     print "                   [options]: tos_image.xml file path"
@@ -390,71 +403,55 @@ def checkImgNum():
     global imgNum
     # Checks for valid image number format
     try:
-        imgNum = int(sys.argv[4])
+        imgNum = int(sys.argv[3])
     except:
         print "ERROR: Image number is not valid"
         sys.exit(-1)
     return imgNum
 
 # ======== MAIN ======== #
-if len(sys.argv) >= 4:
+if len(sys.argv) >= 3:
 
-    if sys.argv[2] in BAUDRATES:
-        baudrate = BAUDRATES[sys.argv[2]]
-    else:
-        try:
-            baudrate = int(sys.argv[2])
-        except:
-            print "ERROR: Wrong baudrate"
-            sys.exit(-1)
-
-    # Initializes serial port communication
-    try:
-        s = tos.Serial(sys.argv[1], baudrate, flush=True, debug=False)
-        am = tos.AM(s)
-    except:
-        print "ERROR: Unable to initialize serial port connection to", sys.argv[1]
-        sys.exit(-1)
+    am = tos.AM()
 
-    # Check if the mote has the Deluge T2 basestation component:
     try:
         print "Checking if node is a Deluge T2 base station ..."
-        ident(timeout=5)
-    except tos.TimeoutError:
+        ident(timeout=1)
+    except tos.Timeout:
         print "ERROR: Timeout. Is the node a Deluge T2 base station?"
         sys.exit(-1)
 
-    if sys.argv[3] in ["-p", "--ping"]:
+    if sys.argv[2] in ["-p", "--ping"]:
         checkImgNum()
         print "Pinging node ..."
         ping(imgNum)
-    elif sys.argv[3] in ["-i", "--inject"] and len(sys.argv) == 6:
+    elif sys.argv[2] in ["-i", "--inject"] and len(sys.argv) == 5:
         checkImgNum()
         print "Pinging node ..."
-        inject(imgNum, sys.argv[5])
-    elif sys.argv[3] in ["-e", "--erase"]:
+        inject(imgNum, sys.argv[4])
+    elif sys.argv[2] in ["-e", "--erase"]:
         checkImgNum()
         if erase(imgNum):
             print "Image number %d erased" % imgNum
-    elif sys.argv[3] in ["-b", "--boot"]:
+    elif sys.argv[2] in ["-b", "--boot"]:
         if boot():
             print "Command sent"
-    elif sys.argv[3] in ["-r", "--reprogram"]:
+    elif sys.argv[2] in ["-r", "--reprogram"]:
         checkImgNum()
         if reprogram(imgNum):
             print "Command sent"
-    elif sys.argv[3] in ["-d", "--disseminate"]:
+    elif sys.argv[2] in ["-d", "--disseminate"]:
         checkImgNum()
         if disseminate(imgNum):
             print "Command sent"
-    elif sys.argv[3] in ["-dr", "--disseminate-and-reboot"]:
+    elif sys.argv[2] in ["-dr", "--disseminate-and-reboot"]:
         checkImgNum()
         if disseminateAndReboot(imgNum):
             print "Command sent"
-    elif sys.argv[3] in ["-s", "--stop"]:
+    elif sys.argv[2] in ["-s", "--stop"]:
         if stop():
             print "Command sent"
-    elif sys.argv[3] in ["-ls", "--local-stop"]:
+    elif sys.argv[2] in ["-ls", "--local-stop"]:
         if localstop():
             print "Command sent"
     else:
diff --git a/tools/tinyos/misc/tos-dump.py b/tools/tinyos/misc/tos-dump.py
new file mode 100644 (file)
index 0000000..1d669e1
--- /dev/null
@@ -0,0 +1,17 @@
+#!/usr/bin/env python
+
+import sys
+import tos
+
+if '-h' in sys.argv:
+    print "Usage:", sys.argv[0], "serial@/dev/ttyUSB0:57600"
+    print "      ", sys.argv[0], "network@host:port"
+    sys.exit()
+
+am = tos.AM()
+
+while True:
+    p = am.read()
+    if p:
+       print p
+
diff --git a/tools/tinyos/misc/tos-nwprog b/tools/tinyos/misc/tos-nwprog
new file mode 100755 (executable)
index 0000000..d8c78a3
--- /dev/null
@@ -0,0 +1,308 @@
+#!/usr/bin/env python
+
+# Copyright (c) 2007 Johns Hopkins University.
+# All rights reserved.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose, without fee, and without written
+# agreement is hereby granted, provided that the above copyright
+# notice, the (updated) modification history and the author appear in
+# all copies of this source code.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+# OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+# @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+# @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+
+# b6lowpan/nwprog port:
+# @author Stephen Dawson-Haggerty <stevedh@cs.berkeley.edu>
+
+import sys, stat, struct, subprocess, time, os.path, socket, getopt, re
+try:
+    import tos
+except ImportError:
+    import posix
+    sys.path = [os.path.join(posix.environ['TOSROOT'], 'support', 'sdk', 'python')] + sys.path
+    import tos
+from datetime import datetime
+
+# Path to the python script that builds Deluge image from XML
+PATH_PY_BUILD_IMAGE  = os.path.join(os.path.dirname(sys.argv[0]), 'tos-build-deluge-image')
+
+# Commands for NWProg
+NWPROG_CMD_ERASE = 1
+NWPROG_CMD_WRITE = 2
+NWPROG_CMD_READ  = 3
+
+
+# Deluge parameters
+DELUGE_MAX_PAGES    = 128
+DELUGE_IDENT_OFFSET = 0
+DELUGE_IDENT_SIZE   = 128
+
+NWPROG_PORT = 5213
+NWPROG_PKT_SIZE = 64
+NWPROG_REQ_FMT = "!BBH"
+NWPROG_REPLY_FMT = "!BBBBH"
+
+ERROR_SUCCESS = 0
+nRetries = 3
+
+class CommandFailedException:
+    pass
+
+def send_command(cmd_str, retries):
+    s.sendto(cmd_str, (remote, NWPROG_PORT))
+    s.settimeout(3)
+    (real_cmd, real_imgno, real_offset) = struct.unpack(NWPROG_REQ_FMT, cmd_str[0:4])
+    try:
+        data, addr = s.recvfrom(1024)
+        # make sure this is the guy we're programming
+        if (addr[0] == remote):
+            (error, pack, cmd, imgno, offset) = struct.unpack(NWPROG_REPLY_FMT, data)
+            if error != ERROR_SUCCESS or real_offset != offset or real_imgno != imgno:
+                print "WARNING: received error while sending block; retrying"
+                raise socket.timeout
+            else: return data
+        else:
+            print "WARNING: received unexpected reply from", addr[0]
+            return False
+    except socket.timeout:
+        # socket timeout out try again
+        if retries > 0:
+            return send_command(cmd_str, retries - 1)
+        else:
+            return False
+
+def erase(imgNum, none=None):
+    e_req = struct.pack(NWPROG_REQ_FMT, NWPROG_CMD_ERASE, imgNum, 0)
+    return send_command(e_req, 1)
+
+def read(imgNum, unused=None):
+    length = 40000
+    pkt_offset = 0
+    while length > 0:
+        sreqpkt = struct.pack(NWPROG_REQ_FMT, NWPROG_CMD_READ, imgNum, pkt_offset)
+
+        data = send_command(sreqpkt, 5)
+        if data != False:
+            (error, pack, cmd, imgno, offset) = struct.unpack(NWPROG_REPLY_FMT, data[0:6])
+            if offset == pkt_offset:
+                for c in data[6:]:
+                    print >>sys.stderr, ord(c)
+            else:
+                print "ERROR: Out of sequence data: aborting"
+                sys.exit(1)
+        pkt_offset += len(data) - 6
+        length -= (len(data) - 6)
+    return True
+            
+
+def write(imgNum, data):
+    length = len(data)
+    total_length = length   # For progress bar
+    next_tick = 100         # For progress bar
+    start_time = time.time()
+
+    print "[0%        25%         50%         75%         100%]\r[",
+
+    pkt_offset = 0
+    pkt_length = 0
+
+    while length > 0:
+        if ((length * 100) / total_length) < next_tick:
+            next_tick = next_tick - 2
+            sys.stdout.write('-')
+            sys.stdout.flush()
+
+        # Calculates the payload size for the current packet
+        if length >= NWPROG_PKT_SIZE:
+            pkt_length = NWPROG_PKT_SIZE
+        else:
+            pkt_length = length
+
+        sreqpkt = struct.pack(NWPROG_REQ_FMT,
+                              NWPROG_CMD_WRITE, imgNum, pkt_offset)
+
+        for i in data[pkt_offset:pkt_offset+pkt_length]:
+            sreqpkt += chr(i)
+
+        # Sends packet to serial
+        if not send_command(sreqpkt, 5):
+            print "\nReceived error from mote while programming"
+            print "Perhaps the block size is too large, or the flash is broken?"
+            return False
+
+        length -= pkt_length
+        pkt_offset += pkt_length
+
+
+    print '\r' + ' ' * 52,
+    elasped_time = time.time() - start_time
+    print "\r%s bytes in %.2f seconds (%.4f bytes/s)" % (total_length, elasped_time, int(total_length) / (elasped_time))
+
+    return True
+
+
+# Injects an image (specified by tos_image_xml) to an image volume
+def upload(imgNum, tos_image_xml):
+    # Checks for valid file path
+    try:
+        os.stat(tos_image_xml)         # Checks whether tos_image_xml is a valid file
+    except:
+        print "ERROR: Unable to find the TOS image XML, \"%s\"" % tos_image_xml
+        return False
+    try:
+        os.stat(PATH_PY_BUILD_IMAGE)   # Checks whether PATH_PY_BUILD_IMAGE is a valid file
+    except:
+        print "ERROR: Unable to find the image building utility, \"%s\"" % PATH_PY_BUILD_IMAGE
+        return False
+
+    # Creates binary image from the TOS image XML
+    print "--------------------------------------------------"
+    cmd = [PATH_PY_BUILD_IMAGE, "-i", str(imgNum), tos_image_xml]
+    print "Create image:", ' '.join(cmd)
+    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+    (out, err) = p.communicate(None)
+    print err,
+    print "--------------------------------------------------"
+
+    # Writes the new binary image
+    image = [struct.unpack("B", c)[0] for c in out]
+    if len(image) > 0 and erase(imgNum):
+        return write(imgNum, image)
+    else:
+        print "Could not proceed: image size is zero or erase failed"
+
+    return False
+
+
+def print_usage():
+    print
+    print "Usage: %s <(-e|-u) image_number> <-f app_xml> [options] [ip_address]" % sys.argv[0]
+    print "  -u --upload      Upload a compiled TinyOS application"
+    print "  -r --read        Read back a volume"
+    print "  -e --erase       Erase an image in the external flash"
+    print "  -f --appfile     The tos_image.xml file to upload"
+    print "  -m --motelist    A file containing a list of IPv6 addresses to upload to"
+    print "  -r --retries     The number of times to retry each operation (currently %i)" % nRetries
+    print "  -p --payload-sz  How much payload to include in every packet (currently %i)" % NWPROG_PKT_SIZE
+    print "  -d --dudfile     File to write list of motes which did not program (default: stdout)"
+    print
+
+def checkImgNum(imgNum):
+    # Checks for valid image number format
+    try:
+        imgNum = int(imgNum)
+    except:
+        print "ERROR: Image number is not valid"
+        sys.exit(-1)
+    return imgNum
+
+# ======== MAIN ======== #
+if __name__ == '__main__':
+
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], "e:u:m:f:r:p:d:r:",
+                                   ["--erase", "--upload", "--motelist", "--appfile",
+                                    "--retries", "--payload", "--dudfile",
+                                    "--upload"])
+    except getopt.GetoptError, err:
+        print str(err)
+        print_usage()
+        sys.exit(1)
+
+    imgNum = None
+    uploadFile = None
+    appFile = None
+    dudFile = None
+    
+    for o, a in opts:
+        if o in ["-e", "--erase"]:
+            imgNum = checkImgNum(a)
+            cmd = "eras"
+        elif o in ["-u", "--upload"]:
+            imgNum = checkImgNum(a)
+            cmd = "upload"
+        elif o in ["-r", "--read"]:
+            imgNum = checkImgNum(a)
+            cmd = "read"
+        elif o in ["-m", "--motelist"]:
+            uploadFile = a
+        elif o in ["-f", "--appfile"]:
+            appFile = a
+        elif o in ["-r", "--retries"]:
+            nRetries = int(a)
+        elif o in ["-p", "--payload-sz"]:
+            NWPROG_PKT_SIZE = int(a)
+        elif o in ["-d", "--dudfile"]:
+            dudFile = a
+
+    if imgNum == None or (cmd != "eras" and cmd != "read" and appFile == None):
+        print_usage()
+        sys.exit(1)
+
+    upload_list = []
+    if uploadFile == None:
+        upload_list = [(ip, nRetries) for ip in args]
+    else:
+        fp = open(uploadFile, "r")
+        rexp = re.compile("^.*#")
+        for ip in fp.readlines():
+            if re.match(rexp,ip): continue
+            upload_list.append( (ip.strip().lower(), nRetries) )
+        fp.close()
+
+    if cmd == 'upload': cmd_fn = upload
+    elif cmd == 'read': cmd_fn = read
+    else: cmd_fn = erase
+
+    print "%sing %i motes" % (cmd, len(upload_list))
+    print "retries: %i payload: %i" % (nRetries, NWPROG_PKT_SIZE)
+
+    for t in range(0, nRetries):
+        for i in range(0, len(upload_list)):
+            remote, tries_left = upload_list[i]
+            if tries_left <= 0: continue
+            print "%sing %s, %i tries remaining ..." % (cmd, remote, tries_left)
+            try:
+                s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
+                if not cmd_fn(imgNum, appFile):
+                    upload_list[i] = (remote, tries_left - 1)
+                else:
+                    upload_list[i] = (remote, -1)
+                    print "Success!"
+                s.close()
+            except KeyboardInterrupt:
+                print "Interrupted; exiting"
+                sys.exit(2)
+            except Exception, e:
+                print "Received unexpected exception while programming"
+                print str(e)
+                s.close()
+                pass
+
+    printedHeading = False
+    if dudFile != None:
+        dudFp = open(dudFile, "w")
+    else: dudFp = sys.stdout
+    
+    for i in range(0, len(upload_list)):
+        remote, tries_left = upload_list[i]
+        if tries_left == 0 and not printedHeading:
+            printedHeading = True
+            print "WARNING: not all motes were succesfully %sed!" % cmd
+        if tries_left == 0:
+            print >>dudFp, remote
+
+    if dudFp != sys.stdout:
+        dudFp.close()
index 885eabeaa5999f065455917d39a0708cfdca395b..22af233e0c3f68df6ea8fef22d46380e77a205a0 100644 (file)
@@ -5,7 +5,7 @@
 tos-storage-at45db - Generate storage volume description code
 .SH SYNOPSIS
 
-\fBtos-storage-at45db\fR [\fB-t\fR] \fIplatform-directory\fR
+\fBtos-storage-at45db\fR [\fB-t\fR] [\fB-s\fR <sector size>] [\fB-f\fR <flash size in sectors>] \fIplatform-directory\fR
 .SH DESCRIPTION
 
 \fBtos-storage-at45db\fR reads a user specification describing the layout
@@ -15,6 +15,8 @@ user specification is in XML and is read from standard input. With all options,
 the code for a header file is written to standard output.  With the 
 optional \fB-t\fR flag specified, a VolumeMapC.nc file is generated that provides 
 interfaces to all the storage volume abstractions defined in the XML file.
+The optional \fB-s\fR flag specifies the sector size on the flash, the default is 256.
+The optional \fB-f\fR flag specifies the total number of sectors on the flash, the default is 2048.
 
 The mandatory \fIplatform-directory\fR argument should specify the platform 
 directory for the current compilation target; this is necessary for the correct 
index 73bb63a9617d5c5311259e288fdcab463ad5a0cc..614c4107cd3f9dcdd18ee4554eaa6482324cf36b 100644 (file)
@@ -18,15 +18,22 @@ import string
 import commands
 #New way of handling arguments........
 try:
-  opts, args = getopt(argv[1:], "t", [])
+  opts, args = getopt(argv[1:], "ts:f:", [])
 except GetoptError, err:
   print str(err) # will print something like "option -a not recognized"
-  stderr.write("Usage: tos-storage-at45db [-t] <platform directory>\n")
+  stderr.write("Usage: tos-storage-at45db [-t] [-s <sector size>] [-f <flash size in sectors>] <platform directory>\n")
   
+sector_size = 256
+flash_size = 2048 # in sectors
+
 cthreads = False
 for o, a in opts:
   if o == "-t":
     cthreads = True
+  elif o == "-s":
+    sector_size = int(a)
+  elif o == "-f":
+    flash_size = int(a)
   else:
     assert False, "unhandled option"
 
@@ -45,9 +52,6 @@ def nfail(s):
   stderr.write(s + "\n")
   exit(2)
 
-sector_size = 256
-flash_size = 2048 # in sectors
-
 volumes = {}
 volmap = []
 volumeNames = []
@@ -229,8 +233,8 @@ if cthreads == True:
   outFile.write("    interface BlockWrite[uint8_t volume_id]; \n")
   outFile.write("    interface LogRead[uint8_t volumeId]; \n")
   outFile.write("    interface LogWrite[uint8_t volumeId]; \n")
-  outFile.write("    interface Mount[uint8_t volumeId]; \n")
-  outFile.write("    interface ConfigStorage[uint8_t volumeId]; \n")
+  outFile.write("    interface Mount[uint8_t volumeId]; \n")
+  outFile.write("    interface ConfigStorage[uint8_t volumeId]; \n")
   outFile.write("  } \n")
   outFile.write("} \n")
   outFile.write("\n")
@@ -241,6 +245,8 @@ if cthreads == True:
   outFile.write("  BlockWrite = VolumeMapP; \n")
   outFile.write("  LogRead = VolumeMapP; \n")
   outFile.write("  LogWrite = VolumeMapP; \n")
+  outFile.write("  Mount = VolumeMapP; \n")
+  outFile.write("  ConfigStorage = VolumeMapP; \n")
 
   for i in range(len(volumeNames)):
     if volumeTypes[volumeNames[i]] == "block":
@@ -257,9 +263,8 @@ if cthreads == True:
       outFile.write("  VolumeMapP.SubLogWrite[" + volumeNames[i] + "] -> LogStorageC_" + volumeNames[i] + "; \n")
       outFile.write("\n")
 
-    elif volumeTypes[volumeNames[i]] == "config":
-      outFile.write("  components new ConfigStorageC(" + volumeNames[i] + ") as ConfigStorageC_" + volumeNames[i] + "; \n")
-      outFile.write("  Mount[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
-      outFile.write("  ConfigStorage[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
+    elif volumeTypes[volumeNames[i]] == "config":
+      outFile.write("  components new ConfigStorageC(" + volumeNames[i] + ") as ConfigStorageC_" + volumeNames[i] + "; \n")
+      outFile.write("  Mount[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
+      outFile.write("  ConfigStorage[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
   outFile.write("} \n")
-
index a82efd54f75aa90f8298ff1de6568f11727d5812..44808e3f02582506a9ac7a57e3cd062afe3759ec 100755 (executable)
@@ -200,8 +200,8 @@ if cthreads == True:
   outFile.write("    interface BlockWrite[uint8_t volume_id]; \n")
   outFile.write("    interface LogRead[uint8_t volumeId]; \n")
   outFile.write("    interface LogWrite[uint8_t volumeId]; \n")
-#   outFile.write("    interface Mount[uint8_t volumeId]; \n")
-#   outFile.write("    interface ConfigStorage[uint8_t volumeId]; \n")
+   outFile.write("    interface Mount[uint8_t volumeId]; \n")
+   outFile.write("    interface ConfigStorage[uint8_t volumeId]; \n")
   outFile.write("  } \n")
   outFile.write("} \n")
   outFile.write("\n")
@@ -212,6 +212,8 @@ if cthreads == True:
   outFile.write("  BlockWrite = VolumeMapP; \n")
   outFile.write("  LogRead = VolumeMapP; \n")
   outFile.write("  LogWrite = VolumeMapP; \n")
+  outFile.write("  Mount = VolumeMapP; \n")
+  outFile.write("  ConfigStorage = VolumeMapP; \n")
 
   for i in range(len(volumeNames)):
     if volumeTypes[volumeNames[i]] == "block":
@@ -228,8 +230,8 @@ if cthreads == True:
       outFile.write("  VolumeMapP.SubLogWrite[" + volumeNames[i] + "] -> LogStorageC_" + volumeNames[i] + "; \n")
       outFile.write("\n")
 
-#     elif volumeTypes[volumeNames[i]] == "config":
-#       outFile.write("  components new ConfigStorageC(" + volumeNames[i] + ") as ConfigStorageC_" + volumeNames[i] + "; \n")
-#       outFile.write("  Mount[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
-#       outFile.write("  ConfigStorage[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
+     elif volumeTypes[volumeNames[i]] == "config":
+       outFile.write("  components new ConfigStorageC(" + volumeNames[i] + ") as ConfigStorageC_" + volumeNames[i] + "; \n")
+       outFile.write("  Mount[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
+       outFile.write("  ConfigStorage[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
   outFile.write("} \n")
index 39e9550f6ba829af930028b6a2a533943243edf8..ed9eb63aa6c65acc36a61bd2a61e4b406feb9941 100644 (file)
@@ -320,8 +320,8 @@ if cthreads == True:
   outFile.write("    interface BlockWrite[uint8_t volume_id]; \n")
   outFile.write("    interface LogRead[uint8_t volumeId]; \n")
   outFile.write("    interface LogWrite[uint8_t volumeId]; \n")
-  outFile.write("    interface Mount[uint8_t volumeId]; \n")
-  outFile.write("    interface ConfigStorage[uint8_t volumeId]; \n")
+  outFile.write("    interface Mount[uint8_t volumeId]; \n")
+  outFile.write("    interface ConfigStorage[uint8_t volumeId]; \n")
   outFile.write("  } \n")
   outFile.write("} \n")
   outFile.write("\n")
@@ -332,6 +332,8 @@ if cthreads == True:
   outFile.write("  BlockWrite = VolumeMapP; \n")
   outFile.write("  LogRead = VolumeMapP; \n")
   outFile.write("  LogWrite = VolumeMapP; \n")
+  outFile.write("  Mount = VolumeMapP; \n")
+  outFile.write("  ConfigStorage = VolumeMapP; \n")
 
   for i in range(len(volumeNames)):
     if volumeTypes[volumeNames[i]] == "block":
@@ -348,8 +350,8 @@ if cthreads == True:
       outFile.write("  VolumeMapP.SubLogWrite[" + volumeNames[i] + "] -> LogStorageC_" + volumeNames[i] + "; \n")
       outFile.write("\n")
 
-    elif volumeTypes[volumeNames[i]] == "config":
-      outFile.write("  components new ConfigStorageC(" + volumeNames[i] + ") as ConfigStorageC_" + volumeNames[i] + "; \n")
-      outFile.write("  Mount[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
-      outFile.write("  ConfigStorage[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
+    elif volumeTypes[volumeNames[i]] == "config":
+      outFile.write("  components new ConfigStorageC(" + volumeNames[i] + ") as ConfigStorageC_" + volumeNames[i] + "; \n")
+      outFile.write("  Mount[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
+      outFile.write("  ConfigStorage[" + volumeNames[i] + "] = ConfigStorageC_" + volumeNames[i] + "; \n")
   outFile.write("} \n")
index 4fcc05b11a0ccf8a313269103b6e06d08f9f6c4b..88fba77e2fd5251285eef8f7fd1337c48a24c346 100644 (file)
@@ -70,7 +70,7 @@ def packagename(elem):
   loc = elem.getAttribute("loc")
   colon = index(loc, ":")
   filename = canonicalise(loc[colon + 1:])
-  for dir in topdirs:
+  for dir in topdir:
     dirlen = len(dir)
     if filename[0:dirlen] == dir:
       filename = filename[dirlen:]
@@ -104,14 +104,32 @@ def canonicalisedir(dirname):
     return dirname
 
 # option processing. See usage string for details.
-(opts, args) = getopt(argv[1:], "t:", [ "topdir=", "preserve", "app", "quiet" ])
-topopts = filter(lambda (x): x[0] != "--preserve" and x[0] != "--app" and x[0] != "--quiet", opts)
-preserve = filter(lambda(x): x[0] == "--preserve", opts) != []
-app = filter(lambda(x): x[0] == "--app", opts) != []
-quiet = filter(lambda(x): x[0] == "--quiet", opts) != []
-topdirs = map(lambda (x): canonicalisedir(x[1]), topopts)
+def process_opts(argv):
+  options = {
+    "topdir":   (True,  lambda (x): topdir + [canonicalisedir(x)]),
+    "preserve":         (False, lambda x: True),
+    "app":      (False, lambda x: True),
+    "quiet":    (False, lambda x: True),
+  }
+  getopt_args = []
+  for p in options:
+    globals()[p] = False
+    opt = p
+    if options[p][0]:
+      opt += "="
+    getopt_args += [ opt ]
+  (opts, args) = getopt(argv, "", getopt_args)
+  topdir = []
+  highlight = ""
+  for o, a in opts:
+    opt = o[2:]
+    globals()[opt] = options[opt][1](a)
+  return args
+
+args = process_opts(argv[1:])
 if len(args) != 1:
   usage()
+  exit(2)
 
 repository = args[0]
 try:
index 03e7c67ffcd1bb1464d42dfc186643b372c6c249..ba4b0631aa77ff7efecb0d6424ebe8422aa7cb22 100644 (file)
@@ -12,7 +12,7 @@ TinyOS 1.x usage:
 TinyOS 2.x: collect documentation from a program:
 .br
 \fBnesdoc\fR -o \fIdocumentation-directory\fR [\fB-preserve\fR]
-       [\fB-new\fR] [\fB-quiet\fR] [\fB-target=\fIplatform\fR] [\fB-topdir=\fIdirectory\fR]
+       [\fB-new\fR] [\fB-quiet\fR] [\fB-target=\fIplatform\fR] [\fB-topdir=\fIdirectory\fR] [\fB-app\fR] 
        [\fIncc-options\fR] \fIfiles...\fR
 
 TinyOS 2.x: generate nesdoc HTML pages:
@@ -77,7 +77,10 @@ Specify directory paths that should be stripped from the source file names
 when generating "package names" for the documentation files.  The directory
 above \fBTOSDIR\fR is automatically added, so this option is only needed for
 directories outside the main TinyOS distribution.
-
+.TP
+\fB-app\fR
+Also generate a graph for the whole application in the current directory -
+this is useful to check the wiring of a particular application.
 .SH SEE ALSO
 
 .IR ncc (1)
index eaad3cbd0c925ce4a3095307dd1a15470402215f..8c76fbc4a4f3d25621fba0cfc227be4f523203b1 100644 (file)
@@ -68,7 +68,7 @@ for ($i = 0; $i <= $#ARGV; $i++) {
     $_ = $ARGV[$i];
     if (/^-/) {
        if (/^-topdir=(.*)/) {
-            push @archive_args, $1;
+            push @archive_args, "--topdir=$1";
            $strip = 1;
        }
        elsif (/^--version$/) {
diff --git a/tools/tinyos/safe/.cvsignore b/tools/tinyos/safe/.cvsignore
new file mode 100644 (file)
index 0000000..282522d
--- /dev/null
@@ -0,0 +1,2 @@
+Makefile
+Makefile.in
index b3b17b02b6648fb4ae1f4017b72648979e29ac58..4f7772107ba6c7930c6a1f3bc4583d46a2745b35 100644 (file)
@@ -1,5 +1,5 @@
 AUTOMAKE_OPTIONS = foreign
 
-dist_man_MANS = tos-decode-flid.1
+dist_man_MANS = tos-decode-flid.1 tos-ramsize.1
 
-bin_SCRIPTS = tos-decode-flid
+bin_SCRIPTS = tos-decode-flid tos-ramsize
diff --git a/tools/tinyos/safe/tos-ramsize b/tools/tinyos/safe/tos-ramsize
new file mode 100755 (executable)
index 0000000..023e88e
--- /dev/null
@@ -0,0 +1,1710 @@
+#!/usr/bin/perl -w
+
+# Copyright (c) 2003-2009 University of Utah and the Flux Group.
+# All rights reserved.
+# 
+# Permission to use, copy, modify, distribute, and sell this software
+# and its documentation is hereby granted without fee, provided that the
+# above copyright notice and this permission/disclaimer notice is
+# retained in all copies or modified versions, and that both notices
+# appear in supporting documentation.  THE COPYRIGHT HOLDERS PROVIDE
+# THIS SOFTWARE "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES,
+# INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE COPYRIGHT
+# HOLDERS DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER
+# RESULTING FROM THE USE OF THIS SOFTWARE.
+# 
+# Users are requested, but not required, to send to csl-dist@cs.utah.edu
+# any improvements that they make and grant redistribution rights to the
+# University of Utah.
+# 
+# Author: John Regehr (regehr@cs.utah.edu)
+# Revised by: Xuejun Yang on 01/10/2009 
+
+# For more information:
+#   http://docs.tinyos.net/index.php/Stack_Analysis
+
+use strict;
+use warnings;
+use Getopt::Long;
+
+# TODO: 
+#
+# support TOSThreads
+#
+# support msp430
+#
+# optionally don't do recursion checking
+#
+# print path to WC stack depth, perhaps graphically
+#
+# make it possible to specify chips individually
+#
+# make it possible to explicitly specify which interrupts are atomic
+# or not
+#
+# tighten results by keeping track of depths inside and out of
+# atomic sections
+#
+# print stack used at thread blocking points
+#
+# support overriding the default heuristic for detecting atomic
+# interrupts
+#
+# get rid of hard-coded non-terminating functions, just derive this
+# when no "ret" is executed
+#
+# test for tightness / soundness using randprog + Avrora
+#
+# read config info from a file
+#   chip parameters
+#   libc information
+#   recursion and interrupt info
+
+##########################################################################
+
+my %VEC_SIZE = (
+    "mica2" => 4,
+    "micaz" => 4,
+    "iris" => 4,
+    );
+
+my %PC_SIZE = (
+    "mica2" => 2,
+    "micaz" => 2,
+    "iris" => 2,
+    );
+
+my %NUM_VECTORS = (
+    "mica2" => 35,
+    "micaz" => 35,
+    "iris" => 51,
+    );
+
+my %RAM_SIZE = (
+    "mica2" => 4096,
+    "micaz" => 4096,
+    "iris" => 8192,
+    );
+
+my %DEV_SIZE = (
+    "mica2" => 256,
+    "micaz" => 256,
+    "iris" => 512,
+    );
+
+my %NORETURN = (
+    "deputy_fail_noreturn_fast" => 1,
+    );
+
+# any icall in the function on the left is assumed to go to the
+# function on the right
+my %ICALL_TARGETS = (
+    "fputc" => "uart_putchar",
+    "puts" => "uart_putchar",
+    );    
+
+# also look below for __prologue_saves__ and __epilogue_restores__
+my %SPECIAL = (
+
+    "TinyThreadSchedulerP__switchThreads" => 10,
+
+    # these have icalls
+    #"__eewr_block" => 35,
+    #"__eerd_block" => 35,
+
+    # these peel a return address off the stack before calling into a
+    # function that returns to the caller's caller
+    "__fp_split1" => 0,
+    "__fp_split2" => 0,
+    "__fp_split3" => 0,
+    "__fp_split_a" => 0,
+    );
+
+##########################################################################
+
+my $verbosity = 1;
+
+my $ORIGIN = 0;
+my $ZERO_STACK = -999999;
+
+my $platform;
+my %insns;
+my %args;
+my %addr_to_label;
+my %label_to_addr;
+my %lines;
+my %line_to_addr;
+my %stack_effect;
+my %successors;
+my %call_targets;
+my %insn_size;
+my %diehere;
+my %raw_text;
+my %jump_lists;
+my $initial_stack_depth;
+
+sub bynum {
+    return $a <=> $b;
+}
+
+sub parse_pair ($) {
+    (my $pair) = @_;
+    if ($pair =~ /^([a-zA-Z0-9]+)\, ([a-zA-Z0-9\+]+)$/) {
+       return ($1, $2);
+    } else {
+       die "tos-ramsize FAIL: expected 'x, y' got '$pair'";
+    }
+}
+
+sub get_relative_address ($) {
+    (my $addr) = @_;
+    my $code = $args{$addr};
+    die "tos-ramsize FAIL" if (!($code =~ /.(\-?[0-9]+)/));
+    return 2+$1;
+}
+
+sub add_insn ($$$$) {
+    (my $addr, my $code, my $size, my $linenum) = @_;
+    if (($code =~ /^([a-zA-Z]+)\s*(.*)?$/)) { 
+       if ($verbosity > 7) {
+           print "$code\n";
+       }
+       $line_to_addr{$linenum} = $addr; 
+       my $insn = $1;
+       my $arg = $2;
+       $insns{$addr} = $insn;
+       $args{$addr} = $arg;
+       
+       if ($verbosity > 7) {
+           print "'$insn' '$arg' @ $addr\n";
+       }
+
+       $insn_size{$addr} = $size;
+    } else {
+       if ($verbosity > 7) {
+           print "???? $code\n";
+       }
+    }
+}
+
+sub disassemble ($) {
+    (my $fn) = @_;
+    open INF, "avr-objdump -zsD $fn |" or die "tos-ramsize FAIL: can't open input file $fn";
+    my $linenum = 0;
+    my $text_go = 0;
+    my $raw_text_go = 0;
+    my $raw_addr;
+    
+    while (my $line = <INF>) {
+       chomp $line;
+
+       $linenum++;
+       $lines{$linenum} = $line;
+
+       if ($line =~ m/Disassembly of section \.text/) {
+           $text_go = 1;
+           $raw_text_go = 0;
+           next;
+       }
+
+       if ($line =~ m/Contents of section \.text/) {
+           $text_go = 0;
+           $raw_text_go = 1;
+           next;
+       }
+
+       if ($line =~ m/Contents of section /) {
+           $text_go = 0;
+           $raw_text_go = 0;
+           next;
+       }
+
+       if ($line =~ m/Disassembly of section /) {
+           $text_go = 0;
+           $raw_text_go = 0;
+           next;
+       }
+
+       # skip blank line and obvious junk
+       next if ($line eq "" or $line =~ /^\s*\.*$/);
+       
+       # kill comments
+       ($line =~ s/\s*;.*$//);
+       
+       if ($verbosity > 7) {
+           print "$line\n";
+       }
+
+       if ($raw_text_go) {
+           $line = substr $line, 0, 43;
+           $line .= " ";
+           if ($line =~ /^\s*([0-9a-f]{4}) ((([0-9a-f][0-9a-f]){1,4} ){1,4})\s*$/) {
+               my $address = hex($1);
+               my $bytes = $2;
+               if (!defined($raw_addr)) {
+                   $raw_addr = $address;
+               } else {
+                   die "tos-ramsize FAIL" if ($raw_addr != $address);
+               }
+               ($bytes =~ s/\s//g);
+               while (length($bytes)>0) {
+                   die "tos-ramsize FAIL" if (length($bytes)==1);
+                   my $b = substr $bytes, 0, 2;
+                   $bytes = substr $bytes, 2, length($bytes)-2;
+                   $raw_text{$raw_addr} = $b;
+                   $raw_addr++;
+               }
+           } else {
+               print "cannot parse raw text: '$line'\n";
+               die "tos-ramsize FAIL";
+           }
+       }
+       
+       if ($text_go) {
+           # label
+           if ($line =~ /^0*([0-9a-f]+) <(.+)>:$/) {
+               my $addr = hex($1);
+               my $label = $2;
+               $addr_to_label{$addr} = $label;
+               $label_to_addr{$label} = $addr;
+               next;
+           }
+           
+           # data in code segment
+           if ($line =~ /^\s+([0-9a-f]+):\s+([0-9a-fA-F][0-9a-fA-F] ){16}\s+/) {
+               next;
+           }
+           
+           # regular code
+           
+           my $a;
+           my $code;
+
+           if ($line =~ /^\s+([0-9a-f]+):\s+([0-9a-f][0-9a-f]\s){4}\s*(.*)$/) {
+               $a = hex($1);
+               $code = $3;
+               add_insn ($a, $code, 4, $linenum);
+               next;
+           }
+           
+           if ($line =~ /^\s+([0-9a-f]+):\s+([0-9a-f][0-9a-f][ \t]){2}\s*(.*)$/) {
+               $a = hex($1);
+               $code = $3;
+               add_insn ($a, $code, 2, $linenum);
+               next;
+           }
+           
+           # paranoid: don't ignore lines that look funny
+           die "tos-ramsize FAIL: can't understand '$line'";
+       }
+    }
+
+    if ($verbosity >= 2) {
+       print "there are:\n";
+       print "  ".scalar(keys %addr_to_label)." labels\n";
+       print "  ".scalar(keys %insns)." instructions\n";
+    }
+    
+    close INF;
+}
+
+sub is_branch ($) {
+    (my $addr) = @_;
+    my $insn = $insns{$addr};
+    return ($insn eq "breq" || $insn eq "brge" || $insn eq "brne" ||
+           $insn eq "brcs" || $insn eq "brcc" || $insn eq "brlt" ||
+           $insn eq "brhc" || $insn eq "brhs" || $insn eq "brid" ||
+           $insn eq "brie" || $insn eq "brmi" || $insn eq "brpl" ||
+           $insn eq "brtc" || $insn eq "brts" || $insn eq "brvc" ||
+           $insn eq "brvs" || $insn eq "brbc" || $insn eq "brbs");
+}
+
+sub is_skip ($) {
+    (my $addr) = @_;
+    my $insn = $insns{$addr};
+    return ($insn eq "sbrs" || $insn eq "sbrc" || $insn eq "cpse" ||
+           $insn eq "sbic" || $insn eq "sbis");
+}
+
+sub is_fallthrough ($) {
+    (my $addr) = @_;
+    my $insn = $insns{$addr};
+    return (
+       $insn eq "prologue_saves" || $insn eq "epilogue_restores" ||
+       $insn eq "init_sp" || $insn eq "constant_push" || $insn eq "constant_pop" ||
+       $insn eq "adc" || $insn eq "add" || $insn eq "adiw" ||
+       $insn eq "and" || $insn eq "andi" || $insn eq "asr" ||
+       $insn eq "bld" || $insn eq "break" || $insn eq "bst" ||
+       $insn eq "cbi" || $insn eq "clh" || $insn eq "cli" ||
+       $insn eq "cln" || $insn eq "cls" || $insn eq "clt" ||
+       $insn eq "clv" || $insn eq "clz" || $insn eq "com" ||
+       $insn eq "cp" || $insn eq "cpc" || $insn eq "cpi" ||
+       $insn eq "dec" || $insn eq "elpm" || $insn eq "eor" ||
+       $insn eq "fmul" || $insn eq "fmuls" || $insn eq "fmulsu" ||
+       $insn eq "in" || $insn eq "inc" || $insn eq "ldi" ||
+       $insn eq "lpm" || $insn eq "lsr" || $insn eq "mov" ||
+       $insn eq "movw" || $insn eq "mul" || $insn eq "muls" ||
+       $insn eq "mulsu" || $insn eq "neg" || $insn eq "nop" ||
+       $insn eq "or" || $insn eq "ori" || $insn eq "out" ||
+       $insn eq "pop" || $insn eq "push" || $insn eq "ror" ||
+       $insn eq "sbc" || $insn eq "sbci" || $insn eq "sbi" ||
+       $insn eq "sbiw" || $insn eq "seh" || $insn eq "sei" ||
+       $insn eq "sen" || $insn eq "ses" || $insn eq "set" ||
+       $insn eq "sev" || $insn eq "sez" || $insn eq "sleep" ||
+       $insn eq "spm" || $insn eq "sub" || $insn eq "subi" ||
+       $insn eq "swap" || $insn eq "wdr" || $insn eq "ld" ||
+       $insn eq "ldd" || $insn eq "sec" || $insn eq "st" ||
+       $insn eq "std" || $insn eq "lds" || $insn eq "sts"
+       );
+}
+
+sub is_jmp ($) {
+    (my $addr) = @_;
+    my $insn = $insns{$addr};
+    return ($insn eq "jmp" || $insn eq "rjmp");
+}
+
+sub is_direct_call ($) {
+    (my $addr) = @_;
+    my $insn = $insns{$addr};
+    return ($insn eq "call" || $insn eq "rcall");
+}
+
+sub insn_stack_effects () {
+    foreach my $addr (keys %insns) {
+       my $insn = $insns{$addr};
+       if ($insn eq "push") {
+           $stack_effect{$addr} = 1;
+       } elsif ($insn eq "pop") {
+           $stack_effect{$addr} = -1;
+       } elsif ($insn eq "ret" || $insn eq "reti") {
+           $stack_effect{$addr} = -$PC_SIZE{$platform};
+       } else {
+           $stack_effect{$addr} = 0;
+       }
+    }
+}
+
+sub make16($$) {
+    (my $l, my $h) = @_;
+    return (hex($h) << 8) + hex($l);
+}
+
+sub jmp_call_target ($) {
+    (my $addr) = @_;
+    die "tos-ramsize FAIL" if ($insns{$addr} ne "jmp" && $insns{$addr} ne "call");
+    my $code = $args{$addr};
+    die "tos-ramsize FAIL" if (!($code =~ /0x([0-9a-f]+)/) && $code != 0);
+    if (($code =~ /0x([0-9a-f]+)/)) {
+       return hex ($1);
+    } else {
+       return 0;
+    }
+}
+
+sub get_target ($) {
+    (my $addr) = @_;
+    my $insn = $insns{$addr};
+    my $hex_addr = sprintf "%x", $addr;
+    
+    if (is_jmp ($addr) || is_direct_call ($addr)) {
+        if ($insn eq "rjmp" || $insn eq "rcall") {
+            return $addr + get_relative_address ($addr);
+        } else {
+           return jmp_call_target ($addr);
+        }
+    }
+
+    if (is_branch ($addr)) {
+       return $addr + get_relative_address ($addr);
+    }
+
+    # skip size depends on size of subsequent insn
+    if (is_skip ($addr)) {
+       die "tos-ramsize FAIL: $hex_addr" if (!defined($insn_size{$addr}));
+       my $next = $addr + $insn_size{$addr};
+       if (!defined($insn_size{$next})) {
+           return $next + 2;
+       } else {
+           return $next + $insn_size{$next};
+       }
+    }
+
+    die "tos-ramsize FAIL";
+}
+
+sub match_branch ($$) {
+    (my $addr, my $instruction) = @_;
+    if (defined($insns{$addr}) && $insns{$addr} eq $instruction) { 
+       return (1, get_target ($addr));
+    } else {
+       return (0, 0);
+    }
+}
+
+sub match_2args ($$) {
+    (my $addr, my $instruction) = @_;
+    if (defined($insns{$addr}) && $insns{$addr} eq $instruction) { 
+        (my $a, my $b) = parse_pair ($args{$addr});
+       return (1, $a, $b);
+    } else {
+       return (0, 0, 0);
+    }
+}
+
+sub match_0args ($$) {
+    (my $addr, my $instruction) = @_;
+    if (defined($insns{$addr}) && $insns{$addr} eq $instruction) { 
+       return 1;
+    } else {
+       return 0;
+    }
+}
+
+# ldi  r28, 0xFF       ; 255
+# ldi  r29, 0x21       ; 33
+# out  0x3e, r29       ; 62
+# out  0x3d, r28       ; 61
+
+sub match_init_sp ($) {
+    (my $addr) = @_;
+    my $match;
+    my $reg;
+    my $immed;
+    ($match, $reg, my $sp_lo) = match_2args ($addr, "ldi");
+    return (0,0,0) if (!$match || $reg ne "r28");
+    ($match, $reg, my $sp_hi) = match_2args ($addr+2, "ldi");
+    return (0,0,0) if (!$match || $reg ne "r29");
+    ($match, $immed, $reg) = match_2args ($addr+4, "out");
+    return (0,0,0) if (!$match || $reg ne "r29" || $immed ne "0x3e");
+    ($match, $immed, $reg) = match_2args ($addr+6, "out");
+    return (0,0,0) if (!$match || $reg ne "r28" || $immed ne "0x3d");
+    my $init = make16($sp_lo,$sp_hi);
+    my $init_stack = $RAM_SIZE{$platform} + $DEV_SIZE{$platform} - $init - 1;
+    if ($verbosity > 3) {
+       print "init = $sp_lo $sp_hi = $init = ${init_stack}\n";
+    }
+    return (1,8,$init_stack);
+}
+
+# cpi  r30, 0x12       ; 18
+# cpc  r31, r1
+# brcs .+2             ; 0x1a88 <SchedulerBasicP_xx_TaskBasic_xx_runTask+0x3e>
+# rjmp .+2218          ; 0x2332 <SchedulerBasicP_xx_TaskBasic_xx_runTask+0x8e8>
+# subi r30, 0xBA       ; 186
+# sbci r31, 0xFF       ; 255
+# add  r30, r30
+# adc  r31, r31
+# lpm  r0, Z+
+# lpm  r31, Z
+# mov  r30, r0
+# ijmp
+
+# cpi  r16, 0x80       ; 128
+# cpc  r17, r1
+# brcs .+2             ; 0x13ec <__stack+0x2ed>
+# rjmp .+148           ; 0x1480 <__stack+0x381>
+# subi r16, 0xBA       ; 186
+# sbci r17, 0xFF       ; 255
+# movw r30, r16
+# add  r30, r30
+# adc  r31, r31
+# lpm  r0, Z+
+# lpm  r31, Z
+# mov  r30, r0
+# ijmp
+
+# cpi  r30, 0x1E       ; 30
+# cpc  r31, r1
+# brcc .+78            ; 0x19ce <main+0x626>
+# subi r30, 0xBA       ; 186
+# sbci r31, 0xFF       ; 255
+# add  r30, r30
+# adc  r31, r31
+# lpm  r0, Z+
+# lpm  r31, Z
+# mov  r30, r0
+# ijmp
+
+# cpi  r26, 0x48       ; 72
+# cpc  r27, r1
+# brcc .+38            ; 0x1954 <__stack+0x855>
+# subi r26, 0xBA       ; 186
+# sbci r27, 0xFF       ; 255
+# movw r30, r26
+# add  r30, r30
+# adc  r31, r31
+# lpm  r0, Z+
+# lpm  r31, Z
+# mov  r30, r0
+# ijmp
+
+sub match_jump_table_1 ($) {
+    (my $addr) = @_;
+    my $match;
+    my $reg1;
+    my $reg2;
+    my $immed;
+    my $oob_target;
+    my @targets;
+    my $inc = 0;
+
+    ($match, $reg1, my $table_size) = match_2args ($addr+$inc, "cpi");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 2;
+    
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "cpc");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 2;
+
+    ($match, $immed) = match_branch ($addr+$inc, "brcs");
+    if ($match) {
+       $inc += 2;
+       ($match, $oob_target) = match_branch ($addr+$inc, "rjmp");
+       return (0, \@targets, 0) if (!$match);
+       $inc += 2;
+    } else {
+       ($match, $oob_target) = match_branch ($addr+$inc, "brcc");
+       return (0, \@targets, 0) if (!$match);  
+       $inc += 2;
+    }
+
+    ($match, $reg1, my $sublo) = match_2args ($addr+$inc, "subi");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 2;
+
+    ($match, $reg1, my $subhi) = match_2args ($addr+$inc, "sbci");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "movw");
+    if ($match) {
+       $inc += 2;
+    }
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "add");
+    return (0, \@targets, 0) if (!$match);    
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "adc");
+    return (0, \@targets, 0) if (!$match);    
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "lpm");
+    return (0, \@targets, 0) if (!$match || $reg1 ne "r0" || $reg2 ne "Z+");    
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "lpm");
+    return (0, \@targets, 0) if (!$match || $reg1 ne "r31" || $reg2 ne "Z");    
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "mov");
+    return (0, \@targets, 0) if (!$match || $reg1 ne "r30" || $reg2 ne "r0");    
+    $inc += 2;
+
+    if (match_0args ($addr+$inc, "ijmp")) {
+       $inc += 2;
+       push @targets, $oob_target;
+       if ($verbosity > 3) {
+           printf "found a jump table of size %d\n", hex($table_size);
+       }
+       for (my $i=0; $i<hex($table_size); $i++) {
+           my $index = 2*($i+65536-make16($sublo,$subhi));
+           my $l = $raw_text{$index};
+           my $h = $raw_text{$index+1};
+           my $targ = 2*make16($l,$h);
+           
+           if ($verbosity > 3) {
+               printf "  entry at %x pointing to %x (%s,%s)\n", $index, $targ, $l, $h;
+           }
+           
+           # this is a strong sanity check-- if we've got something
+           # wrong it's highly unlikely that all jump table entries
+           # will point to actual instructions
+           die "tos-ramsize FAIL" if (!defined($insns{$targ}));
+
+           push @targets, $targ;
+       }
+       return (1, \@targets, $inc);
+    } else {
+       return (0, \@targets, 0);
+    }
+}
+
+# cpi  r30, 0x1D       ; 29
+# cpc  r31, r1
+# brcs .+4             ; 0x39d2 <SchedulerBasicP__TaskBasic__runTask+0x38>
+# jmp  0x547c  ; 0x547c <SchedulerBasicP__TaskBasic__runTask+0x1ae2>
+# subi r30, 0xBA       ; 186
+# sbci r31, 0xFF       ; 255
+# add  r30, r30
+# adc  r31, r31
+# lpm  r0, Z+
+# lpm  r31, Z
+# mov  r30, r0
+# ijmp
+
+sub match_jump_table_2 ($) {
+    (my $addr) = @_;
+    my $match;
+    my $reg1;
+    my $reg2;
+    my $immed;
+    my $oob_target;
+    my @targets;
+    my $inc = 0;
+
+    ($match, $reg1, my $table_size) = match_2args ($addr+$inc, "cpi");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 2;
+    
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "cpc");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 2;
+
+    ($match, $immed) = match_branch ($addr+$inc, "brcs");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 2;
+
+    ($match, $oob_target) = match_branch ($addr+$inc, "jmp");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 4;
+
+    ($match, $reg1, my $sublo) = match_2args ($addr+$inc, "subi");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 2;
+
+    ($match, $reg1, my $subhi) = match_2args ($addr+$inc, "sbci");
+    return (0, \@targets, 0) if (!$match);
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "movw");
+    if ($match) {
+       $inc += 2;
+    }
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "add");
+    return (0, \@targets, 0) if (!$match);    
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "adc");
+    return (0, \@targets, 0) if (!$match);    
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "lpm");
+    return (0, \@targets, 0) if (!$match || $reg1 ne "r0" || $reg2 ne "Z+");    
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "lpm");
+    return (0, \@targets, 0) if (!$match || $reg1 ne "r31" || $reg2 ne "Z");    
+    $inc += 2;
+
+    ($match, $reg1, $reg2) = match_2args ($addr+$inc, "mov");
+    return (0, \@targets, 0) if (!$match || $reg1 ne "r30" || $reg2 ne "r0");    
+    $inc += 2;
+
+    if (match_0args ($addr+$inc, "ijmp")) {
+       $inc += 2;
+       push @targets, $oob_target;
+       if ($verbosity > 3) {
+           printf "found a jump table of size %d\n", hex($table_size);
+       }
+       for (my $i=0; $i<hex($table_size); $i++) {
+           my $index = 2*($i+65536-make16($sublo,$subhi));
+           my $l = $raw_text{$index};
+           my $h = $raw_text{$index+1};
+           my $targ = 2*make16($l,$h);
+           
+           if ($verbosity > 3) {
+               printf "  entry at %x pointing to %x (%s,%s)\n", $index, $targ, $l, $h;
+           }
+           
+           # this is a strong sanity check-- if we've got something
+           # wrong it's highly unlikely that all jump table entries
+           # will point to actual instructions
+           die "tos-ramsize FAIL" if (!defined($insns{$targ}));
+
+           push @targets, $targ;
+       }
+       return (1, \@targets, $inc);
+    } else {
+       return (0, \@targets, 0);
+    }
+}
+
+# in   r28, 0x3d       ; 61 
+# in   r29, 0x3e       ; 62
+# subi r28, 0x9D       ; 157
+# sbci r29, 0x00       ; 0
+# in   r0, 0x3f        ; 63
+# cli
+# out  0x3e, r29       ; 62
+# out  0x3f, r0        ; 63
+# out  0x3d, r28       ; 61
+
+# in   r28, 0x3d       ; 61
+# in   r29, 0x3e       ; 62
+# sbiw r28, 0x14       ; 20
+# in   r0, 0x3f        ; 63
+# cli
+# out  0x3e, r29       ; 62
+# out  0x3f, r0        ; 63
+# out  0x3d, r28       ; 61
+
+sub match_constant_push_1 ($) {
+    (my $addr) = @_;
+    my $hex_addr = sprintf "%x", $addr;
+    my $match;
+    my $reg;
+    my $immed;
+    my $dec;
+    my $inc = 0;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0) if (!$match || $reg ne "r28" || $immed ne "0x3d");
+    $inc +=2;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0) if (!$match || $reg ne "r29" || $immed ne "0x3e");
+    $inc +=2;
+
+    ($match, $reg, $dec) = match_2args ($addr+$inc, "sbiw");
+    if ($match && $reg eq "r28") {
+       $dec = hex($dec);
+       $inc +=2;
+    } else {
+       ($match, $reg, my $dec1) = match_2args ($addr+$inc, "subi");
+       return (0, 0) if (!$match || $reg ne "r28");
+       $inc +=2;
+
+       ($match, $reg, my $dec2) = match_2args ($addr+$inc, "sbci");
+       return (0, 0) if (!$match || $reg ne "r29");    
+       $inc +=2;
+
+       $dec = make16($dec1,$dec2);
+    }
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0) if (!$match || $reg ne "r0" || $immed ne "0x3f");
+    $inc +=2;
+
+    return (0, 0) if (!match_0args($addr+$inc, "cli"));
+    $inc +=2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0) if (!$match || $reg ne "r29" || $immed ne "0x3e");
+    $inc +=2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0) if (!$match || $reg ne "r0" || $immed ne "0x3f");
+    $inc +=2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0) if (!$match || $reg ne "r28" || $immed ne "0x3d");
+    $inc +=2;
+
+    return (1, $dec, $inc);
+}
+
+# in   r28, 0x3d       ; 61
+# in   r29, 0x3e       ; 62
+# sbiw r28, 0x05       ; 5
+# out  0x3e, r29       ; 62
+# out  0x3d, r28       ; 61
+
+sub match_constant_push_2 ($) {
+    (my $addr) = @_;
+    my $hex_addr = sprintf "%x", $addr;
+    my $match;
+    my $reg;
+    my $immed;
+    my $dec;
+    my $inc = 0;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0) if (!$match || $reg ne "r28" || $immed ne "0x3d");
+    $inc +=2;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0) if (!$match || $reg ne "r29" || $immed ne "0x3e");
+    $inc +=2;
+
+    ($match, $reg, $dec) = match_2args ($addr+$inc, "sbiw");
+    return (0, 0) if (!$match || $reg ne "r28");
+    $inc +=2;
+    $dec = hex($dec);
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0) if (!$match || $reg ne "r29" || $immed ne "0x3e");
+    $inc +=2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0) if (!$match || $reg ne "r28" || $immed ne "0x3d");
+    $inc +=2;
+
+    return (1, $dec, $inc);
+}
+
+# rcall        .+0             ; 0x2792 <IPP__icmpv6_input+0x1e>
+
+sub match_constant_push_3 ($) {
+    (my $addr) = @_;
+    my $hex_addr = sprintf "%x", $addr;
+    my $match;
+    my $reg;
+    my $immed;
+    my $dec;
+    my $inc = 0;
+
+    ($match, $reg, $immed) = match_0args ($addr+$inc, "rcall");
+    return (0, 0) if (!$match);
+    return (0, 0) if (get_target($addr) != $addr+$PC_SIZE{$platform});
+    $inc +=2;
+
+    return (1, $PC_SIZE{$platform}, $inc);
+}
+
+# adiw r28, 0x14       ; 20
+# in   r0, 0x3f        ; 63
+# cli
+# out  0x3e, r29       ; 62
+# out  0x3f, r0        ; 63
+# out  0x3d, r28       ; 61
+
+sub match_constant_pop_1 ($) {
+    (my $addr) = @_;
+    my $hex_addr = sprintf "%x", $addr;
+    my $match;
+    my $reg;
+    my $immed;
+    my $dec;
+    my $inc = 0;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "adiw");
+    return (0, 0, 0) if (!$match || $reg ne "r28");
+    $dec = -hex($immed);
+    $inc += 2;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0, 0) if (!$match || $reg ne "r0" || $immed ne "0x3f");
+    $inc += 2;
+
+    return (0, 0, 0) if (!match_0args($addr+$inc, "cli"));
+    $inc += 2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0, 0) if (!$match || $reg ne "r29" || $immed ne "0x3e");
+    $inc += 2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0, 0) if (!$match || $reg ne "r0" || $immed ne "0x3f");
+    $inc += 2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0, 0) if (!$match || $reg ne "r28" || $immed ne "0x3d");
+    $inc += 2;
+
+    return (1, $dec, $inc);
+}
+
+# adiw r28, 0x05       ; 5
+# out  0x3e, r29       ; 62
+# out  0x3d, r28       ; 61
+
+sub match_constant_pop_2 ($) {
+    (my $addr) = @_;
+    my $hex_addr = sprintf "%x", $addr;
+    my $match;
+    my $reg;
+    my $immed;
+    my $dec;
+    my $inc = 0;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "adiw");
+    return (0, 0, 0) if (!$match || $reg ne "r28");
+    $dec = -hex($immed);
+    $inc += 2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0, 0) if (!$match || $reg ne "r29" || $immed ne "0x3e");
+    $inc += 2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0, 0) if (!$match || $reg ne "r28" || $immed ne "0x3d");
+    $inc += 2;
+
+    return (1, $dec, $inc);
+}
+
+# in   r28, 0x3d       ; 61
+# in   r29, 0x3e       ; 62
+# subi r28, 0x9E       ; 158
+# sbci r29, 0xFF       ; 255
+# in   r0, 0x3f        ; 63
+# cli
+# out  0x3e, r29       ; 62
+# out  0x3f, r0        ; 63
+# out  0x3d, r28       ; 61
+
+sub match_constant_stack_op ($) {
+    (my $addr) = @_;
+    my $hex_addr = sprintf "%x", $addr;
+    my $match;
+    my $reg;
+    my $immed;
+    my $inc = 0;
+
+    ($match, $reg, my $dec_lo) = match_2args ($addr+$inc, "subi");
+    return (0, 0, 0) if (!$match || $reg ne "r28");
+    $inc += 2;
+
+    ($match, $reg, my $dec_hi) = match_2args ($addr+$inc, "sbci");
+    return (0, 0, 0) if (!$match || $reg ne "r29");
+    $inc += 2;
+    my $dec = make16($dec_lo,$dec_hi);
+    if ($dec > 32768) {
+       $dec = - (65536 - $dec);
+    }
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0, 0) if (!$match || $reg ne "r0" || $immed ne "0x3f");
+    $inc += 2;
+
+    return (0, 0, 0) if (!match_0args($addr+$inc, "cli"));
+    $inc += 2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0, 0) if (!$match || $reg ne "r29" || $immed ne "0x3e");
+    $inc += 2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0, 0) if (!$match || $reg ne "r0" || $immed ne "0x3f");
+    $inc += 2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0, 0) if (!$match || $reg ne "r28" || $immed ne "0x3d");
+    $inc += 2;
+
+    return (1, $dec, $inc);
+}
+
+# in   r24, 0x3d       ; 61
+# in   r25, 0x3e       ; 62
+# adiw r24, 0x06       ; 6
+# in   r0, 0x3f        ; 63
+# cli
+# out  0x3e, r25       ; 62
+# out  0x3f, r0        ; 63
+# out  0x3d, r24       ; 61
+
+sub match_constant_pop_4 ($) {
+    (my $addr) = @_;
+    my $hex_addr = sprintf "%x", $addr;
+    my $match;
+    my $reg;
+    my $immed;
+    my $stack_inc;
+    my $inc = 0;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0) if (!$match || $reg ne "r24" || $immed ne "0x3d");
+    $inc +=2;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0) if (!$match || $reg ne "r25" || $immed ne "0x3e");
+    $inc +=2;
+
+    ($match, $reg, $stack_inc) = match_2args ($addr+$inc, "adiw");
+    return (0, 0) if (!$match || $reg ne "r24");
+    $stack_inc = -hex($stack_inc);
+    $inc +=2;
+
+    ($match, $reg, $immed) = match_2args ($addr+$inc, "in");
+    return (0, 0) if (!$match || $reg ne "r0" || $immed ne "0x3f");
+    $inc +=2;
+
+    return (0, 0) if (!match_0args($addr+$inc, "cli"));
+    $inc +=2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0) if (!$match || $reg ne "r25" || $immed ne "0x3e");
+    $inc +=2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0) if (!$match || $reg ne "r0" || $immed ne "0x3f");
+    $inc +=2;
+
+    ($match, $immed, $reg) = match_2args ($addr+$inc, "out");
+    return (0, 0) if (!$match || $reg ne "r24" || $immed ne "0x3d");
+    $inc +=2;
+
+    return (1, $stack_inc, $inc);
+}
+
+# ldi  r26, 0x00       ; 0
+# ldi  r27, 0x00       ; 0
+# ldi  r30, 0x97       ; 151
+# ldi  r31, 0x06       ; 6
+# jmp  0x19dc  ; 0x19dc <__prologue_saves__+0x4>
+
+sub match_prologue_saves ($) {
+    (my $addr) = @_;
+    my $hex_addr = sprintf "%x", $addr;
+    my $match;
+    my $reg;
+    my $immed;
+    ($match, $reg, my $im_lo) = match_2args ($addr, "ldi");
+    return (0, 0, 0) if (!$match || $reg ne "r26");
+    ($match, $reg, my $im_hi) = match_2args ($addr+2, "ldi");
+    return (0, 0, 0) if (!$match || $reg ne "r27");
+    ($match, $reg, $immed) = match_2args ($addr+4, "ldi");
+    return (0, 0, 0) if (!$match || $reg ne "r30");
+    ($match, $reg, $immed) = match_2args ($addr+6, "ldi");
+    return (0, 0, 0) if (!$match || $reg ne "r31");
+    ($match, my $target) = match_branch ($addr+8, "jmp");
+    return (0, 0, 0) if (!$match);
+    my $ps = $label_to_addr{"__prologue_saves__"};
+    if (defined($ps) &&
+       $target >= $ps &&
+       $target <= ($ps+38)) {
+       # this is a little conservative since we may jump into the middle
+       my $st = 18+make16($im_lo, $im_hi);
+       return (1, $st, 12);
+    }
+    return (0, 0, 0);
+}
+
+# jmp  0x2598  ; 0x2598 <__epilogue_restores__+0x14>
+
+sub match_epilogue_restores ($) {
+    (my $addr) = @_;
+    my $hex_addr = sprintf "%x", $addr;
+    my $match;
+    my $reg;
+    my $inc = 0;
+
+    ($match, my $target) = match_branch ($addr+$inc, "jmp");
+    return (0,0) if (!$match);
+    my $er = $label_to_addr{"__epilogue_restores__"};
+    if (defined($er) &&
+       $target >= $er &&
+       $target <= ($er+38)) {
+       $addr += 4;
+       return (1, $ZERO_STACK, $inc);
+    } else {
+       return (0,0);
+    }
+}
+
+sub replace_insn ($$$$) {
+    (my $addr, my $size, my $se, my $name) = @_;
+    $insns{$addr} = $name;
+    $insn_size{$addr} = $size;
+    $stack_effect{$addr} = $se;
+    for (my $i=1; $i<$size; $i++) {
+       delete ($insns{$addr+$i});
+    }
+}
+
+sub make_macro_insns () {
+    foreach my $addr (keys %insns) {
+
+       my $res;
+       my $stack;
+       my $listref;
+       my $size;
+
+       # todo-- factor this into list of function 
+
+       ($res, $size, my $initial_depth) = match_init_sp($addr);
+       if ($res) {
+           if (defined($initial_stack_depth)) {
+               # FIXME: avr-gcc-412 initializes SP both in
+               # crt0 and in main(), we can believe the second one
+               #die "tos-ramsize FAIL: multiple initialization of SP?";
+           }
+           die "tos-ramsize FAIL" if ($initial_depth < 0 || $initial_depth >= $RAM_SIZE{$platform});
+           $initial_stack_depth = $initial_depth;
+           replace_insn ($addr, $size, 0, "init_sp");
+       }
+
+       ($res, $listref, $size) = match_jump_table_1($addr);
+       if ($res) {
+           replace_insn ($addr, $size, 0, "jump_table");
+           $jump_lists{$addr} = $listref;
+       }       
+
+       ($res, $listref, $size) = match_jump_table_2($addr);
+       if ($res) {
+           replace_insn ($addr, $size, 0, "jump_table");
+           $jump_lists{$addr} = $listref;
+       }       
+
+       ($res, $stack, $size) = match_constant_push_1 ($addr);
+       if ($res) {
+           replace_insn ($addr, $size, $stack, "constant_push");
+       }
+
+       ($res, $stack, $size) = match_constant_push_2 ($addr);
+       if ($res) {
+           replace_insn ($addr, $size, $stack, "constant_push");
+       }
+
+       ($res, $stack, $size) = match_constant_push_3 ($addr);
+       if ($res) {
+           replace_insn ($addr, $size, $stack, "constant_push");
+       }
+
+       ($res, $stack, $size) = match_constant_pop_1($addr);
+       if ($res) {
+           replace_insn ($addr, $size, $stack, "constant_pop");
+       }
+
+       ($res, $stack, $size) = match_constant_pop_2($addr);
+       if ($res) {
+           replace_insn ($addr, $size, $stack, "constant_pop");
+       }
+
+       ($res, $stack, $size) = match_constant_stack_op($addr);
+       if ($res) {
+           if ($size > 0) {
+               replace_insn ($addr, $size, $stack, "constant_push");
+           } else {
+               replace_insn ($addr, $size, $stack, "constant_pop");
+           }
+       }
+
+       ($res, $stack, $size) = match_constant_pop_4 ($addr);
+       if ($res) {
+           replace_insn ($addr, $size, $stack, "constant_pop");
+       }
+
+       ($res, $stack, $size) = match_prologue_saves($addr);
+       if ($res) {
+           replace_insn ($addr, $size, $stack, "prologue_saves");
+       }
+
+       ($res, $stack, $size) = match_epilogue_restores($addr);
+       if ($res) {
+           # here we ignore the stack effect of epilogue_restores
+           # since the code includes a "ret" that terminates a thread
+           # of the analysis
+           replace_insn ($addr, $size, $stack, "ret");
+       }
+    }
+}
+
+sub make_fine_grain_cfg () {
+    my $last_label;
+    foreach my $addr (sort bynum keys %insns) {
+       my $insn = $insns{$addr};
+       my $hex_addr = sprintf "%x", $addr;
+       my @succ = ();
+       my @callees = ();
+
+       # hack-- we're going to assume this is the name of the
+       # function to which this instruction belongs
+       if (defined($addr_to_label{$addr})) {
+           $last_label = $addr_to_label{$addr};
+       }
+
+       if ($insn eq "ijmp") {
+           $diehere{$addr} = "cannot process raw indirect jump at $hex_addr";
+       } elsif ($insn eq "ret" || $insn eq "reti") {
+           # no control flow from here in our model
+       } elsif (is_branch ($addr) || is_skip ($addr) || is_jmp ($addr)) {
+           if (is_jmp ($addr) && get_target ($addr) == $ORIGIN) {
+               # jump to origin-- nothing to do since this resets the stack
+           } else {
+               push @succ, get_target ($addr);
+               if (!is_jmp($addr)) {
+                   push @succ, ($addr + $insn_size{$addr});
+               }
+           }
+       } elsif ($insn eq "jump_table") {
+           my $listref = $jump_lists{$addr};
+           die "tos-ramsize FAIL" if (!defined($listref));
+           @succ = @{$listref};
+       } elsif (is_fallthrough ($addr)) {
+           push @succ, ($addr + $insn_size{$addr});
+           if ($insn eq "out") {
+               (my $immed, my $reg) = parse_pair ($args{$addr});
+               if ($immed eq "0x3d" || $immed eq "0x3e") {
+                   $diehere{$addr} = "cannot process raw store to SP at $hex_addr";
+               }
+           }
+       } elsif (is_direct_call ($addr) || $insn eq "icall") {
+           my $target;
+           if (is_direct_call ($addr)) {
+               $target = get_target ($addr);
+               die "tos-ramsize FAIL" if (!defined($target));
+           } else {
+               my $target_func = $ICALL_TARGETS{$last_label};
+               if (defined($target_func)) {
+                   $target = $label_to_addr{$target_func};
+                   die "tos-ramsize FAIL" if (!defined($target));
+               } else {
+                   $diehere{$addr} = "cannot process raw indirect call at $hex_addr";
+               }
+           }
+           if (defined($target)) {
+               push @callees, $target;
+               my $l = $addr_to_label{$target};
+               if (!defined($l) || !$NORETURN{$addr_to_label{$target}}) {
+                   push @succ, ($addr + $insn_size{$addr});
+               }
+           }
+       } else {
+           # data interpreted as instruction; this happens sometimes
+           delete ($insns{$addr})
+       }
+       
+       $successors{$addr} = \@succ;
+       $call_targets{$addr}= \@callees;
+    }
+}
+
+sub compute_global_size($) {
+    (my $fn) = @_;
+    open INF, "avr-objdump -h $fn |" or die "tos-ramsize FAIL: can't open input file $fn";
+    my $data_size = 0;
+    my $bss_size = 0;
+
+    while (my $line = <INF>) {
+        chomp $line;
+        if ($line =~ /^\s+[0-9]\s.([a-z]+)\s+([0-9a-f]+)/) {
+            if ($1 eq "bss") {
+                $bss_size = hex($2);
+            }
+            if ($1 eq "data") {
+                $data_size = hex($2);
+            }
+        }
+    }
+    close INF;
+    return ($data_size, $bss_size);
+}
+
+sub max ($$) {
+    (my $a, my $b) = @_;
+    if ($a > $b) {
+       return $a;
+    } else {
+       return $b;
+    }
+}
+
+sub min ($$) {
+    (my $a, my $b) = @_;
+    if ($a < $b) {
+       return $a;
+    } else {
+       return $b;
+    }
+}
+
+# $addr is the address of the current instruction
+# $vec is the name of the interrupt vector we're currently looking at
+# $old_depth is the stack depth before executing this instruction
+
+my %stack_map;
+my %max_stack;
+my %visited;
+my %enables_ints;
+
+sub compute_function_stack ($$) {
+    (my $start_addr, my $vec_type) = @_;
+    
+    my $func_name = $addr_to_label{$start_addr};
+    my @worklist = ();
+    my $start_stack;
+    if ($vec_type eq "intr" || $vec_type eq "func") {
+       $start_stack = $PC_SIZE{$platform};
+    } else {
+       die if ($vec_type ne "main");
+       $start_stack = 0;
+    }
+    my @tmpl = ($start_addr, $start_stack);
+    push @worklist, \@tmpl;
+    my %depths;
+    my %callees;
+
+    while (scalar(@worklist) > 0) {
+       my $lref = pop (@worklist);
+       (my $addr, my $old_depth) = @{$lref};
+
+       die "tos-ramsize FAIL" if (!defined $addr);
+       my $hex_addr = sprintf "%x", $addr;
+
+       if (!defined($insns{$addr})) {
+           die "tos-ramsize FAIL: no instruction at address $hex_addr";
+       }
+
+       my $insn = $insns{$addr};       
+       my $xxx = $diehere{$addr};
+       if (defined ($xxx)) {
+           die "tos-ramsize FAIL: $xxx";
+       }
+
+       $visited{$addr} = 1;
+
+       # FIXME: nonportable AVR
+       if ($insns{$addr} eq "sei") {
+           $enables_ints{$start_addr} = 1;
+       }
+
+       my $se = $stack_effect{$addr};
+       die "tos-ramsize FAIL: no stack effect for $insn" if (!defined($se));
+       my $new_depth;
+       if ($se == $ZERO_STACK) {
+           $new_depth = 0;
+       } else {
+           $new_depth = $old_depth + $se;
+       }
+
+       if ($verbosity > 5) {
+           print "  $hex_addr $insn $new_depth\n";
+       }
+       
+       # something is very wrong
+       if ($new_depth > $RAM_SIZE{$platform}) {
+           printf "tos-ramsize FAIL: stack depth exceeds RAM size at %x\n", $hex_addr;
+           die;
+       }
+
+       # require balanced stack #1
+       if ($insn eq "reti") {
+           die "tos-ramsize FAIL" if ($vec_type ne "intr");
+           die "tos-ramsize FAIL" if ($new_depth != 0);
+           next;
+       }
+
+       # require balanced stack #2
+       if ($insn eq "ret") {
+           die "tos-ramsize FAIL" if ($vec_type ne "func");
+           die "tos-ramsize FAIL -- unbalanced stack on return from $func_name" if ($new_depth != 0);
+           next;
+       }
+
+       # terminate if we're not learning something new about this address
+       next if (defined($depths{$addr}) && $depths{$addr} >= $new_depth);
+
+       # record new depth
+       $depths{$addr} = $new_depth;
+       if (defined($max_stack{$start_addr})) {
+           $max_stack{$start_addr} = 
+               max ($new_depth, $max_stack{$start_addr});
+       } else {
+           $max_stack{$start_addr} = $new_depth;
+       }
+
+       # handle control flow except function calls
+       my $succ_ref = $successors{$addr};
+       my @succ = @{$succ_ref};
+       foreach my $succ_addr (@succ) {
+           my @ll = ($succ_addr, $new_depth);
+           push @worklist, \@ll;
+       }
+
+       # handle function calls
+       my $callee_ref = $call_targets{$addr};
+       my @callees = @{$callee_ref};
+       foreach my $callee_addr (@callees) {
+           $callees{$callee_addr} = 1;
+           my $my_max;
+           if (defined($stack_map{$start_addr}{$callee_addr})) {
+               $my_max = max ($stack_map{$start_addr}{$callee_addr}, $new_depth);
+           } else {
+               $my_max = $new_depth;
+           }
+           $stack_map{$start_addr}{$callee_addr} = $my_max;
+       }
+    }
+
+    my @callee_list = keys %callees;
+
+    if ($verbosity > 2) {
+       print "$func_name (max = $max_stack{$start_addr})\n";
+       foreach my $callee (@callee_list) {
+           print "  -> $addr_to_label{$callee} ";
+           print "depth $stack_map{$start_addr}{$callee}\n";
+       }
+    }
+    
+    return \@callee_list;
+}
+
+sub analyze_functions () {
+    my @worklist = ();
+    my %seen = ();
+    for (my $vec = 0; $vec < $NUM_VECTORS{$platform}; $vec++) {
+       my $addr = $vec * $VEC_SIZE{$platform};
+       my $label = "vector_$vec";
+       $addr_to_label{$addr} = $label;
+       $label_to_addr{$label} = $addr;
+       my $vec_type;
+       if ($vec == 0) {
+           $vec_type = "main";
+       } else {
+           $vec_type = "intr";
+       }
+       my @ll = ($addr, $vec_type);
+       push @worklist, \@ll;
+    }
+    while (scalar(@worklist) > 0) {
+       my $lref = pop @worklist;
+       (my $addr, my $vec_type) = @{$lref};
+       my $hex_addr = sprintf "%x", $addr;
+       next if ($seen{$addr});
+       my $label = $addr_to_label{$addr};
+       if (defined($label) && defined($SPECIAL{$label})) {
+           $max_stack{$addr} = $SPECIAL{$label};
+           next;
+       }
+       $seen{$addr} = 1;
+       my $l;
+       my $lab = $addr_to_label{$addr};
+       if (defined($lab)) {
+           $l = $lab;
+       } else {
+           $l = "[no label]";
+       }
+
+       my $xlref = compute_function_stack ($addr, $vec_type);
+       my @l = @{$xlref};
+       foreach $addr (@l) {
+           my @ll = ($addr, "func");
+           push @worklist, \@ll;
+       }
+    }
+}
+
+# floyd
+sub find_cycles() {
+    my @func_list = keys %max_stack;
+    my %path;
+    my $INFINITY = 9999999;
+    foreach my $x (@func_list) {
+       foreach my $y (@func_list) {
+           if (defined($stack_map{$x}{$y})) {
+               $path{$x}{$y} = 1;
+           } else {
+               $path{$x}{$y} = $INFINITY;
+           }
+       }
+    }
+    foreach my $k (@func_list) {
+       foreach my $i (@func_list) {
+           foreach my $j(@func_list) {
+               $path{$i}{$j} = 
+                   min ($path{$i}{$j},$path{$i}{$k}+$path{$k}{$j});
+           }
+       }
+    }
+    my $min_path = $INFINITY;
+    my $min_func;
+    if ($verbosity > 2) {
+       print "self-path lengths in the callgraph:\n";
+    }
+    foreach my $z (@func_list) {
+       my $len = $path{$z}{$z};
+       if ($verbosity > 2) {
+           print "  $addr_to_label{$z} $len\n";
+       }
+       if ($len < $min_path) {
+           $min_path = $len;
+           $min_func = $z;
+       }
+    }
+    if ($min_path != $INFINITY) {
+       print "cannot estimate stack depth due to recursive loop of length $min_path:\n";
+       my $f = $min_func;
+       for (my $i=$min_path-1; $i>0; $i--) {
+           my @next_list = keys (%{$path{$f}});
+           my $found;
+           foreach my $n (@next_list) {
+               if ($path{$n}{$min_func} == $i &&
+                   $path{$n}{$n} == $min_path) {
+                   $found = $n;
+               }
+           }
+           die "tos-ramsize FAIL graph algo bug" if (!$found);
+           printf "  %s @ %x -> %s @ %x\n", $addr_to_label{$f}, $f, $addr_to_label{$found}, $found;
+           $f = $found;
+       }
+       printf "  %s @ %x -> %s @ %x\n", $addr_to_label{$f}, $f, $addr_to_label{$min_func}, $min_func;
+
+       die "tos-ramsize FAIL";
+    }
+}
+
+my %reachable;
+
+sub find_reachable {
+    (my $addr) = @_;
+    $reachable{$addr} = 1;
+    foreach my $callee (keys (%{$stack_map{$addr}})) {
+       find_reachable($callee);
+    }
+}
+
+my %vector_depth = ();
+my %atomic_vector = ();
+
+sub analyze_vector($$$) {
+    (my $addr, my $vec, my $lref) = @_;
+    my @topo = @{$lref};
+    %reachable = ();
+    $atomic_vector{$vec} = 1;
+    find_reachable ($addr);
+    my %depth = ();
+    my $maxd = 0;
+    my $FAKE = -999;
+    foreach my $v (@topo) {
+       next if (!defined($reachable{$v}));
+       my @edge_list = keys %{$stack_map{$v}};
+       # if any reachable function enables interrupts, the whole vector
+       # in non-atomic
+       if (defined($enables_ints{$v}) && $enables_ints{$v}) {
+           $atomic_vector{$vec} = 0;
+       }
+       push @edge_list, $FAKE;
+       foreach my $w (@edge_list) {
+           my $d = $depth{$w};
+           $d = 0 if (!defined($d));
+           my $d2 = $depth{$v};
+           $d2 = 0 if (!defined($d2));
+           my $edge_weight;
+           if ($w eq $FAKE) {
+               $edge_weight = $max_stack{$v};
+           } else {
+               $edge_weight = $stack_map{$v}{$w};
+           }
+           $d = max ($d, $d2 + $edge_weight);
+           $depth{$w} = $d;
+           $maxd = max ($maxd, $d);
+       }
+       
+    }
+    $vector_depth{$vec} = $maxd;
+}
+
+sub analyze_vectors() {
+    my @topo = ();
+    my %stack_map2 = %stack_map;
+    my @func_list = keys %stack_map2;
+    do {
+        foreach my $f (keys %stack_map2) {
+           my $in_edges = 0;
+           foreach my $f2 (keys %stack_map2) {
+               if (defined($stack_map2{$f2}{$f})) {
+                   $in_edges++;
+               }
+           }
+           if ($in_edges == 0) {
+               push @topo, $f;
+               delete ($stack_map2{$f});
+           }
+       }
+    } while (scalar(keys %stack_map2) > 0);
+
+    if ($verbosity > 3) {
+       foreach my $f (@topo) {
+           my $hex = sprintf "%x", $f;
+           my $s = $addr_to_label{$f};
+           print "  $s $hex\n";
+       }
+    }
+    for (my $vec = 0; $vec < $NUM_VECTORS{$platform}; $vec++) {
+       my $addr = $vec * $VEC_SIZE{$platform};
+       analyze_vector ($addr, $vec, \@topo);
+    }
+}
+
+sub analyze_global_stack_usage() {
+    my $max_atomic = 0;
+    my $total_nonatomic = 0;
+    if ($verbosity > 1) {
+       print "\n";
+       print "per-vector results:\n";
+    }
+    for (my $vec = 0; $vec < $NUM_VECTORS{$platform}; $vec++) {
+       my $addr = $vec * $VEC_SIZE{$platform};
+       my $maxd = $vector_depth{$vec};
+       my $s = "";
+       $s .= sprintf "  vector %d max depth = %d", $vec, $maxd;
+       my $atom = $atomic_vector{$vec};
+       if (defined($atom) && $atom) {
+           $s .= " (atomic)";
+           $max_atomic = max ($max_atomic, $maxd);
+       } else {
+           $s .= " (not atomic)";
+           $total_nonatomic += $maxd;
+       }
+       if ($verbosity > 1 && $maxd != $PC_SIZE{$platform}) {
+           print "$s\n";
+       }
+    }
+    
+    my $depth = $total_nonatomic + $max_atomic;
+    return $depth;
+}
+
+##########################################################################
+################################ MAIN ####################################
+##########################################################################
+
+# redirect stderr to stdout, don't buffer stdout
+open(STDERR,'>&', STDOUT);
+$|=1;
+
+my $result = GetOptions ("verbosity=i" => \$verbosity);
+die "tos-ramsize FAIL" if (!$result);
+
+if (scalar(@ARGV) != 2) {
+    die "usage: ramsize.pl [-verbosity 0-9] mica2|micaz|iris avr_file.elf";
+}
+
+$platform = $ARGV[0];
+die "tos-ramsize FAIL: unknown platform '$platform'" if (!defined($RAM_SIZE{$platform}));
+
+my $file = $ARGV[1];
+die "tos-ramsize FAIL: '$file' not found" if (!(-f $file));
+
+if ($verbosity > 1) {
+    print "analyzing elf file '$file' for platform '$platform'\n";
+}
+
+disassemble ($file);
+insn_stack_effects();
+make_macro_insns();
+make_fine_grain_cfg();
+analyze_functions();
+find_cycles();
+analyze_vectors();
+my $total_depth = analyze_global_stack_usage();
+
+(my $data_size, my $bss_size) = compute_global_size($file);
+my $ramused = $data_size + $bss_size + $total_depth;
+my $free_mem = $RAM_SIZE{$platform} - $ramused;
+
+if ($verbosity > 2) {
+    foreach my $addr (sort bynum keys %insns) {
+       if (!$visited{$addr}) {
+           my $l = $addr_to_label{$addr};
+           if (defined($l) && !defined($SPECIAL{$l})) {
+               printf "unreachable label: %x %s\n", $addr, $l;
+           }
+       }
+    }
+}
+
+if ($verbosity > 0) {
+    print "BSS segment size is ${bss_size}, data segment size is ${data_size}\n";
+}
+print "The upper bound on stack size is ${total_depth}\n";
+print "The upper bound on RAM usage is $ramused\n";
+print "There are $free_mem unused bytes of RAM\n";
+
+##########################################################################
diff --git a/tools/tinyos/safe/tos-ramsize.1 b/tools/tinyos/safe/tos-ramsize.1
new file mode 100755 (executable)
index 0000000..20ddd7b
--- /dev/null
@@ -0,0 +1,16 @@
+.TH tos-ramsize 1 "Apr 10, 2009"
+.LO 1
+.SH NAME
+
+tos-ramsize - Compute RAM usage of a TinyOS application including the stack
+.SH SYNOPSIS
+
+\fBtos-ramsize\fR [-verbosity=n] mica2|micaz|iris elf-file
+.SH DESCRIPTION
+
+This tool disassembles an elf file for AVR-based TinyOS platforms and
+estimates the maximum extent of its call stack.  This number is
+reported, along with the total static and dynamic RAM usage.
+
+The primary documentation for this tool can be found on the TinyOS
+Documentation Wiki.
index 389348bddd906a3869e32b3603f6db622950f02f..c22661506c4e75da35fa6482d24d252ef982cf92 100644 (file)
@@ -4,10 +4,10 @@ dist_man_MANS = tosthreads-dynamic-app.1
 
 tosthreadslibdir=$(libdir)/tinyos/tosthreads
 
-bin_SCRIPTS = tosthreads-dynamic-app
+bin_SCRIPTS = tosthreads-dynamic-app \
+              tosthreads-gen-dynamic-app
 
-tosthreadslib_DATA = tosthreads_standard_api.py  \
-                     tosthreads_tenet_api.py
+tosthreadslib_DATA = tosthreads_standard_api.py
                      
 tosthreads-dynamic-app: tosthreads-dynamic-app.in
        sed -e 's,@tosthreadslibdir\@,$(tosthreadslibdir),g' tosthreads-dynamic-app.in >$@      
diff --git a/tools/tinyos/tosthreads/tosthreads-gen-dynamic-app b/tools/tinyos/tosthreads/tosthreads-gen-dynamic-app
new file mode 100755 (executable)
index 0000000..dcd1d97
--- /dev/null
@@ -0,0 +1,85 @@
+#!/bin/bash
+
+# Copyright (c) 2008 Johns Hopkins University.
+# All rights reserved.
+#
+# Permission to use, copy, modify, and distribute this software and its
+# documentation for any purpose, without fee, and without written
+# agreement is hereby granted, provided that the above copyright
+# notice, the (updated) modification history and the author appear in
+# all copies of this source code.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+# OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+# THE POSSIBILITY OF SUCH DAMAGE.
+
+# @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+
+if [ $# -ne 1 -a $# -ne 2 ]
+then
+  echo "Usage: `basename $0` path_to_cthread_app [options]"
+  echo ""
+  echo "-a --array"
+  echo "     Print out the loadable binary code as a byte array."
+  exit -1
+fi
+
+CFILE=$1
+FLAG=$2
+
+GCC="msp430-gcc"
+OBJCOPY="msp430-objcopy"
+NESCFLAGS="-target=telosb -x nesc -fnesc-target=msp430"
+CFLAGS="-c -gcc=$GCC -mmcu=msp430x1611 -Os -mdisable-hwmul -Wall -Wshadow"
+
+OBJFILE=`basename $CFILE .c`.o
+BINFILE=`basename $CFILE .c`.bin
+TOSFILE=`basename $CFILE .c`.tos
+
+TOS_THREADS_DIR=$TOSDIR/lib/tosthreads
+THREADS_CSYSTEM_DIR=$TOS_THREADS_DIR/csystem
+THREADS_SYSTEM_DIR=$TOS_THREADS_DIR/system
+THREADS_INTERFACES_DIR=$TOS_THREADS_DIR/interfaces
+THREADS_TYPES_DIR=$TOS_THREADS_DIR/types
+THREADS_MSP430_DIR=$TOS_THREADS_DIR/chips/msp430
+THREADS_TMOTE_SENSORS_DIR=$TOS_THREADS_DIR/tos/sensorboards/tmote_onboard
+THREADS_PRINTF_DIR=$TOS_THREADS_DIR/tos/lib/printf
+TOS_TELOSA_DIR=$TOSDIR/platforms/telosa
+TOS_TELOSB_DIR=$TOSDIR/platforms/telosb
+TOS_CC2420_DIR=$TOSDIR/chips/cc2420
+TOS_SERIAL_DIR=$TOSDIR/lib/serial
+TOS_SYSTEM_DIR=$TOSDIR/system
+TOS_TYPES_DIR=$TOSDIR/types
+
+#Set up includes 
+CFLAGS="$CFLAGS -I$THREADS_CSYSTEM_DIR -I$THREADS_SYSTEM_DIR -I$THREADS_INTERFACES_DIR -I$THREADS_TYPES_DIR -I$THREADS_MSP430_DIR"
+CFLAGS="$CFLAGS -I$THREADS_PRINTF_DIR"
+CFLAGS="$CFLAGS -I$THREADS_TMOTE_SENSORS_DIR"
+CFLAGS="$CFLAGS -DTOSTHREAD_EXTERNAL_BINARY"
+
+#Set up the proper scheduler
+NESCFLAGS="$NESCFLAGS -tosscheduler=TinyTaskSchedulerC,TinyTaskSchedulerC.TaskBasic,TaskBasic,TaskBasic,runTask,postTask"
+
+rm -rf $OBJFILE
+rm -rf $TOSFILE
+
+COMMAND="ncc $CFLAGS $NESCFLAGS $CFILE"
+echo $COMMAND
+command  $COMMAND
+
+COMMAND="$OBJCOPY --output-target=binary $OBJFILE $BINFILE"
+echo $COMMAND
+command  $COMMAND
+
+COMMAND="tosthreads-dynamic-app $FLAG $OBJFILE $BINFILE $TOSFILE"
+echo $COMMAND
+command $COMMAND
+rm $BINFILE
+rm $OBJFILE
diff --git a/tools/tinyos/tosthreads/tosthreads-gen-dynamic-app.1 b/tools/tinyos/tosthreads/tosthreads-gen-dynamic-app.1
new file mode 100755 (executable)
index 0000000..5f6abc2
--- /dev/null
@@ -0,0 +1,63 @@
+#!/bin/bash
+
+if [ $# -ne 1 -a $# -ne 2 ]
+then
+  echo "Usage: `basename $0` path_to_cthread_app [options]"
+  echo ""
+  echo "-a --array"
+  echo "     Print out the loadable binary code as a byte array."
+  exit -1
+fi
+
+CFILE=$1
+FLAG=$2
+
+GCC="msp430-gcc"
+OBJCOPY="msp430-objcopy"
+NESCFLAGS="-target=telosb -x nesc -fnesc-target=msp430"
+CFLAGS="-c -gcc=$GCC -mmcu=msp430x1611 -Os -mdisable-hwmul -Wall -Wshadow"
+
+OBJFILE=`basename $CFILE .c`.o
+BINFILE=`basename $CFILE .c`.bin
+TOSFILE=`basename $CFILE .c`.tos
+
+TOS_THREADS_DIR=$TOSDIR/lib/tosthreads
+THREADS_CSYSTEM_DIR=$TOS_THREADS_DIR/csystem
+THREADS_SYSTEM_DIR=$TOS_THREADS_DIR/system
+THREADS_INTERFACES_DIR=$TOS_THREADS_DIR/interfaces
+THREADS_TYPES_DIR=$TOS_THREADS_DIR/types
+THREADS_MSP430_DIR=$TOS_THREADS_DIR/chips/msp430
+THREADS_TMOTE_SENSORS_DIR=$TOS_THREADS_DIR/tos/sensorboards/tmote_onboard
+THREADS_PRINTF_DIR=$TOS_THREADS_DIR/tos/lib/printf
+TOS_TELOSA_DIR=$TOSDIR/platforms/telosa
+TOS_TELOSB_DIR=$TOSDIR/platforms/telosb
+TOS_CC2420_DIR=$TOSDIR/chips/cc2420
+TOS_SERIAL_DIR=$TOSDIR/lib/serial
+TOS_SYSTEM_DIR=$TOSDIR/system
+TOS_TYPES_DIR=$TOSDIR/types
+
+#Set up includes 
+CFLAGS="$CFLAGS -I$THREADS_CSYSTEM_DIR -I$THREADS_SYSTEM_DIR -I$THREADS_INTERFACES_DIR -I$THREADS_TYPES_DIR -I$THREADS_MSP430_DIR"
+CFLAGS="$CFLAGS -I$THREADS_PRINTF_DIR"
+CFLAGS="$CFLAGS -I$THREADS_TMOTE_SENSORS_DIR"
+CFLAGS="$CFLAGS -DTOSTHREAD_EXTERNAL_BINARY"
+
+#Set up the proper scheduler
+NESCFLAGS="$NESCFLAGS -tosscheduler=TinyTaskSchedulerC,TinyTaskSchedulerC.TaskBasic,TaskBasic,TaskBasic,runTask,postTask"
+
+rm -rf $OBJFILE
+rm -rf $TOSFILE
+
+COMMAND="ncc $CFLAGS $NESCFLAGS $CFILE"
+echo $COMMAND
+command  $COMMAND
+
+COMMAND="$OBJCOPY --output-target=binary $OBJFILE $BINFILE"
+echo $COMMAND
+command  $COMMAND
+
+COMMAND="tosthreads-dynamic-app $FLAG $OBJFILE $BINFILE $TOSFILE"
+echo $COMMAND
+command $COMMAND
+rm $BINFILE
+rm $OBJFILE
index ec29b0e53daedd64db72fedc985b93ec832921e5..4b973ad2da9c18cf3ea24ec8e43fccab0e4b9ae8 100644 (file)
@@ -89,5 +89,10 @@ map_extfun = {
 
               "getLeds":107, "setLeds":108,
 
-              "__divmodhi4":109}
+              "__divmodhi4":109,
+              
+              "tosthread_join":110,
+              
+              "volumeConfigMount":111, "volumeConfigRead":112, "volumeConfigWrite":113,
+              "volumeConfigCommit":114, "volumeConfigGetSize":115, "volumeConfigValid":116}
 
diff --git a/tools/tinyos/tosthreads/tosthreads_tenet_api.py b/tools/tinyos/tosthreads/tosthreads_tenet_api.py
deleted file mode 100644 (file)
index 500bdfd..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/usr/bin/python
-
-# Copyright (c) 2008 Johns Hopkins University.
-# All rights reserved.
-#
-# Permission to use, copy, modify, and distribute this software and its
-# documentation for any purpose, without fee, and without written
-# agreement is hereby granted, provided that the above copyright
-# notice, the (updated) modification history and the author appear in
-# all copies of this source code.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
-# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
-# OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
-# THE POSSIBILITY OF SUCH DAMAGE.
-
-# @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
-# @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
-
-import sys, subprocess
-import struct
-
-
-# ===== STEP 0: Prepares function-ID maps ===== #
-map_extfun = {
-              "tosthread_sleep":0, "tosthread_create":1,
-
-              "led0On":2, "led1On":3, "led2On":4, 
-              "led0Off":5, "led1Off":6, "led2Off":7, 
-              "led0Toggle":8, "led1Toggle":9, "led2Toggle":10,
-              "getLeds":11, "setLeds":12,
-              
-              "reboot":13,
-
-              "get_nodeid":14, "get_nexthop":15,
-              "get_globaltime":16, "get_localtime":17,
-              "get_rfpower":18, "get_istimesync":19,
-              "get_globaltimems":20, "get_localtimems":21,
-              "get_clockfreq":22, "get_platform":23,
-              "get_hopcount":24, "get_rfchannel":25,
-
-              "tenet_get_tid":26, "tenet_get_src":27, "tenet_get_numtasks":28,
-
-              "read_voltage":29, "read_internal_temperature":30,
-
-              "tenet_send":31, "tenet_sendto":32,
-
-              "read_tsr_sensor":33, "read_par_sensor":34,
-              "read_temperature":35, "read_humidity":36,
-
-              "__divmodhi4":36
-              }
-
diff --git a/tos.mk b/tos.mk
index ce13d0f3f4dcd2549cdf62dcd64ec048b755af7c..4ed360ebcea8b41a45d8e82fe57addf3f0cfafae 100644 (file)
--- a/tos.mk
+++ b/tos.mk
@@ -7,7 +7,7 @@
 # under Cygwin and using cp2103 based motes).
 
 # Set TOSROOT to the directory in which this include file is located
-this := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) 
+this := $(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
 export TOSROOT := $(shell dirname $(this))
 
 # Build an updated CLASSPATH
index 63d49cdebd48ea50a37d6bcf25f4b12a20cb529d..084001805b60ecf6160dca98c573cebad3f93346 100644 (file)
@@ -127,6 +127,28 @@ typedef uint8_t Atm128_UBRR0H_t;  //!< UART 0 Baud Register (High)
 typedef uint8_t Atm128_UBRR1L_t;  //!< UART 1 Baud Register (Low)
 typedef uint8_t Atm128_UBRR1H_t;  //!< UART 1 Baud Register (High)
 
+typedef uint8_t uart_parity_t;
+typedef uint8_t uart_speed_t;
+typedef uint8_t uart_duplex_t;
+
+enum {
+  TOS_UART_PARITY_NONE = 0,
+  TOS_UART_PARITY_EVEN = 1,
+  TOS_UART_PARITY_ODD  = 2,
+};
+
+enum {
+  TOS_UART_19200  = 0,
+  TOS_UART_38400  = 1,
+  TOS_UART_57600  = 2,
+};
+
+enum {
+  TOS_UART_OFF    = 0,
+  TOS_UART_RONLY  = 1,
+  TOS_UART_TONLY  = 2,
+  TOS_UART_DUPLEX = 3,
+};
 
 #endif //_H_Atm128UART_h
 
index 89f312f8481559f06dafa048651b068c57a8c259..b412d90fe1a7c74c1110d130db91151f39f1a317 100644 (file)
@@ -135,6 +135,23 @@ mcu_power_t mcombine(mcu_power_t m1, mcu_power_t m2) @safe() {
   return (m1 < m2)? m1: m2;
 }
 
-#endif //_H_atmega128hardware_H
+/* Floating-point network-type support.
+   These functions must convert to/from a 32-bit big-endian integer that follows
+   the layout of Java's java.lang.float.floatToRawIntBits method.
+   Conveniently, for the AVR family, this is a straight byte copy...
+*/
+
+typedef float nx_float __attribute__((nx_base_be(afloat)));
+
+inline float __nesc_ntoh_afloat(const void *COUNT(sizeof(float)) source) @safe() {
+  float f;
+  memcpy(&f, source, sizeof(float));
+  return f;
+}
 
+inline float __nesc_hton_afloat(void *COUNT(sizeof(float)) target, float value) @safe() {
+  memcpy(target, &value, sizeof(float));
+  return value;
+}
 
+#endif //_H_atmega128hardware_H
index 75fd6643fd373c104c0cb7088cee0d66ed8c4a0d..94589c1fd6a077cd5fe046726c320698b2c1a97a 100644 (file)
@@ -47,4 +47,8 @@ enum {
     ATM128_I2C_MR_DATA_NACK     = 0x58
 };
 
+#ifndef ATM128_I2C_EXTERNAL_PULLDOWN
+#define ATM128_I2C_EXTERNAL_PULLDOWN FALSE
+#endif
+
 #endif // _H_Atm128I2C_h
index 35cf22939227927221baf71973c124df5cb058eb..aac369b790ea85091124b1aea0192dfdd7126fd2 100644 (file)
  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  * OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
+ * Copyright (c) 2009, Distributed Computing Group (DCG), ETH Zurich.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the copyright holders nor the names of
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ *
+ * */
+  
 #include "Atm128I2C.h"
 
 /**
  * two-wire-interface (TWI) hardware subsystem.
  *
  * @author Philip Levis
+ * @author Philipp Sommer, ETH Zurich, sommer@tik.ee.ethz.ch
+ * @author Roland Flury, ETH Zurich, rflury@tik.ee.ethz.ch
+ * @author Thomas Fahrni, ETH Zurich, tfahrni@ee.ethz.ch
+ * @author Richard Huber, ETH Zurich, rihuber@ee.ethz.ch
+ * @author Lars Schor, ETH Zurich, lschor@ee.ethz.ch
  *
- * @version $Id$
  */
 
 generic module Atm128I2CMasterPacketP() {
@@ -60,6 +91,7 @@ implementation {
     I2C_DATA         = 4,
     I2C_STARTING     = 5,
     I2C_STOPPING     = 6,
+    I2C_SLAVE_ACK       = 7
   } atm128_i2c_state_t;
 
   uint8_t state = I2C_OFF;
@@ -93,7 +125,7 @@ implementation {
   async command error_t AsyncStdControl.start() {
     atomic {
       if (state == I2C_OFF) {
-       call I2C.init(FALSE);
+       call I2C.init(ATM128_I2C_EXTERNAL_PULLDOWN);
        call I2C.readCurrent();
        call I2C.enable(TRUE);
        call I2C.enableInterrupt(FALSE);
@@ -254,81 +286,95 @@ implementation {
   async event void I2C.commandComplete() {
     call I2C.readCurrent();
     atomic {
-      if (state == I2C_DATA) {
-       if (reading == TRUE) {
-         if (index < packetLen) {
-           packetPtr[index] = call I2C.read();
-           if (index == packetLen - 1 &&
-                !(packetFlags & I2C_ACK_END)) { 
-              call I2C.enableAck(FALSE);
-            }
-          }
-         else {
-           call I2C.enableInterrupt(FALSE);
-           if (packetFlags & I2C_STOP) {
-             packetFlags &= ~I2C_STOP;
-             call I2C.setStop(TRUE);
-             call I2C.status();
-           }
-           else {
-             call I2C.setInterruptPending(FALSE);
-           }
-           call I2C.sendCommand();
-           state = I2C_IDLE;
-           signal I2CPacket.readDone(SUCCESS, packetAddr, packetLen, packetPtr);
-           return;
-         }
-         index++;
-         call I2C.sendCommand();
-         return;
+      if (state == I2C_SLAVE_ACK) {        
+        if (reading == TRUE) {         
+               state = I2C_DATA;
+               call I2C.setInterruptPending(TRUE);
+               call I2C.enableAck(TRUE);
+               call I2C.sendCommand();
+        }                                      
+      } else if (state == I2C_DATA) {
+               
+               if (reading == TRUE) {
+                       if (index < packetLen) {
+                       packetPtr[index] = call I2C.read();
+                       if (index == packetLen - 1 &&
+                           !(packetFlags & I2C_ACK_END)) { 
+                         call I2C.enableAck(FALSE);
+                       }
+                       //state = I2C_SLAVE_ACK;
+               }
+               else {
+                       call I2C.enableInterrupt(FALSE);
+                       if (packetFlags & I2C_STOP) {
+                               packetFlags &= ~I2C_STOP;
+                               call I2C.setStop(TRUE);
+                               call I2C.status();
+                       }
+                       else {
+                               call I2C.setInterruptPending(FALSE);
+                       }
+                       
+                       call I2C.sendCommand();
+                       state = I2C_IDLE;
+                       signal I2CPacket.readDone(SUCCESS, packetAddr, packetLen, packetPtr);
+                       return;
+                       }
+                       index++;
+                       call I2C.sendCommand();
+                       return;
         }
         else { // Writing
-         if (index < packetLen) {
-           call I2C.write(packetPtr[index]);
-           index++;
-           call I2C.sendCommand();
-         }
-         else {
-           call I2C.enableInterrupt(FALSE);
-           if (packetFlags & I2C_STOP) {
-             packetFlags &= ~I2C_STOP;
-             call I2C.setStop(TRUE);
-             call WriteDebugLeds.led1On();
-           }
-           else {
-             call I2C.setInterruptPending(FALSE);
-           }
-           call I2C.sendCommand();
-           state = I2C_IDLE;
-           call WriteDebugLeds.led2On();
-           signal I2CPacket.writeDone(SUCCESS, packetAddr, packetLen, packetPtr);
-           return;
-         }
-       }
-      }
-      else if (state == I2C_STARTING) {
-       packetFlags &= ~I2C_START;
-       call I2C.setStart(FALSE);
-       if (call I2C.status() != ATM128_I2C_START &&
-           call I2C.status() != ATM128_I2C_RSTART) {
-         if (reading) {
-           //call ReadDebugLeds.set(call I2C.status() >> 4);
-         }
-         //call ReadDebugLeds.led2On();
-         i2c_abort(FAIL);
-         return;
-       }
-       state = I2C_ADDR;
-       call I2C.enableAck(TRUE);
+                       if (index < packetLen) {
+                       call I2C.write(packetPtr[index]);
+                       index++;
+                       call I2C.sendCommand();
+                       }
+                       else {
+                       call I2C.enableInterrupt(FALSE);
+                       if (packetFlags & I2C_STOP) {
+                               packetFlags &= ~I2C_STOP;
+                               call I2C.setStop(TRUE);
+                               call WriteDebugLeds.led1On();
+                                }
+                       else {
+                               call I2C.setInterruptPending(FALSE);
+                       }
+                       call I2C.sendCommand();
+                       state = I2C_IDLE;
+                       call WriteDebugLeds.led2On();
+                       signal I2CPacket.writeDone(SUCCESS, packetAddr, packetLen, packetPtr);
+                       return;
+                       }
+               }
+       }
+    else if (state == I2C_STARTING) {
+               packetFlags &= ~I2C_START;
+               call I2C.setStart(FALSE);
+               if (call I2C.status() != ATM128_I2C_START &&
+                   call I2C.status() != ATM128_I2C_RSTART) {
+                       if (reading) {
+                       //call ReadDebugLeds.set(call I2C.status() >> 4);
+                       }
+                       //call ReadDebugLeds.led2On();
+                       i2c_abort(FAIL);
+                       return;
+               }
+               state = I2C_ADDR;
+               call I2C.enableAck(TRUE);
       }
       if (state == I2C_ADDR) {
-       if (reading == TRUE) {
-         call I2C.write(((packetAddr & 0x7f) << 1) | ATM128_I2C_SLA_READ);
-       }
-       else
-         call I2C.write(((packetAddr & 0x7f) << 1) | ATM128_I2C_SLA_WRITE);
-       state = I2C_DATA;
-       call I2C.sendCommand();
+               if (reading == TRUE) {
+                       call I2C.write(((packetAddr & 0x7f) << 1) | ATM128_I2C_SLA_READ);
+                       state = I2C_SLAVE_ACK;
+                       //state = I2C_DATA;
+               }
+               else {
+                       call I2C.write(((packetAddr & 0x7f) << 1) | ATM128_I2C_SLA_WRITE);
+                       state = I2C_DATA;
+               }
+       
+               call I2C.sendCommand();
       }
     }
   }
index c10a9f573c9b6af3ee18b0831692554cde603ee9..80d9243171adbcb1813ab29c92b1ba6ff39b2be7 100644 (file)
@@ -65,6 +65,7 @@
 configuration Atm128SpiC {
   provides interface Init;
   provides interface SpiByte;
+  provides interface FastSpiByte;
   provides interface SpiPacket;
   provides interface Resource[uint8_t id];
 }
@@ -76,6 +77,7 @@ implementation {
   Init         = SpiMaster;
   
   SpiByte      = SpiMaster;
+  FastSpiByte  = SpiMaster;
   SpiPacket    = SpiMaster;
   Resource     = SpiMaster;
 
index 6bec916b6c249e94f4677f514eab6d0d76af8f02..1838f7b0d00a48c6a76858b0341c825ebeca97d7 100644 (file)
@@ -76,6 +76,7 @@ module Atm128SpiP @safe() {
   provides {
     interface Init;
     interface SpiByte;
+    interface FastSpiByte;
     interface SpiPacket;
     interface Resource[uint8_t id];
   }
@@ -125,13 +126,46 @@ implementation {
   }
 
   async command uint8_t SpiByte.write( uint8_t tx ) {
+    /* There is no need to enable the SPI bus and update the power state
+       here since that must have been done when the resource was granted. 
+       However there seems to be a bug somewhere in the radio driver for 
+       the MicaZ platform so we cannot remove the following two lines 
+       before that problem is resolved. (Miklos Maroti) */
     call Spi.enableSpi(TRUE);
     call McuPowerState.update();
+
     call Spi.write( tx );
     while ( !( SPSR & 0x80 ) );
     return call Spi.read();
   }
 
+  inline async command void FastSpiByte.splitWrite(uint8_t data) {
+    call Spi.write(data);
+  }
+
+  inline async command uint8_t FastSpiByte.splitRead() {
+    while( !( SPSR & 0x80 ) )
+      ;
+    return call Spi.read();
+  }
+
+  inline async command uint8_t FastSpiByte.splitReadWrite(uint8_t data) {
+    uint8_t b;
+
+    while( !( SPSR & 0x80 ) )
+       ;
+    b = call Spi.read();
+    call Spi.write(data);
+
+    return b;
+  }
+
+  inline async command uint8_t FastSpiByte.write(uint8_t data) {
+    call Spi.write(data);
+    while( !( SPSR & 0x80 ) )
+      ;
+    return call Spi.read();
+  }
 
   /**
    * This component sends SPI packets in chunks of size SPI_ATOMIC_SIZE
index 19b8738cb868ec21cae440ec2d205b1ae25fe762..65f1389c334dab50047b057bd72db380d4e1f444 100644 (file)
@@ -106,10 +106,10 @@ implementation {
       return ATM128_POWER_IDLE;
     }
     // UARTs are active
-    else if (UCSR0B & (1 << TXCIE0 | 1 << RXCIE0)) { // UART
+    else if (UCSR0B & (1 << TXCIE0 | 1 << RXCIE0 | 1 << UDRIE0)) { // UART
       return ATM128_POWER_IDLE;
     }
-    else if (UCSR1B & (1 << TXCIE1 | 1 << RXCIE1)) { // UART
+    else if (UCSR1B & (1 << TXCIE1 | 1 << RXCIE1 | 1 << UDRIE1)) { // UART
       return ATM128_POWER_IDLE;
     }
     // I2C (Two-wire) is active
index 56ef6d102f1963ff86cbf0f5b88e9880613fff45..a5800f16c8ee68144c7463ed9ed1d42c49add8ee 100644 (file)
@@ -188,5 +188,23 @@ typedef struct
   uint8_t xmbk   : 1;    //!< External Memory Bus-keeper Enable
 } Atm128_XMCRB_t;
 
+/* Floating-point network-type support.
+   These functions must convert to/from a 32-bit big-endian integer that follows
+   the layout of Java's java.lang.float.floatToRawIntBits method.
+   Conveniently, for the AVR family, this is a straight byte copy...
+*/
+
+typedef float nx_float __attribute__((nx_base_be(afloat)));
+
+inline float __nesc_ntoh_afloat(const void *COUNT(sizeof(float)) source) @safe() {
+  float f;
+  memcpy(&f, source, sizeof(float));
+  return f;
+}
+
+inline float __nesc_hton_afloat(void *COUNT(sizeof(float)) target, float value) @safe() {
+  memcpy(target, &value, sizeof(float));
+  return value;
+}
 
 #endif //_H_atmega128hardware_H
index 06ce93e9a149c55cf531390c42febce1cba4db62..14b988c629bdd4d43f8c89df89ec33622a7ffe36 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Header definitions for the BQ2403X charge controller chip family. Only the
  * BQ2403X was considered when building this component.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #ifndef BQ2403X_H
 #define BQ2403X_H
 
index da073878918a321028598199d5980cbd57ea13c6..4846f9de42917744e4ca0c249ee37dad9f4a154a 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HIL interface for the BQ2403X charge controller chip.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "BQ2403X.h"
 
 interface BQ2403X {
index 4bcc2c7413b75575cc1c0261f440a5c4aa468897..34d6d398534358045a14c4a66f0156b7278f3238 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HIL implementation for the BQ2403X charge controller chip family.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "BQ2403X.h"
 
 configuration BQ2403XC {
index 1dbd4b3d3d71a42d37dc28468c653a5f847f016e..bb41d9b2cbf2b03b0e8efd5bde194b47371db6fa 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HIL implementation for the BQ2403X charge controller chip family.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "BQ2403X.h"
 
 module BQ2403XP {
@@ -182,7 +182,7 @@ implementation {
   task void signalChange()
   {
     bq2403x_state_t cstate;
-    
+
     atomic cstate = state;
     signal BQ2403X.change(cstate, lastState);
     lastState = cstate;
index d35c243d6667a10f0f13d52f6962438b7f6aecbb..1ad985b970514ab29a04015b097641b448c83593 100644 (file)
@@ -1,5 +1,3 @@
-// $Id$
-
 /*
  * "Copyright (c) 2004-2005 The Regents of the University  of California.  
  * All rights reserved.
@@ -38,7 +36,7 @@
  * addr and group).
  * 
  * @author Philip Levis
- * @date June 19 2005
+ * @author Marco Langerwisch (Packet timestamping)
  */
 
 configuration CC1000ActiveMessageC {
@@ -51,6 +49,11 @@ configuration CC1000ActiveMessageC {
     interface Packet;
     interface PacketAcknowledgements;
     interface LinkPacketMetadata;
+
+    interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
+    interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+    interface PacketTimeSyncOffset;
+    interface LowPowerListening;
   }
 }
 implementation {
@@ -73,4 +76,8 @@ implementation {
   AM.amAddress -> Address;
   AM.Packet     -> Radio;
   
+  PacketTimeStamp32khz = Radio;
+  PacketTimeStampMilli = Radio;
+  PacketTimeSyncOffset = Radio;
+  LowPowerListening    = Radio;
 }
index f5884fd4fb26b0c9bfa2a809e37373677c7b23b4..698ab8cbd205f359ad79079c6cbb7da2718ffba4 100644 (file)
@@ -507,29 +507,21 @@ implementation
     return (1000 * CC1K_LPL_CHECK_TIME) / sleepInterval;
   }
 
-  command void LowPowerListening.setLocalSleepInterval(uint16_t s) {
+  command void LowPowerListening.setLocalWakeupInterval(uint16_t s) {
     sleepTime = validateSleepInterval(s);
   }
 
-  command uint16_t LowPowerListening.getLocalSleepInterval() {
+  command uint16_t LowPowerListening.getLocalWakeupInterval() {
     return sleepTime;
   }
 
-  command void LowPowerListening.setLocalDutyCycle(uint16_t d) {
-    call LowPowerListening.setLocalSleepInterval(dutyToSleep(d));
-  }
-
-  command uint16_t LowPowerListening.getLocalDutyCycle() {
-    return sleepToDuty(call LowPowerListening.getLocalSleepInterval());
-  }
-
-  command void LowPowerListening.setRxSleepInterval(message_t *msg, uint16_t sleepIntervalMs) {
+  command void LowPowerListening.setRemoteWakeupInterval(message_t *msg, uint16_t sleepIntervalMs) {
     cc1000_metadata_t *meta = getMetadata(msg);
 
     meta->strength_or_preamble = -(int16_t)validateSleepInterval(sleepIntervalMs) - 1;
   }
 
-  command uint16_t LowPowerListening.getRxSleepInterval(message_t *msg) {
+  command uint16_t LowPowerListening.getRemoteWakeupInterval(message_t *msg) {
     cc1000_metadata_t *meta = getMetadata(msg);
 
     if (meta->strength_or_preamble >= 0)
@@ -538,22 +530,6 @@ implementation
       return -(meta->strength_or_preamble + 1);
   }
 
-  command void LowPowerListening.setRxDutyCycle(message_t *msg, uint16_t d) {
-    return call LowPowerListening.setRxSleepInterval(msg, dutyToSleep(d));
-  }
-
-  command uint16_t LowPowerListening.getRxDutyCycle(message_t *msg) {
-    return sleepToDuty(call LowPowerListening.getRxSleepInterval(msg));
-  }
-
-  command uint16_t LowPowerListening.dutyCycleToSleepInterval(uint16_t d) {
-    return dutyToSleep(d);
-  }
-
-  command uint16_t LowPowerListening.sleepIntervalToDutyCycle(uint16_t s) {
-    return sleepToDuty(s);
-  }
-
   void setPreambleLength(message_t * ONE msg) {
     cc1000_metadata_t *meta = getMetadata(msg);
     uint16_t s;
index faa5d80e2dcd928dbcb8df5c830e59d5353d2472..a04333660cf7f9073c4a0bb6fe26bcc3a9a5b74c 100644 (file)
@@ -1,4 +1,4 @@
-/* $Id$
+/*
  * "Copyright (c) 2000-2005 The Regents of the University  of California.  
  * All rights reserved.
  *
@@ -44,6 +44,7 @@
  *
  * @author Joe Polastre
  * @author David Gay
+ * @author Marco Langerwisch (Packet timestamping)
  */
 
 #include "CC1000Const.h"
@@ -55,14 +56,17 @@ configuration CC1000CsmaRadioC {
     interface Send;
     interface Receive;
 
-    interface Packet;    
+    interface Packet;
     interface CsmaControl;
     interface CsmaBackoff;
-    interface RadioTimeStamping;
     interface PacketAcknowledgements;
     interface LinkPacketMetadata;
-    
+
     interface LowPowerListening;
+
+    interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
+    interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+    interface PacketTimeSyncOffset;
   }
 }
 implementation {
@@ -86,10 +90,9 @@ implementation {
   CsmaControl = Csma;
   CsmaBackoff = Csma;
   LowPowerListening = Csma;
-  RadioTimeStamping = SendReceive;
   PacketAcknowledgements = SendReceive;
   LinkPacketMetadata = SendReceive;
-  
+
   Csma.CC1000Control -> Control;
   Csma.Random -> RandomC;
   Csma.CC1000Squelch -> Squelch;
@@ -103,7 +106,7 @@ implementation {
   SendReceive.amAddress -> ActiveMessageAddressC;
   SendReceive.RssiRx -> Rssi.Rssi[unique(UQ_CC1000_RSSI)];
   SendReceive.CC1000Squelch -> Squelch;
-  
+
   Csma.RssiNoiseFloor -> Rssi.Rssi[unique(UQ_CC1000_RSSI)];
   Csma.RssiCheckChannel -> Rssi.Rssi[unique(UQ_CC1000_RSSI)];
   Csma.RssiPulseCheck -> Rssi.Rssi[unique(UQ_CC1000_RSSI)];
@@ -114,4 +117,16 @@ implementation {
   Rssi.Resource -> Hpl;
   Control.CC -> Hpl;
   Control.BusyWait -> BusyWaitMicroC;
+
+  PacketTimeStamp32khz = SendReceive;
+  PacketTimeStampMilli = SendReceive;
+  PacketTimeSyncOffset = SendReceive;
+
+  components Counter32khz32C, new CounterToLocalTimeC(T32khz);
+  CounterToLocalTimeC.Counter -> Counter32khz32C;
+  SendReceive.LocalTime32khz -> CounterToLocalTimeC;
+
+  //DummyTimer is introduced to compile apps that use no timers
+  components HilTimerMilliC, new TimerMilliC() as DummyTimer;
+  SendReceive.LocalTimeMilli -> HilTimerMilliC;
 }
index a2df2697cc2e260f32fc007fec02cfce3b9011c8..c106b7a090a1df93c2bfc87ee94420e2b30f8410 100644 (file)
@@ -29,9 +29,15 @@ typedef enum {
 typedef nx_struct CC1KMetadata {
   nx_int16_t strength_or_preamble; /* negative when used for preamble length */
   nx_uint8_t metadataBits;
-  nx_uint16_t time;
+  nx_bool timesync;
+  nx_uint32_t timestamp;
   nx_uint8_t sendSecurityMode;
   nx_uint8_t receiveSecurityMode;  
 } cc1000_metadata_t;
 
+enum
+{
+  CC1000_INVALID_TIMESTAMP  = 0x80000000L,
+};
+
 #endif
index 24781e4f088f9b99205533e00d74d15e664b286d..09a395501aa0d40869a485035d044ac9665e6d83 100644 (file)
@@ -1,5 +1,3 @@
-// $Id$
-
 /*
  * "Copyright (c) 2000-2005 The Regents of the University  of California.  
  * All rights reserved.
@@ -32,6 +30,7 @@
 #include "crc.h"
 #include "CC1000Const.h"
 #include "Timer.h"
+#include "CC1000TimeSyncMessage.h"
 
 /**
  * A rewrite of the low-power-listening CC1000 radio stack.
@@ -50,6 +49,7 @@
  * @author Jaein Jeong
  * @author Joe Polastre
  * @author David Gay
+ * @author Marco Langerwisch (Packet timestamping)
  */
   
 module CC1000SendReceiveP @safe() {
@@ -58,11 +58,14 @@ module CC1000SendReceiveP @safe() {
     interface StdControl;
     interface Send;
     interface Receive;
-    interface RadioTimeStamping;
     interface Packet;
     interface ByteRadio;
     interface PacketAcknowledgements;
     interface LinkPacketMetadata;
+
+    interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
+    interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+    interface PacketTimeSyncOffset;
   }
   uses {
     //interface PowerManagement;
@@ -71,10 +74,21 @@ module CC1000SendReceiveP @safe() {
     interface CC1000Squelch;
     interface ReadNow<uint16_t> as RssiRx;
     async command am_addr_t amAddress();
+
+    interface LocalTime<T32khz> as LocalTime32khz;
+    interface LocalTime<TMilli> as LocalTimeMilli;
   }
 }
 implementation 
 {
+#ifdef PLATFORM_MICA2
+  // estimated calibration, 19.2 Kbps data, Manchester Encoding, time in jiffies (32768 Hz)
+  static const int8_t BIT_CORRECTION[8] = { 27, 28, 30, 32, 34, 36, 38, 40 };
+#else
+  // other platforms not calibrated yet
+  static const uint8_t BIT_CORRECTION[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
+#endif
+
   enum {
     OFF_STATE,
 
@@ -257,10 +271,14 @@ implementation
          return FAIL;
        else {
          cc1000_header_t *header = getHeader(msg);
+          cc1000_metadata_t *metadata = getMetadata(msg);
 
          f.txBusy = TRUE;
          header->length = len;
          txBufPtr = msg;
+
+          metadata->timesync = FALSE;
+          metadata->timestamp = CC1000_INVALID_TIMESTAMP;
        }
       }
     signal ByteRadio.rts(msg);
@@ -299,12 +317,23 @@ implementation
     sendNextByte();
     nextTxByte = SYNC_BYTE2;
     enterTxDataState();
-    signal RadioTimeStamping.transmittedSFD(0, txBufPtr); 
   }
 
   void txData() {
     cc1000_header_t *txHeader = getHeader(txBufPtr);
     sendNextByte();
+
+    if (nextTxByte == SYNC_BYTE2) {
+      // SYNC_WORD has just been sent
+      uint32_t time32khz = call LocalTime32khz.get();
+      call PacketTimeStamp32khz.set(txBufPtr, time32khz);
+
+      if (call PacketTimeSyncOffset.isSet(txBufPtr)) {
+        timesync_radio_t *timesync = (timesync_radio_t*)((void*)txBufPtr + call PacketTimeSyncOffset.get(txBufPtr));
+        // set timesync event time as the offset between the event time and the SFD interrupt time (TEP 133)
+        *timesync  -= time32khz;
+      }
+    }
     
     if (count < txHeader->length + sizeof(message_header_t))
       {
@@ -445,9 +474,12 @@ implementation
     else if (count <= 6)
       {
        // TODO: Modify to be tolerant of bad bits in the preamble...
+        uint32_t time;
        uint16_t tmp;
        uint8_t i;
 
+        time = call LocalTime32khz.get();
+
        // bit shift the data in with previous sample to find sync
        tmp = rxShiftBuf;
        rxShiftBuf = rxShiftBuf << 8 | in;
@@ -464,7 +496,10 @@ implementation
                enterRxState();
                signal ByteRadio.rx();
                f.rxBitOffset = 7 - i;
-               signal RadioTimeStamping.receivedSFD(0);
+                // correct receive time according to bit offset and set timestamp
+                time -= BIT_CORRECTION[f.rxBitOffset];
+                call PacketTimeStamp32khz.set(rxBufPtr, time);
+
                call RssiRx.read();
              }
          }
@@ -629,7 +664,9 @@ implementation
   /* Abstract packet layout */
 
   command void Packet.clear(message_t *msg) {
-    memset(msg, 0, sizeof(message_t));
+    memset(getHeader(msg), 0x0, sizeof(cc1000_header_t));
+    memset(getFooter(msg), 0x0, sizeof(cc1000_footer_t));
+    memset(getMetadata(msg), 0x0, sizeof(cc1000_metadata_t));
   }
 
   command uint8_t Packet.payloadLength(message_t *msg) {
@@ -677,9 +714,71 @@ implementation
   async command bool LinkPacketMetadata.highChannelQuality(message_t* msg) {
     return getMetadata(msg)->metadataBits & CC1000_WHITE_BIT;
   }
-  
-  // Default events for radio send/receive coordinators do nothing.
-  // Be very careful using these, or you'll break the stack.
-  default async event void RadioTimeStamping.transmittedSFD(uint16_t time, message_t *msgBuff) { }
-  default async event void RadioTimeStamping.receivedSFD(uint16_t time) { }
+
+  /***************** PacketTimeStamp32khz Commands ****************/
+  async command bool PacketTimeStamp32khz.isValid(message_t* msg)
+  {
+    return (getMetadata(msg)->timestamp != CC1000_INVALID_TIMESTAMP);
+  }
+
+  async command uint32_t PacketTimeStamp32khz.timestamp(message_t* msg)
+  {
+    return getMetadata(msg)->timestamp;
+  }
+
+  async command void PacketTimeStamp32khz.clear(message_t* msg)
+  {
+    getMetadata(msg)->timesync = FALSE;
+    getMetadata(msg)->timestamp = CC1000_INVALID_TIMESTAMP;
+  }
+
+  async command void PacketTimeStamp32khz.set(message_t* msg, uint32_t value)
+  {
+    getMetadata(msg)->timestamp = value;
+  }
+
+  /***************** PacketTimeStampMilli Commands ****************/
+  // over the air value is always T32khz
+  async command bool PacketTimeStampMilli.isValid(message_t* msg)
+  {
+    return call PacketTimeStamp32khz.isValid(msg);
+  }
+
+  async command uint32_t PacketTimeStampMilli.timestamp(message_t* msg)
+  {
+    int32_t offset = call PacketTimeStamp32khz.timestamp(msg) - call LocalTime32khz.get();
+    return (offset >> 5) + call LocalTimeMilli.get();
+  }
+
+  async command void PacketTimeStampMilli.clear(message_t* msg)
+  {
+    call PacketTimeStamp32khz.clear(msg);
+  }
+
+  async command void PacketTimeStampMilli.set(message_t* msg, uint32_t value)
+  {
+    int32_t offset = (value - call LocalTimeMilli.get()) << 5;
+    call PacketTimeStamp32khz.set(msg, offset + call LocalTime32khz.get());
+  }
+
+  /*----------------- PacketTimeSyncOffset -----------------*/
+  async command bool PacketTimeSyncOffset.isSet(message_t* msg)
+  {
+    return getMetadata(msg)->timesync;
+  }
+
+  async command uint8_t PacketTimeSyncOffset.get(message_t* msg)
+  {
+    return sizeof(cc1000_header_t) + getHeader(msg)->length - sizeof(timesync_radio_t);
+  }
+
+  async command void PacketTimeSyncOffset.set(message_t* msg)
+  {
+    getMetadata(msg)->timesync = TRUE;
+  }
+
+  async command void PacketTimeSyncOffset.cancel(message_t* msg)
+  {
+    getMetadata(msg)->timesync = FALSE;
+  }
 }
diff --git a/tos/chips/cc1000/CC1000TimeSyncMessage.h b/tos/chips/cc1000/CC1000TimeSyncMessage.h
new file mode 100644 (file)
index 0000000..a744fd3
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __TIMESYNCMESSAGE_H__
+#define __TIMESYNCMESSAGE_H__
+
+// this value is sent in the air
+typedef nx_uint32_t timesync_radio_t;
+
+#endif//__TIMESYNCMESSAGE_H__
diff --git a/tos/chips/cc1000/CC1000TimeSyncMessageC.nc b/tos/chips/cc1000/CC1000TimeSyncMessageC.nc
new file mode 100644 (file)
index 0000000..d370f84
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ */
+
+/**
+ * The Active Message layer for the CC1000 radio with timesync support. This
+ * configuration is just layer above CC1000ActiveMessageC that supports
+ * TimeSyncPacket and TimeSyncAMSend interfaces (TEP 133)
+ *
+ * @author: Miklos Maroti
+ * @author: Brano Kusy (CC2420 port)
+ * @author: Marco Langerwisch (CC1000 port)
+ */
+
+#include <Timer.h>
+#include <AM.h>
+
+configuration CC1000TimeSyncMessageC
+{
+    provides
+    {
+        interface SplitControl;
+        interface Receive[am_id_t id];
+        interface Receive as Snoop[am_id_t id];
+        interface Packet;
+        interface AMPacket;
+
+        interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
+        interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+
+        interface TimeSyncAMSend<T32khz, uint32_t> as TimeSyncAMSend32khz[am_id_t id];
+        interface TimeSyncPacket<T32khz, uint32_t> as TimeSyncPacket32khz;
+
+        interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[am_id_t id];
+        interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
+    }
+}
+
+implementation
+{
+        components CC1000TimeSyncMessageP, CC1000ActiveMessageC, LedsC;
+
+        PacketTimeStamp32khz = CC1000ActiveMessageC;
+        PacketTimeStampMilli = CC1000ActiveMessageC;
+
+        TimeSyncAMSend32khz = CC1000TimeSyncMessageP;
+        TimeSyncPacket32khz = CC1000TimeSyncMessageP;
+
+        TimeSyncAMSendMilli = CC1000TimeSyncMessageP;
+        TimeSyncPacketMilli = CC1000TimeSyncMessageP;
+
+        Packet = CC1000TimeSyncMessageP;
+        CC1000TimeSyncMessageP.SubSend -> CC1000ActiveMessageC.AMSend;
+        CC1000TimeSyncMessageP.SubPacket -> CC1000ActiveMessageC.Packet;
+        CC1000TimeSyncMessageP.PacketTimeStamp32khz -> CC1000ActiveMessageC;
+        CC1000TimeSyncMessageP.PacketTimeStampMilli -> CC1000ActiveMessageC;
+        CC1000TimeSyncMessageP.PacketTimeSyncOffset -> CC1000ActiveMessageC;
+
+        components Counter32khz32C,
+            new CounterToLocalTimeC(T32khz) as LocalTime32khzC, LocalTimeMilliC;
+        LocalTime32khzC.Counter -> Counter32khz32C;
+        CC1000TimeSyncMessageP.LocalTime32khz -> LocalTime32khzC;
+        CC1000TimeSyncMessageP.LocalTimeMilli -> LocalTimeMilliC;
+        CC1000TimeSyncMessageP.Leds -> LedsC;
+
+        SplitControl = CC1000ActiveMessageC;
+        Receive = CC1000ActiveMessageC.Receive;
+        Snoop = CC1000ActiveMessageC.Snoop;
+        AMPacket = CC1000ActiveMessageC;
+}
diff --git a/tos/chips/cc1000/CC1000TimeSyncMessageP.nc b/tos/chips/cc1000/CC1000TimeSyncMessageP.nc
new file mode 100644 (file)
index 0000000..1590c52
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * @author: Miklos Maroti
+ * @author: Brano Kusy (CC2420 port)
+ * @author: Marco Langerwisch (CC1000 port)
+ */
+#include "CC1000TimeSyncMessage.h"
+
+module CC1000TimeSyncMessageP
+{
+    provides
+    {
+        interface TimeSyncAMSend<T32khz, uint32_t> as TimeSyncAMSend32khz[uint8_t id];
+        interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[uint8_t id];
+        interface Packet;
+
+        interface TimeSyncPacket<T32khz, uint32_t> as TimeSyncPacket32khz;
+        interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
+    }
+
+    uses
+    {
+        interface AMSend as SubSend[uint8_t id];
+        interface Packet as SubPacket;
+
+        interface PacketTimeStamp<T32khz,uint32_t> as PacketTimeStamp32khz;
+        interface PacketTimeStamp<TMilli,uint32_t> as PacketTimeStampMilli;
+        interface PacketTimeSyncOffset;
+
+        interface LocalTime<T32khz> as LocalTime32khz;
+        interface LocalTime<TMilli> as LocalTimeMilli;
+        interface Leds;
+    }
+}
+
+implementation
+{
+    // TODO: change the Packet.payloadLength and Packet.maxPayloadLength commands to async
+    inline void* getFooter(message_t* msg)
+    {
+        // we use the payload length that we export (the smaller one)
+        return msg->data + call Packet.payloadLength(msg);
+    }
+
+/*----------------- Packet -----------------*/
+    command void Packet.clear(message_t* msg)
+    {
+        call PacketTimeSyncOffset.cancel(msg);
+        call SubPacket.clear(msg);
+    }
+
+    command void Packet.setPayloadLength(message_t* msg, uint8_t len)
+    {
+        call SubPacket.setPayloadLength(msg, len + sizeof(timesync_radio_t));
+    }
+
+    command uint8_t Packet.payloadLength(message_t* msg)
+    {
+        return call SubPacket.payloadLength(msg) - sizeof(timesync_radio_t);
+    }
+
+    command uint8_t Packet.maxPayloadLength()
+    {
+        return call SubPacket.maxPayloadLength() - sizeof(timesync_radio_t);
+    }
+
+    command void* Packet.getPayload(message_t* msg, uint8_t len)
+    {
+        return call SubPacket.getPayload(msg, len + sizeof(timesync_radio_t));
+    }
+
+/*----------------- TimeSyncAMSend32khz -----------------*/
+    command error_t TimeSyncAMSend32khz.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len, uint32_t event_time)
+    {
+        error_t err;
+        timesync_radio_t* timesync = (timesync_radio_t*)(msg->data + len);
+        *timesync = event_time;
+
+        err = call SubSend.send[id](addr, msg, len + sizeof(timesync_radio_t));
+        call PacketTimeSyncOffset.set(msg);
+        return err;
+    }
+
+    command error_t TimeSyncAMSend32khz.cancel[am_id_t id](message_t* msg)
+    {
+        call PacketTimeSyncOffset.cancel(msg);
+        return call SubSend.cancel[id](msg);
+    }
+
+    default event void TimeSyncAMSend32khz.sendDone[am_id_t id](message_t* msg, error_t error) {}
+
+    command uint8_t TimeSyncAMSend32khz.maxPayloadLength[am_id_t id]()
+    {
+        return call SubSend.maxPayloadLength[id]() - sizeof(timesync_radio_t);
+    }
+
+    command void* TimeSyncAMSend32khz.getPayload[am_id_t id](message_t* msg, uint8_t len)
+    {
+        return call SubSend.getPayload[id](msg, len + sizeof(timesync_radio_t));
+    }
+
+/*----------------- TimeSyncAMSendMilli -----------------*/
+    command error_t TimeSyncAMSendMilli.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len, uint32_t event_time)
+    {
+        // compute elapsed time in millisecond
+        event_time = ((event_time - call LocalTimeMilli.get()) << 5) + call LocalTime32khz.get();
+        return call TimeSyncAMSend32khz.send[id](addr, msg, len, event_time);
+    }
+
+    command error_t TimeSyncAMSendMilli.cancel[am_id_t id](message_t* msg)
+    {
+        return call TimeSyncAMSend32khz.cancel[id](msg);
+    }
+
+    default event void TimeSyncAMSendMilli.sendDone[am_id_t id](message_t* msg, error_t error){}
+
+    command uint8_t TimeSyncAMSendMilli.maxPayloadLength[am_id_t id]()
+    {
+        return call TimeSyncAMSend32khz.maxPayloadLength[id]();
+    }
+
+    command void* TimeSyncAMSendMilli.getPayload[am_id_t id](message_t* msg, uint8_t len)
+    {
+        return call TimeSyncAMSend32khz.getPayload[id](msg, len);
+    }
+
+/*----------------- SubSend.sendDone -------------------*/
+    event void SubSend.sendDone[am_id_t id](message_t* msg, error_t error)
+    {
+        signal TimeSyncAMSend32khz.sendDone[id](msg, error);
+        signal TimeSyncAMSendMilli.sendDone[id](msg, error);
+    }
+
+/*----------------- TimeSyncPacket32khz -----------------*/
+    command bool TimeSyncPacket32khz.isValid(message_t* msg)
+    {
+        timesync_radio_t* timesync = getFooter(msg);
+        return call PacketTimeStamp32khz.isValid(msg) && *timesync != CC1000_INVALID_TIMESTAMP;
+    }
+
+    command uint32_t TimeSyncPacket32khz.eventTime(message_t* msg)
+    {
+        timesync_radio_t* timesync = getFooter(msg);
+
+        return (uint32_t)(*timesync) + call PacketTimeStamp32khz.timestamp(msg);
+    }
+
+/*----------------- TimeSyncPacketMilli -----------------*/
+    command bool TimeSyncPacketMilli.isValid(message_t* msg)
+    {
+        timesync_radio_t* timesync = getFooter(msg);
+        return call PacketTimeStampMilli.isValid(msg) && *timesync != CC1000_INVALID_TIMESTAMP;
+    }
+
+    command uint32_t TimeSyncPacketMilli.eventTime(message_t* msg)
+    {
+        timesync_radio_t* timesync = getFooter(msg);
+        return ((int32_t)(*timesync) >> 5) + call PacketTimeStampMilli.timestamp(msg);
+    }
+}
diff --git a/tos/chips/cc1000/LowPowerListening.nc b/tos/chips/cc1000/LowPowerListening.nc
deleted file mode 100644 (file)
index 6fd5d19..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (c) 2005-2006 Rincon Research Corporation
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright
- *   notice, this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the
- *   distribution.
- * - Neither the name of the Arch Rock Corporation nor the names of
- *   its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
- * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE
- */
-/**
- * Low Power Listening interface
- *
- * @author David Moss
- * @author Jonathan Hui
- */
-
-#include <message.h>
-interface LowPowerListening {
-
-  /**
-   * Set this this node's radio sleep interval, in milliseconds.
-   * Once every interval, the node will sleep and perform an Rx check 
-   * on the radio.  Setting the sleep interval to 0 will keep the radio
-   * always on.
-   *
-   * This is the equivalent of setting the local duty cycle rate.
-   *
-   * @param sleepIntervalMs the length of this node's Rx check interval, in [ms]
-   */
-  command void setLocalSleepInterval(uint16_t sleepIntervalMs);
-  
-  /**
-   * @return the local node's sleep interval, in [ms]
-   */
-  command uint16_t getLocalSleepInterval();
-  
-  /**
-   * Set this node's radio duty cycle rate, in units of [percentage*100].
-   * For example, to get a 0.05% duty cycle,
-   * <code>
-   *   call LowPowerListening.setDutyCycle(5);  // or equivalently...
-   *   call LowPowerListening.setDutyCycle(00005);  // for better readability?
-   * </code>
-   *
-   * For a 100% duty cycle (always on),
-   * <code>
-   *   call LowPowerListening.setDutyCycle(10000);
-   * </code>
-   *
-   * This is the equivalent of setting the local sleep interval explicitly.
-   * 
-   * @param dutyCycle The duty cycle percentage, in units of [percentage*100]
-   */
-  command void setLocalDutyCycle(uint16_t dutyCycle);
-  
-  /**
-   * @return this node's radio duty cycle rate, in units of [percentage*100]
-   */
-  command uint16_t getLocalDutyCycle();
-  
-  
-  /**
-   * Configure this outgoing message so it can be transmitted to a neighbor mote
-   * with the specified Rx sleep interval.
-   * @param 'message_t* ONE msg' Pointer to the message that will be sent
-   * @param sleepInterval The receiving node's sleep interval, in [ms]
-   */
-  command void setRxSleepInterval(message_t *msg, uint16_t sleepIntervalMs);
-  
-  /**
-   * @return the destination node's sleep interval configured in this message
-   */
-  command uint16_t getRxSleepInterval(message_t *msg);
-  
-  /**
-   * Configure this outgoing message so it can be transmitted to a neighbor mote
-   * with the specified Rx duty cycle rate.
-   * Duty cycle is in units of [percentage*100], i.e. 0.25% duty cycle = 25.
-   * 
-   * @param msg Pointer to the message that will be sent
-   * @param dutyCycle The duty cycle of the receiving mote, in units of 
-   *     [percentage*100]
-   */
-  command void setRxDutyCycle(message_t *msg, uint16_t dutyCycle);
-  
-  /**
-   * @return the destination node's duty cycle configured in this message
-   *     in units of [percentage*100]
-   */
-  command uint16_t getRxDutyCycle(message_t *msg);
-  
-  /**
-   * Convert a duty cycle, in units of [percentage*100], to
-   * the sleep interval of the mote in milliseconds
-   * @param dutyCycle The duty cycle in units of [percentage*100]
-   * @return The equivalent sleep interval, in units of [ms]
-   */
-  command uint16_t dutyCycleToSleepInterval(uint16_t dutyCycle);
-  
-  /**
-   * Convert a sleep interval, in units of [ms], to a duty cycle
-   * in units of [percentage*100]
-   * @param sleepInterval The sleep interval in units of [ms]
-   * @return The duty cycle in units of [percentage*100]
-   */
-  command uint16_t sleepIntervalToDutyCycle(uint16_t sleepInterval);
-  
-}
diff --git a/tos/chips/cc1000/PacketTimeSyncOffset.nc b/tos/chips/cc1000/PacketTimeSyncOffset.nc
new file mode 100644 (file)
index 0000000..b3cef8c
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti, Brano Kusy
+ *
+ * Interface for one hop time synchronization. Allows to modify timesync
+ * messages in the MAC layer with elapsed time of an event (ETA timesync
+ * primitive). Interface also provides a command to determine offset within
+ * a CC1000 packet, where the timesync ETA value is stored. word 'timestamping'
+ * used in describing commands does not refer to metadata.timestamp value,
+ * rather it refers to the timesync ETA timestamp which is part of data
+ * payload and is transmitted over the air.
+ */
+
+interface PacketTimeSyncOffset
+{
+    /**
+     * @param 'message_t *ONE msg' message to examine.
+     *
+     * Returns TRUE if the current message should be timestamped.
+     */
+    async command bool isSet(message_t* msg);
+
+    /**
+     * @param 'message_t *ONE msg' message to examine.
+     *
+     * Returns the offset of where the timesync timestamp is sotred in a
+     * CC2420 packet
+     */
+    async command uint8_t get(message_t* msg);
+
+    /**
+     * @param 'message_t *ONE msg' message to modify.
+     *
+     *  Sets the current message to be timestamped in the MAC layer.
+     */
+    async command void set(message_t* msg);
+
+    /**
+     * @param 'message_t *ONE msg' message to modify.
+     *
+     * Cancels any pending requests to timestamp the message in MAC.
+     */
+    async command void cancel(message_t* msg);
+}
+
index 798107f0ebcb0367ee9e7822cfc8d1b5d0ca095c..eae62c35b82fb2e7add4e331a2859de8264f25e2 100644 (file)
@@ -38,8 +38,8 @@
 
 typedef uint8_t cc2420_status_t;
 
-#ifndef TFRAMES_ENABLED
-#define CC2420_IFRAME_TYPE
+#if defined(TFRAMES_ENABLED) && defined(IEEE154FRAMES_ENABLED)
+#error "Both TFRAMES and IEEE154FRAMES enabled!"
 #endif
 
 /**
@@ -81,6 +81,17 @@ typedef uint8_t cc2420_status_t;
  * All of these fields will be filled in automatically by the radio stack 
  * when you attempt to send a message.
  */
+/**
+ * CC2420 Security Header
+ */
+typedef nx_struct security_header_t {
+  nx_uint8_t secLevel:3;
+  nx_uint8_t keyMode:2;
+  nx_uint8_t reserved:3;
+  nx_uint32_t frameCounter;
+  nx_uint8_t keyID[1]; // One byte for now
+} security_header_t;
+
 typedef nx_struct cc2420_header_t {
   nxle_uint8_t length;
   nxle_uint16_t fcf;
@@ -88,18 +99,19 @@ typedef nx_struct cc2420_header_t {
   nxle_uint16_t destpan;
   nxle_uint16_t dest;
   nxle_uint16_t src;
+  /** CC2420 802.15.4 header ends here */
+#ifdef CC2420_HW_SECURITY
+  security_header_t secHdr;
+#endif
   
+#ifndef TFRAMES_ENABLED
   /** I-Frame 6LowPAN interoperability byte */
-#ifdef CC2420_IFRAME_TYPE
   nxle_uint8_t network;
 #endif
 
-#ifndef TINYOS_IP
   nxle_uint8_t type;
-#endif
-
 } cc2420_header_t;
-  
+
 /**
  * CC2420 Packet Footer
  */
@@ -128,7 +140,6 @@ typedef nx_struct cc2420_metadata_t {
   nx_uint16_t maxRetries;
   nx_uint16_t retryDelay;
 #endif
-
 } cc2420_metadata_t;
 
 
@@ -165,7 +176,6 @@ typedef nx_struct cc2420_packet_t {
 #define TINYOS_6LOWPAN_NETWORK_ID 0x3f
 #endif
 
-
 enum {
   // size of the header not including the length byte
   MAC_HEADER_SIZE = sizeof( cc2420_header_t ) - 1,
@@ -175,6 +185,8 @@ enum {
   MAC_PACKET_SIZE = MAC_HEADER_SIZE + TOSH_DATA_LENGTH + MAC_FOOTER_SIZE,
 
   CC2420_SIZE = MAC_HEADER_SIZE + MAC_FOOTER_SIZE,
+
+  AM_OVERHEAD = 2,
 };
 
 enum cc2420_enums {
@@ -407,6 +419,22 @@ enum cc2420_sfdmux_enums {
   CC2420_SFDMUX_XOSC16M_STABLE = 24,
 };
 
+enum cc2420_security_enums{
+  CC2420_NO_SEC = 0,
+  CC2420_CBC_MAC = 1,
+  CC2420_CTR = 2,
+  CC2420_CCM = 3,
+  NO_SEC = 0,
+  CBC_MAC_4 = 1,
+  CBC_MAC_8 = 2,
+  CBC_MAC_16 = 3,
+  CTR = 4,
+  CCM_4 = 5,
+  CCM_8 = 6,
+  CCM_16 = 7
+};
+norace uint8_t SECURITYLOCK = 0;
+
 enum
 {
   CC2420_INVALID_TIMESTAMP  = 0x80000000L,
index 21734736d9323621bb96db1dce851a46e8985b2e..752d20a4643c589599b814021fede954a96116ca 100644 (file)
 
 #include "CC2420.h"
 #include "AM.h"
+#include "Ieee154.h"
+
+#ifdef IEEE154FRAMES_ENABLED
+#error "CC2420 AM layer cannot work when IEEE 802.15.4 frames only are used"
+#endif
 
 configuration CC2420ActiveMessageC {
   provides {
@@ -55,29 +60,18 @@ configuration CC2420ActiveMessageC {
   }
 }
 implementation {
+  enum {
+    CC2420_AM_SEND_ID     = unique(RADIO_SEND_RESOURCE),
+  };
 
+  components CC2420RadioC as Radio;
   components CC2420ActiveMessageP as AM;
-  components CC2420CsmaC as CsmaC;
   components ActiveMessageAddressC;
-  components UniqueSendC;
-  components UniqueReceiveC;
-  components CC2420TinyosNetworkC;
-  components CC2420PacketC;
+  components CC2420CsmaC as CsmaC;
   components CC2420ControlC;
+  components CC2420PacketC;
   
-#if defined(LOW_POWER_LISTENING) || defined(ACK_LOW_POWER_LISTENING)
-  components DefaultLplC as LplC;
-#else
-  components DummyLplC as LplC;
-#endif
-
-#if defined(PACKET_LINK)
-  components PacketLinkC as LinkC;
-#else
-  components PacketLinkDummyC as LinkC;
-#endif
-
-  
+  SplitControl = Radio;
   RadioBackoff = AM;
   Packet = AM;
   AMSend = AM;
@@ -85,28 +79,16 @@ implementation {
   Receive = AM.Receive;
   Snoop = AM.Snoop;
   AMPacket = AM;
-  PacketLink = LinkC;
-  LowPowerListening = LplC;
-  CC2420Packet = CC2420PacketC;
-  PacketAcknowledgements = CC2420PacketC;
-  LinkPacketMetadata = CC2420PacketC;
-  
-  // SplitControl Layers
-  SplitControl = LplC;
-  LplC.SubControl -> CsmaC;
+  PacketLink = Radio;
+  LowPowerListening = Radio;
+  CC2420Packet = Radio;
+  PacketAcknowledgements = Radio;
+  LinkPacketMetadata = Radio;
   
-  // Send Layers
-  AM.SubSend -> UniqueSendC;
-  UniqueSendC.SubSend -> LinkC;
-  LinkC.SubSend -> LplC.Send;
-  LplC.SubSend -> CC2420TinyosNetworkC.Send;
-  CC2420TinyosNetworkC.SubSend -> CsmaC;
-  
-  // Receive Layers
-  AM.SubReceive -> LplC;
-  LplC.SubReceive -> UniqueReceiveC.Receive;
-  UniqueReceiveC.SubReceive -> CC2420TinyosNetworkC.Receive;
-  CC2420TinyosNetworkC.SubReceive -> CsmaC;
+  // Radio resource for the AM layer
+  AM.RadioResource -> Radio.Resource[CC2420_AM_SEND_ID];
+  AM.SubSend -> Radio.ActiveSend;
+  AM.SubReceive -> Radio.ActiveReceive;
 
   AM.ActiveMessageAddress -> ActiveMessageAddressC;
   AM.CC2420Packet -> CC2420PacketC;
@@ -114,5 +96,7 @@ implementation {
   AM.CC2420Config -> CC2420ControlC;
   
   AM.SubBackoff -> CsmaC;
-  
+
+  components LedsC;
+  AM.Leds -> LedsC;
 }
index 0db2423c7b83167d7bf41b4797e85c117b52cb8f..f3d5de3987dca244cca393046eae84d606713874 100644 (file)
@@ -53,9 +53,26 @@ module CC2420ActiveMessageP @safe() {
     interface CC2420Config;
     interface ActiveMessageAddress;
     interface RadioBackoff as SubBackoff;
+
+    interface Resource as RadioResource;
+    interface Leds;
   }
 }
 implementation {
+  uint16_t pending_length;
+  message_t *pending_message = NULL;
+  /***************** Resource event  ****************/
+  event void RadioResource.granted() {
+    uint8_t rc;
+    cc2420_header_t* header = call CC2420PacketBody.getHeader( pending_message );
+
+    signal SendNotifier.aboutToSend[header->type](header->dest, pending_message);
+    rc = call SubSend.send( pending_message, pending_length );
+    if (rc != SUCCESS) {
+      call RadioResource.release();
+      signal AMSend.sendDone[header->type]( pending_message, rc );
+    }
+  }
 
   /***************** AMSend Commands ****************/
   command error_t AMSend.send[am_id_t id](am_addr_t addr,
@@ -72,9 +89,21 @@ implementation {
     header->destpan = call CC2420Config.getPanAddr();
     header->src = call AMPacket.address();
     
-    signal SendNotifier.aboutToSend[id](addr, msg);
-    
-    return call SubSend.send( msg, len );
+    if (call RadioResource.immediateRequest() == SUCCESS) {
+      error_t rc;
+      signal SendNotifier.aboutToSend[id](addr, msg);
+      
+      rc = call SubSend.send( msg, len );
+      if (rc != SUCCESS) {
+        call RadioResource.release();
+      }
+
+      return rc;
+    } else {
+      pending_length  = len;
+      pending_message = msg;
+      return call RadioResource.request();
+    }
   }
 
   command error_t AMSend.cancel[am_id_t id](message_t* msg) {
@@ -158,7 +187,7 @@ implementation {
   }
   
   command uint8_t Packet.maxPayloadLength() {
-    return TOSH_DATA_LENGTH;
+    return call SubSend.maxPayloadLength();
   }
   
   command void* Packet.getPayload(message_t* msg, uint8_t len) {
@@ -168,6 +197,7 @@ implementation {
   
   /***************** SubSend Events ****************/
   event void SubSend.sendDone(message_t* msg, error_t result) {
+    call RadioResource.release();
     signal AMSend.sendDone[call AMPacket.type(msg)](msg, result);
   }
 
@@ -175,10 +205,6 @@ implementation {
   /***************** SubReceive Events ****************/
   event message_t* SubReceive.receive(message_t* msg, void* payload, uint8_t len) {
     
-    if(!(call CC2420PacketBody.getMetadata(msg))->crc) {
-      return msg;
-    }
-    
     if (call AMPacket.isForMe(msg)) {
       return signal Receive.receive[call AMPacket.type(msg)](msg, payload, len);
     }
@@ -235,8 +261,6 @@ implementation {
   async command void RadioBackoff.setCca[am_id_t amId](bool useCca) {
     call SubBackoff.setCca(useCca);
   }
-
-
   
   /***************** Defaults ****************/
   default event message_t* Receive.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
@@ -248,6 +272,7 @@ implementation {
   }
 
   default event void AMSend.sendDone[uint8_t id](message_t* msg, error_t err) {
+    call RadioResource.release();
   }
 
   default event void SendNotifier.aboutToSend[am_id_t amId](am_addr_t addr, message_t *msg) {
diff --git a/tos/chips/cc2420/CC2420Ieee154MessageC.nc b/tos/chips/cc2420/CC2420Ieee154MessageC.nc
new file mode 100644 (file)
index 0000000..9d9965a
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*                                                                     tab:4
+ * "Copyright (c) 2005 Stanford University. All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+ * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
+ * HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
+ * ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * IEEE 802.15.4 layer for the cc2420.  Provides a simplistic 
+ *       link layer with dispatching on the 6lowpan "network" field
+ *
+ * @author Philip Levis
+ * @author David Moss
+ * @author Stephen Dawson-Haggerty
+ * @version $Revision$ $Date$
+ */
+
+#include "CC2420.h"
+#ifdef TFRAMES_ENABLED
+#error "The CC2420 Ieee 802.15.4 layer does not work with TFRAMES"
+#endif
+
+configuration CC2420Ieee154MessageC {
+  provides {
+    interface SplitControl;
+
+    interface Resource as SendResource[uint8_t clientId];
+    interface Ieee154Send;
+    interface Receive as Ieee154Receive;
+
+    interface Ieee154Packet;
+    interface Packet;
+
+    interface CC2420Packet;
+    interface PacketAcknowledgements;
+    interface LinkPacketMetadata;
+    interface LowPowerListening;
+    interface CC2420Config;
+    interface PacketLink;
+  }
+}
+implementation {
+
+  components CC2420RadioC as Radio;
+  components CC2420Ieee154MessageP as Msg;
+  components CC2420PacketC;
+  components CC2420ControlC;
+
+  SendResource = Radio.Resource;
+  Ieee154Receive = Radio.Receive;
+  Ieee154Send = Msg;
+  Ieee154Packet = Msg;
+  Packet = Msg;
+  CC2420Packet = CC2420PacketC;
+
+  SplitControl = Radio;
+  CC2420Packet = Radio;
+  PacketAcknowledgements = Radio;
+  LinkPacketMetadata = Radio;
+  LowPowerListening = Radio;
+  CC2420Config = CC2420ControlC;
+  PacketLink = Radio;
+
+  Msg.SubSend -> Radio.Send;
+
+  Msg.CC2420Packet -> CC2420PacketC;
+  Msg.CC2420PacketBody -> CC2420PacketC;
+  Msg.CC2420Config -> CC2420ControlC;
+
+}
diff --git a/tos/chips/cc2420/CC2420Ieee154MessageP.nc b/tos/chips/cc2420/CC2420Ieee154MessageP.nc
new file mode 100644 (file)
index 0000000..2629943
--- /dev/null
@@ -0,0 +1,175 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*                                                                     tab:4
+ * "Copyright (c) 2005 Stanford University. All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+ * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
+ * HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
+ * ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+
+/**
+ *
+ * @author Stephen Dawson-Haggerty
+ * @version $Revision$ $Date$
+ */
+#include "CC2420.h"
+#include "IEEE802154.h"
+
+module CC2420Ieee154MessageP {
+
+  provides {
+    interface Ieee154Send;
+    interface Ieee154Packet;
+    interface Packet;
+  }
+  
+  uses {
+    interface Send as SubSend;
+    interface CC2420Packet;
+    interface CC2420PacketBody;
+    interface CC2420Config;
+  }
+}
+implementation {
+
+  /***************** Ieee154Send Commands ****************/
+  command error_t Ieee154Send.send(ieee154_saddr_t addr,
+                                   message_t* msg,
+                                   uint8_t len) {
+    cc2420_header_t* header = call CC2420PacketBody.getHeader( msg );
+    header->dest = addr;
+    header->destpan = call CC2420Config.getPanAddr();
+    header->src = call CC2420Config.getShortAddr();
+
+    return call SubSend.send( msg, len );
+  }
+
+  command error_t Ieee154Send.cancel(message_t* msg) {
+    return call SubSend.cancel(msg);
+  }
+
+  command uint8_t Ieee154Send.maxPayloadLength() {
+    return call Packet.maxPayloadLength();
+  }
+
+  command void* Ieee154Send.getPayload(message_t* m, uint8_t len) {
+    return call Packet.getPayload(m, len);
+  }
+
+  /***************** Ieee154Packet Commands ****************/
+  command ieee154_saddr_t Ieee154Packet.address() {
+    return call CC2420Config.getShortAddr();
+  }
+  command ieee154_saddr_t Ieee154Packet.destination(message_t* msg) {
+    cc2420_header_t* header = call CC2420PacketBody.getHeader(msg);
+    return header->dest;
+  }
+  command ieee154_saddr_t Ieee154Packet.source(message_t* msg) {
+    cc2420_header_t* header = call CC2420PacketBody.getHeader(msg);
+    return header->src;
+  }
+
+  command void Ieee154Packet.setDestination(message_t* msg, ieee154_saddr_t addr) {
+    cc2420_header_t* header = call CC2420PacketBody.getHeader(msg);
+    header->dest = addr;
+  }
+
+  command void Ieee154Packet.setSource(message_t* msg, ieee154_saddr_t addr) {
+    cc2420_header_t* header = call CC2420PacketBody.getHeader(msg);
+    header->src = addr;
+  }
+
+  command bool Ieee154Packet.isForMe(message_t* msg) {
+    return (call Ieee154Packet.destination(msg) == call Ieee154Packet.address() ||
+           call Ieee154Packet.destination(msg) == IEEE154_BROADCAST_ADDR);
+  }
+
+  command ieee154_panid_t Ieee154Packet.pan(message_t* msg) {
+    return (call CC2420PacketBody.getHeader(msg))->destpan;
+  }
+
+  command void Ieee154Packet.setPan(message_t* msg, ieee154_panid_t grp) {
+    // Overridden intentionally when we send()
+    (call CC2420PacketBody.getHeader(msg))->destpan = grp;
+  }
+
+  command ieee154_panid_t Ieee154Packet.localPan() {
+    return call CC2420Config.getPanAddr();
+  }
+
+
+  /***************** Packet Commands ****************/
+  command void Packet.clear(message_t* msg) {
+    memset(call CC2420PacketBody.getHeader(msg), sizeof(cc2420_header_t) - AM_OVERHEAD, 0);
+    memset(call CC2420PacketBody.getMetadata(msg), sizeof(cc2420_metadata_t), 0);
+  }
+  
+  command uint8_t Packet.payloadLength(message_t* msg) {
+    return (call CC2420PacketBody.getHeader(msg))->length - CC2420_SIZE + AM_OVERHEAD;
+  }
+  
+  command void Packet.setPayloadLength(message_t* msg, uint8_t len) {
+    (call CC2420PacketBody.getHeader(msg))->length  = len + CC2420_SIZE - AM_OVERHEAD;
+  }
+  
+  command uint8_t Packet.maxPayloadLength() {
+    return TOSH_DATA_LENGTH + AM_OVERHEAD;
+  }
+  
+  command void* Packet.getPayload(message_t* msg, uint8_t len) {
+        return call SubSend.getPayload( msg, len );
+  }
+
+  
+  /***************** SubSend Events ****************/
+  event void SubSend.sendDone(message_t* msg, error_t result) {
+    signal Ieee154Send.sendDone(msg, result);
+  }
+
+  /***************** CC2420Config Events ****************/
+  event void CC2420Config.syncDone( error_t error ) {
+  }
+
+  default event void Ieee154Send.sendDone(message_t *msg, error_t e) {
+
+  }
+}
diff --git a/tos/chips/cc2420/CC2420RadioC.nc b/tos/chips/cc2420/CC2420RadioC.nc
new file mode 100644 (file)
index 0000000..a30c281
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * "Copyright (c) 2005 Stanford University. All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+ * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
+ * HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
+ * ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * Radio wiring for the CC2420.  This layer seperates the common
+ * wiring of the lower-layer components of the CC2420 stack and makes
+ * them available to clients like the AM stack and the IEEE802.15.4
+ * stack.
+ *
+ * This component provides the highest-level internal interface to
+ * other components of the CC2420 stack.
+ *
+ * @author Philip Levis
+ * @author David Moss
+ * @author Stephen Dawson-Haggerty
+ * @version $Revision$ $Date$
+ */
+
+#include "CC2420.h"
+
+configuration CC2420RadioC {
+  provides {
+    interface SplitControl;
+
+    interface Resource[uint8_t clientId];
+    interface Send;
+    interface Receive;
+
+    interface Send as ActiveSend;
+    interface Receive as ActiveReceive;
+
+    interface CC2420Packet;
+    interface PacketAcknowledgements;
+    interface LinkPacketMetadata;
+    interface LowPowerListening;
+    interface PacketLink;
+
+  }
+}
+implementation {
+
+  components CC2420CsmaC as CsmaC;
+  components UniqueSendC;
+  components UniqueReceiveC;
+  components CC2420TinyosNetworkC;
+  components CC2420PacketC;
+  components CC2420ControlC;
+  
+#if defined(LOW_POWER_LISTENING) || defined(ACK_LOW_POWER_LISTENING)
+  components DefaultLplC as LplC;
+#else
+  components DummyLplC as LplC;
+#endif
+
+#if defined(PACKET_LINK)
+  components PacketLinkC as LinkC;
+#else
+  components PacketLinkDummyC as LinkC;
+#endif
+  
+  PacketLink = LinkC;
+  LowPowerListening = LplC;
+  CC2420Packet = CC2420PacketC;
+  PacketAcknowledgements = CC2420PacketC;
+  LinkPacketMetadata = CC2420PacketC;
+  
+  Resource = CC2420TinyosNetworkC;
+  Send = CC2420TinyosNetworkC.Send;
+  Receive = CC2420TinyosNetworkC.Receive;
+  ActiveSend = CC2420TinyosNetworkC.ActiveSend;
+  ActiveReceive = CC2420TinyosNetworkC.ActiveReceive;
+
+  // SplitControl Layers
+  SplitControl = LplC;
+  LplC.SubControl -> CsmaC;
+  
+  // Send Layers
+  CC2420TinyosNetworkC.SubSend -> UniqueSendC;
+  UniqueSendC.SubSend -> LinkC;
+  LinkC.SubSend -> LplC.Send;
+  LplC.SubSend -> CsmaC;
+  
+  // Receive Layers
+  CC2420TinyosNetworkC.SubReceive -> LplC;
+  LplC.SubReceive -> UniqueReceiveC.Receive;
+  UniqueReceiveC.SubReceive ->  CsmaC;
+  
+}
index a744fd385bc0972f4f81dfb36ac618a12c8ad4c0..3051750c3a5c32a383076d32b4a9713eaf62b2a6 100644 (file)
 #ifndef __TIMESYNCMESSAGE_H__
 #define __TIMESYNCMESSAGE_H__
 
+#ifndef AM_TIMESYNCMSG
+#define AM_TIMESYNCMSG 0x3D
+#endif
+
 // this value is sent in the air
 typedef nx_uint32_t timesync_radio_t;
 
+typedef struct timesync_footer_t
+{
+       nx_am_id_t type;
+  timesync_radio_t timestamp;
+} timesync_footer_t;
+
+
 #endif//__TIMESYNCMESSAGE_H__
index 94ed0c9ab45e467b32983baf8954fb387530a667..ae8ed312bc82766869b267837292b1a3977e0d5d 100644 (file)
@@ -30,6 +30,7 @@
 
 #include <Timer.h>
 #include <AM.h>
+#include "CC2420TimeSyncMessage.h"
 
 configuration CC2420TimeSyncMessageC
 {
@@ -40,7 +41,9 @@ configuration CC2420TimeSyncMessageC
         interface Receive as Snoop[am_id_t id];
         interface Packet;
         interface AMPacket;
-
+        interface PacketAcknowledgements;
+        interface LowPowerListening;
+    
         interface TimeSyncAMSend<T32khz, uint32_t> as TimeSyncAMSend32khz[am_id_t id];
         interface TimeSyncPacket<T32khz, uint32_t> as TimeSyncPacket32khz;
 
@@ -61,10 +64,10 @@ implementation
 
         Packet = CC2420TimeSyncMessageP;
         // use the AMSenderC infrastructure to avoid concurrent send clashes
-        components AMQueueP, ActiveMessageC;
-        CC2420TimeSyncMessageP.SubSend -> AMQueueP.Send[unique(UQ_AMQUEUE_SEND)];
-        CC2420TimeSyncMessageP.AMPacket -> ActiveMessageC;
-        CC2420TimeSyncMessageP.SubPacket -> ActiveMessageC;
+        components new AMSenderC(AM_TIMESYNCMSG);
+        CC2420TimeSyncMessageP.SubSend -> AMSenderC;
+       CC2420TimeSyncMessageP.SubAMPacket -> AMSenderC;
+        CC2420TimeSyncMessageP.SubPacket -> AMSenderC;
 
         CC2420TimeSyncMessageP.PacketTimeStamp32khz -> CC2420PacketC;
         CC2420TimeSyncMessageP.PacketTimeStampMilli -> CC2420PacketC;
@@ -75,8 +78,14 @@ implementation
         CC2420TimeSyncMessageP.LocalTimeMilli -> LocalTimeMilliC;
         CC2420TimeSyncMessageP.Leds -> LedsC;
 
+        components ActiveMessageC;
         SplitControl = CC2420ActiveMessageC;
-        Receive = CC2420ActiveMessageC.Receive;
-        Snoop = CC2420ActiveMessageC.Snoop;
-        AMPacket = CC2420ActiveMessageC;
+        PacketAcknowledgements = CC2420ActiveMessageC;
+        LowPowerListening = CC2420ActiveMessageC;
+        
+        Receive = CC2420TimeSyncMessageP.Receive;
+        Snoop = CC2420TimeSyncMessageP.Snoop;
+        AMPacket = CC2420TimeSyncMessageP;
+        CC2420TimeSyncMessageP.SubReceive -> ActiveMessageC.Receive[AM_TIMESYNCMSG];
+        CC2420TimeSyncMessageP.SubSnoop -> ActiveMessageC.Snoop[AM_TIMESYNCMSG];
 }
index 70e677ae111f712854dcd52c38f6389cdf143740..446a48fb4283207ea2e542dd160d5f7b5b8a0226 100644 (file)
@@ -30,16 +30,23 @@ module CC2420TimeSyncMessageP
         interface TimeSyncAMSend<T32khz, uint32_t> as TimeSyncAMSend32khz[uint8_t id];
         interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[uint8_t id];
         interface Packet;
+        interface AMPacket;
 
         interface TimeSyncPacket<T32khz, uint32_t> as TimeSyncPacket32khz;
         interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
+        
+        interface Receive[am_id_t id];
+        interface Receive as Snoop[am_id_t id];
     }
 
     uses
     {
-        interface Send as SubSend;
-        interface AMPacket;
+          interface AMSend as SubSend;
         interface Packet as SubPacket;
+        interface AMPacket as SubAMPacket;
+
+        interface Receive as SubReceive;
+        interface Receive as SubSnoop;
 
         interface PacketTimeStamp<T32khz,uint32_t> as PacketTimeStamp32khz;
         interface PacketTimeStamp<TMilli,uint32_t> as PacketTimeStampMilli;
@@ -54,10 +61,10 @@ module CC2420TimeSyncMessageP
 implementation
 {
     // TODO: change the Packet.payloadLength and Packet.maxPayloadLength commands to async
-    inline void* getFooter(message_t* msg)
+    inline timesync_footer_t* getFooter(message_t* msg)
     {
         // we use the payload length that we export (the smaller one)
-        return msg->data + call Packet.payloadLength(msg);
+        return (timesync_footer_t*)(msg->data + call Packet.payloadLength(msg));
     }
 
 /*----------------- Packet -----------------*/
@@ -69,34 +76,90 @@ implementation
 
     command void Packet.setPayloadLength(message_t* msg, uint8_t len)
     {
-        call SubPacket.setPayloadLength(msg, len + sizeof(timesync_radio_t));
+        call SubPacket.setPayloadLength(msg, len + sizeof(timesync_footer_t));
     }
 
     command uint8_t Packet.payloadLength(message_t* msg)
     {
-        return call SubPacket.payloadLength(msg) - sizeof(timesync_radio_t);
+        return call SubPacket.payloadLength(msg) - sizeof(timesync_footer_t);
     }
 
     command uint8_t Packet.maxPayloadLength()
     {
-        return call SubPacket.maxPayloadLength() - sizeof(timesync_radio_t);
+        return call SubPacket.maxPayloadLength() - sizeof(timesync_footer_t);
     }
 
     command void* Packet.getPayload(message_t* msg, uint8_t len)
     {
-        return call SubPacket.getPayload(msg, len + sizeof(timesync_radio_t));
+        return call SubPacket.getPayload(msg, len + sizeof(timesync_footer_t));
     }
 
+/*----------------- AMPacket -----------------*/
+
+       inline command am_addr_t AMPacket.address()
+       {
+               return call SubAMPacket.address();
+       }
+
+       inline command am_group_t AMPacket.localGroup()
+       {
+               return call SubAMPacket.localGroup();
+       }
+
+       inline command bool AMPacket.isForMe(message_t* msg)
+       {
+               return call SubAMPacket.isForMe(msg) && call SubAMPacket.type(msg) == AM_TIMESYNCMSG;
+       }
+
+       inline command am_addr_t AMPacket.destination(message_t* msg)
+       {
+               return call SubAMPacket.destination(msg);
+       }
+
+       inline command void AMPacket.setDestination(message_t* msg, am_addr_t addr)
+       {
+               call SubAMPacket.setDestination(msg, addr);
+       }
+
+       inline command am_addr_t AMPacket.source(message_t* msg)
+       {
+               return call SubAMPacket.source(msg);
+       }
+
+       inline command void AMPacket.setSource(message_t* msg, am_addr_t addr)
+       {
+               call SubAMPacket.setSource(msg, addr);
+       }
+
+       inline command am_id_t AMPacket.type(message_t* msg)
+       {
+               return getFooter(msg)->type;
+       }
+
+       inline command void AMPacket.setType(message_t* msg, am_id_t type)
+       {
+               getFooter(msg)->type = type;
+       }
+
+       inline command am_group_t AMPacket.group(message_t* msg)
+       {
+               return call SubAMPacket.group(msg);
+       }
+
+       inline command void AMPacket.setGroup(message_t* msg, am_group_t grp)
+       {
+               call SubAMPacket.setGroup(msg, grp);
+       }
+
 /*----------------- TimeSyncAMSend32khz -----------------*/
     command error_t TimeSyncAMSend32khz.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len, uint32_t event_time)
     {
         error_t err;
-        void * timesync = msg->data + len;
-        *(timesync_radio_t*)timesync = event_time;
+        timesync_footer_t* footer = (timesync_footer_t*)(msg->data + len);
+        footer->type = id;
+        footer->timestamp = event_time;
 
-        call AMPacket.setDestination(msg, addr);
-        call AMPacket.setType(msg, id);
-        err = call SubSend.send(msg, len + sizeof(timesync_radio_t));
+        err = call SubSend.send(addr, msg, len + sizeof(timesync_footer_t));
         call PacketTimeSyncOffset.set(msg);
         return err;
     }
@@ -111,12 +174,12 @@ implementation
 
     command uint8_t TimeSyncAMSend32khz.maxPayloadLength[am_id_t id]()
     {
-        return call SubSend.maxPayloadLength() - sizeof(timesync_radio_t);
+        return call SubSend.maxPayloadLength() - sizeof(timesync_footer_t);
     }
 
     command void* TimeSyncAMSend32khz.getPayload[am_id_t id](message_t* msg, uint8_t len)
     {
-        return call SubSend.getPayload(msg, len + sizeof(timesync_radio_t));
+        return call SubSend.getPayload(msg, len + sizeof(timesync_footer_t));
     }
 
 /*----------------- TimeSyncAMSendMilli -----------------*/
@@ -144,6 +207,26 @@ implementation
         return call TimeSyncAMSend32khz.getPayload[id](msg, len);
     }
 
+/*----------------- SubReceive -------------------*/
+
+    event message_t* SubReceive.receive(message_t* msg, void* payload, uint8_t len)
+    {
+        am_id_t id = call AMPacket.type(msg);
+        return signal Receive.receive[id](msg, payload, len - sizeof(timesync_footer_t));
+    }
+
+    default event message_t* Receive.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) { return msg; }
+
+/*----------------- SubSnoop -------------------*/
+
+    event message_t* SubSnoop.receive(message_t* msg, void* payload, uint8_t len)
+    {
+        am_id_t id = call AMPacket.type(msg);
+        return signal Snoop.receive[id](msg, payload, len - sizeof(timesync_footer_t));
+    }
+
+    default event message_t* Snoop.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) { return msg; }
+
 /*----------------- SubSend.sendDone -------------------*/
     event void SubSend.sendDone(message_t* msg, error_t error)
     {
@@ -155,27 +238,22 @@ implementation
 /*----------------- TimeSyncPacket32khz -----------------*/
     command bool TimeSyncPacket32khz.isValid(message_t* msg)
     {
-        timesync_radio_t* timesync = getFooter(msg);
-        return call PacketTimeStamp32khz.isValid(msg) && *timesync != CC2420_INVALID_TIMESTAMP;
+        return call PacketTimeStamp32khz.isValid(msg) && getFooter(msg)->timestamp != CC2420_INVALID_TIMESTAMP;
     }
 
     command uint32_t TimeSyncPacket32khz.eventTime(message_t* msg)
     {
-        timesync_radio_t* timesync = getFooter(msg);
-
-        return (uint32_t)(*timesync) + call PacketTimeStamp32khz.timestamp(msg);
+        return (uint32_t)(getFooter(msg)->timestamp) + call PacketTimeStamp32khz.timestamp(msg);
     }
 
 /*----------------- TimeSyncPacketMilli -----------------*/
     command bool TimeSyncPacketMilli.isValid(message_t* msg)
     {
-        timesync_radio_t* timesync = getFooter(msg);
-        return call PacketTimeStampMilli.isValid(msg) && *timesync != CC2420_INVALID_TIMESTAMP;
+        return call PacketTimeStampMilli.isValid(msg) && getFooter(msg)->timestamp != CC2420_INVALID_TIMESTAMP;
     }
 
     command uint32_t TimeSyncPacketMilli.eventTime(message_t* msg)
     {
-        timesync_radio_t* timesync = getFooter(msg);
-        return ((int32_t)(*timesync) >> 5) + call PacketTimeStampMilli.timestamp(msg);
+        return ((int32_t)(getFooter(msg)->timestamp) >> 5) + call PacketTimeStampMilli.timestamp(msg);
     }
 }
index 3b144a63307267f918600b853b8f294010d3588d..c6fdd8c2bc7fb70ef4da70353df6fdf33ea13795 100644 (file)
@@ -393,7 +393,7 @@ implementation {
   }
 
   event void RssiResource.granted() { 
-    uint16_t data;
+    uint16_t data = 0;
     call CSN.clr();
     call RSSI.read(&data);
     call CSN.set();
index e67f921763774af7c11d0e2492e7a9973083b020..42e087c86ed40bccdcddaa2e1932a6f7cabeaae3 100644 (file)
@@ -134,7 +134,11 @@ implementation {
     }
 
     header->length = len + CC2420_SIZE;
+#ifdef CC2420_HW_SECURITY
+    header->fcf &= ((1 << IEEE154_FCF_ACK_REQ)|(1 << IEEE154_FCF_SECURITY_ENABLED));
+#else
     header->fcf &= 1 << IEEE154_FCF_ACK_REQ;
+#endif
     header->fcf |= ( ( IEEE154_TYPE_DATA << IEEE154_FCF_FRAME_TYPE ) |
                     ( 1 << IEEE154_FCF_INTRAPAN ) |
                     ( IEEE154_ADDR_SHORT << IEEE154_FCF_DEST_ADDR_MODE ) |
@@ -156,7 +160,7 @@ implementation {
 
   command void* Send.getPayload(message_t* m, uint8_t len) {
     if (len <= call Send.maxPayloadLength()) {
-      return (void* COUNT_NOK(len))m->data;
+      return (void* COUNT_NOK(len ))(m->data);
     }
     else {
       return NULL;
diff --git a/tos/chips/cc2420/interfaces/CC2420Keys.nc b/tos/chips/cc2420/interfaces/CC2420Keys.nc
new file mode 100644 (file)
index 0000000..aedf58f
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+* Copyright (c) 2008 Johns Hopkins University.
+* All rights reserved.
+*
+* Permission to use, copy, modify, and distribute this software and its
+* documentation for any purpose, without fee, and without written
+* agreement is hereby granted, provided that the above copyright
+* notice, the (updated) modification history and the author appear in
+* all copies of this source code.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED  TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR  PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR  CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE,  DATA,
+* OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR  OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author JeongGil Ko
+ * @author Razvan Musaloiu-E.
+ * @author Jong Hyun Lim
+ */
+
+interface CC2420Keys
+{
+  command error_t setKey(uint8_t keyNo, uint8_t* key);
+  event void setKeyDone(uint8_t keyNo, uint8_t* key);
+}
index b18df717a1080f3f14667ca71fc62dbd807d3612..1c403fe908b3955b229a6fac28c1123da1c4ee25 100644 (file)
@@ -70,5 +70,10 @@ interface CC2420Packet {
    * ack was received.
    */
   async command uint8_t getLqi( message_t* p_msg );
+
+
+  async command uint8_t getNetwork( message_t* p_msg );
+
+  async command void setNetwork( message_t* p_msg, uint8_t networkId );
   
 }
diff --git a/tos/chips/cc2420/interfaces/CC2420SecurityMode.nc b/tos/chips/cc2420/interfaces/CC2420SecurityMode.nc
new file mode 100644 (file)
index 0000000..dca7a40
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+* Copyright (c) 2008 Johns Hopkins University.
+* All rights reserved.
+*
+* Permission to use, copy, modify, and distribute this software and its
+* documentation for any purpose, without fee, and without written
+* agreement is hereby granted, provided that the above copyright
+* notice, the (updated) modification history and the author appear in
+* all copies of this source code.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED  TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR  PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR  CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE,  DATA,
+* OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR  OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author JeongGil Ko
+ * @author Razvan Musaloiu-E.
+ * @author Jong Hyun Lim
+ */
+
+interface CC2420SecurityMode
+{
+  command error_t setCtr(message_t* msg, uint8_t setKey, uint8_t setSkip);
+  // Valid sizes are: 4, 6, 8, 10, 12, 14, 16
+  command error_t setCbcMac(message_t* msg, uint8_t setKey, uint8_t setSkip, uint8_t size);
+  command error_t setCcm(message_t* msg, uint8_t setKey, uint8_t setSkip, uint8_t size);
+}
index 9e2c273aa0e0621650f2eea77c2bff7bffff7781..829d32bc37daf7d4f9806d676a1011ccb4b5a78c 100644 (file)
@@ -51,7 +51,6 @@ configuration PacketLinkC {
 implementation {
 
   components PacketLinkP,
-      ActiveMessageC,
       CC2420PacketC,
       RandomC,
       new StateC() as SendStateC,
@@ -63,8 +62,7 @@ implementation {
   
   PacketLinkP.SendState -> SendStateC;
   PacketLinkP.DelayTimer -> DelayTimerC;
-  PacketLinkP.PacketAcknowledgements -> ActiveMessageC;
-  PacketLinkP.AMPacket -> ActiveMessageC;
+  PacketLinkP.PacketAcknowledgements -> CC2420PacketC;
   PacketLinkP.CC2420PacketBody -> CC2420PacketC;
 
 }
index 2ea159cef3c9492ce2d565b40fea2af258a8dd02..de1ef6d8c81655393ac9b9ce4e37161a4f626f32 100644 (file)
@@ -48,12 +48,12 @@ configuration PacketLinkDummyC {
 
 implementation {
   components PacketLinkDummyP,
-      ActiveMessageC;
+      CC2420RadioC;
   
   PacketLink = PacketLinkDummyP;
   Send = SubSend;
   
-  PacketLinkDummyP.PacketAcknowledgements -> ActiveMessageC;
+  PacketLinkDummyP.PacketAcknowledgements -> CC2420RadioC;
   
 }
 
index fef6c2bf21319875071874da366c9e5914e25645..0622fcda04cd418f69e83fe633c7202f9b26efff 100644 (file)
@@ -48,7 +48,6 @@ module PacketLinkP {
     interface State as SendState;
     interface PacketAcknowledgements;
     interface Timer<TMilli> as DelayTimer;
-    interface AMPacket;
     interface CC2420PacketBody;
   }
 }
@@ -221,6 +220,7 @@ implementation {
   void signalDone(error_t error) {
     call DelayTimer.stop();
     call SendState.toIdle();
+    (call CC2420PacketBody.getMetadata(currentSendMsg))->maxRetries = totalRetries;
     signal Send.sendDone(currentSendMsg, error);
   }
 }
index 3581b120f0d91b0d4d8b1fc87ad2c13c2a2a3b64..62d063153cd7904ae11eabc79316f721bca40571 100644 (file)
  */
  
 #include "CC2420.h"
+#include "Ieee154.h"
 
 configuration CC2420TinyosNetworkC {
   provides {
+    interface Resource[uint8_t clientId];
     interface Send;
     interface Receive;
+
+    interface Send as ActiveSend;
+    interface Receive as ActiveReceive;
   }
   
   uses {
@@ -72,21 +77,27 @@ configuration CC2420TinyosNetworkC {
 
 implementation {
 
-#ifdef CC2420_IFRAME_TYPE
+  enum {
+    TINYOS_N_NETWORKS = uniqueCount(RADIO_SEND_RESOURCE),
+  };
+
+  components MainC;
   components CC2420TinyosNetworkP;
   components CC2420PacketC;
-  
-  CC2420TinyosNetworkP.Send = Send;
-  CC2420TinyosNetworkP.Receive = Receive;
+  components new FcfsResourceQueueC(TINYOS_N_NETWORKS);
+
+  CC2420TinyosNetworkP.BareSend = Send;
+  CC2420TinyosNetworkP.BareReceive = Receive;
   CC2420TinyosNetworkP.SubSend = SubSend;
   CC2420TinyosNetworkP.SubReceive = SubReceive;
-  
-  CC2420TinyosNetworkP.CC2420PacketBody -> CC2420PacketC;
+  CC2420TinyosNetworkP.Resource = Resource;
+  CC2420TinyosNetworkP.ActiveSend = ActiveSend;
+  CC2420TinyosNetworkP.ActiveReceive = ActiveReceive;
 
-#else
-  Send = SubSend;
-  Receive = SubReceive;
-#endif
+  CC2420TinyosNetworkP.CC2420Packet -> CC2420PacketC;
+  CC2420TinyosNetworkP.CC2420PacketBody -> CC2420PacketC;
+  CC2420TinyosNetworkP.Queue -> FcfsResourceQueueC;
 
+  MainC.SoftwareInit -> FcfsResourceQueueC;
 }
 
index e490f37cece3c55e6f3eccbc3ed3a93086037d7e..8e8061a9f8612aa70623baf49ec567b37092d66b 100644 (file)
  *
  * @author David Moss
  */
+
 #include "CC2420.h"
+#include "Ieee154.h"
 
 module CC2420TinyosNetworkP @safe() {
   provides {
-    interface Send;
-    interface Receive;
-    
-    interface Receive as NonTinyosReceive[uint8_t networkId];
+    interface Resource[uint8_t client];
+
+    interface Send as BareSend;
+    interface Receive as BareReceive;
+
+    interface Send as ActiveSend;
+    interface Receive as ActiveReceive;
   }
   
   uses {
     interface Send as SubSend;
     interface Receive as SubReceive;
+    interface CC2420Packet;
     interface CC2420PacketBody;
+    interface ResourceQueue as Queue;
   }
 }
 
 implementation {
 
-  /***************** Send Commands ****************/
-  command error_t Send.send(message_t* msg, uint8_t len) {
-    (call CC2420PacketBody.getHeader(msg))->network = TINYOS_6LOWPAN_NETWORK_ID;
+  enum {
+    OWNER_NONE = 0xff,
+    TINYOS_N_NETWORKS = uniqueCount(RADIO_SEND_RESOURCE),
+  } state;
+
+  norace uint8_t resource_owner = OWNER_NONE, next_owner;
+
+  command error_t ActiveSend.send(message_t* msg, uint8_t len) {
+    call CC2420Packet.setNetwork(msg, TINYOS_6LOWPAN_NETWORK_ID);
     return call SubSend.send(msg, len);
   }
 
-  command error_t Send.cancel(message_t* msg) {
+  command error_t ActiveSend.cancel(message_t* msg) {
     return call SubSend.cancel(msg);
   }
 
-  command uint8_t Send.maxPayloadLength() {
+  command uint8_t ActiveSend.maxPayloadLength() {
     return call SubSend.maxPayloadLength();
   }
 
-  command void* Send.getPayload(message_t* msg, uint8_t len) {
-    return call SubSend.getPayload(msg, len);
+  command void* ActiveSend.getPayload(message_t* msg, uint8_t len) {
+    if (len <= call ActiveSend.maxPayloadLength()) {
+      return msg->data;
+    } else {
+      return NULL;
+    }
+  }
+
+  /***************** Send Commands ****************/
+  command error_t BareSend.send(message_t* msg, uint8_t len) {
+    return call SubSend.send(msg, len - AM_OVERHEAD);
+  }
+
+  command error_t BareSend.cancel(message_t* msg) {
+    return call SubSend.cancel(msg);
+  }
+
+  command uint8_t BareSend.maxPayloadLength() {
+    return call SubSend.maxPayloadLength() + AM_OVERHEAD;
+  }
+
+  command void* BareSend.getPayload(message_t* msg, uint8_t len) {
+#ifndef TFRAMES_ENABLED                      
+    cc2420_header_t *hdr = call CC2420PacketBody.getHeader(msg);
+    return &hdr->network;
+#else
+    // you really can't use BareSend with TFRAMES
+#error "BareSend is not supported with TFRAMES: only the ActiveMessage layer is supported"
+#endif
   }
   
   /***************** SubSend Events *****************/
   event void SubSend.sendDone(message_t* msg, error_t error) {
-    signal Send.sendDone(msg, error);
+    if (call CC2420Packet.getNetwork(msg) == TINYOS_6LOWPAN_NETWORK_ID) {
+      signal ActiveSend.sendDone(msg, error);
+    } else {
+      signal BareSend.sendDone(msg, error);
+    }
   }
-  
+
   /***************** SubReceive Events ***************/
   event message_t *SubReceive.receive(message_t *msg, void *payload, uint8_t len) {
-    if((call CC2420PacketBody.getHeader(msg))->network == TINYOS_6LOWPAN_NETWORK_ID) {
-      return signal Receive.receive(msg, payload, len);
-      
+
+    if(!(call CC2420PacketBody.getMetadata(msg))->crc) {
+      return msg;
+    }
+#ifndef TFRAMES_ENABLED
+    if (call CC2420Packet.getNetwork(msg) == TINYOS_6LOWPAN_NETWORK_ID) {
+      return signal ActiveReceive.receive(msg, payload, len);
     } else {
-      return signal NonTinyosReceive.receive[(call CC2420PacketBody.getHeader(msg))->network](msg, payload, len);
+      cc2420_header_t *hdr = call CC2420PacketBody.getHeader(msg);
+      return signal BareReceive.receive(msg, &hdr->network, len + AM_OVERHEAD);
     }
+#else
+    return signal ActiveReceive.receive(msg, payload, len);
+#endif
   }
-  
+
+  /***************** Resource ****************/
+  // SDH : 8-7-2009 : testing if there's more then one client allows
+  // the compiler to eliminate most of the logic when there's only one
+  // client.
+  task void grantTask() {
+
+
+    if (TINYOS_N_NETWORKS > 1) {
+      if (resource_owner == OWNER_NONE && !(call Queue.isEmpty())) {
+        resource_owner = call Queue.dequeue();
+
+        if (resource_owner != OWNER_NONE) {
+          signal Resource.granted[resource_owner]();
+        }
+      }
+    } else {
+      if (next_owner != resource_owner) {
+        resource_owner = next_owner;
+        signal Resource.granted[resource_owner]();
+      }
+    }
+  }
+
+  async command error_t Resource.request[uint8_t id]() {
+
+    post grantTask();
+
+    if (TINYOS_N_NETWORKS > 1) {
+
+      return call Queue.enqueue(id);
+    } else {
+      if (id == resource_owner) {
+        return EALREADY;
+      } else {
+        next_owner = id;
+        return SUCCESS;
+      }
+    }
+  }
+
+  async command error_t Resource.immediateRequest[uint8_t id]() {
+    if (resource_owner == id) return EALREADY;
+
+    if (TINYOS_N_NETWORKS > 1) {
+      if (resource_owner == OWNER_NONE && call Queue.isEmpty()) {
+        resource_owner = id;
+        return SUCCESS;
+      }
+      return FAIL;
+    } else {
+      resource_owner = id;
+      return SUCCESS;
+    }
+  }
+  async command error_t Resource.release[uint8_t id]() {
+    if (TINYOS_N_NETWORKS > 1) {
+      post grantTask();
+    }
+    resource_owner = OWNER_NONE;
+    return SUCCESS;
+  }
+  async command bool Resource.isOwner[uint8_t id]() {
+    return (id == resource_owner);
+  }
+
   /***************** Defaults ****************/
-  default event message_t *NonTinyosReceive.receive[uint8_t networkId](message_t *msg, void *payload, uint8_t len) {
+  default event message_t *BareReceive.receive(message_t *msg, void *payload, uint8_t len) {
     return msg;
   }
-  
+  default event void BareSend.sendDone(message_t *msg, error_t error) {
+
+  }
+  default event message_t *ActiveReceive.receive(message_t *msg, void *payload, uint8_t len) {
+    return msg;
+  }
+  default event void ActiveSend.sendDone(message_t *msg, error_t error) {
+
+  }
+  default event void Resource.granted[uint8_t client]() {
+    call Resource.release[client]();
+  }
+
 }
index f74db43b950c4b3ac211f67b2789230c808cd70d..760ece79ee89c7df5a76d710f8fd0b45f2491f42 100644 (file)
@@ -47,14 +47,6 @@ typedef enum {
 } lpl_sendstate_t;
 
 
-/**
- * Amount of time, in milliseconds, to keep the radio on after
- * a successful receive addressed to this node
- */
-#ifndef DELAY_AFTER_RECEIVE
-#define DELAY_AFTER_RECEIVE 100
-#endif
-
 /**
  * This is a measured value of the time in ms the radio is actually on
  * We round this up to err on the side of better performance ratios
index 4fc8b7e18e6c400ab493f27d172dc0e4ee53077b..b18b08a5ffff1df5b23d1d594896781393edd967 100644 (file)
@@ -58,7 +58,7 @@ implementation {
   components MainC,
       DefaultLplP,
       PowerCycleC,
-      CC2420ActiveMessageC,
+      CC2420RadioC,
       CC2420CsmaC,
       CC2420TransmitC,
       CC2420PacketC,
@@ -66,6 +66,7 @@ implementation {
       new StateC() as SendStateC,
       new TimerMilliC() as OffTimerC,
       new TimerMilliC() as SendDoneTimerC,
+      SystemLowPowerListeningC,
       LedsC;
   
   LowPowerListening = DefaultLplP;
@@ -89,11 +90,10 @@ implementation {
   DefaultLplP.SendDoneTimer -> SendDoneTimerC;
   DefaultLplP.PowerCycle -> PowerCycleC;
   DefaultLplP.Resend -> CC2420TransmitC;
-  DefaultLplP.PacketAcknowledgements -> CC2420ActiveMessageC;
-  DefaultLplP.AMPacket -> CC2420ActiveMessageC;
+  DefaultLplP.PacketAcknowledgements -> CC2420RadioC;
   DefaultLplP.CC2420PacketBody -> CC2420PacketC;
   DefaultLplP.RadioBackoff -> CC2420CsmaC;
   DefaultLplP.Random -> RandomC;
   DefaultLplP.Leds -> LedsC;
-  
+  DefaultLplP.SystemLowPowerListening -> SystemLowPowerListeningC;
 }
index 3ada9db65353e9e75ee182fecf2c558124f87ac0..4c5c63b48988cd4b8def306abd9840baa4775a87 100644 (file)
@@ -40,6 +40,7 @@
  * @author David Moss
  */
 
+#include "Lpl.h"
 #include "DefaultLpl.h"
 #include "AM.h"
 
@@ -56,7 +57,6 @@ module DefaultLplP {
     interface CC2420Transmit as Resend;
     interface RadioBackoff;
     interface Receive as SubReceive;
-    interface AMPacket;
     interface SplitControl as SubControl;
     interface PowerCycle;
     interface CC2420PacketBody;
@@ -68,6 +68,7 @@ module DefaultLplP {
     interface Timer<TMilli> as SendDoneTimer;
     interface Random;
     interface Leds;
+    interface SystemLowPowerListening;
   }
 }
 
@@ -112,7 +113,6 @@ implementation {
   
   void initializeSend();
   void startOffTimer();
-  uint16_t getActualDutyCycle(uint16_t dutyCycle);
   
   /***************** Init Commands ***************/
   command error_t Init.init() {
@@ -122,134 +122,42 @@ implementation {
   
   /***************** LowPowerListening Commands ***************/
   /**
-   * Set this this node's radio sleep interval, in milliseconds.
+   * Set this this node's radio wakeup interval, in milliseconds.
    * Once every interval, the node will sleep and perform an Rx check 
-   * on the radio.  Setting the sleep interval to 0 will keep the radio
+   * on the radio.  Setting the wakeup interval to 0 will keep the radio
    * always on.
    *
-   * This is the equivalent of setting the local duty cycle rate.
-   *
-   * @param sleepIntervalMs the length of this node's Rx check interval, in [ms]
+   * @param intervalMs the length of this node's wakeup interval, in [ms]
    */
-  command void LowPowerListening.setLocalSleepInterval(
-      uint16_t sleepIntervalMs) {
-    call PowerCycle.setSleepInterval(sleepIntervalMs);
+  command void LowPowerListening.setLocalWakeupInterval(uint16_t intervalMs) {
+    call PowerCycle.setSleepInterval(intervalMs);
   }
   
   /**
-   * @return the local node's sleep interval, in [ms]
+   * @return the local node's wakeup interval, in [ms]
    */
-  command uint16_t LowPowerListening.getLocalSleepInterval() {
+  command uint16_t LowPowerListening.getLocalWakeupInterval() {
     return call PowerCycle.getSleepInterval();
   }
   
-  /**
-   * Set this node's radio duty cycle rate, in units of [percentage*100].
-   * For example, to get a 0.05% duty cycle,
-   * <code>
-   *   call LowPowerListening.setDutyCycle(5);
-   * </code>
-   *
-   * For a 100% duty cycle (always on),
-   * <code>
-   *   call LowPowerListening.setDutyCycle(10000);
-   * </code>
-   *
-   * This is the equivalent of setting the local sleep interval explicitly.
-   * 
-   * @param dutyCycle The duty cycle percentage, in units of [percentage*100]
-   */
-  command void LowPowerListening.setLocalDutyCycle(uint16_t dutyCycle) {
-    call PowerCycle.setSleepInterval(
-        call LowPowerListening.dutyCycleToSleepInterval(dutyCycle));
-  }
-  
-  /**
-   * @return this node's radio duty cycle rate, in units of [percentage*100]
-   */
-  command uint16_t LowPowerListening.getLocalDutyCycle() {
-    return call LowPowerListening.sleepIntervalToDutyCycle(
-        call PowerCycle.getSleepInterval());
-  }
-  
-  
   /**
    * Configure this outgoing message so it can be transmitted to a neighbor mote
-   * with the specified Rx sleep interval.
+   * with the specified wakeup interval.
    * @param msg Pointer to the message that will be sent
-   * @param sleepInterval The receiving node's sleep interval, in [ms]
+   * @param intervalMs The receiving node's wakeup interval, in [ms]
    */
-  command void LowPowerListening.setRxSleepInterval(message_t *msg, 
-      uint16_t sleepIntervalMs) {
-    (call CC2420PacketBody.getMetadata(msg))->rxInterval = sleepIntervalMs;
+  command void LowPowerListening.setRemoteWakeupInterval(message_t *msg, 
+      uint16_t intervalMs) {
+    (call CC2420PacketBody.getMetadata(msg))->rxInterval = intervalMs;
   }
   
   /**
-   * @return the destination node's sleep interval configured in this message
+   * @return the destination node's wakeup interval configured in this message
    */
-  command uint16_t LowPowerListening.getRxSleepInterval(message_t *msg) {
+  command uint16_t LowPowerListening.getRemoteWakeupInterval(message_t *msg) {
     return (call CC2420PacketBody.getMetadata(msg))->rxInterval;
   }
   
-  /**
-   * Configure this outgoing message so it can be transmitted to a neighbor mote
-   * with the specified Rx duty cycle rate.
-   * Duty cycle is in units of [percentage*100], i.e. 0.25% duty cycle = 25.
-   * 
-   * @param msg Pointer to the message that will be sent
-   * @param dutyCycle The duty cycle of the receiving mote, in units of 
-   *     [percentage*100]
-   */
-  command void LowPowerListening.setRxDutyCycle(message_t *msg, 
-      uint16_t dutyCycle) {
-    (call CC2420PacketBody.getMetadata(msg))->rxInterval =
-        call LowPowerListening.dutyCycleToSleepInterval(dutyCycle);
-  }
-  
-    
-  /**
-   * @return the destination node's duty cycle configured in this message
-   *     in units of [percentage*100]
-   */
-  command uint16_t LowPowerListening.getRxDutyCycle(message_t *msg) {
-    return call LowPowerListening.sleepIntervalToDutyCycle(
-        (call CC2420PacketBody.getMetadata(msg))->rxInterval);
-  }
-  
-  /**
-   * Convert a duty cycle, in units of [percentage*100], to
-   * the sleep interval of the mote in milliseconds
-   * @param dutyCycle The duty cycle in units of [percentage*100]
-   * @return The equivalent sleep interval, in units of [ms]
-   */
-  command uint16_t LowPowerListening.dutyCycleToSleepInterval(
-      uint16_t dutyCycle) {
-    dutyCycle = getActualDutyCycle(dutyCycle);
-    
-    if(dutyCycle == 10000) {
-      return 0;
-    }
-    
-    return ((uint32_t)DUTY_ON_TIME * (10000 - dutyCycle)) / dutyCycle;
-  }
-  
-  /**
-   * Convert a sleep interval, in units of [ms], to a duty cycle
-   * in units of [percentage*100]
-   * @param sleepInterval The sleep interval in units of [ms]
-   * @return The duty cycle in units of [percentage*100]
-   */
-  command uint16_t LowPowerListening.sleepIntervalToDutyCycle(
-      uint16_t sleepInterval) {
-    if(sleepInterval == 0) {
-      return 10000;
-    }
-    
-    return getActualDutyCycle(((uint32_t)DUTY_ON_TIME * 10000) 
-        / (sleepInterval + DUTY_ON_TIME));
-  }
-
-  
   /***************** Send Commands ***************/
   /**
    * Each call to this send command gives the message a single
@@ -481,10 +389,10 @@ implementation {
   
   /***************** Functions ***************/
   void initializeSend() {
-    if(call LowPowerListening.getRxSleepInterval(currentSendMsg) 
+    if(call LowPowerListening.getRemoteWakeupInterval(currentSendMsg) 
       > ONE_MESSAGE) {
     
-      if(call AMPacket.destination(currentSendMsg) == AM_BROADCAST_ADDR) {
+      if((call CC2420PacketBody.getHeader(currentSendMsg))->dest == IEEE154_BROADCAST_ADDR) {
         call PacketAcknowledgements.noAck(currentSendMsg);
       } else {
         // Send it repetitively within our transmit window
@@ -492,7 +400,7 @@ implementation {
       }
 
       call SendDoneTimer.startOneShot(
-          call LowPowerListening.getRxSleepInterval(currentSendMsg) + 20);
+          call LowPowerListening.getRemoteWakeupInterval(currentSendMsg) + 20);
     }
         
     post send();
@@ -500,21 +408,8 @@ implementation {
   
   
   void startOffTimer() {
-    call OffTimer.startOneShot(DELAY_AFTER_RECEIVE);
+    call OffTimer.startOneShot(call SystemLowPowerListening.getDelayAfterReceive());
   }
   
-  /**
-   * Check the bounds on a given duty cycle
-   * We're never over 100%, and we're never at 0%
-   */
-  uint16_t getActualDutyCycle(uint16_t dutyCycle) {
-    if(dutyCycle > 10000) {
-      return 10000;
-    } else if(dutyCycle == 0) {
-      return 1;
-    }
-    
-    return dutyCycle;
-  }  
 }
 
index dbc6bb53932c0d15c7ce618eacb086c44ae781e4..36a79ffaa9b632611b7ea19878109b891f182da6 100644 (file)
@@ -32,7 +32,7 @@
 /**
  * Dummy low power listening interface used when LowPowerListening is not
  * compiled in with the application.
- * Sleep interval is always 0, and duty cycle is always 100%
+ * Wakeup interval is always 0 (always on)
  * @author David Moss
  */
  
@@ -44,41 +44,19 @@ module DummyLplP {
 
 implementation {
 
-  command void LowPowerListening.setLocalSleepInterval(uint16_t sleepIntervalMs) {
+  command void LowPowerListening.setLocalWakeupInterval(uint16_t intervalMs) {
   }
   
-  command uint16_t LowPowerListening.getLocalSleepInterval() {
+  command uint16_t LowPowerListening.getLocalWakeupInterval() {
     return 0;
   }
   
-  command void LowPowerListening.setLocalDutyCycle(uint16_t dutyCycle) {
+  command void LowPowerListening.setRemoteWakeupInterval(message_t *msg, uint16_t intervalMs) {
   }
   
-  command uint16_t LowPowerListening.getLocalDutyCycle() {
-    return 10000;
-  }
-  
-  command void LowPowerListening.setRxSleepInterval(message_t *msg, uint16_t sleepIntervalMs) {
-  }
-  
-  command uint16_t LowPowerListening.getRxSleepInterval(message_t *msg) {
+  command uint16_t LowPowerListening.getRemoteWakeupInterval(message_t *msg) {
     return 0;
   }
   
-  command void LowPowerListening.setRxDutyCycle(message_t *msg, uint16_t dutyCycle) {
-  }
-  
-  command uint16_t LowPowerListening.getRxDutyCycle(message_t *msg) {
-    return 10000;
-  }
-  
-  command uint16_t LowPowerListening.dutyCycleToSleepInterval(uint16_t dutyCycle) {
-    return 0;
-  }
-  
-  command uint16_t LowPowerListening.sleepIntervalToDutyCycle(uint16_t sleepInterval) {
-    return 10000;
-  }
-  
 }
 
index 41dca278ccd3e229fcf87d347d200bec2b742322..971cf15a8d959f283bc47d3de65635513079eeb0 100644 (file)
@@ -76,7 +76,6 @@ implementation {
   PowerCycleP.SplitControlState -> SplitControlStateC;
   PowerCycleP.OnTimer -> OnTimerC;
   PowerCycleP.Leds -> LedsC;
-    
 }
 
 
index 34099244f5fd5fd982902d2345fee96c2c795d8a..741224ce60d97ea226f00b67907ae6f902424cbd 100644 (file)
@@ -75,7 +75,7 @@ module PowerCycleP {
 implementation {
   
   /** The current period of the duty cycle, equivalent of wakeup interval */
-  uint16_t sleepInterval = 0;
+  uint16_t sleepInterval = LPL_DEF_LOCAL_WAKEUP;
   
   /** The number of times the CCA has been sampled in this wakeup period */
   uint16_t ccaChecks;
@@ -99,7 +99,6 @@ implementation {
   bool finishSplitControlRequests();
   bool isDutyCycling();
   
-  
   /***************** PowerCycle Commands ****************/
   /**
    * Set the sleep interval, in binary milliseconds
index de537664f7284389ea7898884d292b564c6a9c15..9e3415546b1c8d1efb0811ab236f04383d77f9ee 100644 (file)
@@ -60,9 +60,6 @@ implementation {
   PacketTimeStampMilli = CC2420PacketP;
   PacketTimeSyncOffset = CC2420PacketP;
 
-  components CC2420ActiveMessageC;
-  CC2420PacketP.Packet -> CC2420ActiveMessageC;
-
   components Counter32khz32C, new CounterToLocalTimeC(T32khz);
   CounterToLocalTimeC.Counter -> Counter32khz32C;
   CC2420PacketP.LocalTime32khz -> CounterToLocalTimeC;
index 0a730484f83c8dcf06837f507b5d3b0cd05d6fd6..50b138fcf19280a03a228bb5e6d5718cf3663a77 100644 (file)
@@ -95,6 +95,21 @@ implementation {
     return (call CC2420PacketBody.getMetadata( p_msg ))->lqi;
   }
 
+  async command uint8_t CC2420Packet.getNetwork( message_t* p_msg ) {
+#if defined(TFRAMES_ENABLED)
+    return TINYOS_6LOWPAN_NETWORK_ID;
+#else
+    return (call CC2420PacketBody.getHeader( p_msg ))->network;
+#endif
+  }
+
+  async command void CC2420Packet.setNetwork( message_t* p_msg , uint8_t networkId ) {
+#if ! defined(TFRAMES_ENABLED)
+    (call CC2420PacketBody.getHeader( p_msg ))->network = networkId;
+#endif
+  }    
+
+
   /***************** CC2420PacketBody Commands ****************/
   async command cc2420_header_t * ONE CC2420PacketBody.getHeader( message_t* ONE msg ) {
     return TCAST(cc2420_header_t* ONE, (uint8_t *)msg + offsetof(message_t, data) - sizeof( cc2420_header_t ));
@@ -138,10 +153,13 @@ implementation {
     return call PacketTimeStamp32khz.isValid(msg);
   }
 
+  //timestmap is always represented in 32khz
+  //28.1 is coefficient difference between T32khz and TMilli on MicaZ
   async command uint32_t PacketTimeStampMilli.timestamp(message_t* msg)
   {
-    int32_t offset = call PacketTimeStamp32khz.timestamp(msg) - call LocalTime32khz.get();
-    return (offset >> 5) + call LocalTimeMilli.get();
+    int32_t offset = (call LocalTime32khz.get()-call PacketTimeStamp32khz.timestamp(msg));
+    offset/=28.1;
+    return call LocalTimeMilli.get() - offset;
   }
 
   async command void PacketTimeStampMilli.clear(message_t* msg)
index 14c723f6e68f31f9e1c5a6407f7dbdfeadff40f5..f659a9e11f549729f4fa766e757f0d7d68c54ae1 100644 (file)
@@ -78,4 +78,13 @@ implementation {
   CC2420ReceiveP.PacketTimeStamp -> CC2420PacketC;
   CC2420ReceiveP.CC2420Config -> CC2420ControlC;
 
+  CC2420ReceiveP.SECCTRL0 -> Spi.SECCTRL0;
+  CC2420ReceiveP.SECCTRL1 -> Spi.SECCTRL1;
+  CC2420ReceiveP.SRXDEC -> Spi.SRXDEC;
+  CC2420ReceiveP.RXNONCE -> Spi.RXNONCE;
+  CC2420ReceiveP.KEY0 -> Spi.KEY0;
+  CC2420ReceiveP.KEY1 -> Spi.KEY1;
+  CC2420ReceiveP.RXFIFO_RAM -> Spi.RXFIFO_RAM;
+  CC2420ReceiveP.SNOP -> Spi.SNOP;
+
 }
index 5bd4e852e54eb383c85a67d7be24b94a80e15a47..4d9c055508a397292798b0fefba7a86af54b3c09 100644 (file)
@@ -33,6 +33,8 @@
  * @author Jonathan Hui <jhui@archrock.com>
  * @author David Moss
  * @author Jung Il Choi
+ * @author JeongGil Ko
+ * @author Razvan Musaloiu-E
  * @version $Revision$ $Date$
  */
 
@@ -62,6 +64,15 @@ module CC2420ReceiveP @safe() {
   uses interface CC2420Config;
   uses interface PacketTimeStamp<T32khz,uint32_t>;
 
+  uses interface CC2420Strobe as SRXDEC;
+  uses interface CC2420Register as SECCTRL0;
+  uses interface CC2420Register as SECCTRL1;
+  uses interface CC2420Ram as KEY0;
+  uses interface CC2420Ram as KEY1;
+  uses interface CC2420Ram as RXNONCE;
+  uses interface CC2420Ram as RXFIFO_RAM;
+  uses interface CC2420Strobe as SNOP;
+
   uses interface Leds;
 }
 
@@ -71,6 +82,8 @@ implementation {
     S_STOPPED,
     S_STARTED,
     S_RX_LENGTH,
+    S_RX_DEC,
+    S_RX_DEC_WAIT,
     S_RX_FCF,
     S_RX_PAYLOAD,
   } cc2420_receive_state_t;
@@ -88,8 +101,12 @@ implementation {
   uint8_t m_timestamp_size;
   
   /** Number of packets we missed because we were doing something else */
+#ifdef CC2420_HW_SECURITY
+  norace uint8_t m_missed_packets;
+#else
   uint8_t m_missed_packets;
-  
+#endif
+
   /** TRUE if we are receiving a valid packet into the stack */
   bool receivingPacket;
   
@@ -101,9 +118,25 @@ implementation {
   norace message_t* ONE_NOK m_p_rx_buf;
 
   message_t m_rx_buf;
-  
+#ifdef CC2420_HW_SECURITY
+  norace cc2420_receive_state_t m_state;
+  norace uint8_t packetLength = 0;
+  norace uint8_t pos = 0;
+  norace uint8_t secHdrPos = 0;
+  uint8_t nonceValue[16] = {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+  norace uint8_t skip;
+  norace uint8_t securityOn = 0;
+  norace uint8_t authentication = 0;
+  norace uint8_t micLength = 0;
+  uint8_t flush_flag = 0;
+  uint16_t startTime = 0;
+
+  void beginDec();
+  void dec();
+#else
   cc2420_receive_state_t m_state;
-  
+#endif
+
   /***************** Prototypes ****************/
   void reset_state();
   void beginReceive();
@@ -111,9 +144,9 @@ implementation {
   void waitForNextPacket();
   void flush();
   bool passesAddressCheck(message_t * ONE msg);
-  
+
   task void receiveDone_task();
-  
+
   /***************** Init Commands ****************/
   command error_t Init.init() {
     m_p_rx_buf = &m_rx_buf;
@@ -178,17 +211,310 @@ implementation {
   /***************** InterruptFIFOP Events ****************/
   async event void InterruptFIFOP.fired() {
     if ( m_state == S_STARTED ) {
+#ifndef CC2420_HW_SECURITY
+      m_state = S_RX_LENGTH;
       beginReceive();
-      
+#else
+      m_state = S_RX_DEC;
+      atomic receivingPacket = TRUE;
+      beginDec();
+#endif
     } else {
       m_missed_packets++;
     }
   }
+
+  /*****************Decryption Options*********************/
+#ifdef CC2420_HW_SECURITY
+  task void waitTask(){
+
+    if(SECURITYLOCK == 1){
+      post waitTask();
+    }else{
+      m_state = S_RX_DEC;
+      beginDec();
+    }
+  }
+
+  void beginDec(){
+    if(call SpiResource.isOwner()) {
+      dec();
+    } else if (call SpiResource.immediateRequest() == SUCCESS) {
+      dec();
+    } else {
+      call SpiResource.request();
+    }
+  }
+
+  norace uint8_t decLoopCount = 0;
+
+  task void waitDecTask(){
+
+    cc2420_status_t status;
+
+    call CSN.clr();
+    status = call SNOP.strobe();
+    call CSN.set();
+
+    atomic decLoopCount ++;
+
+    if(decLoopCount > 10){
+      call CSN.clr();
+      atomic call SECCTRL0.write((0 << CC2420_SECCTRL0_SEC_MODE) |
+                                (0 << CC2420_SECCTRL0_SEC_M) |
+                                (0 << CC2420_SECCTRL0_SEC_RXKEYSEL) |
+                                (1 << CC2420_SECCTRL0_SEC_CBC_HEAD) |
+                                (1 << CC2420_SECCTRL0_RXFIFO_PROTECTION)) ;
+      call CSN.set();
+      SECURITYLOCK = 0;
+      call SpiResource.release();
+      atomic flush_flag = 1;
+      beginReceive();
+    }else if(status & CC2420_STATUS_ENC_BUSY){
+      post waitDecTask();
+    }else{
+      call CSN.clr();
+      atomic call SECCTRL0.write((0 << CC2420_SECCTRL0_SEC_MODE) |
+                                (0 << CC2420_SECCTRL0_SEC_M) |
+                                (0 << CC2420_SECCTRL0_SEC_RXKEYSEL) |
+                                (1 << CC2420_SECCTRL0_SEC_CBC_HEAD) |
+                                (1 << CC2420_SECCTRL0_RXFIFO_PROTECTION)) ;
+      call CSN.set();
+      SECURITYLOCK = 0;
+      call SpiResource.release();
+      beginReceive();
+    }
+
+  }
+
+  void waitDec(){
+    cc2420_status_t status;
+    call CSN.clr();
+    status = call SNOP.strobe();
+    call CSN.set();
+
+    if(status & CC2420_STATUS_ENC_BUSY){
+      atomic decLoopCount = 1;
+      post waitDecTask();
+    }else{
+      call CSN.clr();
+      atomic call SECCTRL0.write((0 << CC2420_SECCTRL0_SEC_MODE) |
+                                (0 << CC2420_SECCTRL0_SEC_M) |
+                                (0 << CC2420_SECCTRL0_SEC_RXKEYSEL) |
+                                (1 << CC2420_SECCTRL0_SEC_CBC_HEAD) |
+                                (1 << CC2420_SECCTRL0_RXFIFO_PROTECTION)) ;
+      call CSN.set();
+      SECURITYLOCK = 0;
+      call SpiResource.release();
+      beginReceive();
+    }
+  }
+
+  void dec(){
+    cc2420_header_t header;
+    security_header_t secHdr;
+    uint8_t mode, key, temp, crc;
+
+    atomic pos = (packetLength+pos)%RXFIFO_SIZE;
+    atomic secHdrPos = (pos+10)%RXFIFO_SIZE;
+
+    if (pos + 3 > RXFIFO_SIZE){
+      temp = RXFIFO_SIZE - pos;
+      call CSN.clr();
+      atomic call RXFIFO_RAM.read(pos,(uint8_t*)&header, temp);
+      call CSN.set();
+      call CSN.clr();
+      atomic call RXFIFO_RAM.read(0,(uint8_t*)&header+temp, 3-temp);
+      call CSN.set();
+    }else{
+      call CSN.clr();
+      atomic call RXFIFO_RAM.read(pos,(uint8_t*)&header, 3);
+      call CSN.set();
+    }
+
+    packetLength = header.length+1;
+
+    if(packetLength == 6){ // ACK packet
+      m_state = S_RX_LENGTH;
+      call SpiResource.release();
+      beginReceive();
+      return;
+    }
+
+    if (pos + sizeof(cc2420_header_t) > RXFIFO_SIZE){
+      temp = RXFIFO_SIZE - pos;
+      call CSN.clr();
+      atomic call RXFIFO_RAM.read(pos,(uint8_t*)&header, temp);
+      call CSN.set();
+      call CSN.clr();
+      atomic call RXFIFO_RAM.read(0,(uint8_t*)&header+temp, sizeof(cc2420_header_t)-temp);
+      call CSN.set();
+    }else{
+      call CSN.clr();
+      atomic call RXFIFO_RAM.read(pos,(uint8_t*)&header, sizeof(cc2420_header_t));
+      call CSN.set();
+    }
+
+    if (pos+header.length+1 > RXFIFO_SIZE){
+      temp = header.length - (RXFIFO_SIZE - pos);
+      call CSN.clr();
+      atomic call RXFIFO_RAM.read(temp,&crc, 1);
+      call CSN.set();
+    }else{
+      call CSN.clr();
+      atomic call RXFIFO_RAM.read(pos+header.length,&crc, 1);
+      call CSN.set();
+    }
+
+    if(header.length+1 > RXFIFO_SIZE || !(crc << 7)){
+      atomic flush_flag = 1;
+      m_state = S_RX_LENGTH;
+      call SpiResource.release();
+      beginReceive();
+      return;
+    }
+    if( (header.fcf & (1 << IEEE154_FCF_SECURITY_ENABLED)) && (crc << 7) ){
+      if(call CC2420Config.isAddressRecognitionEnabled()){
+       if(!(header.dest==call CC2420Config.getShortAddr() || header.dest==AM_BROADCAST_ADDR)){
+         packetLength = header.length + 1;
+         m_state = S_RX_LENGTH;
+         call SpiResource.release();
+         beginReceive();
+         return;
+       }
+      }
+      if(SECURITYLOCK == 1){
+       call SpiResource.release();
+       post waitTask();
+       return;
+      }else{
+       //We are going to decrypt so lock the registers
+       atomic SECURITYLOCK = 1;
+
+       if (secHdrPos + sizeof(security_header_t) > RXFIFO_SIZE){
+         temp = RXFIFO_SIZE - secHdrPos;
+         call CSN.clr();
+         atomic call RXFIFO_RAM.read(secHdrPos,(uint8_t*)&secHdr, temp);
+         call CSN.set();
+         call CSN.clr();
+         atomic call RXFIFO_RAM.read(0,(uint8_t*)&secHdr+temp, sizeof(security_header_t) - temp);
+         call CSN.set();
+       } else {
+         call CSN.clr();
+         atomic call RXFIFO_RAM.read(secHdrPos,(uint8_t*)&secHdr, sizeof(security_header_t));
+         call CSN.set();
+       }
+
+       key = secHdr.keyID[0];
+
+       if (secHdr.secLevel == NO_SEC){
+         mode = CC2420_NO_SEC;
+         micLength = 0;
+       }else if (secHdr.secLevel == CBC_MAC_4){
+         mode = CC2420_CBC_MAC;
+         micLength = 4;
+       }else if (secHdr.secLevel == CBC_MAC_8){
+         mode = CC2420_CBC_MAC;
+         micLength = 8;
+       }else if (secHdr.secLevel == CBC_MAC_16){
+         mode = CC2420_CBC_MAC;
+         micLength = 16;
+       }else if (secHdr.secLevel == CTR){
+         mode = CC2420_CTR;
+         micLength = 0;
+       }else if (secHdr.secLevel == CCM_4){
+         mode = CC2420_CCM;
+         micLength = 4;
+       }else if (secHdr.secLevel == CCM_8){
+         mode = CC2420_CCM;
+         micLength = 8;
+       }else if (secHdr.secLevel == CCM_16){
+         mode = CC2420_CCM;
+         micLength = 16;
+       }else{
+         atomic SECURITYLOCK = 0;
+         packetLength = header.length + 1;
+         m_state = S_RX_LENGTH;
+         call SpiResource.release();
+         beginReceive();
+         return;
+       }
+
+       if(mode < 4 && mode > 0) { // if mode is valid
   
-  
+         securityOn = 1;
+
+         memcpy(&nonceValue[3], &(secHdr.frameCounter), 4);
+         skip = secHdr.reserved;
+
+         if(mode == CC2420_CBC_MAC || mode == CC2420_CCM){
+           authentication = 1;
+           call CSN.clr();
+           atomic call SECCTRL0.write((mode << CC2420_SECCTRL0_SEC_MODE) |
+                                      ((micLength-2)/2 << CC2420_SECCTRL0_SEC_M) |
+                                      (key << CC2420_SECCTRL0_SEC_RXKEYSEL) |
+                                      (1 << CC2420_SECCTRL0_SEC_CBC_HEAD) |
+                                      (1 << CC2420_SECCTRL0_RXFIFO_PROTECTION)) ;
+           call CSN.set();
+         }else{
+           call CSN.clr();
+           atomic call SECCTRL0.write((mode << CC2420_SECCTRL0_SEC_MODE) |
+                                      (1 << CC2420_SECCTRL0_SEC_M) |
+                                      (key << CC2420_SECCTRL0_SEC_RXKEYSEL) |
+                                      (1 << CC2420_SECCTRL0_SEC_CBC_HEAD) |
+                                      (1 << CC2420_SECCTRL0_RXFIFO_PROTECTION)) ;
+           call CSN.set();
+         }
+
+         call CSN.clr();
+#ifndef TFRAMES_ENABLED
+         atomic call SECCTRL1.write(skip+11+sizeof(security_header_t)+((skip+11+sizeof(security_header_t))<<8));
+#else
+         atomic call SECCTRL1.write(skip+10+sizeof(security_header_t)+((skip+10+sizeof(security_header_t))<<8));
+#endif
+         call CSN.set();
+
+         call CSN.clr();
+         atomic call RXNONCE.write(0, nonceValue, 16);
+         call CSN.set();
+
+         call CSN.clr();
+         atomic call SRXDEC.strobe();
+         call CSN.set();
+
+         atomic decLoopCount = 0;
+         post waitDecTask();
+         return;
+
+       }else{
+         atomic SECURITYLOCK = 0;
+         packetLength = header.length + 1;
+         m_state = S_RX_LENGTH;
+         call SpiResource.release();
+         beginReceive();
+         return;
+       }
+      }
+    }else{
+      packetLength = header.length + 1;
+      m_state = S_RX_LENGTH;
+      call SpiResource.release();
+      beginReceive();
+      return;
+    }
+  }
+#endif
   /***************** SpiResource Events ****************/
   event void SpiResource.granted() {
+#ifdef CC2420_HW_SECURITY
+    if(m_state == S_RX_DEC){
+      dec();
+    }else{
+      receive();
+    }
+#else
     receive();
+#endif
   }
   
   /***************** RXFIFO Events ****************/
@@ -207,7 +533,14 @@ implementation {
 
     case S_RX_LENGTH:
       m_state = S_RX_FCF;
-      if ( rxFrameLength + 1 > m_bytes_left ) {
+#ifdef CC2420_HW_SECURITY
+      packetLength = rxFrameLength+1;
+#endif
+      if ( rxFrameLength + 1 > m_bytes_left
+#ifdef CC2420_HW_SECURITY
+           || flush_flag == 1
+#endif
+           ) {
         // Length of this packet is bigger than the RXFIFO, flush it out.
         flush();
         
@@ -266,20 +599,19 @@ implementation {
           call SACK.strobe();
           call CSN.set();
           call CSN.clr();
-          call RXFIFO.beginRead(buf + 1 + SACK_HEADER_LENGTH, 
-              rxFrameLength - SACK_HEADER_LENGTH);
+         call RXFIFO.beginRead(buf + 1 + SACK_HEADER_LENGTH,
+                               rxFrameLength - SACK_HEADER_LENGTH);
           return;
         }
       }
-      
       // Didn't flip CSn, we're ok to continue reading.
       call RXFIFO.continueRead(buf + 1 + SACK_HEADER_LENGTH, 
-          rxFrameLength - SACK_HEADER_LENGTH);
+                              rxFrameLength - SACK_HEADER_LENGTH);
       break;
-    
+
     case S_RX_PAYLOAD:
+
       call CSN.set();
-      
       if(!m_missed_packets) {
         // Release the SPI only if there are no more frames to download
         call SpiResource.release();
@@ -342,20 +674,32 @@ implementation {
     uint8_t length = header->length;
     uint8_t tmpLen __DEPUTY_UNUSED__ = sizeof(message_t) - (offsetof(message_t, data) - sizeof(cc2420_header_t));
     uint8_t* COUNT(tmpLen) buf = TCAST(uint8_t* COUNT(tmpLen), header);
-    
+
     metadata->crc = buf[ length ] >> 7;
     metadata->lqi = buf[ length ] & 0x7f;
     metadata->rssi = buf[ length - 1 ];
-    
+
     if (passesAddressCheck(m_p_rx_buf) && length >= CC2420_SIZE) {
-      m_p_rx_buf = signal Receive.receive( m_p_rx_buf, m_p_rx_buf->data, 
+#ifdef CC2420_HW_SECURITY
+      if(securityOn == 1){
+       if(m_missed_packets > 0){
+         m_missed_packets --;
+       }
+       if(authentication){
+         length -= micLength;
+       }
+      }
+      micLength = 0;
+      securityOn = 0;
+      authentication = 0;
+#endif
+      m_p_rx_buf = signal Receive.receive( m_p_rx_buf, m_p_rx_buf->data,
                                           length - CC2420_SIZE);
     }
-    
     atomic receivingPacket = FALSE;
     waitForNextPacket();
   }
-  
+
   /****************** CC2420Config Events ****************/
   event void CC2420Config.syncDone( error_t error ) {
   }
@@ -366,7 +710,6 @@ implementation {
    */
   void beginReceive() { 
     m_state = S_RX_LENGTH;
-    
     atomic receivingPacket = TRUE;
     if(call SpiResource.isOwner()) {
       receive();
@@ -383,7 +726,16 @@ implementation {
    * Flush out the Rx FIFO
    */
   void flush() {
+#ifdef CC2420_HW_SECURITY
+    flush_flag = 0;
+    pos =0;
+    packetLength =0;
+    micLength = 0;
+    securityOn = 0;
+    authentication = 0;
+#endif
     reset_state();
+
     call CSN.set();
     call CSN.clr();
     call SFLUSHRX.strobe();
@@ -427,14 +779,20 @@ implementation {
        * If the line stays low without generating an interrupt, that means
        * there's still more data to be received.
        */
+
       if ( ( m_missed_packets && call FIFO.get() ) || !call FIFOP.get() ) {
         // A new packet is buffered up and ready to go
         if ( m_missed_packets ) {
           m_missed_packets--;
         }
-        
-        beginReceive();
-        
+#ifdef CC2420_HW_SECURITY
+       call SpiResource.release();
+       m_state = S_RX_DEC;
+       beginDec();
+#else
+       beginReceive();
+#endif
+
       } else {
         // Wait for the next packet to arrive
         m_state = S_STARTED;
@@ -468,4 +826,5 @@ implementation {
     return (header->dest == call CC2420Config.getShortAddr()
         || header->dest == AM_BROADCAST_ADDR);
   }
+
 }
diff --git a/tos/chips/cc2420/security/CC2420KeysC.nc b/tos/chips/cc2420/security/CC2420KeysC.nc
new file mode 100644 (file)
index 0000000..ab995ff
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2008 Johns Hopkins University.
+* All rights reserved.
+*
+* Permission to use, copy, modify, and distribute this software and its
+* documentation for any purpose, without fee, and without written
+* agreement is hereby granted, provided that the above copyright
+* notice, the (updated) modification history and the author appear in
+* all copies of this source code.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED  TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR  PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR  CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE,  DATA,
+* OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR  OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author JeongGil Ko
+ * @author Razvan Musaloiu-E.
+ * @author Jong Hyun Lim
+ */
+
+configuration CC2420KeysC
+{
+  provides interface CC2420Keys;
+}
+
+implementation
+{
+  components new CC2420SpiC();
+  components HplCC2420PinsC as Pins;
+  components CC2420KeysP;
+
+  CC2420Keys = CC2420KeysP;
+
+  CC2420KeysP.CSN -> Pins.CSN;
+  CC2420KeysP.KEY0 -> CC2420SpiC.KEY0;
+  CC2420KeysP.KEY1 -> CC2420SpiC.KEY1;
+  CC2420KeysP.Resource -> CC2420SpiC.Resource;
+}
diff --git a/tos/chips/cc2420/security/CC2420KeysP.nc b/tos/chips/cc2420/security/CC2420KeysP.nc
new file mode 100644 (file)
index 0000000..bf0348c
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+* Copyright (c) 2008 Johns Hopkins University.
+* All rights reserved.
+*
+* Permission to use, copy, modify, and distribute this software and its
+* documentation for any purpose, without fee, and without written
+* agreement is hereby granted, provided that the above copyright
+* notice, the (updated) modification history and the author appear in
+* all copies of this source code.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED  TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR  PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR  CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE,  DATA,
+* OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR  OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author JeongGil Ko
+ * @author Razvan Musaloiu-E.
+ * @author Jong Hyun Lim
+ */
+
+module CC2420KeysP
+{
+  provides interface CC2420Keys;
+
+  uses {
+    interface GeneralIO as CSN;
+    interface CC2420Ram as KEY0;
+    interface CC2420Ram as KEY1;
+    interface Resource;
+  }
+}
+
+implementation
+{
+  uint8_t *currentKey = NULL;
+  bool currentKeyNo;
+
+  task void resourceReq()
+  {
+    error_t error;
+    error = call Resource.immediateRequest();
+    if(error != SUCCESS){
+      post resourceReq();
+    }
+  }
+
+  command error_t CC2420Keys.setKey(uint8_t keyNo, uint8_t* key)
+  {
+    if (currentKey != NULL || keyNo > 1) {
+      return FAIL;
+    }
+    currentKey = key;
+    currentKeyNo = keyNo;
+
+    if(call Resource.request() != SUCCESS){
+      post resourceReq();
+    }
+
+    return SUCCESS;
+  }
+
+  event void Resource.granted()
+  {
+    if (currentKeyNo) {
+      call CSN.clr();
+      call KEY1.write(0, currentKey, 16);
+      call CSN.set();
+    } else {
+      call CSN.clr();
+      call KEY0.write(0, currentKey, 16);
+      call CSN.set();
+    }
+    call Resource.release();
+    currentKey = NULL;
+    signal CC2420Keys.setKeyDone(currentKeyNo, currentKey);
+  }
+}
diff --git a/tos/chips/cc2420/security/SecAMSenderC.nc b/tos/chips/cc2420/security/SecAMSenderC.nc
new file mode 100644 (file)
index 0000000..99405fc
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+* Copyright (c) 2008 Johns Hopkins University.
+* All rights reserved.
+*
+* Permission to use, copy, modify, and distribute this software and its
+* documentation for any purpose, without fee, and without written
+* agreement is hereby granted, provided that the above copyright
+* notice, the (updated) modification history and the author appear in
+* all copies of this source code.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED  TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR  PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR  CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE,  DATA,
+* OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR  OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author JeongGil Ko
+ * @author Razvan Musaloiu-E.
+ * @author Jong Hyun Lim
+ */
+
+generic configuration SecAMSenderC(am_id_t id)
+{
+  provides {
+    interface AMSend;
+    interface Packet;
+    interface AMPacket;
+    interface PacketAcknowledgements as Acks;
+    interface CC2420SecurityMode;
+  }
+}
+
+implementation
+{
+  components ActiveMessageC;
+  components NoLedsC;
+  components LedsC;
+  components new CC2420SpiC();
+  components CC2420ActiveMessageC;
+  components new AMSenderC(id);
+  components new SecAMSenderP(id);
+
+  AMSend = SecAMSenderP.AMSend;
+  Packet = AMSenderC;
+  Acks = CC2420ActiveMessageC;
+  AMPacket = CC2420ActiveMessageC;
+  CC2420SecurityMode = SecAMSenderP;
+
+  SecAMSenderP.SubAMSend -> AMSenderC;
+  SecAMSenderP.SecurityPacket -> AMSenderC;
+  SecAMSenderP.Leds -> NoLedsC;
+}
diff --git a/tos/chips/cc2420/security/SecAMSenderP.nc b/tos/chips/cc2420/security/SecAMSenderP.nc
new file mode 100644 (file)
index 0000000..3d8d2ac
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+* Copyright (c) 2008 Johns Hopkins University.
+* All rights reserved.
+*
+* Permission to use, copy, modify, and distribute this software and its
+* documentation for any purpose, without fee, and without written
+* agreement is hereby granted, provided that the above copyright
+* notice, the (updated) modification history and the author appear in
+* all copies of this source code.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  `AS IS'
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED  TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR  PURPOSE
+* ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR  CONTRIBUTORS
+* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE,  DATA,
+* OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR  OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+* THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author JeongGil Ko
+ * @author Razvan Musaloiu-E.
+ * @author Jong Hyun Lim
+ */
+
+generic module SecAMSenderP(am_id_t id)
+{
+  provides {
+    interface AMSend;
+    interface CC2420SecurityMode;
+  }
+
+  uses {
+    interface AMSend as SubAMSend;
+    interface Packet as SecurityPacket;
+    interface AMPacket;
+    interface Leds;
+  }
+}
+
+implementation
+{
+  uint32_t nonceCounter = 0;
+  uint8_t secLevel = NO_SEC;
+  uint8_t keyIndex = 0;
+  uint8_t reserved = 0; // skip in cc2420 implementations
+  uint8_t micLength = 0;
+  uint8_t length;
+
+  command error_t AMSend.send(am_addr_t addr, message_t* msg, uint8_t len)
+  {
+    cc2420_header_t* hdr = (cc2420_header_t*)msg->header;
+    security_header_t* secHdr = (security_header_t*)&hdr->secHdr;
+
+    if(secHdr->secLevel == CBC_MAC_4 || secHdr->secLevel == CCM_4){
+      micLength = 4;
+    }else if(secHdr->secLevel == CBC_MAC_8 || secHdr->secLevel == CCM_8){
+      micLength = 8;
+    }else if(secHdr->secLevel == CBC_MAC_16 || secHdr->secLevel == CCM_16){
+      micLength = 16;
+    }
+
+    return call SubAMSend.send(addr, msg, len + (((secHdr->secLevel >= CBC_MAC_4 && secHdr->secLevel <= CBC_MAC_16) || (secHdr->secLevel >= CCM_4 && secHdr->secLevel <= CCM_16)) ? micLength : 0));
+  }
+
+  command uint8_t AMSend.maxPayloadLength()
+  {
+    return call SecurityPacket.maxPayloadLength();
+  }
+
+  command void* AMSend.getPayload(message_t* msg, uint8_t len)
+  {
+    return call SecurityPacket.getPayload(msg, len);
+  }
+
+  command error_t AMSend.cancel(message_t* msg) { return call SubAMSend.cancel(msg); }
+  event void SubAMSend.sendDone(message_t *msg, error_t error) { signal AMSend.sendDone(msg, error); }
+
+
+
+
+  command error_t CC2420SecurityMode.setCtr(message_t* msg, uint8_t setKey, uint8_t setSkip)
+  {
+    cc2420_header_t* hdr = (cc2420_header_t*)msg->header;
+    security_header_t* secHdr = (security_header_t*)&hdr->secHdr;
+
+    if (setKey > 1 || setSkip > 7){
+      return FAIL;
+    }
+    secLevel = CTR;
+    keyIndex = setKey;
+    reserved = setSkip;
+
+    nonceCounter++;
+
+    secHdr->secLevel = secLevel;
+    secHdr->keyMode = 1; // Fixed to 1 for now
+    secHdr->reserved = reserved; //skip in cc2420
+    secHdr->frameCounter = nonceCounter;
+    secHdr->keyID[0] = keyIndex; // Always first position for now due to fixed keyMode
+    hdr->fcf |= 1 << IEEE154_FCF_SECURITY_ENABLED;
+    return SUCCESS;
+  }
+
+
+
+  command error_t CC2420SecurityMode.setCbcMac(message_t* msg, uint8_t setKey, uint8_t setSkip, uint8_t size)
+  {
+    cc2420_header_t* hdr = (cc2420_header_t*)msg->header;
+    security_header_t* secHdr = (security_header_t*)&hdr->secHdr;
+
+    if (setKey > 1 || (size != 4 && size != 8 && size != 16) || (setSkip > 7)){
+      return FAIL;
+    }
+
+    if(size == 4)
+      secLevel = CBC_MAC_4;
+    else if (size == 8)
+      secLevel = CBC_MAC_8;
+    else if (size == 16)
+      secLevel = CBC_MAC_16;
+    else
+      return FAIL;
+    keyIndex = setKey;
+    reserved = setSkip;
+
+    nonceCounter++;
+
+    secHdr->secLevel = secLevel;
+    secHdr->keyMode = 1; // Fixed to 1 for now
+    secHdr->reserved = reserved; //skip in cc2420
+    secHdr->frameCounter = nonceCounter;
+    secHdr->keyID[0] = keyIndex; // Always first position for now due to fixed keyMode
+    hdr->fcf |= 1 << IEEE154_FCF_SECURITY_ENABLED;
+
+    return SUCCESS;
+  }
+
+
+  command error_t CC2420SecurityMode.setCcm(message_t* msg, uint8_t setKey, uint8_t setSkip, uint8_t size)
+  {
+    cc2420_header_t* hdr = (cc2420_header_t*)msg->header;
+    security_header_t* secHdr = (security_header_t*)&hdr->secHdr;
+
+    if (setKey > 1 || (size != 4 && size != 8 && size != 16) || (setSkip > 7)){
+      return FAIL;
+    }
+
+    if(size == 4)
+      secLevel = CCM_4;
+    else if (size == 8)
+      secLevel = CCM_8;
+    else if (size == 16)
+      secLevel = CCM_16;
+    else
+      return FAIL;
+    keyIndex = setKey;
+    reserved = setSkip;
+
+    nonceCounter++;
+
+    secHdr->secLevel = secLevel;
+    secHdr->keyMode = 1; // Fixed to 1 for now
+    secHdr->reserved = reserved; //skip in cc2420
+    secHdr->frameCounter = nonceCounter;
+    secHdr->keyID[0] = keyIndex; // Always first position for now due to fixed keyMode
+    hdr->fcf |= 1 << IEEE154_FCF_SECURITY_ENABLED;
+
+    return SUCCESS;
+  }
+}
index 50e015e9a9bc3ccbf899c925dedebd6bf689854c..582b46af58d34c405ae667b2aa17fff47091713b 100644 (file)
@@ -86,6 +86,12 @@ generic configuration CC2420SpiC() {
   provides interface CC2420Ram as PANID;
   provides interface CC2420Ram as SHORTADR;
   provides interface CC2420Ram as TXFIFO_RAM;
+  provides interface CC2420Ram as RXFIFO_RAM;
+  provides interface CC2420Ram as KEY0;
+  provides interface CC2420Ram as KEY1;
+  provides interface CC2420Ram as SABUF;
+  provides interface CC2420Ram as TXNONCE;
+  provides interface CC2420Ram as RXNONCE;
 
   // fifos
   provides interface CC2420Fifo as RXFIFO;
@@ -150,6 +156,12 @@ implementation {
   PANID = Spi.Ram[ CC2420_RAM_PANID ];
   SHORTADR = Spi.Ram[ CC2420_RAM_SHORTADR ];
   TXFIFO_RAM = Spi.Ram[ CC2420_RAM_TXFIFO ];
+  RXFIFO_RAM = Spi.Ram[ CC2420_RAM_RXFIFO ];
+  KEY0 = Spi.Ram[ CC2420_RAM_KEY0 ];
+  KEY1 = Spi.Ram[ CC2420_RAM_KEY1 ];
+  SABUF = Spi.Ram[ CC2420_RAM_SABUF ];
+  TXNONCE = Spi.Ram[ CC2420_RAM_TXNONCE ];
+  RXNONCE = Spi.Ram[ CC2420_RAM_RXNONCE ];
 
   // fifos
   RXFIFO = Spi.Fifo[ CC2420_RXFIFO ];
index 8624d981ed92dd30e1fb102bac78daaea25f123b..bb79ee1b1c92344a1c4d822758147861c555fa88 100644 (file)
@@ -84,6 +84,12 @@ implementation {
   CC2420TransmitP.TXFIFO      -> Spi.TXFIFO;
   CC2420TransmitP.TXFIFO_RAM  -> Spi.TXFIFO_RAM;
   CC2420TransmitP.MDMCTRL1    -> Spi.MDMCTRL1;
+  CC2420TransmitP.SECCTRL0 -> Spi.SECCTRL0;
+  CC2420TransmitP.SECCTRL1 -> Spi.SECCTRL1;
+  CC2420TransmitP.STXENC -> Spi.STXENC;
+  CC2420TransmitP.TXNONCE -> Spi.TXNONCE;
+  CC2420TransmitP.KEY0 -> Spi.KEY0;
+  CC2420TransmitP.KEY1 -> Spi.KEY1;
   
   components CC2420ReceiveC;
   CC2420TransmitP.CC2420Receive -> CC2420ReceiveC;
@@ -96,4 +102,5 @@ implementation {
 
   components LedsC;
   CC2420TransmitP.Leds -> LedsC;
+
 }
index cd640b1e7f29336bdbcef0a65e8a46bf238496cd..7e12cec89ae136f5c2b5496975083e72528f2cb7 100644 (file)
@@ -33,6 +33,8 @@
  * @author Jonathan Hui <jhui@archrock.com>
  * @author David Moss
  * @author Jung Il Choi Initial SACK implementation
+ * @author JeongGil Ko
+ * @author Razvan Musaloiu-E
  * @version $Revision$ $Date$
  */
 
@@ -71,6 +73,13 @@ module CC2420TransmitP @safe() {
   uses interface CC2420Strobe as SFLUSHTX;
   uses interface CC2420Register as MDMCTRL1;
 
+  uses interface CC2420Strobe as STXENC;
+  uses interface CC2420Register as SECCTRL0;
+  uses interface CC2420Register as SECCTRL1;
+  uses interface CC2420Ram as KEY0;
+  uses interface CC2420Ram as KEY1;
+  uses interface CC2420Ram as TXNONCE;
+
   uses interface CC2420Receive;
   uses interface Leds;
 }
@@ -96,6 +105,17 @@ implementation {
   enum {
     CC2420_ABORT_PERIOD = 320
   };
+
+#ifdef CC2420_HW_SECURITY
+  uint16_t startTime = 0;
+  norace uint8_t secCtrlMode = 0;
+  norace uint8_t nonceValue[16] = {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
+  norace uint8_t skip;
+  norace uint16_t CTR_SECCTRL0, CTR_SECCTRL1;
+  uint8_t securityChecked = 0;
+  
+  void securityCheck();
+#endif
   
   norace message_t * ONE_NOK m_msg;
   
@@ -104,7 +124,7 @@ implementation {
   norace uint8_t m_tx_power;
   
   cc2420_transmit_state_t m_state = S_STOPPED;
-  
+
   bool m_receiving = FALSE;
   
   uint16_t m_prev_time;
@@ -375,7 +395,6 @@ implementation {
     if ( type == IEEE154_TYPE_ACK && m_msg) {
       ack_header = call CC2420PacketBody.getHeader( ack_msg );
       msg_header = call CC2420PacketBody.getHeader( m_msg );
-
       
       if ( m_state == S_ACK_WAIT && msg_header->dsn == ack_header->dsn ) {
         call BackoffTimer.stop();
@@ -534,6 +553,9 @@ implementation {
         return FAIL;
       }
       
+#ifdef CC2420_HW_SECURITY
+      securityChecked = 0;
+#endif
       m_state = S_LOAD;
       m_cca = cca;
       m_msg = p_msg;
@@ -578,7 +600,123 @@ implementation {
     
     return SUCCESS;
   }
-  
+#ifdef CC2420_HW_SECURITY
+
+  task void waitTask(){
+    call Leds.led2Toggle();
+    if(SECURITYLOCK == 1){
+      post waitTask();
+    }else{
+      securityCheck();
+    }
+  }
+
+  void securityCheck(){
+
+    cc2420_header_t* msg_header;
+    cc2420_status_t status;
+    security_header_t* secHdr;
+    uint8_t mode;
+    uint8_t key;
+    uint8_t micLength;
+
+    msg_header = call CC2420PacketBody.getHeader( m_msg );
+
+    if(!(msg_header->fcf & (1 << IEEE154_FCF_SECURITY_ENABLED))){
+      // Security is not used for this packet
+      // Make sure to set mode to 0 and the others to the default values
+      CTR_SECCTRL0 = ((0 << CC2420_SECCTRL0_SEC_MODE) |
+                     (1 << CC2420_SECCTRL0_SEC_M) |
+                     (1 << CC2420_SECCTRL0_SEC_TXKEYSEL) |
+                     (1 << CC2420_SECCTRL0_SEC_CBC_HEAD)) ;
+      
+      call CSN.clr();
+      call SECCTRL0.write(CTR_SECCTRL0);
+      call CSN.set();
+
+      return;
+    }
+
+    if(SECURITYLOCK == 1){
+      post waitTask();
+    }else {
+      //Will perform encryption lock registers
+      atomic SECURITYLOCK = 1;
+
+      secHdr = (security_header_t*) &msg_header->secHdr;
+      memcpy(&nonceValue[3], &(secHdr->frameCounter), 4);
+
+      skip = secHdr->reserved;
+      key = secHdr->keyID[0]; // For now this is the only key selection mode.
+
+      if (secHdr->secLevel == NO_SEC){
+       mode = CC2420_NO_SEC;
+       micLength = 4;
+      }else if (secHdr->secLevel == CBC_MAC_4){
+       mode = CC2420_CBC_MAC;
+       micLength = 4;
+      }else if (secHdr->secLevel == CBC_MAC_8){
+       mode = CC2420_CBC_MAC;
+       micLength = 8;
+      }else if (secHdr->secLevel == CBC_MAC_16){
+       mode = CC2420_CBC_MAC;
+       micLength = 16;
+      }else if (secHdr->secLevel == CTR){
+       mode = CC2420_CTR;
+       micLength = 4;
+      }else if (secHdr->secLevel == CCM_4){
+       mode = CC2420_CCM;
+       micLength = 4;
+      }else if (secHdr->secLevel == CCM_8){
+       mode = CC2420_CCM;
+       micLength = 8;
+      }else if (secHdr->secLevel == CCM_16){
+       mode = CC2420_CCM;
+       micLength = 16;
+      }else{
+       return;
+      }
+
+      CTR_SECCTRL0 = ((mode << CC2420_SECCTRL0_SEC_MODE) |
+                     ((micLength-2)/2 << CC2420_SECCTRL0_SEC_M) |
+                     (key << CC2420_SECCTRL0_SEC_TXKEYSEL) |
+                     (1 << CC2420_SECCTRL0_SEC_CBC_HEAD)) ;
+#ifndef TFRAMES_ENABLED
+      CTR_SECCTRL1 = (skip+11+sizeof(security_header_t)+((skip+11+sizeof(security_header_t))<<8));
+#else
+      CTR_SECCTRL1 = (skip+10+sizeof(security_header_t)+((skip+10+sizeof(security_header_t))<<8));
+#endif
+
+      call CSN.clr();
+      call SECCTRL0.write(CTR_SECCTRL0);
+      call CSN.set();
+
+      call CSN.clr();
+      call SECCTRL1.write(CTR_SECCTRL1);
+      call CSN.set();
+
+      call CSN.clr();
+      call TXNONCE.write(0, nonceValue, 16);
+      call CSN.set();
+
+      call CSN.clr();
+      status = call SNOP.strobe();
+      call CSN.set();
+
+      while(status & CC2420_STATUS_ENC_BUSY){
+       call CSN.clr();
+       status = call SNOP.strobe();
+       call CSN.set();
+      }
+      
+      // Inline security will be activated by STXON or STXONCCA strobes
+
+      atomic SECURITYLOCK = 0;
+
+    }
+  }
+#endif
+
   /**
    * Attempt to send the packet we have loaded into the tx buffer on 
    * the radio chip.  The STXONCCA will send the packet immediately if
@@ -591,6 +729,9 @@ implementation {
    *
    * If the packet got sent, we should expect an SFD interrupt to take
    * over, signifying the packet is getting sent.
+   * 
+   * If security is enabled, STXONCCA or STXON will perform inline security
+   * options before transmitting the packet.
    */
   void attemptSend() {
     uint8_t status;
@@ -605,10 +746,13 @@ implementation {
         signal Send.sendDone( m_msg, ECANCEL );
         return;
       }
-      
-      
+#ifdef CC2420_HW_SECURITY
+      if(securityChecked != 1){
+       securityCheck();
+      }
+      securityChecked = 1;
+#endif
       call CSN.clr();
-
       status = m_cca ? call STXONCCA.strobe() : call STXON.strobe();
       if ( !( status & CC2420_STATUS_TX_ACTIVE ) ) {
         status = call SNOP.strobe();
@@ -616,11 +760,11 @@ implementation {
           congestion = FALSE;
         }
       }
-      
+
       m_state = congestion ? S_SAMPLE_CCA : S_SFD;
       call CSN.set();
     }
-    
+
     if ( congestion ) {
       totalCcaChecks = 0;
       releaseSpiResource();
@@ -702,5 +846,6 @@ implementation {
     call ChipSpiResource.attemptRelease();
     signal Send.sendDone( m_msg, err );
   }
+
 }
 
index 7688a55eaa13bfc927a1d84a35617b572238911e..edeebfe6bdf05dafa16e192ac5a789b2c44b3ea8 100644 (file)
  */
 
 /**
- * An async version of the SplitControl interface.
+ * This interface is a mixture of a SplitControl/AsyncStdControl interface.
  * @author Jan Hauer <hauer@tkn.tu-berlin.de>
  */
 
 interface CC2420AsyncSplitControl
 {
   /**
-   * Start this component and all of its subcomponents.  Return
-   * values of SUCCESS will always result in a <code>startDone()</code>
-   * event being signalled.
+   * Start this component and all of its subcomponents.  
    *
-   * @return SUCCESS if the device is already in the process of 
-   *         starting or the device was off and the device is now ready to turn 
-   *         on.  After receiving this return value, you should expect a 
-   *         <code>startDone</code> event in the near future.<br>
-   *         EBUSY if the component is in the middle of powering down
-   *               i.e. a <code>stop()</code> command has been called,
-   *               and a <code>stopDone()</code> event is pending<br>
-   *         EALREADY if the device is already on <br>
+   * @return SUCCESS if the component was started successfully.<br>
    *         FAIL Otherwise
    */
   async command error_t start();
 
-  /** 
-   * Notify caller that the component has been started and is ready to
-   * receive other commands.
-   *
-   * @param <b>error</b> -- SUCCESS if the component was successfully
-   *                        turned on, FAIL otherwise
-   */
-  async event void startDone(error_t error);
-
   /**
-   * Start this component and all of its subcomponents.  Return
-   * values of SUCCESS will always result in a <code>startDone()</code>
-   * event being signalled.
+   * Stop this component and all of its subcomponents - iff this command
+   * succeeds then <tt>stopDone</tt> will signal the result of the stop
+   * operation.
    *
-   * @return SUCCESS if the device is already in the process of 
-   *         stopping or the device was on and the device is now ready to turn 
-   *         off.  After receiving this return value, you should expect a 
-   *         <code>stopDone</code> event in the near future.<br>
-   *         EBUSY if the component is in the middle of powering up
-   *               i.e. a <code>start()</code> command has been called,
-   *               and a <code>startDone()</code> event is pending<br>
-   *         EALREADY if the device is already off <br>
-   *         FAIL Otherwise
+   * @return SUCCESS Stop operation was started, <tt>stopDone</tt> will be signalled
+   *         FAIL Otherwise (<tt>stopDone</tt> will not be signalled)
    */
   async command error_t stop();
 
   /**
-   * Notify caller that the component has been stopped.
+   * Notify caller that the component has been stopped. This event
+   * completes the <tt>stop()</tt> operation.
    *
   * @param <b>error</b> -- SUCCESS if the component was successfully
   *                        turned off, FAIL otherwise
index 64e4adf8f33f8b726fb867bf8266f4d32e99402b..030f8afcf21ca8f1e364544f1e636a957e0610ce 100644 (file)
@@ -33,7 +33,7 @@
  * @author Jonathan Hui <jhui@archrock.com>
  * @author David Moss
  * @author Urs Hunkeler (ReadRssi implementation)
- * @author Jan Hauer <hauer@tkn.tu-berlin.de> (support for promiscuous mode)
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
  * @version $Revision$ $Date$
  */
 
@@ -53,6 +53,7 @@ module CC2420ControlP {
   uses interface GeneralIO as RSTN;
   uses interface GeneralIO as VREN;
   uses interface GpioInterrupt as InterruptCCA;
+  uses interface GeneralIO as FIFO;
 
   uses interface CC2420Ram as IEEEADR;
   uses interface CC2420Register as FSCTRL;
@@ -62,17 +63,17 @@ module CC2420ControlP {
   uses interface CC2420Register as MDMCTRL1;
   uses interface CC2420Register as RXCTRL1;
   uses interface CC2420Register as RSSI;
+  uses interface CC2420Register as RXFIFO_REGISTER;
+  uses interface CC2420Strobe as SNOP;
   uses interface CC2420Strobe as SRXON;
   uses interface CC2420Strobe as SRFOFF;
   uses interface CC2420Strobe as SXOSCOFF;
   uses interface CC2420Strobe as SXOSCON;
-  uses interface CC2420Strobe as SACKPEND; // JH: ACKs must have pending flag set
+  uses interface CC2420Strobe as SACKPEND;
+  uses interface CC2420Strobe as SFLUSHRX;
   uses interface CC2420Register as TXCTRL;
   uses interface AMPacket;
-  
   uses interface Resource as SpiResource;
-
-  uses interface Leds;
   uses interface FrameUtility;
 }
 
@@ -122,6 +123,12 @@ implementation {
   }
 
   /***************** Resource Commands ****************/
+  /* This module never actively requests the SPI resource,
+   * instead the caller MUST request the SPI through this module
+   * before it calls any of the provided commands and it must
+   * release it afterwards (the caller can call multiple  
+   * commands in this module before it releases the SPI, though).
+   */ 
   async command error_t Resource.immediateRequest() {
     error_t error = call SpiResource.immediateRequest();
     if ( error == SUCCESS ) {
@@ -145,29 +152,9 @@ implementation {
     }
   }
 
-  void switchToUnbufferedMode()
-  {
-    uint16_t mdmctrol1;
-    call CSN.set();
-    call CSN.clr();
-    call MDMCTRL1.read(&mdmctrol1);
-    call CSN.set();
-    mdmctrol1 &= ~0x0003;
-    mdmctrol1 |= 0x0000;
-    call CSN.clr();
-    call MDMCTRL1.write(mdmctrol1);
-    call CSN.set();
-  }
-
-  void switchToBufferedMode()
-  {
-    uint16_t mdmctrol1;
-    call CSN.set();
-    call CSN.clr();
-    call MDMCTRL1.read(&mdmctrol1);
-    mdmctrol1 &= ~0x03;
-    call MDMCTRL1.write(mdmctrol1);
-    call CSN.set();
+  event void SpiResource.granted() {
+/*    call CSN.clr();*/
+    signal Resource.granted();
   }
 
   /***************** CC2420Power Commands ****************/
@@ -179,7 +166,7 @@ implementation {
       m_state = S_VREG_STARTING;
     }
     call VREN.set();
-    call StartupAlarm.start( CC2420_TIME_VREN * 2 ); // JH: a 15.4 symbol is about two 32khz ticks
+    call StartupAlarm.start( CC2420_TIME_VREN * 2 ); // JH: changed from 32khz jiffies
     return SUCCESS;
   }
 
@@ -241,32 +228,52 @@ implementation {
 
   async command error_t CC2420Power.rxOn() {
     atomic {
-      if ( m_state != S_XOSC_STARTED ) {
+      if ( !call SpiResource.isOwner() )
         return FAIL;
-      }
       call CSN.set();
       call CSN.clr();
       call SRXON.strobe();
-      call SACKPEND.strobe();  // JH: ACKs have the pending bit set
+      call SACKPEND.strobe();  // JH: ACKs need the pending bit set
       call CSN.set();
     }
     return SUCCESS;
   }
 
   async command error_t CC2420Power.rfOff() {
-    atomic {  
-      if ( m_state != S_XOSC_STARTED ) {
+    atomic {
+      if ( !call SpiResource.isOwner() )
         return FAIL;
-      }
       call CSN.set();
       call CSN.clr();
-      call SACKPEND.strobe();  // JH: ACKs have the pending bit set
       call SRFOFF.strobe();
       call CSN.set();
     }
     return SUCCESS;
   }
 
+  async command error_t CC2420Power.flushRxFifo()
+  {
+    uint16_t dummy;
+    atomic {
+      if ( !call SpiResource.isOwner() )
+        return FAIL;
+      if ( call FIFO.get() ){ // check if there is something in the RXFIFO
+        // SFLUSHRX: "Flush the RX FIFO buffer and reset the demodulator. 
+        // Always read at least one byte from the RXFIFO before 
+        // issuing the SFLUSHRX command strobe" (CC2420 Datasheet)
+        call CSN.clr();
+        call RXFIFO_REGISTER.read(&dummy); // reading the byte
+        call CSN.set();
+        call CSN.clr();
+        // "SFLUSHRX command strobe should be issued twice to ensure 
+        // that the SFD pin goes back to its idle state." (CC2420 Datasheet)
+        call SFLUSHRX.strobe();
+        call SFLUSHRX.strobe();
+        call CSN.set();
+      }
+    }
+    return SUCCESS;
+  }
   
   /***************** CC2420Config Commands ****************/
   command uint8_t CC2420Config.getChannel() {
@@ -363,17 +370,16 @@ implementation {
   async command bool CC2420Config.needsSync(){
     atomic return m_needsSync;
   }
+
   /**
    * Sync must be called to commit software parameters configured on
    * the microcontroller (through the CC2420Config interface) to the
    * CC2420 radio chip.
-   * ASSUMPTION: caller owns the SPI, radio will be switched off !
    */
   async command error_t CC2420Config.sync() {
     atomic {
-      if ( m_state != S_XOSC_STARTED ) {
+      if ( !call SpiResource.isOwner() )
         return FAIL;
-      }
       if (m_needsSync){
         call CSN.set();
         call CSN.clr();
@@ -396,25 +402,22 @@ implementation {
   /***************** ReadRssi Commands ****************/
   
   async command error_t CC2420Power.rssi(int8_t *rssi) {
-    // we are owner of the Spi !
     uint16_t data;
     cc2420_status_t status;
-    call CSN.clr();
-    status = call RSSI.read(&data);
-    call CSN.set();
-    if ((status & 0x02)){
-      *rssi = (data & 0x00FF);
-      return SUCCESS;
-    } else
-      return FAIL;
-  }
-
-  event void SpiResource.granted() {
-/*    call CSN.clr();*/
-    signal Resource.granted();
+    atomic {
+      if ( !call SpiResource.isOwner() )
+        return FAIL;
+      call CSN.set();
+      call CSN.clr();
+      status = call RSSI.read(&data);
+      call CSN.set();
+      if ((status & 0x02)){
+        *rssi = (data & 0x00FF);
+        return SUCCESS;
+      } else
+        return FAIL;
+    }
   }
-
-
   
   /***************** StartupAlarm Events ****************/
   async event void StartupAlarm.fired() {
index 76f8568ea7a6f1cd3f71d1224a2155614be8a323..64e1834f630d85be5a22c6fa110318873198518f 100644 (file)
@@ -64,7 +64,6 @@ configuration CC2420ControlTransmitC {
     interface Alarm<T62500hz,uint32_t> as AckAlarm;
     interface CaptureTime;
     interface ReferenceTime;
-    interface Leds;
   }
 }
 
@@ -76,7 +75,6 @@ implementation {
   CC2420Config = CC2420ControlP;
   CC2420Power = CC2420ControlP;
   FrameUtility = CC2420ControlP;
-  CC2420ControlP.Leds = Leds;
 
   components MainC;
   MainC.SoftwareInit -> CC2420ControlP;
@@ -86,6 +84,7 @@ implementation {
   CC2420ControlP.CSN -> Pins.CSN;
   CC2420ControlP.RSTN -> Pins.RSTN;
   CC2420ControlP.VREN -> Pins.VREN;
+  CC2420ControlP.FIFO -> Pins.FIFO;
 
   components HplCC2420InterruptsC as Interrupts;
   CC2420ControlP.InterruptCCA -> Interrupts.InterruptCCA;
@@ -106,7 +105,10 @@ implementation {
   CC2420ControlP.TXCTRL      -> Spi.TXCTRL;
   CC2420ControlP.IEEEADR -> Spi.IEEEADR;
   CC2420ControlP.RXCTRL1 -> Spi.RXCTRL1;
+  CC2420ControlP.SFLUSHRX-> Spi.SFLUSHRX;
   CC2420ControlP.RSSI  -> Spi.RSSI;
+  CC2420ControlP.RXFIFO_REGISTER -> Spi.RXFIFO_REGISTER;
+  CC2420ControlP.SNOP -> Spi.SNOP;
 
   // CC2420TransmitC
   components CC2420TransmitP;
@@ -115,13 +117,14 @@ implementation {
   AckAlarm = CC2420TransmitP;
   CaptureTime = CC2420TransmitP;
   ReferenceTime = CC2420TransmitP;
-  CC2420TransmitP.Leds = Leds;
 
   MainC.SoftwareInit -> CC2420TransmitP;
   CC2420TransmitP.CCA -> Pins.CCA;
   CC2420TransmitP.CSN -> Pins.CSN;
   CC2420TransmitP.SFD -> Pins.SFD;
   CC2420TransmitP.CaptureSFD -> Interrupts.CaptureSFD;
+  CC2420TransmitP.FIFOP -> Pins.FIFOP;
+  CC2420TransmitP.FIFO -> Pins.FIFO;
 
   CC2420TransmitP.ChipSpiResource -> Spi;
   CC2420TransmitP.SNOP        -> Spi.SNOP;
index a213f31d5d7a1c938a7122360ff7c05687d14d79..403bfb0bc386fb0afabdc22d39aec36f993871ec 100644 (file)
@@ -99,7 +99,15 @@ interface CC2420Power {
 
   /**
    * Read RSSI from the radio. 
-   * @return SUCCESS if RSSI was read successfulyy, FAIL otherwise.
+   * @return SUCCESS if RSSI was read successfully, FAIL otherwise.
    */
   async command error_t rssi(int8_t *rssi);
+  /**
+   * Flush the RXFIFO if it is not empty. 
+   * Radio SHOULD be disabled (off) when calling this command.
+   *
+   * @return SUCCESS if fifo was flushed (or it was empty), FAIL otherwise.
+   */
+  async command error_t flushRxFifo(); 
 }
index 1ba224edaf377e91d2120e26a1523be8a494278b..a49e988cc9d570ef7c229e6d00c4c4d847a64435 100644 (file)
@@ -45,7 +45,7 @@ interface CC2420Receive {
    *
    * @param time at which the capture happened.
    */
-  async command void sfd( ieee154_reftime_t *time );
+  async command void sfd( ieee154_timestamp_t *time );
 
   /**
    * Notification that the packet has been dropped by the radio
index f838182249ce907b11dbe72e14a533ae7c62f96b..77aac38c3ca67de633312373946b7cd7e9852122 100644 (file)
@@ -43,7 +43,6 @@ configuration CC2420ReceiveC {
   provides interface CC2420Receive; // to CC2420TransmitP for ACK
   provides interface CC2420Rx;      // to the driver
   uses interface ReferenceTime;
-  uses interface Leds;
   uses interface FrameUtility;
   uses interface CC2420Config;
 }
@@ -56,7 +55,6 @@ implementation {
   components HplCC2420PinsC as Pins;
   components HplCC2420InterruptsC as InterruptsC;
 
-  CC2420ReceiveP.Leds = Leds;
   CC2420AsyncSplitControl = CC2420ReceiveP;
   CC2420Receive = CC2420ReceiveP;
   CC2420Rx = CC2420ReceiveP;
index 04860924a488ddde3f10208aa7eec13e79484eb1..fddf5dd68188fa47aff9b99ea45b26ad69a970a8 100644 (file)
@@ -42,7 +42,6 @@ module CC2420ReceiveP {
   provides interface CC2420AsyncSplitControl as AsyncSplitControl; 
   provides interface CC2420Receive;
   provides interface CC2420Rx;
-/*  provides interface ReceiveIndicator as PacketIndicator;*/
 
   uses interface GeneralIO as CSN;
   uses interface GeneralIO as FIFO;
@@ -54,15 +53,12 @@ module CC2420ReceiveP {
   uses interface CC2420Strobe as SACK;
   uses interface CC2420Strobe as SFLUSHRX;
   uses interface CC2420Strobe as SRXON;
-  uses interface CC2420Strobe as SACKPEND; // JH: ACKs must have pending flag set
+  uses interface CC2420Strobe as SACKPEND; 
   uses interface CC2420Register as MDMCTRL1;
   uses interface ReferenceTime;
   uses interface FrameUtility;
   uses interface CC2420Config;
-/*  uses interface CC2420Packet;*/
-/*  uses interface CC2420PacketBody;*/
-  
-  uses interface Leds;
+  uses interface CC2420Ram as RXFIFO_RAM;
 }
 
 implementation {
@@ -70,7 +66,6 @@ implementation {
   typedef enum {
     S_STOPPED,
     S_STARTING,
-    S_STARTING_FLUSHRX,
     S_STARTED,
     S_RX_LENGTH,
     S_RX_FCF,
@@ -85,8 +80,8 @@ implementation {
     SACK_HEADER_LENGTH = 3,
   };
 
-  ieee154_reftime_t m_timestamp_queue[ TIMESTAMP_QUEUE_SIZE ];
-  ieee154_reftime_t m_timestamp;
+  ieee154_timestamp_t m_timestamp_queue[ TIMESTAMP_QUEUE_SIZE ];
+  ieee154_timestamp_t m_timestamp;
   norace bool m_timestampValid;
   
   uint8_t m_timestamp_head;
@@ -125,7 +120,6 @@ implementation {
   void flush();
   void switchToUnbufferedMode();
   void switchToBufferedMode();
-  void startingSpiReserved();
   void continueStart();
   void continueStop();
   task void stopContinueTask();
@@ -139,79 +133,45 @@ implementation {
     return SUCCESS;
   }
 
-  /***************** AsyncSplitControl ****************
-   * IMPORTANT: when AsyncSplitControl.start is called, 
-   * the radio MUST be off !
+  /***************** AsyncSplitControl ****************/
+  /* NOTE: AsyncSplitControl does not switch the state of the radio 
+   * hardware (i.e. it does not put the radio in Rx mode, this has to
+   * be done by the caller through a separate interface/component). 
    */
-  async command error_t AsyncSplitControl.start()
-  {
-    atomic {
-      if (m_state != S_STOPPED){
-        call Leds.led0On();
-        return FAIL;
-      } else {
-        m_state = S_STARTING;
-        if (call SpiResource.isOwner()){ 
-          call Leds.led0On(); // internal error (debug) !
-          startingSpiReserved();
-        }
-        if (call SpiResource.immediateRequest() == SUCCESS)
-          startingSpiReserved();
-        else
-          call SpiResource.request();        
-      }
-    }
-    return SUCCESS;
-  }
 
-  void startingSpiReserved()
+  /** 
+   * AsyncSplitControl.start should be called before radio
+   * is switched to Rx mode (or at least early enough before
+   * a packet has been received, i.e. before FIFOP changes)
+   */
+  async command error_t AsyncSplitControl.start()
   {
     atomic {
-      if (!call FIFOP.get() || call FIFO.get()){ // FIFOP is inverted
-        // there is something in RXFIFO: flush it out 
-        // the datasheet says at least one byte should 
-        // be read before flushing
-        m_state = S_STARTING_FLUSHRX;
-        call CSN.set();
-        call CSN.clr();
-        call RXFIFO.beginRead( &m_dummy, 1 ); // will continue in continueFlushStart()
-        return;
+      if ( !call FIFO.get() && !call FIFOP.get() ){
+        // RXFIFO has some data (remember: FIFOP is inverted)
+        // the problem is that this messses up the timestamping
+        // so why don't we flush here ourselves? 
+        // because we don't own the SPI...
+        return FAIL; 
       }
-    }
-    continueStart();
-  }
-
-
-  void continueFlushStart()
-  {
-    atomic {
-      call CSN.set();
-      call CSN.clr();
-      call SFLUSHRX.strobe();
-      call SFLUSHRX.strobe();
-      call CSN.set();
-    }
-    continueStart();
-  }
-  
-  void continueStart()
-  {
-    // RXFIFO is empty
-    if (!call FIFOP.get() || call FIFO.get()){
-      call Leds.led0On();
-    }
-    atomic {
+      ASSERT(m_state == S_STOPPED);
       reset_state();
       m_state = S_STARTED;
+      call InterruptFIFOP.enableFallingEdge(); // ready!
     }
-    call SpiResource.release();
-    call InterruptFIFOP.enableFallingEdge();
-    signal AsyncSplitControl.startDone(SUCCESS);
+    return SUCCESS;
   }
 
-  /***************** AsyncSplitControl ****************
+  /* AsyncSplitControl.stop:
+   *
    * IMPORTANT: when AsyncSplitControl.stop is called, 
-   * the radio MUST NOT be off !
+   * then either
+   * 1) the radio MUST still be in RxMode
+   * 2) it was never put in RxMode after  
+   *    AsyncSplitControl.start() was called
+   *
+   * => The radio may be switched off only *after* the
+   * stopDone() event was signalled.
    */
   async command error_t AsyncSplitControl.stop()
   {
@@ -222,9 +182,9 @@ implementation {
         m_stop = TRUE;
         call InterruptFIFOP.disable();
         if (!receivingPacket)
-          continueStop();
-        // else stopContinueTask will be posted after 
-        // current Rx operation is finished, because m_stop is set
+          continueStop(); // it is safe to stop now
+        // else continueStop will be called after 
+        // current Rx operation is finished
       }
     }
     return SUCCESS;
@@ -233,6 +193,9 @@ implementation {
   void continueStop()
   {
     atomic {
+      if (!m_stop){
+        return;
+      }
       m_stop = FALSE;
       m_state = S_STOPPED;
     }
@@ -241,49 +204,24 @@ implementation {
 
   task void stopContinueTask()
   {
-    if (receivingPacket){
-      call Leds.led0On();
-    }
+    ASSERT(receivingPacket != TRUE);
     call SpiResource.release(); // may fail
     atomic m_state = S_STOPPED;
     signal AsyncSplitControl.stopDone(SUCCESS);
   }
 
-  void switchToUnbufferedMode()
-  {
-    uint16_t mdmctrol1;
-    call CSN.set();
-    call CSN.clr();
-    call MDMCTRL1.read(&mdmctrol1);
-    mdmctrol1 &= ~0x03;
-    mdmctrol1 |= 0x01;
-    call MDMCTRL1.write(mdmctrol1);
-    call CSN.set();
-  }
-
-  void switchToBufferedMode()
-  {
-    uint16_t mdmctrol1;
-    call CSN.set();
-    call CSN.clr();
-    call MDMCTRL1.read(&mdmctrol1);
-    mdmctrol1 &= ~0x03;
-    call MDMCTRL1.write(mdmctrol1);
-    call CSN.set();
-  }
-
   /***************** CC2420Receive Commands ****************/
   /**
    * Start frame delimiter signifies the beginning/end of a packet
    * See the CC2420 datasheet for details.
    */
-  async command void CC2420Receive.sfd( ieee154_reftime_t *time ) {
+  async command void CC2420Receive.sfd( ieee154_timestamp_t *time ) {
     if (m_state == S_STOPPED)
       return;
     if ( m_timestamp_size < TIMESTAMP_QUEUE_SIZE ) {
       uint8_t tail =  ( ( m_timestamp_head + m_timestamp_size ) % 
                         TIMESTAMP_QUEUE_SIZE );
-      memcpy(&m_timestamp_queue[ tail ], time, sizeof(ieee154_reftime_t) );
+      memcpy(&m_timestamp_queue[ tail ], time, sizeof(ieee154_timestamp_t) );
       m_timestamp_size++;
     }
   }
@@ -314,39 +252,12 @@ implementation {
     atomic {
       switch (m_state)
       {
-        case S_STARTING: startingSpiReserved(); break;
-        case S_STARTING_FLUSHRX: // fall through
-        case S_STOPPED: call Leds.led0On(); 
-                        call SpiResource.release(); break;
+        case S_STOPPED: ASSERT(0); break; // this should never happen!
         default: receive();
       }
     }
   }
   
-  uint8_t mhrLength(uint8_t *fcf)
-  {
-    uint8_t idCompression;
-    uint8_t len = MHR_INDEX_ADDRESS;
-    if (fcf[MHR_INDEX_FC1] & FC1_SECURITY_ENABLED)
-      return 0xFF; // not supported 
-    idCompression = (fcf[0] & FC1_PAN_ID_COMPRESSION);
-    if (fcf[MHR_INDEX_FC2] & 0x08){ // short or ext. address
-      len += 4; // pan id + short address
-      if (fcf[MHR_INDEX_FC2] & 0x04) // ext. address
-        len += 6; // diff to short address
-    }
-    if (fcf[MHR_INDEX_FC2] & 0x80){ // short or ext. address
-      len += 2;
-      if (!idCompression)
-        len += 2;
-      if (fcf[MHR_INDEX_FC2] & 0x40) // ext. address
-        len += 6; // diff to short address
-    }
-    return len;
-  }
-    
-  
   /***************** RXFIFO Events ****************/
   /**
    * We received some bytes from the SPI bus.  Process them in the context
@@ -441,9 +352,9 @@ implementation {
       }
       
       if ( m_timestamp_size ) {
-        if ( rxFrameLength > 10 ) {
+        if ( rxFrameLength > 4 ) {
           //((ieee154_metadata_t*) m_rxFramePtr->metadata)->timestamp = m_timestamp_queue[ m_timestamp_head ];
-          memcpy(&m_timestamp, &m_timestamp_queue[ m_timestamp_head ], sizeof(ieee154_reftime_t) );
+          memcpy(&m_timestamp, &m_timestamp_queue[ m_timestamp_head ], sizeof(ieee154_timestamp_t) );
           m_timestampValid = TRUE;
           m_timestamp_head = ( m_timestamp_head + 1 ) % TIMESTAMP_QUEUE_SIZE;
           m_timestamp_size--;
@@ -471,8 +382,6 @@ implementation {
       waitForNextPacket();
       break;
 
-    case S_STARTING_FLUSHRX: continueFlushStart(); break;
-      
     default:
       atomic receivingPacket = FALSE;
       call CSN.set();
@@ -500,12 +409,7 @@ implementation {
     uint8_t payloadLen = ((ieee154_header_t*) m_rxFramePtr->header)->length - m_mhrLen - 2;
     ieee154_metadata_t *metadata = (ieee154_metadata_t*) m_rxFramePtr->metadata;
 
-    atomic {
-      if (m_state == S_STOPPED){
-        call Leds.led0On();
-        return;
-      }
-    }
+    atomic ASSERT(m_state != S_STOPPED);
     ((ieee154_header_t*) m_rxFramePtr->header)->length = m_rxFramePtr->data[payloadLen+1] & 0x7f; // temp. LQI
     metadata->rssi = m_rxFramePtr->data[payloadLen];
     metadata->linkQuality = ((ieee154_header_t*) m_rxFramePtr->header)->length; // copy back
@@ -538,8 +442,7 @@ implementation {
    */
   void beginReceive() { 
     atomic {
-      if ( m_state == S_STOPPED){
-        call Leds.led0On();
+      if (m_state == S_STOPPED || m_stop){
         return;
       }
       m_state = S_RX_LENGTH;
@@ -591,11 +494,11 @@ implementation {
    */
   void waitForNextPacket() {
     atomic {
-      receivingPacket = FALSE;
       if ( m_state == S_STOPPED) {
         call SpiResource.release();
         return;
       }
+      receivingPacket = FALSE;
       if (m_stop){
         continueStop();
         return;
index 1f1abf2e4924c15dbbab1bf1dcb7aefbde1d1cb5..bb7943420414e59c70cca8f080ad9747510c8972 100644 (file)
@@ -42,7 +42,7 @@ interface CC2420Rx {
    * Receive a packet buffer, returning a buffer for the signaling
    * component to use for the next reception. 
    */
-  event message_t* received(message_t *data, ieee154_reftime_t *timestamp);
+  event message_t* received(message_t *data, ieee154_timestamp_t *timestamp);
 
 }
 
index 18da878a2e4cd2151eb5d3cfa435e32e0b6dd2a8..9909839004115611f9d964736be7182b74ddb216 100644 (file)
@@ -41,10 +41,13 @@ configuration CC2420TKN154C
     interface SplitControl;
     interface RadioRx;
     interface RadioTx;
+    interface SlottedCsmaCa;
+    interface UnslottedCsmaCa;
     interface EnergyDetection;
     interface RadioOff;
     interface Set<bool> as RadioPromiscuousMode;
     interface Timestamp;
+    interface GetNow<bool> as CCA;
   } uses {
     interface Notify<const void*> as PIBUpdate[uint8_t attributeID];
     interface LocalTime<T62500hz>;
@@ -55,7 +58,6 @@ configuration CC2420TKN154C
     interface ReferenceTime;
     interface ReliableWait;
     interface TimeCalc;
-    interface Leds;
     interface Random;
   }
 } implementation {
@@ -65,6 +67,8 @@ configuration CC2420TKN154C
   SplitControl = PHY;
   RadioRx = PHY;
   RadioTx = PHY;
+  SlottedCsmaCa = PHY;
+  UnslottedCsmaCa = PHY;
   RadioOff = PHY;
   EnergyDetection = PHY;
   PIBUpdate = PHY;
@@ -74,9 +78,9 @@ configuration CC2420TKN154C
   ReliableWait = PHY;
   ReferenceTime = PHY;
   TimeCalc = PHY;
+  CCA = PHY;
 
   PHY.Random = Random;
-  Leds = PHY.Leds;
 
   components CC2420ControlTransmitC;
   PHY.SpiResource -> CC2420ControlTransmitC;
@@ -84,7 +88,6 @@ configuration CC2420TKN154C
   PHY.CC2420Config -> CC2420ControlTransmitC;
   CC2420ControlTransmitC.StartupAlarm = Alarm2;
   FrameUtility = CC2420ControlTransmitC;
-  Leds = CC2420ControlTransmitC;
 
   PHY.TxControl -> CC2420ControlTransmitC;
   PHY.CC2420Tx -> CC2420ControlTransmitC;
@@ -96,7 +99,6 @@ configuration CC2420TKN154C
   PHY.RxControl -> CC2420ReceiveC;
   PHY.CC2420Rx -> CC2420ReceiveC.CC2420Rx;
   ReferenceTime = CC2420ReceiveC;
-  Leds = CC2420ReceiveC;
   FrameUtility = CC2420ReceiveC;
   CC2420ReceiveC.CC2420Config -> CC2420ControlTransmitC;
 }
index 2546253eddd3f02c50205dc94ec298c5aa8fec80..d6a144b97c14a6e64a372c0b91f82b11efb31ad7 100644 (file)
@@ -43,12 +43,15 @@ module CC2420TKN154P
 
   provides {
     interface SplitControl;
+    interface RadioOff;
     interface RadioRx;
     interface RadioTx;
-    interface RadioOff;
+    interface SlottedCsmaCa;
+    interface UnslottedCsmaCa;
     interface EnergyDetection;
     interface Set<bool> as RadioPromiscuousMode;
     interface Timestamp;
+    interface GetNow<bool> as CCA;
   } uses {
     interface Notify<const void*> as PIBUpdate[uint8_t attributeID];
     interface LocalTime<T62500hz> as LocalTime;
@@ -72,88 +75,84 @@ module CC2420TKN154P
     S_STOPPED,
     S_STOPPING,
     S_STARTING,
-
-    S_RADIO_OFF,
     S_ED,
+    S_RADIO_OFF,
 
     S_RESERVE_RX_SPI,
-    S_RX_PREPARED,
+    S_RX_PENDING,
     S_RECEIVING,
     S_OFF_PENDING,
 
-    S_LOAD_TXFIFO,
-    S_TX_LOADED,
-    S_TX_ACTIVE,
-    S_TX_CANCEL,
-    S_TX_DONE,
+    S_LOAD_TXFIFO_NO_CSMA,
+    S_LOAD_TXFIFO_UNSLOTTED,
+    S_LOAD_TXFIFO_SLOTTED,
+    S_TX_PENDING,
+    S_TX_BACKOFF_UNSLOTTED,
+    S_TX_BACKOFF_SLOTTED,
+    S_TX_ACTIVE_NO_CSMA,
+    S_TX_ACTIVE_UNSLOTTED_CSMA,
+    S_TX_ACTIVE_SLOTTED_CSMA,
   } m_state_t;
 
   norace m_state_t m_state = S_STOPPED;
-  norace ieee154_txframe_t *m_txdata;
-  norace error_t m_txError;
-  norace ieee154_reftime_t m_txReferenceTime;
+  norace ieee154_txframe_t *m_txframe;
+  norace error_t m_txResult;
   norace bool m_ackFramePending;
-  uint32_t m_edDuration;
+  norace uint16_t m_remainingBackoff;
+  norace bool m_resume;
+  norace ieee154_csma_t *m_csma;
   bool m_pibUpdated;
-  uint8_t m_numCCA;
-  ieee154_reftime_t *m_t0Tx;
-  uint32_t m_dtTx;
 
-  norace uint8_t m_txLockOnCCAFail;
-  norace bool m_rxAfterTx = FALSE;
-  norace bool m_stop = FALSE;
+  /* timing */
+  norace ieee154_timestamp_t *m_timestamp;
+  norace uint32_t m_dt;
+  norace union {
+    uint32_t regular;
+    ieee154_timestamp_t native;
+  } m_t0;
+
 
+  /* energy detection */
+  int8_t m_maxEnergy;
+  uint32_t m_edDuration;
+  uint32_t m_edStartTime;
+
+  /* task prototypes */
+  task void energyDetectionTask();
   task void startDoneTask();
   task void rxControlStopDoneTask();
-  task void stopTask();
+  task void configSyncTask();
 
+  /* function prototypes */
   uint8_t dBmToPA_LEVEL(int dbm);
   void txDoneRxControlStopped();
   void rxSpiReserved();
   void txSpiReserved();
-  void txDoneSpiReserved();
-  void signalTxDone();
-  void finishTx();
-  void stopContinue();
+  void sendDoneSpiReserved();
   void offSpiReserved();
   void offStopRxDone();
-  void continueTxPrepare();
-  
+  uint16_t getRandomBackoff(uint8_t BE);
+  void loadTxFrame(ieee154_txframe_t *frame);
+  void checkEnableRxForACK();
 
-  /******************************/
-  /* StdControl Operations      */
-  /******************************/
-
-  /****************************************/
-  /*     TelosB Pin connection (debug)    */
-  /*                                      */
-  /* R1 = P6.6 = ADC6, R2 = P6.7 = ADC7   */
-  /* S1 = P2.3 = GIO2, S2 = P2.6 = GIO3   */
-  /* R1 is at 6pin-expansion pin 1,       */               
-  /* R2 is at 6pin-expansion pin 2,       */               
-  /****************************************/
+  /* ----------------------- StdControl Operations ----------------------- */
 
   command error_t SplitControl.start()
   {
-    // debug
-    //P6SEL &= ~0xC0;     // debug PIN: 6.6, 6.7, set to I/O function
-    //P6DIR |= 0xC0;      // output
-    //P6OUT &= ~0xC0;     // low
-    
     atomic {
       if (m_state == S_RADIO_OFF)
         return EALREADY;
-      else {
-        if (m_state != S_STOPPED)
-          return FAIL;
-        m_state = S_STARTING;
-      }
+      else if (m_state != S_STOPPED)
+        return FAIL;
+      m_state = S_STARTING;
     }
-    return call SpiResource.request();
+    call SpiResource.request(); /* continue in startSpiReserved() */
+    return SUCCESS;
   }
 
-  void startReserved()
+  void startSpiReserved()
   {
+    /* we own the SPI bus */
     call CC2420Power.startVReg();
   }
 
@@ -164,8 +163,8 @@ module CC2420TKN154P
 
   async event void CC2420Power.startOscillatorDone() 
   {
-    // default configuration (addresses, etc) has been written
     call CC2420Power.rfOff();
+    call CC2420Power.flushRxFifo();
     call CC2420Tx.unlockChipSpi();
     post startDoneTask();
   }
@@ -181,7 +180,6 @@ module CC2420TKN154P
     call CC2420Config.setTxPower(dBmToPA_LEVEL(IEEE154_DEFAULT_TRANSMITPOWER_dBm));
     call CC2420Config.sync();
     call SpiResource.release();
-    m_stop = FALSE;
     m_state = S_RADIO_OFF;
     signal SplitControl.startDone(SUCCESS);
   }
@@ -191,53 +189,46 @@ module CC2420TKN154P
     atomic {
       if (m_state == S_STOPPED)
         return EALREADY;
+      else if (m_state != S_RADIO_OFF)
+        return FAIL;
+      m_state = S_STOPPING;
     }
-    post stopTask();
+    call SpiResource.request();
     return SUCCESS;
   }
 
-  task void stopTask()
+  void stopSpiReserved()
   {
-    atomic {
-      if (m_state == S_RADIO_OFF)
-        m_state = S_STOPPING;
-    }
-    if (m_state != S_STOPPING)
-      post stopTask(); // this will not happen, because the caller has switched radio off
-    else 
-      if (call RxControl.stop() == EALREADY)
-        stopContinue();
+    /* we own the SPI bus */
+    call CC2420Power.rfOff();
+    call CC2420Power.flushRxFifo();
+    call CC2420Power.stopOscillator(); 
+    call CC2420Power.stopVReg();
+    call CC2420Tx.unlockChipSpi();
+    call SpiResource.release();
+    m_state  = S_STOPPED;
+    signal SplitControl.stopDone(SUCCESS);
   }
 
-  void stopContinue()
-  {
-    call SpiResource.request();
-  }
+  /* ----------------------- Helpers / PIB Updates ----------------------- */
 
-  void stopReserved()
+  /* Returns a random number [0,(2^BE) - 1] (uniform distr.) */
+  /* multiplied by backoff period time (in symbols)          */
+  uint16_t getRandomBackoff(uint8_t BE)
   {
-    // we own the SPI bus
-    atomic {
-      call CC2420Power.rfOff();
-      call CC2420Tx.unlockChipSpi();
-      call TxControl.stop();
-      call CC2420Power.stopOscillator(); 
-      call CC2420Power.stopVReg();
-      call SpiResource.release();
-      m_state  = S_STOPPED;
-      signal SplitControl.stopDone(SUCCESS);
-    }
+    uint16_t res = call Random.rand16();
+    uint16_t mask = 0xFFFF;
+    mask <<= BE;
+    mask = ~mask;
+    res &= mask;
+    return (res * IEEE154_aUnitBackoffPeriod);
   }
 
-  /*********************************/
-  /*  PIB Updates                  */
-  /*********************************/
-  
-  // input: power in dBm, output: PA_LEVEL parameter for cc2420 TXCTRL register
+  /* input: power in dBm, output: PA_LEVEL setting for CC2420 TXCTRL register */
   uint8_t dBmToPA_LEVEL(int dBm)
   {
     uint8_t result;
-    // the cc2420 has 8 discrete (documented) values - we take the closest
+    /* the cc2420 has 8 discrete (documented) values */
     if (dBm >= 0)
       result = 31;
     else if (dBm > -2)
@@ -275,16 +266,32 @@ module CC2420TKN154P
         call CC2420Config.setPanCoordinator(*((ieee154_macPanCoordinator_t*) PIBAttributeValue));
         break;
       case IEEE154_phyTransmitPower:
-        // lower 6 bits are twos-complement in dBm (range -32..+31 dBm)
+        /* lower 6 bits are twos-complement in dBm (range -32 to +31 dBm) */
         txpower = (*((ieee154_phyTransmitPower_t*) PIBAttributeValue)) & 0x3F;
         if (txpower & 0x20)
-          txpower |= 0xC0; // make it negative, to be interpreted as int8_t
+          txpower |= 0xC0; /* make it negative, to be interpreted as int8_t */
         call CC2420Config.setTxPower(dBmToPA_LEVEL((int8_t) txpower));
         break;
       case IEEE154_phyCCAMode:
         call CC2420Config.setCCAMode(*((ieee154_phyCCAMode_t*) PIBAttributeValue));
         break;
     }
+    if (m_state == S_RECEIVING || m_state == S_RX_PENDING)
+      post configSyncTask();
+  }
+
+  task void configSyncTask()
+  {
+    if (call SpiResource.immediateRequest() == SUCCESS) {
+      call CC2420Config.sync(); 
+      if (m_state == S_RECEIVING) {
+        // need to toggle radio state to make changes effective now
+        call CC2420Power.rfOff();
+        call CC2420Power.rxOn();
+      }
+      call SpiResource.release();
+    } else
+      post configSyncTask(); // spin (should be short time, until packet is received)
   }
 
   command void RadioPromiscuousMode.set( bool val )
@@ -292,67 +299,66 @@ module CC2420TKN154P
     call CC2420Config.setPromiscuousMode(val);
   }
 
-  /*********************************/
-  /* Energy Detection              */
-  /*********************************/
+  /* ----------------------- Energy Detection ----------------------- */
 
   command error_t EnergyDetection.start(uint32_t duration)
   {
-    error_t status = FAIL;
     atomic {
-      if (m_state == S_RADIO_OFF){
-        m_state = S_ED;
-        m_edDuration = duration;
-        status = SUCCESS;
-      }
+      if (m_state == S_ED)
+        return EALREADY;
+      else if (m_state != S_RADIO_OFF)
+        return FAIL;
+      m_state = S_ED;
     }
-    if (status == SUCCESS)
-      call SpiResource.request(); // we will not give up the SPI until we're done
-    return status;
+    m_edDuration = duration;
+    m_maxEnergy = -128 + 45; /* initialization (45 will be substracted below) */
+    call SpiResource.request();
+    return SUCCESS;
   }
 
   void edReserved()
   {
-    int8_t value, maxEnergy = -128;
-    uint32_t start = call LocalTime.get();
-    call CC2420Config.sync(); // put PIB changes into operation (if any)
+    call CC2420Config.sync(); /* put PIB changes into operation (if any) */
     call CC2420Power.rxOn();
-    // reading an RSSI value over SPI will usually almost
-    // take as much time as 8 symbols, i.e. there's 
-    // no point using an Alarm here (but maybe a BusyWait?)
-    while (!call TimeCalc.hasExpired(start, m_edDuration)){
-      if (call CC2420Power.rssi(&value) != SUCCESS)
-        continue;
-      if (value > maxEnergy)
-        maxEnergy = value;
-    }
-    // P = RSSI_VAL + RSSI_OFFSET [dBm] 
-    // RSSI_OFFSET is approximately -45.
-    if (maxEnergy > -128)
-      maxEnergy -= 45; 
-    call CC2420Power.rfOff();
-    m_state = S_RADIO_OFF;
-    call SpiResource.release();
-    signal EnergyDetection.done(SUCCESS, maxEnergy);
+    m_edStartTime = call LocalTime.get();
+    post energyDetectionTask();
   }
 
-  /****************************************/
-  /*     Transceiver Off                  */
-  /****************************************/
+  task void energyDetectionTask()
+  {
+    int8_t value;
+    if (call CC2420Power.rssi(&value) == SUCCESS)
+      if (value > m_maxEnergy)
+        m_maxEnergy = value;
+
+    if (call TimeCalc.hasExpired(m_edStartTime, m_edDuration)) {
+      /* P = RSSI_VAL + RSSI_OFFSET [dBm]  */
+      /* RSSI_OFFSET is approximately -45. */
+      m_maxEnergy -= 45; 
+      call CC2420Power.rfOff();
+      call CC2420Power.flushRxFifo();
+      call SpiResource.release();
+      m_state = S_RADIO_OFF;
+      signal EnergyDetection.done(SUCCESS, m_maxEnergy);
+    } else
+      post energyDetectionTask();
+  }
+
+  /* ----------------------- RadioOff ----------------------- */
 
   async command error_t RadioOff.off()
   {
+    error_t result;
     atomic {
       if (m_state == S_RADIO_OFF)
         return EALREADY;
-      else if (m_state != S_RECEIVING && m_state != S_TX_LOADED && m_state != S_RX_PREPARED)
+      else if (m_state != S_RECEIVING)
         return FAIL;
       m_state = S_OFF_PENDING;
     }
-    call SpiResource.release(); // may fail
-    if (call RxControl.stop() == EALREADY) // will trigger offStopRxDone()
-      offStopRxDone();
-    return SUCCESS;
+    result = call RxControl.stop();
+    ASSERT(result == SUCCESS);
+    return result;
   }
   
   void offStopRxDone()
@@ -360,14 +366,14 @@ module CC2420TKN154P
     if (call SpiResource.immediateRequest() == SUCCESS)
       offSpiReserved();
     else
-      call SpiResource.request();  // will trigger offSpiReserved()
+      call SpiResource.request();  /* will continue in offSpiReserved() */
   }
 
   void offSpiReserved()
   {
     call TxControl.stop();
     call CC2420Power.rfOff();
-    call CC2420Config.sync(); // put any PIB updates into operation
+    call CC2420Power.flushRxFifo();
     call CC2420Tx.unlockChipSpi();
     call SpiResource.release();
     m_state = S_RADIO_OFF;
@@ -379,331 +385,532 @@ module CC2420TKN154P
     return m_state == S_RADIO_OFF;
   }
 
-  /****************************************/
-  /*     Receive Operations               */
-  /****************************************/
+  /* ----------------------- RadioRx ----------------------- */
 
-  async command error_t RadioRx.prepare()
+  async command error_t RadioRx.enableRx(uint32_t t0, uint32_t dt)
   {
+    error_t result;
     atomic {
-      if (call RadioRx.isPrepared())
-        return EALREADY;
-      else if (m_state != S_RADIO_OFF)
+      if (m_state != S_RADIO_OFF)
         return FAIL;
       m_state = S_RESERVE_RX_SPI;
     }
-    if (call RxControl.start() != SUCCESS){  // will trigger rxStartRxDone()
-      m_state = S_RADIO_OFF;
-      call Leds.led0On();
-      return FAIL; 
-    }
-    return SUCCESS; 
-  }
-
-  void rxStartRxDone()
-  {
-    if (call SpiResource.immediateRequest() == SUCCESS)   // will trigger rxSpiReserved()
-      rxSpiReserved();
-    else
-      call SpiResource.request();
+    m_t0.regular = t0;
+    m_dt = dt;
+    result = call RxControl.start(); 
+    ASSERT(result == SUCCESS);
+    if (result == SUCCESS)
+      if (call SpiResource.immediateRequest() == SUCCESS)
+        rxSpiReserved();
+      else
+        call SpiResource.request();   /* will continue in rxSpiReserved()  */
+    return result; 
   }
 
   void rxSpiReserved()
   {
-    call CC2420Config.sync(); // put PIB changes into operation
-    call TxControl.start();   // for timestamping
-    m_state = S_RX_PREPARED;
-    signal RadioRx.prepareDone(); // keep owning the SPI
-  }
-
-  async command bool RadioRx.isPrepared()
-  { 
-    return m_state == S_RX_PREPARED;
-  }
-
-  async command error_t RadioRx.receive(ieee154_reftime_t *t0, uint32_t dt)
-  {
+    m_state = S_RX_PENDING;
+    call CC2420Config.sync(); /* put any pending PIB changes into operation      */
+    call TxControl.stop();    /* reset Tx logic for timestamping (SFD interrupt) */
+    call TxControl.start();   
     atomic {
-      if (m_state != S_RX_PREPARED){
-        call Leds.led0On();
-        return FAIL;
-      }
-      if (t0 != NULL && dt)
-        call ReliableWait.waitRx(t0, dt);
-      else
+      if (call TimeCalc.hasExpired(m_t0.regular, m_dt))
         signal ReliableWait.waitRxDone();
+      else
+        call ReliableWait.waitRx(m_t0.regular, m_dt); /* will signal waitRxDone() just in time */
     }
-    return SUCCESS;
   }
 
   async event void ReliableWait.waitRxDone()
   {
+    error_t result;
     atomic {
-      if (call CC2420Power.rxOn() != SUCCESS)
-        call Leds.led0On();
       m_state = S_RECEIVING;
+      result = call CC2420Power.rxOn(); 
     }
+    ASSERT(result == SUCCESS);
     call CC2420Tx.lockChipSpi();
-    call SpiResource.release();    
+    call SpiResource.release();
+    signal RadioRx.enableRxDone();
   }
 
-  event message_t* CC2420Rx.received(message_t *data, ieee154_reftime_t *timestamp) 
+  event message_t* CC2420Rx.received(message_t *frame, ieee154_timestamp_t *timestamp) 
   {
     if (m_state == S_RECEIVING)
-      return signal RadioRx.received(data, timestamp);
+      return signal RadioRx.received(frame, timestamp);
     else
-      return data;
+      return frame;
   }
 
   async command bool RadioRx.isReceiving()
-  { 
+  {
     return m_state == S_RECEIVING;
   }
 
-  /******************************/
-  /*     Transmit Operations    */
-  /******************************/
+  /* ----------------------- RadioTx ----------------------- */
 
-  async command error_t RadioTx.load(ieee154_txframe_t *frame)
+  async command error_t RadioTx.transmit( ieee154_txframe_t *frame, const ieee154_timestamp_t *t0, uint32_t dt )
   {
-    bool startRxControl;
+    if( frame == NULL || frame->header == NULL || 
+        frame->payload == NULL || frame->metadata == NULL || 
+        (frame->headerLen + frame->payloadLen + 2) > IEEE154_aMaxPHYPacketSize )
+      return EINVAL;
+
     atomic {
-      if (m_state != S_RADIO_OFF && m_state != S_TX_LOADED)
+      if( m_state != S_RADIO_OFF )
         return FAIL;
-      startRxControl = (m_state == S_RADIO_OFF);
-      m_txdata = frame;
-      m_state = S_LOAD_TXFIFO;
+      m_state = S_LOAD_TXFIFO_NO_CSMA;
+    }
+    m_txframe = frame;
+    if( t0 == NULL )
+      m_dt = 0;
+    else {
+      memcpy( &m_t0.native, t0, sizeof(ieee154_timestamp_t) );
+      m_dt = dt;
     }
-    if (!startRxControl)
-      continueTxPrepare();
-    else if (call RxControl.start() != SUCCESS) // will trigger continueTxPrepare()
-      call Leds.led0On();
+    loadTxFrame(frame); /* will continue in loadDoneRadioTx() */
     return SUCCESS;
   }
 
-  void continueTxPrepare()
+  void loadDoneRadioTx()
   {
-    if (call SpiResource.immediateRequest() == SUCCESS) 
-      txSpiReserved();
-    else
-      call SpiResource.request(); // will trigger txSpiReserved()
+    /* frame was loaded into TXFIFO */
+    atomic {
+      m_state = S_TX_PENDING;
+      if (m_dt == 0)
+        signal ReliableWait.waitTxDone();
+      else
+        call ReliableWait.waitTx(&m_t0.native, m_dt); /* will signal waitTxDone() just in time */
+    }
   }
 
-  void txSpiReserved()
+  async event void ReliableWait.waitTxDone()
   {
-    call CC2420Config.sync();
-    call TxControl.start();
-    if (call CC2420Tx.loadTXFIFO(m_txdata) != SUCCESS)
-      call Leds.led0On();
+    error_t result;
+    ASSERT(m_state == S_TX_PENDING);
+    atomic {
+      m_state = S_TX_ACTIVE_NO_CSMA;
+      result = call CC2420Tx.send(FALSE); /* transmit without CCA, this must succeed */ 
+      checkEnableRxForACK();
+    }
+    ASSERT(result == SUCCESS); 
   }
 
-  async event void CC2420Tx.loadTXFIFODone(ieee154_txframe_t *data, error_t error)
+  inline void txDoneRadioTx(ieee154_txframe_t *frame, ieee154_timestamp_t *timestamp, error_t result)
+  {
+    /* transmission completed */
+    signal RadioTx.transmitDone(frame, timestamp, result);
+  }
+
+  /* ----------------------- UnslottedCsmaCa ----------------------- */
+
+  async command error_t UnslottedCsmaCa.transmit(ieee154_txframe_t *frame, ieee154_csma_t *csma)
   {
-    if (m_state != S_LOAD_TXFIFO || error != SUCCESS)
-      call Leds.led0On();
-    m_state = S_TX_LOADED;
-    signal RadioTx.loadDone();  // we keep owning the SPI
+    if( frame == NULL || frame->header == NULL || 
+        frame->payload == NULL || frame->metadata == NULL || 
+        (frame->headerLen + frame->payloadLen + 2) > IEEE154_aMaxPHYPacketSize )
+      return EINVAL;
+    atomic {
+      if( m_state != S_RADIO_OFF )
+        return FAIL;
+      m_state = S_LOAD_TXFIFO_UNSLOTTED;
+    }
+    m_txframe = frame;
+    m_csma = csma;
+    loadTxFrame(frame); /* will continue in nextIterationUnslottedCsma()  */
+    return SUCCESS;
   }
 
-  async command ieee154_txframe_t* RadioTx.getLoadedFrame()
+  void nextIterationUnslottedCsma()
   {
-    if (m_state == S_TX_LOADED)
-     return m_txdata;
-    else 
-      return NULL;
+    /* wait for a random time of [0,(2^BE) - 1] backoff slots */
+    uint16_t backoff = getRandomBackoff(m_csma->BE); 
+    m_state = S_TX_BACKOFF_UNSLOTTED;
+    call ReliableWait.waitBackoff(backoff);  /* will continue in waitBackoffDoneUnslottedCsma()  */
   }
 
-  async command error_t RadioTx.transmit(ieee154_reftime_t *t0, uint32_t dt, uint8_t numCCA, bool ackRequest)
+  void waitBackoffDoneUnslottedCsma()
   {
+    /* backoff finished, try to transmit now */
+    int8_t dummy;
+    ieee154_txframe_t *frame = NULL;
+    ieee154_csma_t *csma = NULL;
+
     atomic {
-      if (m_state != S_TX_LOADED)
-        return FAIL;
-      m_numCCA = numCCA;
-      m_t0Tx = t0;
-      m_dtTx = dt;
-      if (numCCA){
-        // for CCA we need to be in Rx mode
-        call CC2420Power.rxOn();
-        call ReliableWait.busyWait(20); // turnaround + CCA valid time
-        if (numCCA == 2){
-          // first CCA is done in software (8 symbols after backoff boundary)
-          if (t0 != NULL){
-            call ReliableWait.waitCCA(t0, dt-IEEE154_aUnitBackoffPeriod-12);
-            return SUCCESS;
-          }
+      /* The CC2420 needs to be in an Rx mode for STXONCCA strobe */
+      /* Note: the receive logic of the CC2420 driver is not yet  */
+      /* started, i.e. we cannot (yet) receive any packets        */
+      call CC2420Power.rxOn();
+      m_state = S_TX_ACTIVE_UNSLOTTED_CSMA;
+
+      /* wait for CC2420 Rx to calibrate + CCA valid time */
+      while (call CC2420Power.rssi(&dummy) != SUCCESS)
+        ;
+
+      /* transmit with a single CCA done in hardware (STXONCCA strobe) */
+      if (call CC2420Tx.send(TRUE) == SUCCESS) {
+        /* frame is being sent now, do we need Rx logic ready for an ACK? */
+        checkEnableRxForACK();
+      } else {
+        /* channel is busy */
+        call CC2420Power.rfOff();
+        /* we might have accidentally caught something during CCA, flush it out */
+        call CC2420Power.flushRxFifo(); 
+        m_csma->NB += 1;
+        if (m_csma->NB > m_csma->macMaxCsmaBackoffs) {
+          /* CSMA-CA failure, we're done. The MAC may decide to retransmit. */
+          frame = m_txframe;
+          csma = m_csma;
+          /* continue below */
+        } else {
+          /* Retry -> next iteration of the unslotted CSMA-CA */
+          m_csma->BE += 1;
+          if (m_csma->BE > m_csma->macMaxBE)
+            m_csma->BE = m_csma->macMaxBE;
+          nextIterationUnslottedCsma();
         }
       }
-      signal ReliableWait.waitCCADone();
     }
+    if (frame != NULL) {
+      call CC2420Tx.unlockChipSpi();
+      call TxControl.stop();
+      call SpiResource.release();
+      m_state = S_RADIO_OFF;
+      signal UnslottedCsmaCa.transmitDone(frame, csma, FALSE, FAIL);
+    }
+  }
+
+  inline void txDoneUnslottedCsma(ieee154_txframe_t *frame, ieee154_csma_t *csma, bool ackPendingFlag, error_t result)
+  {
+    /* transmission completed */
+    signal UnslottedCsmaCa.transmitDone(frame, csma, ackPendingFlag, result);
+  }
+
+  /* ----------------------- SlottedCsmaCa ----------------------- */
+
+    /* The slotted CSMA-CA requires very exact timing, because transmissions
+     * must start on 320 us backoff boundaries. Because it is accessed over SPI
+     * the CC2420 is not good at meeting these timing requirements, so consider 
+     * the "SlottedCsmaCa"-code below as experimental. */
+
+  async command error_t SlottedCsmaCa.transmit(ieee154_txframe_t *frame, ieee154_csma_t *csma,
+      const ieee154_timestamp_t *slot0Time, uint32_t dtMax, bool resume, uint16_t remainingBackoff)
+  {
+    if( frame == NULL || frame->header == NULL || slot0Time == NULL ||
+        frame->payload == NULL || frame->metadata == NULL || 
+        (frame->headerLen + frame->payloadLen + 2) > IEEE154_aMaxPHYPacketSize)
+      return EINVAL;
+    atomic {
+      if( m_state != S_RADIO_OFF )
+        return FAIL;
+      m_state = S_LOAD_TXFIFO_SLOTTED;
+    }
+    m_txframe = frame;
+    m_csma = csma;
+    memcpy( &m_t0.native, slot0Time, sizeof(ieee154_timestamp_t) );
+    m_dt = dtMax;
+    m_resume = resume;
+    m_remainingBackoff = remainingBackoff;
+    loadTxFrame(frame); /* will continue in nextIterationSlottedCsma()  */
     return SUCCESS;
   }
 
-  async event void ReliableWait.waitCCADone()
-  {
-    bool cca = call CC2420Tx.cca();
-    if (m_numCCA == 2 && !cca){
-      // channel is busy
-      ieee154_reftime_t now;
-      call ReferenceTime.getNow(&now, IEEE154_aUnitBackoffPeriod+12);
-      memcpy(&m_txReferenceTime, &now, sizeof(ieee154_reftime_t));
-      m_ackFramePending = FALSE;
-      m_txError = EBUSY;
-      signalTxDone();
-      return;
-    } else {
-      // the second CCA (or first CCA if there's only one) is done in hardware...
-      uint16_t offset = 0;
-      if (m_numCCA)
-        offset = 12;
-      if (m_t0Tx)
-        call ReliableWait.waitTx(m_t0Tx, m_dtTx-offset);
-      else
-        signal ReliableWait.waitTxDone();
+  void nextIterationSlottedCsma()
+  {
+    uint32_t dtTxTarget;
+    uint16_t backoff;
+    ieee154_txframe_t *frame = NULL;
+    ieee154_csma_t *csma = NULL;
+
+    atomic {
+      if (m_resume) {
+        backoff = m_remainingBackoff;
+        m_resume = FALSE;
+      } else
+        backoff = getRandomBackoff(m_csma->BE);
+      dtTxTarget = call TimeCalc.timeElapsed(call ReferenceTime.toLocalTime(&m_t0.native), call LocalTime.get());
+      dtTxTarget += backoff;
+      if (dtTxTarget > m_dt) {
+        /* frame doesn't fit into remaining CAP */
+        uint32_t overlap = dtTxTarget - m_dt;
+        overlap = overlap + (IEEE154_aUnitBackoffPeriod - (overlap % IEEE154_aUnitBackoffPeriod));
+        backoff = overlap;
+        frame = m_txframe;
+        csma = m_csma;
+      } else {
+        /* backoff now */
+        m_state = S_TX_BACKOFF_SLOTTED;
+        call ReliableWait.waitBackoff(backoff);  /* will continue in waitBackoffDoneSlottedCsma()  */
+      }
+    }
+    if (frame != NULL) { /* frame didn't fit in the remaining CAP */
+      call CC2420Tx.unlockChipSpi();
+      call TxControl.stop();
+      call SpiResource.release();
+      m_state = S_RADIO_OFF;
+      signal SlottedCsmaCa.transmitDone(frame, csma, FALSE, backoff, ERETRY);
     }
   }
 
-  async event void ReliableWait.waitTxDone()
+  void waitBackoffDoneSlottedCsma()
   {
-    m_state = S_TX_ACTIVE;
-    call CC2420Tx.send(m_numCCA>0); // go (with or without CCA) !
+    int8_t dummy;
+    bool ccaFailure = FALSE;
+    error_t result = FAIL;
+    ieee154_txframe_t *frame = NULL;
+    ieee154_csma_t *csma = NULL;
+
+    atomic {
+      /* The CC2420 needs to be in an Rx mode for STXONCCA strobe */
+      /* Note: the receive logic of the CC2420 driver is not yet  */
+      /* started, i.e. we cannot (yet) receive any packets        */
+      call CC2420Power.rxOn();
+      m_state = S_TX_ACTIVE_SLOTTED_CSMA;
+
+      /* wait for CC2420 Rx to calibrate + CCA valid time */
+      while (call CC2420Power.rssi(&dummy) != SUCCESS)
+        ;
+
+      /* perform CCA on slot boundary (i.e. 8 symbols after backoff bounday);    */
+      /* this platform-specific command is supposed to return just in time, so   */
+      /* that the frame will be transmitted exactly on the next backoff boundary */
+      if (call ReliableWait.ccaOnBackoffBoundary(&m_t0.native)) {
+        /* first CCA succeeded */
+        if (call CC2420Tx.send(TRUE) == SUCCESS) {
+          /* frame is being sent now, do we need Rx logic ready for an ACK? */
+          checkEnableRxForACK();
+          return;
+        } else
+          ccaFailure = TRUE; /* second CCA failed */
+      } else
+        ccaFailure = TRUE; /* first CCA failed */
+
+      /* did not transmit the frame */
+      call CC2420Power.rfOff();
+      call CC2420Power.flushRxFifo(); /* we might have (accidentally) caught something */
+      m_state = S_LOAD_TXFIFO_SLOTTED;
+      if (ccaFailure) {
+        m_csma->NB += 1;
+        if (m_csma->NB > m_csma->macMaxCsmaBackoffs) {
+          /* CSMA-CA failure, we're done. The MAC may decide to retransmit. */
+          frame = m_txframe;
+          csma = m_csma;
+          result = FAIL;
+        } else {
+          /* next iteration of slotted CSMA-CA */
+          m_csma->BE += 1;
+          if (m_csma->BE > m_csma->macMaxBE)
+            m_csma->BE = m_csma->macMaxBE;
+          nextIterationSlottedCsma();
+        }
+      } else {
+        /* frame didn't fit into remaining CAP, this can only happen */
+        /* if the runtime overhead was too high. this should actually not happen.  */
+        /* (in principle the frame should have fitted, because we checked before) */
+        frame = m_txframe;
+        csma = m_csma;
+        result = ERETRY;
+      }
+    }
+    if (frame != NULL) {
+      call CC2420Tx.unlockChipSpi();
+      call TxControl.stop();
+      call SpiResource.release();
+      m_state = S_RADIO_OFF;
+      signal SlottedCsmaCa.transmitDone(frame, csma, FALSE, 0, result);
+    }
   }
 
-  async event void CC2420Tx.transmissionStarted( ieee154_txframe_t *data )
+  inline void txDoneSlottedCsmaCa(ieee154_txframe_t *frame, ieee154_csma_t *csma, 
+      bool ackPendingFlag, uint16_t remainingBackoff, error_t result)
   {
-    uint8_t frameType = data->header->mhr[0] & FC1_FRAMETYPE_MASK;
-    uint8_t token = data->headerLen;
-    signal Timestamp.transmissionStarted(frameType, data->handle, data->payload, token);
+    /* transmission completed */
+    signal SlottedCsmaCa.transmitDone(frame, csma, ackPendingFlag, remainingBackoff, result);
   }
 
-  async event void CC2420Tx.transmittedSFD(uint32_t time, ieee154_txframe_t *data)
+  /* ----------------------- Common Tx Operations ----------------------- */
+
+  void loadTxFrame(ieee154_txframe_t *frame)
   {
-    uint8_t frameType = data->header->mhr[0] & FC1_FRAMETYPE_MASK;
-    uint8_t token = data->headerLen;
-    signal Timestamp.transmittedSFD(time, frameType, data->handle, data->payload, token);
-    // ATTENTION: here we release the SPI, so we can receive a possible ACK
-    call SpiResource.release();
+    if (call SpiResource.isOwner() || call SpiResource.immediateRequest() == SUCCESS) 
+      txSpiReserved();
+    else
+      call SpiResource.request(); /* will continue in txSpiReserved() */
+  }
+
+  void txSpiReserved()
+  {
+    error_t result;
+    call CC2420Config.sync();
+    call TxControl.start();
+    result = call CC2420Tx.loadTXFIFO(m_txframe);
+    ASSERT(result == SUCCESS);
+  }
+
+  async event void CC2420Tx.loadTXFIFODone(ieee154_txframe_t *data, error_t error)
+  {
+    atomic {
+      switch (m_state)
+      {
+        case S_LOAD_TXFIFO_NO_CSMA: loadDoneRadioTx(); break;
+        case S_LOAD_TXFIFO_UNSLOTTED: nextIterationUnslottedCsma(); break;
+        case S_LOAD_TXFIFO_SLOTTED: nextIterationSlottedCsma(); break;
+        default: ASSERT(0); break;
+      }
+    }
   }
 
-  async command void Timestamp.modifyMACPayload(uint8_t token, uint8_t offset, uint8_t* buf, uint8_t len )
+  void checkEnableRxForACK()
   {
-    if (m_state == S_TX_ACTIVE)
-      call CC2420Tx.modify(offset+1+token, buf, len);
+    /* A frame is currently being transmitted, check if we  */
+    /* need the Rx logic ready for the ACK                  */
+    bool ackRequest = (m_txframe->header->mhr[MHR_INDEX_FC1] & FC1_ACK_REQUEST) ? TRUE : FALSE;
+    error_t result = SUCCESS;
+
+    if (ackRequest) {
+      /* release SpiResource and start Rx logic, so the latter  */
+      /* can take over after Tx is finished to receive the ACK */
+      call SpiResource.release();
+      result = call RxControl.start();
+    }
+    ASSERT(result == SUCCESS);
   }
 
-  async event void CC2420Tx.sendDone(ieee154_txframe_t *frame, ieee154_reftime_t *referenceTime, 
-      bool ackPendingFlag, error_t error)
+  async event void CC2420Tx.sendDone(ieee154_txframe_t *frame, 
+      ieee154_timestamp_t *timestamp, bool ackPendingFlag, error_t result)
   {
-    memcpy(&m_txReferenceTime, referenceTime, sizeof(ieee154_reftime_t));
+    m_timestamp = timestamp;
     m_ackFramePending = ackPendingFlag;
-    m_txError = error;
-    if (error == EBUSY) // CCA failure, i.e. didn't transmit
-      signalTxDone();
-    else 
-      // reset radio
-      if (call RxControl.stop() != SUCCESS) // will trigger txDoneRxControlStopped()
-        call Leds.led0On();
+    m_txResult = result;
+    if (!call SpiResource.isOwner()) {
+      /* this means an ACK was requested and during the transmission */
+      /* we released the Spi to allow the Rx part to take over */
+      ASSERT((frame->header->mhr[MHR_INDEX_FC1] & FC1_ACK_REQUEST));
+      result = call RxControl.stop();
+      ASSERT(result == SUCCESS); /* will continue in txDoneRxControlStopped() */
+    } else
+      sendDoneSpiReserved();
   }
 
   void txDoneRxControlStopped()
   {
-    // get SPI to switch radio off
+    /* get the Spi to switch radio off */
     if (call SpiResource.isOwner() || call SpiResource.immediateRequest() == SUCCESS) 
-      txDoneSpiReserved();
+      sendDoneSpiReserved();
     else
-      call SpiResource.request(); // will trigger txDoneSpiReserved()
+      call SpiResource.request(); /* will continue in sendDoneSpiReserved() */
   }
 
-  void txDoneSpiReserved() 
-  { 
-    // switch radio off
-    call CC2420Power.rfOff(); 
+  void sendDoneSpiReserved()
+  {
+    /* transmission completed, we're owning the Spi, Rx logic is disabled */
+    m_state_t state = m_state;
+    ieee154_txframe_t *frame = m_txframe;
+    ieee154_csma_t *csma = m_csma;
+
+    call CC2420Power.rfOff();
+    call CC2420Power.flushRxFifo();
+    call CC2420Tx.unlockChipSpi();
     call TxControl.stop();
-    call SpiResource.release(); // for RxControl.start to succeed
-    if (m_txError == SUCCESS)
-      signalTxDone();
-    else {
-      call TxControl.start();
-      call RxControl.start(); // will trigger txDoneRxControlStarted()
-    }
+    call SpiResource.release();
+    m_state = S_RADIO_OFF;
+
+    if (state == S_TX_ACTIVE_NO_CSMA)
+      txDoneRadioTx(frame, m_timestamp, m_txResult); 
+    else if (state == S_TX_ACTIVE_UNSLOTTED_CSMA)
+      txDoneUnslottedCsma(frame, csma, m_ackFramePending, m_txResult);
+    else if (state == S_TX_ACTIVE_SLOTTED_CSMA)
+      txDoneSlottedCsmaCa(frame, csma, m_ackFramePending, m_remainingBackoff, m_txResult);
+    else
+      ASSERT(0);
   }
 
-  void txDoneRxControlStarted()
+  async event void CC2420Tx.transmissionStarted( ieee154_txframe_t *frame )
   {
-    m_state = S_TX_DONE;
-    call SpiResource.request(); // will trigger signalTxDone()
+    uint8_t frameType = frame->header->mhr[0] & FC1_FRAMETYPE_MASK;
+    uint8_t token = frame->headerLen;
+    signal Timestamp.transmissionStarted(frameType, frame->handle, frame->payload, token);
   }
 
-  void signalTxDone() 
-  { 
-    // radio is off, Rx component is started, radio is loaded, we own the SPI
-    if (m_txError == SUCCESS)
-      m_state = S_RADIO_OFF;
-    else
-      m_state = S_TX_LOADED;
-    signal RadioTx.transmitDone(m_txdata, &m_txReferenceTime, m_ackFramePending, m_txError);
+  async event void CC2420Tx.transmittedSFD( uint32_t time, ieee154_txframe_t *frame )
+  {
+    uint8_t frameType = frame->header->mhr[0] & FC1_FRAMETYPE_MASK;
+    uint8_t token = frame->headerLen;
+    signal Timestamp.transmittedSFD( time, frameType, frame->handle, frame->payload, token );
   }
 
-  /*************/
-  /* RxControl */
-  /*************/
-
-  async event void RxControl.stopDone(error_t error)
+  async command void Timestamp.modifyMACPayload( uint8_t token, uint8_t offset, uint8_t* buf, uint8_t len )
   {
-    post rxControlStopDoneTask();
+    if (m_state == S_TX_ACTIVE_NO_CSMA || 
+        m_state == S_TX_ACTIVE_SLOTTED_CSMA ||
+        m_state == S_LOAD_TXFIFO_UNSLOTTED )
+      call CC2420Tx.modify( offset+1+token, buf, len );
   }
 
-  task void rxControlStopDoneTask()
+  async event void ReliableWait.waitBackoffDone()
   {
-    if (m_stop && m_state != S_STOPPING)
-      return;
     switch (m_state)
     {
-      case S_OFF_PENDING: offStopRxDone(); break;
-      case S_RX_PREPARED: rxStartRxDone(); break;
-      case S_TX_ACTIVE: txDoneRxControlStopped(); break;
-      case S_STOPPING: stopContinue(); break;            
-      default: // huh ?
-           call Leds.led0On(); break;
+      case S_TX_BACKOFF_SLOTTED: waitBackoffDoneSlottedCsma(); break;
+      case S_TX_BACKOFF_UNSLOTTED: waitBackoffDoneUnslottedCsma(); break;
+      default: ASSERT(0); break;
     }
   }
 
-  async event void RxControl.startDone(error_t error)
+  /* ----------------------- RxControl ----------------------- */
+
+  async event void RxControl.stopDone(error_t error)
+  {
+    post rxControlStopDoneTask();
+  }
+
+  task void rxControlStopDoneTask()
   {
     switch (m_state)
     {
-      case S_RESERVE_RX_SPI: rxStartRxDone(); break;
-      case S_LOAD_TXFIFO: continueTxPrepare(); break;
-      case S_TX_ACTIVE: txDoneRxControlStarted(); break;
-      default: // huh ?
-           call Leds.led0On(); break;
+      case S_OFF_PENDING:              offStopRxDone(); break;
+      case S_TX_ACTIVE_NO_CSMA:        /* fall through */
+      case S_TX_ACTIVE_UNSLOTTED_CSMA: /* fall through */
+      case S_TX_ACTIVE_SLOTTED_CSMA:   txDoneRxControlStopped(); break;
+      default:                         ASSERT(0); break;
     }
   }
 
-  /***********************/
-  /* SPI Bus Arbitration */
-  /***********************/
+  /* ----------------------- SPI Bus Arbitration ----------------------- */
 
   event void SpiResource.granted() 
   {
     switch (m_state)
     {
-      case S_STARTING: startReserved(); break;
-      case S_ED: edReserved(); break;
-      case S_RESERVE_RX_SPI: rxSpiReserved(); break;
-      case S_LOAD_TXFIFO: txSpiReserved(); break;
-      case S_TX_ACTIVE: txDoneSpiReserved(); break;
-      case S_STOPPING: stopReserved(); break;
-      case S_TX_DONE: signalTxDone(); break;
-      case S_OFF_PENDING: offSpiReserved(); break;
-      default: // huh ?
-           call Leds.led0On(); break;
+      case S_STARTING:                 startSpiReserved(); break;
+      case S_ED:                       edReserved(); break;
+      case S_RESERVE_RX_SPI:           rxSpiReserved(); break;
+      case S_LOAD_TXFIFO_NO_CSMA:      /* fall through */
+      case S_LOAD_TXFIFO_UNSLOTTED:    /* fall through */
+      case S_LOAD_TXFIFO_SLOTTED:      txSpiReserved(); break;
+      case S_TX_ACTIVE_NO_CSMA:        /* fall through */
+      case S_TX_ACTIVE_UNSLOTTED_CSMA: /* fall through */
+      case S_TX_ACTIVE_SLOTTED_CSMA:   sendDoneSpiReserved(); break;
+      case S_STOPPING:                 stopSpiReserved(); break;
+      case S_OFF_PENDING:              offSpiReserved(); break;
+      default:                         ASSERT(0); break;
     }
   }
 
+  async command bool CCA.getNow()
+  {
+    return call CC2420Tx.cca();
+  }
+
+  default event void SplitControl.startDone(error_t error) {}
+  default event void SplitControl.stopDone(error_t error) {}
+  
+  default async event void UnslottedCsmaCa.transmitDone(ieee154_txframe_t *frame, 
+      ieee154_csma_t *csma, bool ackPendingFlag, error_t result) {}
+  default async event void SlottedCsmaCa.transmitDone(ieee154_txframe_t *frame, ieee154_csma_t *csma, 
+      bool ackPendingFlag,  uint16_t remainingBackoff, error_t result) {}
 
-  default event void SplitControl.startDone(error_t error){}
-  default event void SplitControl.stopDone(error_t error){}
-  default async event void Timestamp.transmissionStarted(uint8_t frameType, uint8_t msduHandle, uint8_t *msdu, uint8_t token){}
-  default async event void Timestamp.transmittedSFD(uint32_t time, uint8_t frameType, uint8_t msduHandle, uint8_t *msdu, uint8_t token){}
+  default async event void Timestamp.transmissionStarted(uint8_t frameType, uint8_t msduHandle, uint8_t *msdu, uint8_t token) {}
+  default async event void Timestamp.transmittedSFD(uint32_t time, uint8_t frameType, uint8_t msduHandle, uint8_t *msdu, uint8_t token) {}
 }
 
index d746c854098e781a7849e1e647be7672e588ff94..4e4c955437f39e60a400e08cc6fc93e850071164 100644 (file)
  * @author David Moss
  * @author Jung Il Choi Initial SACK implementation
  * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ *
+ * IMPORTANT: this module does not use the SPI Resource interface,
+ * instead the caller must take care of the resource arbitration
+ * (i.e. the caller must own the resource before calling commands
+ * like CC2420Tx.loadTXFIFO())
+ * Note: on TelosB there seems to be a problem if BackoffAlarm
+ * is virtualized - i.e. BackoffAlarm should be a dedicated Alarm.
+ *
  * @version $Revision$ $Date$
  */
 
@@ -45,21 +53,15 @@ module CC2420TransmitP {
 
   provides interface Init;
   provides interface AsyncStdControl;
-/*    interface CC2420Transmit;*/
   provides interface CC2420Tx;
-/*  provides interface RadioBackoff;*/
-/*  provides interface RadioTimeStamping as TimeStamp;*/
-/*  provides interface ReceiveIndicator as EnergyIndicator;*/
-/*  provides interface ReceiveIndicator as ByteIndicator;*/
-  
-/*  uses interface Alarm<T32khz,uint32_t> as BackoffAlarm;*/
   uses interface Alarm<T62500hz,uint32_t> as BackoffAlarm;
   uses interface GpioCapture as CaptureSFD;
   uses interface GeneralIO as CCA;
   uses interface GeneralIO as CSN;
   uses interface GeneralIO as SFD;
+  uses interface GeneralIO as FIFO;
+  uses interface GeneralIO as FIFOP;
 
-/*  uses interface Resource as SpiResource;*/
   uses interface ChipSpiResource;
   uses interface CC2420Fifo as TXFIFO;
   uses interface CC2420Ram as TXFIFO_RAM;
@@ -71,7 +73,7 @@ module CC2420TransmitP {
   uses interface CC2420Strobe as SRXON;
   uses interface CC2420Strobe as SRFOFF;
   uses interface CC2420Strobe as SFLUSHRX;
-  uses interface CC2420Strobe as SACKPEND; // JH: ACKs must have pending flag set
+  uses interface CC2420Strobe as SACKPEND;
   uses interface CC2420Register as MDMCTRL1;
   uses interface CaptureTime;
   uses interface ReferenceTime;
@@ -86,26 +88,22 @@ implementation {
     S_STOPPED,
     S_STARTED,
     S_LOAD,
-    S_SAMPLE_CCA,
-    S_BEGIN_TRANSMIT,
+    S_READY_TX,
     S_SFD,
     S_EFD,
     S_ACK_WAIT,
-    S_CANCEL,
   } cc2420_transmit_state_t;
 
-  // This specifies how many jiffies the stack should wait after a
+  // This specifies how many symbols the stack should wait after a
   // TXACTIVE to receive an SFD interrupt before assuming something is
   // wrong and aborting the send. There seems to be a condition
   // on the micaZ where the SFD interrupt is never handled.
   enum {
-    CC2420_ABORT_PERIOD = 320
+    CC2420_ABORT_PERIOD = 320*3,
   };
   
-/*  norace message_t *m_msg;*/
-  norace ieee154_txframe_t *m_data;
-  norace uint8_t m_txFrameLen;
-  ieee154_reftime_t m_timestamp;
+  norace ieee154_txframe_t *m_frame;
+  ieee154_timestamp_t m_timestamp;
   
   cc2420_transmit_state_t m_state = S_STOPPED;
   
@@ -119,27 +117,16 @@ implementation {
   /** Let the CC2420 driver keep a lock on the SPI while waiting for an ack */
   norace bool abortSpiRelease;
   
-  /** Total CCA checks that showed no activity before the NoAck LPL send */
-  norace int8_t totalCcaChecks;
-  
   /** The initial backoff period */
   norace uint16_t myInitialBackoff;
   
   /** The congestion backoff period */
   norace uint16_t myCongestionBackoff;
+  norace uint32_t alarmStartTime;
   
 
   /***************** Prototypes ****************/
-  error_t load( ieee154_txframe_t *data );
-  error_t resend( bool cca );
-  void loadTXFIFO();
-  void attemptSend(bool cca);
-  void congestionBackoff();
-  error_t acquireSpiResource();
-  error_t releaseSpiResource();
-/*  void signalDone( error_t err );*/
   void signalDone( bool ackFramePending, error_t err );
-/*  void cancelTx();*/
   
   /***************** Init Commands *****************/
   command error_t Init.init() {
@@ -166,81 +153,91 @@ implementation {
       m_state = S_STOPPED;
       call BackoffAlarm.stop();
       call CaptureSFD.disable();
-/*      call SpiResource.release();  // REMOVE*/
       call CSN.set();
     }
     return SUCCESS;
   }
 
 
-  /**************** Send Commands ****************/
+  /**************** Load/Send Commands ****************/
 
-/*  async command error_t Send.send( message_t* p_msg, bool useCca ) {*/
-  async command error_t CC2420Tx.loadTXFIFO(ieee154_txframe_t *data) {
-    return load( data);
-  }
-
-  async command void CC2420Tx.send(bool cca)
+  async command error_t CC2420Tx.loadTXFIFO(ieee154_txframe_t *data) 
   {
-    attemptSend(cca);
-  }
-  
-  async command bool CC2420Tx.cca()
-  {
-    return call CCA.get();
-  }
-
-  async command error_t CC2420Tx.modify( uint8_t offset, uint8_t* buf, 
-                                     uint8_t len ) {
-    call CSN.set();
-    call CSN.clr();
-    call TXFIFO_RAM.write( offset, buf, len );
-    call CSN.set();
+    atomic {
+      if ( m_state != S_STARTED )
+        return FAIL;
+      m_state = S_LOAD;
+      m_frame = data;
+      m_frame->header->length = m_frame->headerLen + m_frame->payloadLen + 2; // 2 for CRC
+      call CSN.set();
+      call CSN.clr();
+      call SFLUSHTX.strobe(); // flush out anything that was in TXFIFO
+      call CSN.set();
+      call CSN.clr();
+      call TXFIFO.write( &(m_frame->header->length), 1 );
+    }
     return SUCCESS;
-  }
-  
-  async command void CC2420Tx.lockChipSpi()
+  }   
+
+  async event void TXFIFO.writeDone( uint8_t* tx_buf, uint8_t tx_len, error_t error) 
   {
-    abortSpiRelease = TRUE;
+    atomic {
+      call CSN.set();
+      if (tx_buf == &(m_frame->header->length)){
+        call CSN.clr();
+        call TXFIFO.write( m_frame->header->mhr, m_frame->headerLen );
+        return;
+      } else if (tx_buf == m_frame->header->mhr) {
+        call CSN.clr();
+        call TXFIFO.write( m_frame->payload, m_frame->payloadLen );
+        return;
+      }
+    }
+    m_state = S_READY_TX;
+    signal CC2420Tx.loadTXFIFODone(m_frame, error);
   }
-  async command void CC2420Tx.unlockChipSpi()
+
+  async command error_t CC2420Tx.send(bool cca)
   {
-    abortSpiRelease = FALSE;
-  }
+    cc2420_status_t status;
+    bool congestion = TRUE;
 
-  /***************** Indicator Commands ****************/
-/*  command bool EnergyIndicator.isReceiving() {*/
-/*    return !(call CCA.get());*/
-/*  }*/
-/*  */
-/*  command bool ByteIndicator.isReceiving() {*/
-/*    bool high;*/
-/*    atomic high = sfdHigh;*/
-/*    return high;*/
-/*  }*/
-  
+    atomic {
+      if (m_state != S_READY_TX)
+        return EOFF;
+      call CSN.set();
+      call CSN.clr();
 
-  /***************** RadioBackoff Commands ****************/
-  /**
-   * Must be called within a requestInitialBackoff event
-   * @param backoffTime the amount of time in some unspecified units to backoff
-   */
-/*  async command void RadioBackoff.setInitialBackoff(uint16_t backoffTime) {*/
-/*    myInitialBackoff = backoffTime + 1;*/
-/*  }*/
-  
-  /**
-   * Must be called within a requestCongestionBackoff event
-   * @param backoffTime the amount of time in some unspecified units to backoff
-   */
-/*  async command void RadioBackoff.setCongestionBackoff(uint16_t backoffTime) {*/
-/*    myCongestionBackoff = backoffTime + 1;*/
-/*  }*/
-  
-/*  async command void RadioBackoff.setCca(bool useCca) {*/
-/*  }*/
-  
-  
+      // DEBUG
+      //P2OUT |= 0x40;      // P2.6 high
+      status = cca ? call STXONCCA.strobe() : call STXON.strobe();
+      //status = call STXON.strobe();
+      //U0TXBUF = 0x04; // strobe STXON
+      //while (!(IFG1 & URXIFG0));
+      //status = U0RXBUF;
+      //call CSN.set();
+
+      if ( !( status & CC2420_STATUS_TX_ACTIVE ) ) {
+        status = call SNOP.strobe();
+        if ( status & CC2420_STATUS_TX_ACTIVE ) {
+          congestion = FALSE;
+        }
+      }
+      
+      call CSN.set();
+      // DEBUG: on telosb SFD is connected to Pin P4.1
+      //if (!congestion) {while (!(P4IN & 0x02)) ;  P6OUT &= ~0x80;}
+
+      if (congestion){
+        return FAIL; // channel busy
+      } else {
+        m_state = S_SFD;
+        m_frame->metadata->timestamp = IEEE154_INVALID_TIMESTAMP; // pessimistic
+        call BackoffAlarm.start(CC2420_ABORT_PERIOD); 
+        return SUCCESS;
+      }
+    }
+  }
   
   /**
    * The CaptureSFD event is actually an interrupt from the capture pin
@@ -256,33 +253,19 @@ implementation {
    * would have picked up and executed had our microcontroller been fast enough.
    */
   async event void CaptureSFD.captured( uint16_t time ) {
-    // "time" is from TimerB capture, which is sourced by SMCLK (1MHz)
     //P2OUT &= ~0x40;      // debug: P2.6 low
-    uint32_t localTime;
     atomic {
       switch( m_state ) {
         
       case S_SFD:
         m_state = S_EFD;
         sfdHigh = TRUE;
-        call CaptureTime.convert(time, &m_timestamp, -8); // -8 for the preamble
         call CaptureSFD.captureFallingEdge();
-/*        signal TimeStamp.transmittedSFD( time, m_msg );*/
-        localTime = call ReferenceTime.toLocalTime(&m_timestamp);
-        signal CC2420Tx.transmittedSFD(localTime, m_data );
-        //if ( (call CC2420PacketBody.getHeader( m_msg ))->fcf & ( 1 << IEEE154_FCF_ACK_REQ ) ) {
-        //if ( (m_data->header)[0] & ( 1 << IEEE154_FCF_ACK_REQ ) ) {
-          // This is an ack packet, don't release the chip's SPI bus lock.
-        //}
-        releaseSpiResource();
+        // timestamp denotes time of first bit (chip) of PPDU on the channel
+        // offset: -10 for 5 bytes (preamble+SFD)
+        if (call CaptureTime.convert(time, &m_timestamp, -10) == SUCCESS) 
+          m_frame->metadata->timestamp = call ReferenceTime.toLocalTime(&m_timestamp);
         call BackoffAlarm.stop();
-        m_data->metadata->timestamp = localTime;
-
-        
-/*        if ( ( ( (call CC2420PacketBody.getHeader( m_msg ))->fcf >> IEEE154_FCF_FRAME_TYPE ) & 7 ) == IEEE154_TYPE_DATA ) {*/
-/*          (call CC2420PacketBody.getMetadata( m_msg ))->time = time;*/
-/*        }*/
-        
         if ( call SFD.get() ) {
           break;
         }
@@ -291,11 +274,15 @@ implementation {
       case S_EFD:
         sfdHigh = FALSE;
         call CaptureSFD.captureRisingEdge();
-        
-/*        if ( (call CC2420PacketBody.getHeader( m_msg ))->fcf & ( 1 << IEEE154_FCF_ACK_REQ ) ) {*/
-        if ( (m_data->header->mhr)[0] & ( 1 << IEEE154_FCF_ACK_REQ ) ) {
+        signal CC2420Tx.transmissionStarted(m_frame);
+        if ( (m_frame->header->mhr)[0] & ( 1 << IEEE154_FCF_ACK_REQ ) ) {
+          // wait for the ACK
           m_state = S_ACK_WAIT;
-          call BackoffAlarm.start( 200 ); // we need to have *completely* received the ACK
+          alarmStartTime = call BackoffAlarm.getNow();
+          // we need to have *completely* received the ACK, 32+22 symbols
+          // should theroretically be enough, but there can be delays in 
+          // servicing the FIFOP interrupt, so we use 100 symbols here
+          call BackoffAlarm.start( 100 ); 
         } else {
           signalDone(FALSE, SUCCESS);
         }
@@ -306,11 +293,11 @@ implementation {
         /** Fall Through because the next interrupt was already received */
         
       default:
+        // The CC2420 is in receive mode.
         if ( !m_receiving ) {
           sfdHigh = TRUE;
           call CaptureSFD.captureFallingEdge();
-/*          signal TimeStamp.receivedSFD( time );*/
-          call CaptureTime.convert(time, &m_timestamp, -8);
+          call CaptureTime.convert(time, &m_timestamp, -10);
           call CC2420Receive.sfd( &m_timestamp );
           m_receiving = TRUE;
           m_prev_time = time;
@@ -318,26 +305,44 @@ implementation {
             // wait for the next interrupt before moving on
             return;
           }
+          // if we move on, then the timestamp will be invalid!
         }
         
         sfdHigh = FALSE;
         call CaptureSFD.captureRisingEdge();
         m_receiving = FALSE;
-/*        if ( time - m_prev_time < 10 ) {*/
-#ifdef PIERCEBOARD_ENABLED
-        if ( time - m_prev_time < 10*30 ) {
-#else
-        if ( time - m_prev_time < 10 ) {
-#endif
+        if (!call CaptureTime.isValidTimestamp(m_prev_time, time))
           call CC2420Receive.sfd_dropped();
-        }
         break;
       
       }
     }
   }
+   
+  async command bool CC2420Tx.cca()
+  {
+    return call CCA.get();
+  }
+
+  async command error_t CC2420Tx.modify( uint8_t offset, uint8_t* buf, uint8_t len ) 
+  {
+    call CSN.set();
+    call CSN.clr();
+    call TXFIFO_RAM.write( offset, buf, len );
+    call CSN.set();
+    return SUCCESS;
+  }
+  
+  async command void CC2420Tx.lockChipSpi()
+  {
+    abortSpiRelease = TRUE;
+  }
+
+  async command void CC2420Tx.unlockChipSpi()
+  {
+    abortSpiRelease = FALSE;
+  }
 
-  /***************** ChipSpiResource Events ****************/
   async event void ChipSpiResource.releasing() {
     if(abortSpiRelease) {
       call ChipSpiResource.abortRelease();
@@ -351,392 +356,57 @@ implementation {
    * our send is complete.
    */
   async event void CC2420Receive.receive(  uint8_t type, message_t *ackFrame ){
-/*  async event void CC2420Receive.receive( uint8_t type, message_t* ack_msg ) {*/
-/*    cc2420_header_t* ack_header;*/
-/*    cc2420_header_t* msg_header;*/
-/*    cc2420_metadata_t* msg_metadata;*/
-/*    uint8_t* ack_buf;*/
-/*    uint8_t length;*/
-
     atomic {
       if ( type == IEEE154_TYPE_ACK ) {
-
-        /*      ack_header = call CC2420PacketBody.getHeader( ack_msg );*/
-        /*      msg_header = call CC2420PacketBody.getHeader( m_msg );*/
-
-        /*      if ( m_state == S_ACK_WAIT && msg_header->dsn == ack_header->dsn ) {*/
         if (  m_state == S_ACK_WAIT && 
-            m_data->header->mhr[2] == ((ieee154_header_t*) ackFrame->header)->mhr[2] ) { // compare seqno
+            m_frame->header->mhr[2] == ((ieee154_header_t*) ackFrame->header)->mhr[2] ) { // compare seqno
           call BackoffAlarm.stop();
-
-          /*        msg_metadata = call CC2420PacketBody.getMetadata( m_msg );*/
-          /*        ack_buf = (uint8_t *) ack_header;*/
-          /*        length = ack_header->length;*/
-          /*        */
-          /*        msg_metadata->ack = TRUE;*/
-          /*        msg_metadata->rssi = ack_buf[ length - 1 ];*/
-          /*        msg_metadata->lqi = ack_buf[ length ] & 0x7f;*/
           signalDone(( ((ieee154_header_t*) ackFrame->header)->mhr[0] & 0x10) ? TRUE: FALSE, SUCCESS);
         }
       }
     }
   }
-
-  /***************** SpiResource Events ****************/
-    /*
-  event void SpiResource.granted() {
-    uint8_t cur_state;
-
-    atomic {
-      cur_state = m_state;
-    }
-
-    switch( cur_state ) {
-    case S_LOAD:
-      loadTXFIFO();
-      break;
-      
-    case S_BEGIN_TRANSMIT:
-      attemptSend();
-      break;
-      
-    case S_CANCEL:
-      cancelTx();
-      break;
-      
-    default:
-      releaseSpiResource();
-      break;
-    }
-  }
-  */
-  
-  /***************** TXFIFO Events ****************/
-  /**
-   * The TXFIFO is used to load packets into the transmit buffer on the
-   * chip
-   */
-  async event void TXFIFO.writeDone( uint8_t* tx_buf, uint8_t tx_len,
-                                     error_t error ) {
-
-    call CSN.set();
-    
-    if (tx_buf == &m_txFrameLen){
-      // until here: 1.65 ms
-      call CSN.clr();
-      call TXFIFO.write( m_data->header->mhr, m_data->headerLen );
-      return;
-    } else if (tx_buf == m_data->header->mhr) {
-      // until here: 2.2 ms
-      call CSN.clr();
-      call TXFIFO.write( m_data->payload, m_data->payloadLen );
-      return;
-    }
-    // until here: 4.6 ms (no DMA on USART0)
-    // until here: 3.3 ms (with DMA on USART0)
-    // P2OUT &= ~0x40;      // P2.1 low 
-    
-/*    if ( m_state == S_CANCEL ) {*/
-/*      atomic {*/
-/*        call CSN.clr();*/
-/*        call SFLUSHTX.strobe();*/
-/*        call CSN.set();*/
-/*      }*/
-/*      releaseSpiResource();*/
-/*      m_state = S_STARTED;*/
-            
-/*    } else if ( !m_cca ) {*/
-/*    } else  {*/
-      m_state = S_BEGIN_TRANSMIT;
-      releaseSpiResource();
-      signal CC2420Tx.loadTXFIFODone(m_data, error);
-/*      attemptSend();*/
-/*    }*/
-
-/*    } else {*/
-/*      releaseSpiResource();*/
-/*      atomic {*/
-/*        if (m_state == S_LOAD_CANCEL) {*/
-/*          m_state = S_CCA_CANCEL;*/
-/*        } else {*/
-/*          m_state = S_SAMPLE_CCA;*/
-/*        }*/
-/*      }*/
-/*      signal CC2420Tx.loadTXFIFODone(m_data, error);*/
-      
-/*      signal RadioBackoff.requestInitialBackoff(m_msg);*/
-/*      call BackoffAlarm.start(myInitialBackoff);*/
-/*    }*/
-  }
-
-  
-  async event void TXFIFO.readDone( uint8_t* tx_buf, uint8_t tx_len, 
-      error_t error ) {
-  }
   
-  
-  /***************** Timer Events ****************/
-  /**
-   * The backoff timer is mainly used to wait for a moment before trying
-   * to send a packet again. But we also use it to timeout the wait for
-   * an acknowledgement, and timeout the wait for an SFD interrupt when
-   * we should have gotten one.
-   */
   async event void BackoffAlarm.fired() {
     atomic {
       switch( m_state ) {
-        
-      case S_SAMPLE_CCA : 
-        // sample CCA and wait a little longer if free, just in case we
-        // sampled during the ack turn-around window
-        if ( call CCA.get() ) {
-          m_state = S_BEGIN_TRANSMIT;
-          call BackoffAlarm.start( CC2420_TIME_ACK_TURNAROUND );
-          
-        } else {
-          congestionBackoff();
-        }
-        break;
-        
-      case S_BEGIN_TRANSMIT:
-      case S_CANCEL:
-        // should never happen
-        call Leds.led0On();
-/*        if ( acquireSpiResource() == SUCCESS ) {*/
-/*          attemptSend();*/
-/*        }*/
-        break;
-        
-      case S_ACK_WAIT:
-/*        signalDone( SUCCESS );*/
-        signalDone( FALSE, FAIL );
-        break;
-
-      case S_SFD:
-        // We didn't receive an SFD interrupt within CC2420_ABORT_PERIOD
-        // jiffies. Assume something is wrong.
-        atomic {
-          call CSN.set();
-          call CSN.clr();
-          call SFLUSHTX.strobe();
-          call CSN.set();
-        }
-        signalDone( FALSE, ERETRY );
-        releaseSpiResource();
-        //call CaptureSFD.captureRisingEdge();
-        break;
-
-      default:
-        break;
-      }
-    }
-  }
 
-  /***************** Functions ****************/
-  /**
-   * Set up a message to be sent. First load it into the outbound tx buffer
-   * on the chip, then attempt to send it.
-   * @param *p_msg Pointer to the message that needs to be sent
-   * @param cca TRUE if this transmit should use clear channel assessment
-   */
-  error_t load( ieee154_txframe_t *data) {
-    atomic {
-      if (m_state == S_CANCEL) {
-        return ECANCEL;
-      }
-      
-      if ( m_state != S_STARTED ) {
-        return FAIL;
-      }
-      
-      m_state = S_LOAD;
-/*      m_msg = p_msg;*/
-      m_data = data;
-      totalCcaChecks = 0;
-    }
-    
-    if ( acquireSpiResource() == SUCCESS ) {
-      loadTXFIFO();
-    }
-
-    return SUCCESS;
-  }
-  
-  /**
-   * Resend a packet that already exists in the outbound tx buffer on the
-   * chip
-   * @param cca TRUE if this transmit should use clear channel assessment
-   */
-/*  error_t resend( bool cca ) {*/
-
-/*    atomic {*/
-/*      if (m_state == S_LOAD_CANCEL*/
-/*          || m_state == S_CCA_CANCEL*/
-/*          || m_state == S_TX_CANCEL) {*/
-/*        return ECANCEL;*/
-/*      }*/
-/*      */
-/*      if ( m_state != S_STARTED ) {*/
-/*        return FAIL;*/
-/*      }*/
-/*      */
-/*      m_cca = cca;*/
-/*      m_state = cca ? S_SAMPLE_CCA : S_BEGIN_TRANSMIT;*/
-/*      totalCcaChecks = 0;*/
-/*    }*/
-/*    */
-/*    if(m_cca) {*/
-/*      signal RadioBackoff.requestInitialBackoff(m_msg);*/
-/*      call BackoffAlarm.start( myInitialBackoff );*/
-/*      */
-/*    } else if ( acquireSpiResource() == SUCCESS ) {*/
-/*      attemptSend();*/
-/*    }*/
-/*    */
-/*    return SUCCESS;*/
-/*  }*/
-  
-  /**
-   * Attempt to send the packet we have loaded into the tx buffer on 
-   * the radio chip.  The STXONCCA will send the packet immediately if
-   * the channel is clear.  If we're not concerned about whether or not
-   * the channel is clear (i.e. m_cca == FALSE), then STXON will send the
-   * packet without checking for a clear channel.
-   *
-   * If the packet didn't get sent, then congestion == TRUE.  In that case,
-   * we reset the backoff timer and try again in a moment.
-   *
-   * If the packet got sent, we should expect an SFD interrupt to take
-   * over, signifying the packet is getting sent.
-   */
-  void attemptSend(bool cca) {
-    uint8_t status;
-    bool congestion = TRUE;
-
-    atomic {
-      call CSN.set();
-      call CSN.clr();
+        case S_SFD:
+        case S_EFD: // fall through
+          // We didn't receive an SFD interrupt within CC2420_ABORT_PERIOD
+          // jiffies. Assume something is wrong.
+          atomic {
+            call CSN.set();
+            call CSN.clr();
+            call SFLUSHTX.strobe();
+            call CSN.set();
+          }
+          signalDone( FALSE, ERETRY );
+          break;
 
-      // STXONCCA costs about ? symbols, i.e. attemptSend should be called
-      // ? symbols, before the actual CCA
-      //P2OUT |= 0x40;      // P2.6 high
-      status = cca ? call STXONCCA.strobe() : call STXON.strobe();
-      //status = call STXON.strobe();
-      //U0TXBUF = 0x04; // strobe STXON
-      //while (!(IFG1 & URXIFG0));
-      //status = U0RXBUF;
-      //call CSN.set();
+        case S_ACK_WAIT:
+          /*        signalDone( SUCCESS );*/
+          signalDone( FALSE, ENOACK );
+          break;
 
-      if ( !( status & CC2420_STATUS_TX_ACTIVE ) ) {
-        status = call SNOP.strobe();
-        if ( status & CC2420_STATUS_TX_ACTIVE ) {
-          congestion = FALSE;
-        }
-      }
-      
-      call CSN.set();
-      // debug: on telosb SFD is connected to Pin P4.1
-      if (!congestion) {while (!(P4IN & 0x02)) ;  P6OUT &= ~0x80;}
 
-      if (congestion){
-        call ReferenceTime.getNow(&m_timestamp, 0);
-        m_state = S_BEGIN_TRANSMIT; // don't use a state S_SAMPLE_CCA
-        releaseSpiResource();
-        signal CC2420Tx.sendDone(m_data, &m_timestamp, FALSE, EBUSY); // waiting for the next send()
-      } else {
-        m_state = S_SFD; // wait for an ACK
-        signal CC2420Tx.transmissionStarted(m_data);
-        call BackoffAlarm.start(CC2420_ABORT_PERIOD*3);
+        default:
+          break;
       }
-      return; // we still own the SPI, either we wait for an ACK or resend is going to be called soon
     }
-    
-/*    if ( congestion ) {*/
-/*      totalCcaChecks = 0;*/
-/*      releaseSpiResource();*/
-/*      congestionBackoff();*/
-/*    } else {*/
-/*      call BackoffAlarm.start(CC2420_ABORT_PERIOD);*/
-/*    }*/
   }
-  
-  /**  
-   * Congestion Backoff
-   */
-  void congestionBackoff() {
-    atomic {
-/*      signal RadioBackoff.requestCongestionBackoff(m_msg);*/
-      call BackoffAlarm.start(myCongestionBackoff);
-    }
-  }
-  
-  error_t acquireSpiResource() {
-    return SUCCESS;
-    /*
-    error_t error = call SpiResource.immediateRequest();
-    if ( error != SUCCESS ) {
-      call SpiResource.request();
-    }
-    return error;
-    */
-  }
-
-  error_t releaseSpiResource() {
-    //call SpiResource.release();
-    return SUCCESS;
-  }
-
-
-  /** 
-   * Setup the packet transmission power and load the tx fifo buffer on
-   * the chip with our outbound packet.  
-   *
-   * Warning: the tx_power metadata might not be initialized and
-   * could be a value other than 0 on boot.  Verification is needed here
-   * to make sure the value won't overstep its bounds in the TXCTRL register
-   * and is transmitting at max power by default.
-   *
-   * It should be possible to manually calculate the packet's CRC here and
-   * tack it onto the end of the header + payload when loading into the TXFIFO,
-   * so the continuous modulation low power listening strategy will continually
-   * deliver valid packets.  This would increase receive reliability for
-   * mobile nodes and lossy connections.  The crcByte() function should use
-   * the same CRC polynomial as the CC2420's AUTOCRC functionality.
-   */
-  void loadTXFIFO() {
-/*    cc2420_header_t* header = call CC2420PacketBody.getHeader( m_msg );*/
-/*    uint8_t tx_power = (call CC2420PacketBody.getMetadata( m_msg ))->tx_power;*/
-    m_txFrameLen = m_data->headerLen + m_data->payloadLen + 2;
 
-/*    if ( !tx_power ) {*/
-/*      tx_power = CC2420_DEF_RFPOWER;*/
-/*    }*/
-    call CSN.set();
-    call CSN.clr();
-    call SFLUSHTX.strobe(); // flush out anything that was in there
-    call CSN.set();
-    call CSN.clr();
-    
-/*    call TXFIFO.write( (uint8_t*)header, header->length - 1);*/
-    call TXFIFO.write( &m_txFrameLen, 1 );
-
-  }
-  
   void signalDone( bool ackFramePending, error_t err ) {
+    ieee154_timestamp_t *txTime = &m_timestamp;
     atomic m_state = S_STARTED;
-    signal CC2420Tx.sendDone( m_data, &m_timestamp, ackFramePending, err );
+    if (m_frame->metadata->timestamp == IEEE154_INVALID_TIMESTAMP)
+      txTime = NULL;
+    signal CC2420Tx.sendDone( m_frame, txTime, ackFramePending, err );
     call ChipSpiResource.attemptRelease();
-/*    signal Send.sendDone( m_msg, err );*/
   }
-  
-  /***************** Tasks ****************/
-
-  /***************** Defaults ****************/
-/*  default async event void TimeStamp.transmittedSFD( uint16_t time, message_t* p_msg ) {*/
-/*  }*/
-  
-/*  default async event void TimeStamp.receivedSFD( uint16_t time ) {*/
-/*  }*/
 
+  async event void TXFIFO.readDone( uint8_t* tx_buf, uint8_t tx_len, 
+      error_t error ) {
+  }
 }
 
index 53e1fc9fda513b145d5aece88c893717465140bf..d27f89253d24afd448b9fa486fc346ec0c90b723 100644 (file)
@@ -40,8 +40,8 @@ interface CC2420Tx {
   async command error_t loadTXFIFO(ieee154_txframe_t *data);
   async event void loadTXFIFODone(ieee154_txframe_t *data, error_t error );
 
-  async command void send(bool cca);
-  async event void sendDone(ieee154_txframe_t *frame, ieee154_reftime_t *referenceTime, 
+  async command error_t send(bool cca);
+  async event void sendDone(ieee154_txframe_t *frame, ieee154_timestamp_t *referenceTime, 
       bool ackPendingFlag, error_t error);
 
   async command bool cca();
index 45e7300e7083e98c5f707d4274f3eff845bbba47..14980fda9be603d725cc3e478194744b5887d064 100644 (file)
@@ -38,6 +38,20 @@ interface CaptureTime
    * @param   time  capture time
    * @param   localTime capture time converted to local time + offset symbols
    * @param   offset time in symbols (16 us) to add to capture time
+   * @return  SUCCESS if conversion was made successfully, FAIL otherwise
    */
-  async command void convert(uint16_t time, ieee154_reftime_t *localTime, int16_t offset);
+  async command error_t convert(uint16_t time, ieee154_timestamp_t *localTime, int16_t offset);
+
+  /**
+   * Tells whether the timestamp is valid. On the CC2420 an SFD transition
+   * does not necessarily mean that the packet is put in the RXFIFO.
+   * This command should return FALSE iff the time between the rising SFD
+   * and the falling SFD is too short for the smallest possible frame, i.e.
+   * ACK frame (see CC2420 datasheet for details on SFD timing).
+   *
+   * @param  risingSFDTime capture time of rising SFD
+   * @param  fallingSFDTime capture time of falling SFD
+   * @return FALSE if time offset is too small for a valid packet
+   */
+  async command bool isValidTimestamp(uint16_t risingSFDTime, uint16_t fallingSFDTime);
 }
index e91e0e6bca0fc13d384adb35d6fd9609dda3027e..3e77e3c85acbc3f8e887e8991c4641216b30fad3 100644 (file)
 interface ReferenceTime
 {
   /** 
-   * Gets current reference time plus dt symbols.
+   * Gets current time and adds dt symbols.
    */
-  async command void getNow(ieee154_reftime_t* reftime, uint16_t dt);
+  async command void getNow(ieee154_timestamp_t* time, uint16_t dt);
 
   /** 
    * Converts reference time to local time.
    */
-  async command uint32_t toLocalTime(ieee154_reftime_t* refTime);
+  async command uint32_t toLocalTime(const ieee154_timestamp_t* time);
 }
index 02140b1116fb1181ff4e5dff2cddd9a5b56979e8..9cd3b0dfe6dc64842cecc0098780d3b50493305d 100644 (file)
  */
 interface ReliableWait
 {
-
-  async command void busyWait(uint16_t dt);
-
-  /*
-   * The following command/event pairs are platform-specific
-   * busy-waits. 
-   */
-  
-  async command void waitRx(ieee154_reftime_t *t0, uint16_t dt);
+  async command void waitRx(uint32_t t0, uint32_t dt);
   async event void waitRxDone();
-  async command void waitCCA(ieee154_reftime_t *t0, uint16_t dt);
-  async event void waitCCADone();
-  async command void waitTx(ieee154_reftime_t *t0, uint16_t dt);
+  async command void waitTx(ieee154_timestamp_t *t0, uint32_t dt);
   async event void waitTxDone();
+  async command void waitBackoff(uint32_t dt);
+  async event void waitBackoffDone();
+  async command bool ccaOnBackoffBoundary(ieee154_timestamp_t *slot0);
 }
index 12b69f058d27802d2e2a3d38651e53881247bae3..71d6920a395bd340e5b72cb1271b46fb7768b801 100644 (file)
@@ -51,11 +51,7 @@ enum {
   IEEE154_MIN_LIFS_PERIOD     = 40,
   IEEE154_MIN_SIFS_PERIOD     = 12,
   IEEE154_ACK_WAIT_DURATION   = (20 + 12 + IEEE154_SHR_DURATION + 6 * IEEE154_SYMBOLS_PER_OCTET),
-  // TODO: check BATT_LIFE_EXT
-  IEEE154_BATT_LIFE_EXT_PERIODS      = 1,
-  IEEE154_BATT_LIFE_EXT_PERIOD_TERM3 = 1,
-  IEEE154_TIMESTAMP_SUPPORTED        = TRUE,
-
+  IEEE154_TIMESTAMP_SUPPORTED = TRUE,
 };
 
 #include "Timer62500hz.h"
index 0f041631c10bef564c55454f22f83b8240ecedc1..9a1270d867865e5efe288f1680edc58e7653fb53 100644 (file)
@@ -69,7 +69,7 @@ interface Timestamp
   /**
    * Modify (overwrite) the contents of the MAC payload. This command must 
    * only be called in the context of a <code>transmittedSFD()<\code> event and it
-   * should return fast. Note: the smaller offset is the faster 
+   * should return fast. Note: the smaller the offset is the faster 
    * <code>transmittedSFD()<\code> must be finished (offset of zero might not work).
    *
    * @param token   the token signalled by <code>transmittedSFD()<\code>
index c8fd2b1792c203a4a2dc0c264491493ff9d42514..8a31f19b4353eea65f97a05e2edfac95e14bd88a 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HIL interface for the CP210X USB/serial controller chip.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 interface CP210X {
   /**
    * @returns the current attach state of the USB connector.
index 8e3d56b4a75567a0753835747a2e516641d4f04b..c29adfd51f10e42a616ea0e076bfdf78485209f9 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HIL implementation for the CP210X USB/serial controller chip family.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration CP210XC {
   provides interface CP210X;
 }
index 6fa38ffb854dc1216ccf66f69200b415dfa25d4d..3060880ba12d0243b1940db8fe67770f6a3176a1 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HIL implementation for the CP210X USB/serial controller chip family.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 module CP210XP {
   provides {
     interface Init;
@@ -99,7 +99,7 @@ implementation {
   task void signalChange()
   {
     bool suspended;
-    
+
     atomic suspended = call USB_SUSPENDn.get();
     if (suspended)
       signal CP210X.suspended();
diff --git a/tos/chips/ds2401/CachedIeeeEui64P.nc b/tos/chips/ds2401/CachedIeeeEui64P.nc
new file mode 100644 (file)
index 0000000..4a3ab1d
--- /dev/null
@@ -0,0 +1,47 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+/**
+ * Cache an EUI 64 at initialization time and return the cached value for
+ * subsequent queries.
+ */
+module CachedIeeeEui64P {
+  uses interface LocalIeeeEui64 as SubIeeeEui64;
+  provides {
+    interface LocalIeeeEui64;
+    interface Init;
+  }
+} implementation {
+
+  ieee_eui64_t eui;
+
+  command error_t Init.init() {
+    atomic eui = call SubIeeeEui64.getId();
+    return SUCCESS;
+  }
+
+  command ieee_eui64_t LocalIeeeEui64.getId() {
+    return eui;
+  }
+}
diff --git a/tos/chips/ds2401/Ds2401.h b/tos/chips/ds2401/Ds2401.h
new file mode 100644 (file)
index 0000000..6b80485
--- /dev/null
@@ -0,0 +1,42 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+#ifndef DS2401_H
+#define DS2401_H
+
+enum {
+  DS2401_SERIAL_LENGTH = 6,
+  DS2401_DATA_LENGTH = 8
+};
+
+typedef union ds2401_serial_t {
+  uint8_t data[DS2401_DATA_LENGTH];
+  struct {
+     uint8_t family_code;
+     uint8_t serial[DS2401_SERIAL_LENGTH];
+     uint8_t crc;
+  };
+} ds2401_serial_t;
+
+#endif // DS2401_H
diff --git a/tos/chips/ds2401/Ds2401ToIeeeEui64C.nc b/tos/chips/ds2401/Ds2401ToIeeeEui64C.nc
new file mode 100644 (file)
index 0000000..5720263
--- /dev/null
@@ -0,0 +1,63 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+#include "Ds2401.h"
+#include "IeeeEui64.h"
+#include "PlatformIeeeEui64.h"
+
+/**
+ * Convert silicon serial ID to IEEE EUI 64, according to Application Note
+ * 186 - Creating Global Identifiers Using 1-Wire Devices from Dallas/Maxim.
+ */
+module Ds2401ToIeeeEui64C {
+  uses interface HplDs2401 as Hpl;
+  provides interface LocalIeeeEui64;
+} implementation {
+
+  command ieee_eui64_t LocalIeeeEui64.getId() {
+    ds2401_serial_t rom;
+    ieee_eui64_t eui;
+    
+    atomic {
+      call Hpl.read(&rom);
+    }
+
+    // company ID
+    eui.data[0] = IEEE_EUI64_COMPANY_ID_0;
+    eui.data[1] = IEEE_EUI64_COMPANY_ID_1;
+    eui.data[2] = IEEE_EUI64_COMPANY_ID_2;
+
+    // 16 bits of the ID is generated by software
+    // could be used for hardware model id and revision, for example
+    eui.data[3] = IEEE_EUI64_SERIAL_ID_0;
+    eui.data[4] = IEEE_EUI64_SERIAL_ID_1;
+
+    // 24 least significant bits of the serial ID read from the DS2401
+    eui.data[5] = rom.data[3];
+    eui.data[6] = rom.data[2];
+    eui.data[7] = rom.data[1];
+
+    return eui;
+  }
+}
diff --git a/tos/chips/ds2401/HplDs2401.nc b/tos/chips/ds2401/HplDs2401.nc
new file mode 100644 (file)
index 0000000..ba45390
--- /dev/null
@@ -0,0 +1,38 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+#include "Ds2401.h"
+
+/**
+ * Interface to read the 64-bit hardware ID from the DS2401 chip.
+ */
+interface HplDs2401 {
+
+/**
+ * Read the 64-bit hardware ID (family id, serial, crc) from the DS2401 chip.
+ * @param rom Pointer to a ds2401_serial_t struct, defined in ds2401.h.
+ * @returns SUCCESS on success, an error code otherwise.
+ */
+  async command error_t read(ds2401_serial_t* rom);
+}
diff --git a/tos/chips/ds2401/HplDs2401C.nc b/tos/chips/ds2401/HplDs2401C.nc
new file mode 100644 (file)
index 0000000..deb677b
--- /dev/null
@@ -0,0 +1,66 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+#include "Ds2401.h"
+
+/**
+ * HPL for the DS2401 hardware ID chip.
+ */
+module HplDs2401C {
+  provides interface HplDs2401 as Hpl;
+  uses interface OneWireMaster as OneWire;
+}
+implementation {
+  bool busy = FALSE;
+
+  async command error_t Hpl.read(ds2401_serial_t* rom) {
+    uint8_t i;
+
+    if(busy) {
+      return EBUSY;
+    }
+
+    busy = TRUE;
+
+    call OneWire.init();
+
+    if(call OneWire.reset() != SUCCESS) {
+      call OneWire.release();
+      busy = FALSE;
+      return EOFF;
+    }
+
+    call OneWire.writeByte(0x33);
+
+    for(i=0;i<DS2401_DATA_LENGTH;i++) {
+      rom->data[i] = call OneWire.readByte();
+    }
+
+    // TODO: crc check
+
+    call OneWire.release();
+    busy = FALSE;
+    return SUCCESS;
+  }
+}
diff --git a/tos/chips/ds2401/OneWireMaster.nc b/tos/chips/ds2401/OneWireMaster.nc
new file mode 100644 (file)
index 0000000..2a01ae9
--- /dev/null
@@ -0,0 +1,69 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+/**
+ * Interface to interact with 1-wire bus devices, as a master on the 1-wire
+ * bus.
+ */
+interface OneWireMaster {
+  /**
+   * Initialize bus (pin is input with pullup).
+   */
+  async command void idle();
+  /**
+   * Initialize bus, start sourcing current (pin is input with pullup).
+   */
+  async command void init();
+  /**
+   * Release bus, stop sourcing current (pin is three-stated input).
+   */
+  async command void release();
+  /**
+   * Generate reset signal.
+   * @returns SUCCESS if a client is present, an error_t error value otherwise.
+   */
+  async command error_t reset();
+  /**
+   * Write bit 1 to the bus.
+   */
+  async command void writeOne();
+  /**
+   * Write bit 0 to the bus.
+   */
+  async command void writeZero();
+  /**
+   * Write 8 bits to the bus, LSB first.
+   * @param b the byte to write.
+   */
+  async command void writeByte(uint8_t b);
+  /**
+   * Read a bit from the bus.
+   */
+  async command bool readBit();
+  /**
+   * Read 8 bits from the bus, LSB first.
+   * @returns the byte read.
+   */
+  async command uint8_t readByte();
+}
diff --git a/tos/chips/ds2401/OneWireMasterC.nc b/tos/chips/ds2401/OneWireMasterC.nc
new file mode 100644 (file)
index 0000000..2d81ae8
--- /dev/null
@@ -0,0 +1,128 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+/**
+ * This module is the implementation of an 1-wire bus master.
+ *
+ */
+module OneWireMasterC {
+  uses interface GeneralIO as Pin;
+  uses interface BusyWait<TMicro, uint16_t> as BusyWaitMicro;
+  provides interface OneWireMaster as OneWire;
+
+}
+implementation {
+
+  async command void OneWire.idle() {
+    call Pin.makeInput();
+    call Pin.set(); // start sourcing current
+  }
+
+  async command void OneWire.init() {
+    call OneWire.idle();
+    call BusyWaitMicro.wait(500); // wait at least 500us after bootup
+  }
+
+  async command void OneWire.release() {
+    call Pin.makeInput();
+    call Pin.clr(); // stop sourcing current
+  }
+
+  async command error_t OneWire.reset() {
+    bool clientPresent;
+
+    // it is assumed that the bus is in idle state here
+
+    // transmit reset pulse
+    call Pin.makeOutput(); // output low
+    call Pin.clr();
+    call BusyWaitMicro.wait(500); // must be at least 480us
+    call OneWire.idle(); // input with pullup set
+
+    // test for present pulse
+    call BusyWaitMicro.wait(80); // presence pulse is sent 18-60us after reset
+    clientPresent = call Pin.get(); // test for presence pulse
+    call BusyWaitMicro.wait(400); // presence pulse is 60-240us long
+
+    if (clientPresent == 0) {
+      return SUCCESS;
+    } else {
+      return EOFF;
+    }
+  }
+
+  async command void OneWire.writeOne() {
+    call Pin.makeOutput(); // output low
+    call Pin.clr();
+    call BusyWaitMicro.wait(8); // must be 1-15us
+    call OneWire.idle(); // input with pullup set
+    call BusyWaitMicro.wait(72); // low time plus idle time must 60-120us
+  }
+
+  async command void OneWire.writeZero() {
+    call Pin.makeOutput(); // output low
+    call Pin.clr();
+    call BusyWaitMicro.wait(72); // must be 60-120us
+    call OneWire.idle(); // input with pullup set
+    call BusyWaitMicro.wait(8); // low time plus idle time must 60-120us
+  }
+
+  async command void OneWire.writeByte(uint8_t b) {
+    uint8_t i;
+
+    // send out bits, LSB first
+    for(i=0;i<8;i++) {
+      if(b & 0x01) {
+        call OneWire.writeOne();
+      } else {
+        call OneWire.writeZero();
+      }
+      b >>= 1;
+    }
+  }
+
+  async command bool OneWire.readBit() {
+    bool b;
+    call Pin.makeOutput(); // output low
+    call Pin.clr();
+    call BusyWaitMicro.wait(1);
+    call OneWire.idle(); // input with pullup set
+    call BusyWaitMicro.wait(8); // must be 1-15us
+    b = call Pin.get(); // read pin
+    call BusyWaitMicro.wait(71); // timeslot length must be 60-120us
+    return b;
+  }
+
+  async command uint8_t OneWire.readByte() {
+    uint8_t i,b=0;
+
+    // read bits, LSB first
+    for(i=0;i<8;i++) {
+      b >>= 1;
+      b |= call OneWire.readBit() << 7;
+    }
+    return b;
+  }
+
+}
diff --git a/tos/chips/ds2782/DS2782.h b/tos/chips/ds2782/DS2782.h
new file mode 100644 (file)
index 0000000..7394af8
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Types and definitions for the Dallas DS2782 I2C Battery Monitor
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Phil Buonadonna <pbuonadonna@archrock.com>
+ */
+
+#ifndef _DS2782_H
+#define _DS2782_H
+
+#define DS2782_PTR_SC          (0x01)
+#define DS2782_PTR_TEMPMSB     (0x0A)
+#define DS2782_PTR_TEMPLSB     (0x0B)
+#define DS2782_PTR_VOLTMSB     (0x0C)
+#define DS2782_PTR_VOLTLSB     (0x0D)
+#define DS2782_PTR_CURRMSB     (0x0E)
+#define DS2782_PTR_CURRLSB     (0x0F)
+#define DS2782_PTR_ACCURMSB    (0x10)
+#define DS2782_PTR_ACCURLSB    (0x11)
+#define DS2782_PTR_OFFSETBIAS  (0x61)
+#define DS2782_PTR_ACCBIAS     (0x62)
+#define DS2782_PTR_CONTROL  (0x60)
+
+#define DS2782_SC_PORF         (1 << 6)
+#define DS2782_SC_SMOD         (1 << 5)
+#define DS2782_SC_NBEN         (1 << 4)
+#define DS2782_SC_PIO          (1 << 3)
+#define DS2782_SC_FQ(_x)       (((_x) & 0x3))
+
+#endif /* _DS2782_H */
diff --git a/tos/chips/ds2782/HplDS2782.nc b/tos/chips/ds2782/HplDS2782.nc
new file mode 100644 (file)
index 0000000..fada282
--- /dev/null
@@ -0,0 +1,210 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arched Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * HplDS2782 is the HPL inteface to the Dallas DS2782 I2C Battery 
+ * Monitor.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Phil Buonadonna <pbuonadonna@archrock.com>
+ */
+
+interface HplDS2782 {
+
+  /**
+   * Sets a new value to the DS2782 configuration register.
+   *
+   * @param val the new value to be written
+   *
+   * @return SUCCESS if the set will be performed
+   */
+  command error_t setConfig( uint8_t val );
+
+  /**
+   * Signals the completion of the configuration register set.
+   *
+   * @param error SUCCESS if the set was successful
+   */
+  async event void setConfigDone( error_t error );
+
+  /**
+   * Tells the DS2782 whether or not is is allowed to go into sleep.
+   *
+   * @param allow True allows sleep.
+   * 
+   * @return SUCCESS if the set will be performed
+   */
+  command error_t allowSleep(bool allow);
+
+  /**
+   * Signals the completion of the sleep call.
+   *
+   * @param error SUCCESS if the set was successful
+   */
+  async event void allowSleepDone( error_t error );
+
+  /**
+   * Starts a temperature measurement.
+   *
+   * @return SUCCESS if the measurement will be made
+   */
+  command error_t measureTemperature();
+
+  /**
+   * Presents the result of a temperature measurement.
+   *
+   * @param error SUCCESS if the measurement was successful
+   * @param val the temperature reading
+   */
+  async event void measureTemperatureDone( error_t error, uint16_t val );
+
+
+  /** 
+   * Starts a voltage measurement.
+   *
+   * @return SUCCESS if the measurement will be made
+   */
+  command error_t measureVoltage();
+
+  /**
+   * Presents the result of a voltage measurement.
+   *
+   * @param error SUCCESS if the measurement was successful
+   * @param val the voltage reading
+   */
+  async event void measureVoltageDone( error_t error, uint16_t val);
+
+
+  /** 
+   * Starts a current measurement.
+   *
+   * @return SUCCESS if the measurement will be made
+   */
+  command error_t measureCurrent();
+
+  /**
+   * Presents the result of a current measurement.
+   *
+   * @param error SUCCESS if the measurement was successful
+   * @param val the current reading
+   */
+  async event void measureCurrentDone( error_t error, uint16_t val);
+
+
+  /** 
+   * Starts an accumulated current measurement.
+   *
+   * @return SUCCESS if the measurement will be made
+   */
+  command error_t measureAccCurrent();
+
+  /**
+   * Presents the result of a accumulated current measurement.
+   *
+   * @param error SUCCESS if the measurement was successful
+   * @param val the accumulated current reading
+   */
+  async event void measureAccCurrentDone( error_t error, uint16_t val);
+
+
+  /** 
+   * Initiates setting of the current offset bias value
+   *
+   * @param The signed two's complement bias value.
+   *
+   * @return SUCCESS if the setting will be made
+   */
+  command error_t setOffsetBias(int8_t val);
+
+  /**
+   * Signals completion and error, if any, in setting the current
+   * offset bias value.
+   *
+   * @param error SUCCESS if the setting was successful
+   */
+  async event void setOffsetBiasDone( error_t error );
+
+
+  /** 
+   * Initiates setting of the accumulated current offset bias value
+   *
+   * @param The signed two's complement bias value.
+   *
+   * @return SUCCESS if the setting will be made
+   */
+  command error_t setAccOffsetBias(int8_t val);
+
+  /**
+   * Signals completion and error, if any, in setting the accumulated
+   * current offset bias value.
+   *
+   * @param error SUCCESS if the setting was successful
+   */
+  async event void setAccOffsetBiasDone( error_t error );
+
+
+}
diff --git a/tos/chips/ds2782/HplDS2782LogicP.nc b/tos/chips/ds2782/HplDS2782LogicP.nc
new file mode 100644 (file)
index 0000000..dcd0266
--- /dev/null
@@ -0,0 +1,324 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arched Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * HplDS2782LogicP is the driver for the Dallas DS2782. It requires 
+ * I2C packet and resource interfaces and provides the HplDS2782 HPL interface.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com> 
+ * @author Phil Buonadonna <pbuonadonna@archrock.com>
+ */
+
+#include "DS2782.h"
+#include "I2C.h"
+
+generic module HplDS2782LogicP(uint16_t devAddr)
+{
+  provides interface StdControl;
+  provides interface HplDS2782;
+
+  uses interface I2CPacket<TI2CBasicAddr>;
+  uses interface Resource as I2CResource;
+
+}
+
+implementation {
+
+  enum {
+    STATE_IDLE,
+    STATE_STOPPED,
+    STATE_SETCONFIG,
+    STATE_READTEMP,
+    STATE_READVOLTAGE,
+    STATE_READCURRENT,
+    STATE_READACCCURRENT,
+    STATE_SETBIAS,
+    STATE_SETACCBIAS,
+    STATE_ALLOWSLEEP
+  };
+
+  uint8_t mI2CBuffer[4];
+  uint8_t mState = STATE_STOPPED;
+  bool read;
+
+  norace error_t mSSError = SUCCESS;
+
+  static error_t doReadReg(uint8_t nextState, uint8_t reg) {
+    error_t error = SUCCESS;
+
+    atomic {
+      if (mState == STATE_IDLE) {
+        mState = nextState;
+      }
+      else {
+        error = EBUSY;
+      }
+    }
+    if (error)
+      return error;
+
+    mI2CBuffer[0] = reg;
+    read = true;
+    error = call I2CResource.request();
+
+    if (error) 
+      atomic mState = STATE_IDLE;
+
+    return error;
+
+  }
+
+  static error_t doSetReg(uint8_t nextState, uint8_t reg, uint16_t val) {
+    error_t error = SUCCESS;
+
+    atomic {
+      if (mState == STATE_IDLE) {
+        mState = nextState;
+      }
+      else {
+        error = EBUSY;
+      }
+    }
+    if (error)
+      return error;
+
+    mI2CBuffer[0] = reg;
+    mI2CBuffer[1] = val;
+
+    read = false;
+    error = call I2CResource.request();
+
+    if (error)
+      atomic mState = STATE_IDLE;
+
+    return error;
+  }
+
+  command error_t StdControl.start() {
+    error_t error = SUCCESS;
+    atomic {
+      if (mState == STATE_STOPPED) { 
+        mState = STATE_IDLE; 
+      }
+      else {
+        error = EBUSY;
+      }
+    }
+    return error;
+  }
+
+  command error_t StdControl.stop() {
+    error_t error = SUCCESS;
+    atomic {
+      if (mState == STATE_IDLE) {
+        mState = STATE_STOPPED;
+      }
+      else {
+        error = EBUSY;
+      }
+    }
+    return error;
+  }
+
+  command error_t HplDS2782.setConfig(uint8_t val) {
+    return doSetReg(STATE_SETCONFIG,DS2782_PTR_SC,val);
+  }
+
+  command error_t HplDS2782.allowSleep(bool allow) {
+    if (allow)
+      return doSetReg(STATE_ALLOWSLEEP,DS2782_PTR_CONTROL,0x60);
+    else 
+      return doSetReg(STATE_ALLOWSLEEP,DS2782_PTR_CONTROL,0x0);
+  }
+
+  command error_t HplDS2782.measureTemperature() { 
+    return doReadReg(STATE_READTEMP,DS2782_PTR_TEMPMSB);
+  }
+
+  command error_t HplDS2782.measureVoltage() { 
+    return doReadReg(STATE_READVOLTAGE,DS2782_PTR_VOLTMSB);
+  }
+
+  command error_t HplDS2782.measureCurrent() { 
+    return doReadReg(STATE_READCURRENT,DS2782_PTR_CURRMSB);
+  }
+
+  command error_t HplDS2782.measureAccCurrent() { 
+    return doReadReg(STATE_READTEMP,DS2782_PTR_ACCURMSB);
+  }
+
+  command error_t HplDS2782.setOffsetBias(int8_t val) { 
+    return doSetReg(STATE_SETBIAS,DS2782_PTR_OFFSETBIAS,val); 
+  }
+
+  command error_t HplDS2782.setAccOffsetBias(int8_t val) {
+    return doSetReg(STATE_SETACCBIAS,DS2782_PTR_ACCBIAS,val); 
+  }
+
+  async event void I2CPacket.readDone(error_t i2c_error, uint16_t chipAddr, uint8_t len, uint8_t *buf) {
+    uint16_t tempVal;
+    tempVal = buf[0];
+    tempVal = ((tempVal << 8) | buf[1]);
+
+    switch (mState) {
+      case STATE_READTEMP:
+        signal HplDS2782.measureTemperatureDone(i2c_error,tempVal);
+        break;
+      case STATE_READVOLTAGE:
+        signal HplDS2782.measureVoltageDone(i2c_error,tempVal);
+        break;
+      case STATE_READCURRENT:
+        signal HplDS2782.measureCurrentDone(i2c_error,tempVal);
+        break;
+      case STATE_READACCCURRENT:
+        signal HplDS2782.measureAccCurrentDone(i2c_error,tempVal);
+        break;
+      default:
+        break;
+    }
+    call I2CResource.release();
+    atomic mState = STATE_IDLE;
+    return;
+  }
+
+  event void I2CResource.granted() {
+    if (read) {
+      call I2CPacket.write(I2C_START,devAddr,1,mI2CBuffer);
+    } else {
+      call I2CPacket.write((I2C_START | I2C_STOP),devAddr,2,mI2CBuffer);
+    }
+  }
+
+  async event void I2CPacket.writeDone(error_t i2c_error, uint16_t chipAddr, uint8_t len, uint8_t *buf) {
+    error_t error = i2c_error;
+
+    switch (mState) {
+      case STATE_SETCONFIG:
+        call I2CResource.release();
+        atomic mState = STATE_IDLE;
+        signal HplDS2782.setConfigDone(error);
+        break;     
+      case STATE_READTEMP:
+        if (error) 
+          signal HplDS2782.measureTemperatureDone(error,0);
+        else
+          error = call I2CPacket.read((I2C_START | I2C_STOP),devAddr,2,mI2CBuffer);
+        break;
+      case STATE_READVOLTAGE:
+        if (error) 
+          signal HplDS2782.measureVoltageDone(error,0);
+        else
+          error = call I2CPacket.read((I2C_START | I2C_STOP),devAddr,2,mI2CBuffer);
+        break;
+      case STATE_READCURRENT:
+        if (error) 
+          signal HplDS2782.measureCurrentDone(error,0);
+        else 
+          error = call I2CPacket.read((I2C_START | I2C_STOP),devAddr,2,mI2CBuffer);
+        break;
+      case STATE_READACCCURRENT:
+        if (error) 
+          signal HplDS2782.measureAccCurrentDone(error,0);
+        else
+          error = call I2CPacket.read((I2C_START | I2C_STOP),devAddr,2,mI2CBuffer);
+        break;
+      case STATE_SETBIAS:
+        call I2CResource.release();
+        atomic mState = STATE_IDLE;
+        signal HplDS2782.setOffsetBiasDone(error);
+        break;
+      case STATE_SETACCBIAS:
+        call I2CResource.release();
+        atomic mState = STATE_IDLE;
+        signal HplDS2782.setAccOffsetBiasDone(error);
+        break;
+      case STATE_ALLOWSLEEP:
+        call I2CResource.release();
+        atomic mState = STATE_IDLE;
+        signal HplDS2782.allowSleepDone(error);
+        break;
+      default:
+        call I2CResource.release();
+        atomic mState = STATE_IDLE;
+        break;
+    }
+    if (error) {
+      call I2CResource.release();
+      atomic mState = STATE_IDLE;
+    }
+    return;
+  }
+
+  default async event void HplDS2782.setConfigDone(error_t error) { return; }
+  default async event void HplDS2782.allowSleepDone( error_t error ) { return; }
+  default async event void HplDS2782.measureTemperatureDone( error_t error, uint16_t val ){ return; }
+  default async event void HplDS2782.measureVoltageDone( error_t error, uint16_t val ){ return; }
+  default async event void HplDS2782.measureCurrentDone( error_t error, uint16_t val ){ return; }
+  default async event void HplDS2782.measureAccCurrentDone( error_t error, uint16_t val ){ return; }
+  default async event void HplDS2782.setOffsetBiasDone( error_t error ){ return; }
+  default async event void HplDS2782.setAccOffsetBiasDone(error_t error){ return; }
+}
diff --git a/tos/chips/m16c62p/McuSleepC.nc b/tos/chips/m16c62p/McuSleepC.nc
new file mode 100755 (executable)
index 0000000..864cca1
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Wiring of TEP 112 (Microcontroller Power Management).
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+configuration McuSleepC
+{
+  provides interface McuSleep;
+  provides interface McuPowerState;
+
+  uses interface McuPowerOverride;
+}
+implementation
+{
+  components McuSleepP,
+      M16c62pControlC;
+
+  McuSleep = McuSleepP;
+  McuPowerState = McuSleepP;
+  McuSleepP = McuPowerOverride;
+  McuSleepP.M16c62pControl -> M16c62pControlC;
+}
diff --git a/tos/chips/m16c62p/McuSleepP.nc b/tos/chips/m16c62p/McuSleepP.nc
new file mode 100755 (executable)
index 0000000..3dffaf8
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Implementation of TEP 112 (Microcontroller Power Management).
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+module McuSleepP
+{
+  provides interface McuSleep;
+  provides interface McuPowerState;
+
+  uses interface McuPowerOverride;
+  uses interface M16c62pControl;
+}
+implementation
+{
+  async command void McuSleep.sleep()
+  {
+    call M16c62pControl.sleep();
+  }
+
+  async command void McuPowerState.update()
+  {
+  }
+
+  default async command mcu_power_t McuPowerOverride.lowestState()
+  {
+    return M16C62P_POWER_STOP;
+  }
+}
diff --git a/tos/chips/m16c62p/adc/Adc.h b/tos/chips/m16c62p/adc/Adc.h
new file mode 100755 (executable)
index 0000000..5b87118
--- /dev/null
@@ -0,0 +1,23 @@
+/* $Id$
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+/*
+ * @author David Gay
+ */
+#ifndef __ADC_H__
+#define __ADC_H__
+
+#include "M16c62pAdc.h"
+
+/* Read and ReadNow share client ids */
+#define UQ_ADC_READ "adc.read"
+#define UQ_ADC_READNOW UQ_ADC_READ
+#define UQ_ADC_READSTREAM "adc.readstream"
+
+#endif  // __ADC_H__
diff --git a/tos/chips/m16c62p/adc/AdcP.nc b/tos/chips/m16c62p/adc/AdcP.nc
new file mode 100755 (executable)
index 0000000..d456c3e
--- /dev/null
@@ -0,0 +1,151 @@
+/* $Id$
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ *
+ * Copyright (c) 2004, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+ * Convert M16c62p HAL A/D interface to the HIL interfaces.
+ * @author Fan Zhang <fanzha@ltu.se>
+ */
+#include "Timer.h"
+
+module AdcP
+{
+  provides {
+    interface Read<uint16_t>[uint8_t client];
+    interface ReadNow<uint16_t>[uint8_t client];
+  }
+  uses {
+    interface M16c62pAdcSingle;
+    interface M16c62pAdcConfig[uint8_t client];
+  }
+}
+implementation {
+  enum {
+    IDLE,
+    ACQUIRE_DATA,
+    ACQUIRE_DATA_NOW,
+  };
+
+  /* Resource reservation is required, and it's incorrect to call getData
+     again before dataReady is signaled, so there are no races in correct
+     programs */
+  norace uint8_t state;
+  norace uint8_t client;
+  norace uint16_t val;
+
+  uint8_t channel() {
+    return call M16c62pAdcConfig.getChannel[client]();
+  }
+
+  uint8_t precision() {
+    return call M16c62pAdcConfig.getPrecision[client]();
+  }
+
+  uint8_t prescaler() {
+    return call M16c62pAdcConfig.getPrescaler[client]();
+  }
+
+  void sample() {
+    call M16c62pAdcSingle.getData(channel(), precision(), prescaler());
+  }
+
+  error_t startGet(uint8_t newState, uint8_t newClient) {
+    /* Note: we retry imprecise results in dataReady */
+    state = newState;
+    client = newClient;
+    sample();
+
+    return SUCCESS;
+  }
+
+  command error_t Read.read[uint8_t c]() {
+    return startGet(ACQUIRE_DATA, c);
+  }
+
+  async command error_t ReadNow.read[uint8_t c]() {
+    return startGet(ACQUIRE_DATA_NOW, c);
+  }
+
+  task void acquiredData() {
+    state = IDLE;
+    signal Read.readDone[client](SUCCESS, val);
+  }
+
+  async event void M16c62pAdcSingle.dataReady(uint16_t data, bool precise) {
+    switch (state)
+    {
+      case ACQUIRE_DATA:
+               if (!precise)
+                 sample();
+               else
+               {
+                   val = data;
+                   post acquiredData();
+               }
+               break;
+
+      case ACQUIRE_DATA_NOW:
+               if (!precise)
+                 sample();
+               else
+               {
+                   state = IDLE;
+                   signal ReadNow.readDone[client](SUCCESS, data);
+               }
+               break;
+
+      default:
+               break;
+     }
+  }
+
+  /* Configuration defaults. Read ground fast! ;-) */
+  default async command uint8_t M16c62pAdcConfig.getChannel[uint8_t c]() {
+    return M16c62p_ADC_CHL_AN0;
+  }
+
+  default async command uint8_t M16c62pAdcConfig.getPrecision[uint8_t c]() {
+    return M16c62p_ADC_PRECISION_10BIT;
+  }
+
+  default async command uint8_t M16c62pAdcConfig.getPrescaler[uint8_t c]() {
+    return M16c62p_ADC_PRESCALE_2;
+  }
+
+  default event void Read.readDone[uint8_t c](error_t e, uint16_t d) { }
+  default async event void ReadNow.readDone[uint8_t c](error_t e, uint16_t d) { }
+}
diff --git a/tos/chips/m16c62p/adc/AdcReadClientC.nc b/tos/chips/m16c62p/adc/AdcReadClientC.nc
new file mode 100755 (executable)
index 0000000..2f8588c
--- /dev/null
@@ -0,0 +1,40 @@
+/* $Id$
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+/**
+ * Provide, as per TEP101, arbitrated access via a Read interface to the
+ * M16c62p ADC.  Users of this component must link it to an
+ * implementation of M16c62pAdcConfig which provides the ADC parameters
+ * (channel, etc).
+ * 
+ * @author Fan Zhang <fanzha@ltu.se>
+ */
+
+#include "Adc.h"
+
+generic configuration AdcReadClientC() {
+  provides interface Read<uint16_t>;
+  uses {
+    interface M16c62pAdcConfig;
+    interface ResourceConfigure;
+  }
+}
+implementation {
+  components WireAdcP, M16c62pAdcC;
+
+  enum {
+    ID = unique(UQ_ADC_READ),
+    HAL_ID = unique(UQ_M16c62pADC_RESOURCE)
+  };
+
+  Read = WireAdcP.Read[ID];
+  M16c62pAdcConfig = WireAdcP.M16c62pAdcConfig[ID];
+  WireAdcP.Resource[ID] -> M16c62pAdcC.Resource[HAL_ID];
+  ResourceConfigure = M16c62pAdcC.ResourceConfigure[HAL_ID];
+}
diff --git a/tos/chips/m16c62p/adc/AdcReadNowClientC.nc b/tos/chips/m16c62p/adc/AdcReadNowClientC.nc
new file mode 100755 (executable)
index 0000000..aac167a
--- /dev/null
@@ -0,0 +1,43 @@
+/* $Id$
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+/**
+ * Provide, as per TEP101, Resource-based access to the M16c62p ADC via a
+ * ReadNow interface.  Users of this component must link it to an
+ * implementation of M16c62pAdcConfig which provides the ADC parameters
+ * (channel, etc).
+ * 
+ * @author Fan Zhang <fanzha@ltu.se>
+ */
+
+#include "Adc.h"
+
+generic configuration AdcReadNowClientC() {
+  provides {
+    interface Resource;
+    interface ReadNow<uint16_t>;
+  }
+  uses {
+    interface M16c62pAdcConfig;
+    interface ResourceConfigure;
+  }
+}
+implementation {
+  components WireAdcP, M16c62pAdcC;
+
+  enum {
+    ID = unique(UQ_ADC_READNOW),
+    HAL_ID = unique(UQ_M16c62pADC_RESOURCE)
+  };
+
+  ReadNow = WireAdcP.ReadNow[ID];
+  M16c62pAdcConfig = WireAdcP.M16c62pAdcConfig[ID];
+  Resource = M16c62pAdcC.Resource[HAL_ID];
+  ResourceConfigure = M16c62pAdcC.ResourceConfigure[HAL_ID];
+}
diff --git a/tos/chips/m16c62p/adc/AdcReadStreamClientC.nc b/tos/chips/m16c62p/adc/AdcReadStreamClientC.nc
new file mode 100755 (executable)
index 0000000..9886d13
--- /dev/null
@@ -0,0 +1,40 @@
+/* $Id$
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+/**
+ * Provide, as per TEP101, arbitrated access via a ReadStream interface to
+ * the M16c62p ADC.  Users of this component must link it to an
+ * implementation of M16c62pAdcConfig which provides the ADC parameters
+ * (channel, etc).
+ * 
+ * @author Fan Zhang <fanzha@ltu.se>
+ */
+
+#include "Adc.h"
+
+generic configuration AdcReadStreamClientC() {
+  provides interface ReadStream<uint16_t>;
+  uses {
+    interface M16c62pAdcConfig;
+    interface ResourceConfigure;
+  }
+}
+implementation {
+  components WireAdcStreamP, M16c62pAdcC;
+
+  enum {
+    ID = unique(UQ_ADC_READSTREAM),
+    HAL_ID = unique(UQ_M16c62pADC_RESOURCE)
+  };
+
+  ReadStream = WireAdcStreamP.ReadStream[ID];
+  M16c62pAdcConfig = WireAdcStreamP.M16c62pAdcConfig[ID];
+  WireAdcStreamP.Resource[ID] -> M16c62pAdcC.Resource[HAL_ID];
+  ResourceConfigure = M16c62pAdcC.ResourceConfigure[HAL_ID];
+}
diff --git a/tos/chips/m16c62p/adc/AdcStreamP.nc b/tos/chips/m16c62p/adc/AdcStreamP.nc
new file mode 100755 (executable)
index 0000000..bb65d24
--- /dev/null
@@ -0,0 +1,270 @@
+/* $Id$
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ *
+ * Copyright (c) 2004, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/**
+ * Convert M16c62p HAL A/D interface to the HIL interfaces.
+ * @author Fan Zhang <hauer@tkn.tu-berlin.de>
+ */
+#include "Timer.h"
+
+module AdcStreamP
+{
+  provides {
+    interface Init @atleastonce();
+    interface ReadStream<uint16_t>[uint8_t client];
+  }
+  uses {
+    interface M16c62pAdcSingle;
+    interface M16c62pAdcConfig[uint8_t client];
+    //interface M16c62pCalibrate;
+    interface Alarm<TMicro, uint32_t>;
+  }
+}
+implementation {
+  enum {
+    NSTREAM = uniqueCount(UQ_ADC_READSTREAM)
+  };
+
+  /* Resource reservation is required, and it's incorrect to call getData
+     again before dataReady is signaled, so there are no races in correct
+     programs */
+  norace uint8_t client = NSTREAM;
+
+  /* Stream data */
+  struct list_entry_t {
+    uint16_t count;
+    struct list_entry_t * ONE_NOK next;
+  };
+  struct list_entry_t *bufferQueue[NSTREAM];
+  struct list_entry_t * ONE_NOK * bufferQueueEnd[NSTREAM];
+  uint16_t * COUNT_NOK(lastCount) lastBuffer, lastCount;
+
+  norace uint16_t count;
+  norace uint16_t * COUNT_NOK(count) buffer; 
+  norace uint16_t * BND_NOK(buffer, buffer+count) pos;
+  norace uint32_t now, period;
+
+
+  command error_t Init.init() {
+    uint8_t i;
+
+    for (i = 0; i != NSTREAM; i++)
+      bufferQueueEnd[i] = &bufferQueue[i];
+    
+    return SUCCESS;
+  }
+
+  uint8_t channel() {
+    return call M16c62pAdcConfig.getChannel[client]();
+  }
+
+  uint8_t precision() {
+    return call M16c62pAdcConfig.getPrecision[client]();
+  }
+
+  uint8_t prescaler() {
+    return call M16c62pAdcConfig.getPrescaler[client]();
+  }
+
+  void sample() {
+    call M16c62pAdcSingle.getData(channel(), precision(), prescaler());
+  }
+
+  command error_t ReadStream.postBuffer[uint8_t c](uint16_t *buf, uint16_t n) {
+    if (n < sizeof(struct list_entry_t))
+      return ESIZE;
+    atomic
+      {
+       struct list_entry_t * ONE newEntry = TCAST(struct list_entry_t * ONE, buf);
+
+       if (!bufferQueueEnd[c]) // Can't post right now.
+         return FAIL;
+
+       newEntry->count = n;
+       newEntry->next = NULL;
+       *bufferQueueEnd[c] = newEntry;
+       bufferQueueEnd[c] = &newEntry->next;
+      }
+    return SUCCESS;
+  }
+
+  task void readStreamDone() {
+    uint8_t c = client;
+    //uint32_t actualPeriod = call M16c62pCalibrate.actualMicro(period);
+    uint32_t actualPeriod = period; // fanzha not debug
+    atomic
+      {
+       bufferQueue[c] = NULL;
+       bufferQueueEnd[c] = &bufferQueue[c];
+      }
+
+    client = NSTREAM;
+    signal ReadStream.readDone[c](SUCCESS, actualPeriod);
+  }
+
+  task void readStreamFail() {
+    /* By now, the pending bufferDone has been signaled (see readStream). */
+    struct list_entry_t *entry;
+    uint8_t c = client;
+
+    atomic entry = bufferQueue[c];
+    for (; entry; entry = entry->next){
+      uint16_t tmp_count __DEPUTY_UNUSED__ = entry->count;
+      signal ReadStream.bufferDone[c](FAIL, TCAST(uint16_t * COUNT_NOK(tmp_count),entry), entry->count);
+    }
+
+    atomic
+      {
+       bufferQueue[c] = NULL;
+       bufferQueueEnd[c] = &bufferQueue[c];
+      }
+
+    client = NSTREAM;
+    signal ReadStream.readDone[c](FAIL, 0);
+  }
+
+  task void bufferDone() {
+    uint16_t *b, c;
+    atomic
+      {
+       b = lastBuffer;
+       c = lastCount;
+       lastBuffer = NULL;
+      }
+
+    signal ReadStream.bufferDone[client](SUCCESS, b, c);
+  }
+
+  void nextAlarm() {
+    call Alarm.startAt(now, period);
+    now += period;
+  }
+
+  async event void Alarm.fired() {
+    sample();
+  }
+
+  command error_t ReadStream.read[uint8_t c](uint32_t usPeriod)
+  {
+    /* The first reading may be imprecise. So we just do a dummy read
+       to get things rolling - this is indicated by setting count to 0 */
+    buffer = pos = NULL;
+    count = 0;
+    //period = call M16c62pCalibrate.calibrateMicro(usPeriod);
+    client = c;
+    sample();
+
+    return SUCCESS;
+  }
+
+  void nextBuffer() {
+    atomic
+      {
+       struct list_entry_t *entry = bufferQueue[client];
+
+       if (!entry)
+         {
+           // all done
+           bufferQueueEnd[client] = NULL; // prevent post
+           post readStreamDone();
+         }
+       else
+         {
+            uint16_t tmp_count;
+           bufferQueue[client] = entry->next;
+           if (!bufferQueue[client])
+             bufferQueueEnd[client] = &bufferQueue[client];
+           pos = buffer = NULL;
+           count = entry->count;
+            tmp_count = count;
+           pos = buffer = TCAST(uint16_t * COUNT_NOK(tmp_count), entry);
+           nextAlarm();
+         }
+      }
+  }
+
+  async event void M16c62pAdcSingle.dataReady(uint16_t data, bool precise) {
+    if (client == NSTREAM)
+      return;
+
+    if (count == 0)
+      {
+       now = call Alarm.getNow();
+       nextBuffer();
+      }
+    else
+      {
+       *pos++ = data;
+       if (pos == buffer + count)
+         {
+           atomic
+             {
+               if (lastBuffer)
+                 {
+                   /* We failed to signal bufferDone in time. Fail. */
+                   bufferQueueEnd[client] = NULL; // prevent post
+                   post readStreamFail();
+                   return;
+                 }
+               else
+                 {
+                   lastCount = count;
+                   lastBuffer = buffer;
+                 }
+             }
+           post bufferDone();
+           nextBuffer();
+         }
+       else
+         nextAlarm();
+      }       
+  }
+
+  /* Configuration defaults. Read ground fast! ;-) */
+  default async command uint8_t M16c62pAdcConfig.getChannel[uint8_t c]() {
+    return M16c62p_ADC_CHL_AN0;
+  }
+
+  default async command uint8_t M16c62pAdcConfig.getPrecision[uint8_t c]() {
+    return M16c62p_ADC_PRECISION_10BIT;
+  }
+
+  default async command uint8_t M16c62pAdcConfig.getPrescaler[uint8_t c]() {
+    return M16c62p_ADC_PRESCALE_2;
+  }
+}
diff --git a/tos/chips/m16c62p/adc/HplM16c62pAdc.nc b/tos/chips/m16c62p/adc/HplM16c62pAdc.nc
new file mode 100755 (executable)
index 0000000..71f82ac
--- /dev/null
@@ -0,0 +1,165 @@
+/// $Id$
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ */
+
+#include "M16c62pAdc.h"
+
+/**
+ * HPL interface to the M16c62p A/D conversion subsystem. 
+ * <p>
+ * conversion when the ADC and ADC interrupt are enabled.
+ *
+ * @author Martin Turon <mturon@xbow.com>
+ * @author Hu Siquan <husq@xbow.com>
+ * @author David Gay
+ */
+
+interface HplM16c62pAdc {
+  /**
+   * Read the ADCON0 (ADC control register 0)
+   * @return Current ADCON0 value
+   */
+  async command M16c62pADCON0_t getADCON0();
+  /**
+   * Set the ADCON0 (ADC control register 0)
+   * @param adcon0 New ADCON0 value
+   */
+  async command void setADCON0(M16c62pADCON0_t adcon0);
+/////////////////////////////////////////////////////////////////////////////////
+  /**
+   * Read the ADCON1 (ADC control) register
+   * @return Current ADCON1 value
+   */
+  async command M16c62pADCON1_t getADCON1();
+  /**
+   * Set the ADCON1 (ADC control) register
+   * @param adcon1 New ADCON1 value
+   */
+  async command void setADCON1(M16c62pADCON1_t adcon1);
+//////////////////////////////////////////////////////////////////////////////////   
+  /**
+   * Read the ADCON2 (ADC control) register
+   * @return Current ADCON2 value
+   */
+  async command M16c62pADCON2_t getADCON2();
+  /**
+   * Set the ADCON2 (ADC control) register
+   * @param adcon2 New ADCON2 value
+   */
+  async command void setADCON2(M16c62pADCON2_t adcon2);
+/////////////////////////////////////////////////////////////////////////////////
+  /**
+   * Read the latest A/D conversion result
+   * @return A/D value
+   */
+  async command uint16_t getValue();
+
+  /// A/D control utilities. All of these clear any pending A/D interrupt.
+
+  /**
+   * Enable ADC sampling
+   */
+  async command void enableAdc();
+  /**
+   * Disable ADC sampling
+   */
+  async command void disableAdc();
+
+  /**
+   * Enable ADC interrupt
+   */
+  async command void enableInterruption();
+  /**
+   * Disable ADC interrupt
+   */
+  async command void disableInterruption();
+  /**
+   * Clear the ADC interrupt flag
+   */
+  async command void resetInterrupt();
+
+  /**
+   * Start ADC conversion. If ADC interrupts are enabled, the dataReady event
+   * will be signaled once (in non-continuous mode) or repeatedly (in
+   * continuous mode).
+   */
+  async command void startConversion();
+  /**
+   * Enable continuous sampling
+   */
+  async command void setContinuous();
+  /**
+   * Disable continuous sampling
+   */
+  async command void setSingle();
+
+  /* A/D status checks */
+
+  /**
+   * Is ADC enabled?
+   * @return TRUE if the ADC is enabled, FALSE otherwise
+   */
+  async command bool isEnabled();
+  /**
+   * Is A/D conversion in progress?
+   * @return TRUE if the A/D conversion is in progress, FALSE otherwise
+   */
+  async command bool isStarted();
+  /**
+   * Is A/D conversion complete? Note that this flag is automatically
+   * cleared when an A/D interrupt occurs.
+   * @return TRUE if the A/D conversion is complete, FALSE otherwise
+   */
+  async command bool isComplete();
+  
+  
+  /**
+   * Set ADC precision selection bits
+   * @param scale New ADC prescision. Must be one of the M16c62p_ADC_PRECISION_xxx
+   *   values from M16c62pAdc.h
+   */
+  async command void setPrecision(uint8_t precision);
+  
+  /**
+   * Set ADC prescaler selection bits
+   * @param scale New ADC prescaler. Must be one of the M16c62p_ADC_PRESCALE_xxx
+   *   values from M16c62pAdc.h
+   */
+  async command void setPrescaler(uint8_t scale);
+
+  /**
+   * Cancel A/D conversion and any pending A/D interrupt. Also disables the
+   * ADC interruption (otherwise a sample might start at the next sleep
+   * instruction). This command can assume that the A/D converter is enabled. 
+   * @return TRUE if an A/D conversion was in progress or an A/D interrupt
+   *   was pending, FALSE otherwise. In single conversion mode, a return
+   *   of TRUE implies that the dataReady event will not be signaled.
+   */
+  async command bool cancel();
+
+  /**
+   * A/D interrupt occured
+   * @param data Latest A/D conversion result
+   */
+  async event void dataReady(uint16_t data);     
+}
diff --git a/tos/chips/m16c62p/adc/HplM16c62pAdcC.nc b/tos/chips/m16c62p/adc/HplM16c62pAdcC.nc
new file mode 100755 (executable)
index 0000000..b38ca0c
--- /dev/null
@@ -0,0 +1,43 @@
+/// $Id$
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ */
+
+#include "M16c62pAdc.h"
+
+/**
+ * HPL for the M16c62p A/D conversion susbsystem.
+ *
+ * @author Martin Turon <mturon@xbow.com>
+ * @author Hu Siquan <husq@xbow.com>
+ * @author David Gay
+ */
+
+configuration HplM16c62pAdcC {
+  provides interface HplM16c62pAdc;
+}
+implementation {
+  components HplM16c62pAdcP, McuSleepC;
+
+  HplM16c62pAdc = HplM16c62pAdcP;
+  HplM16c62pAdcP.McuPowerState -> McuSleepC;
+}
diff --git a/tos/chips/m16c62p/adc/HplM16c62pAdcP.nc b/tos/chips/m16c62p/adc/HplM16c62pAdcP.nc
new file mode 100755 (executable)
index 0000000..01dea2d
--- /dev/null
@@ -0,0 +1,160 @@
+/// $Id$
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ */
+
+#include "M16c62pAdc.h"
+
+/**
+ * HPL for the M16c62p A/D conversion susbsystem.
+ *
+ * @author Fan Zhang <fanzha@ltu.se>
+ *
+ */
+
+module HplM16c62pAdcP
+{
+  provides interface HplM16c62pAdc;
+  uses interface McuPowerState;
+}
+implementation
+{
+  //=== Direct read of HW registers. =================================
+  async command M16c62pADCON0_t HplM16c62pAdc.getADCON0() { 
+    return *(M16c62pADCON0_t*)&ADCON0; 
+  }
+  async command M16c62pADCON1_t HplM16c62pAdc.getADCON1() { 
+    return *(M16c62pADCON1_t*)&ADCON1; 
+  }
+  async command M16c62pADCON2_t HplM16c62pAdc.getADCON2() { 
+    return *(M16c62pADCON2_t*)&ADCON2; 
+  }
+  async command uint16_t HplM16c62pAdc.getValue() { 
+    uint8_t channel = ADCON0.BYTE&0x07;
+    if(channel==0x00){return AD0.WORD;}
+    else if(channel==0x01){return AD1.WORD;}
+    else if(channel==0x02){return AD2.WORD;}
+    else if(channel==0x03){return AD3.WORD;}
+    else if(channel==0x04){return AD4.WORD;}
+    else if(channel==0x05){return AD5.WORD;}
+    else if(channel==0x06){return AD6.WORD;}
+    else {return AD7.WORD;}
+     
+  }
+
+  DEFINE_UNION_CAST(ADCON02int, M16c62pADCON0_t, uint8_t); // type change from M16c62pADCON0_t to uint8_t
+  DEFINE_UNION_CAST(ADCON12int, M16c62pADCON1_t, uint8_t);
+  DEFINE_UNION_CAST(ADCON22int, M16c62pADCON2_t, uint8_t);
+
+  //=== Direct write of HW registers. ================================
+  async command void HplM16c62pAdc.setADCON0( M16c62pADCON0_t x ) { 
+    ADCON0.BYTE = ADCON02int(x); 
+  }
+  async command void HplM16c62pAdc.setADCON1( M16c62pADCON1_t x ) { 
+    ADCON1.BYTE = ADCON12int(x); 
+  }
+  async command void HplM16c62pAdc.setADCON2( M16c62pADCON2_t x ) { 
+    ADCON2.BYTE = ADCON22int(x); 
+  }
+  /* precision = 8 or 10, that means 8bit or 10bit */ 
+  async command void HplM16c62pAdc.setPrecision(uint8_t precision){
+    if(precision == M16c62p_ADC_PRECISION_8BIT)
+      ADCON1.BIT.BITS = 0;    
+    else if(precision == M16c62p_ADC_PRECISION_10BIT)
+      ADCON1.BIT.BITS = 1;
+  }
+  /* Set ADC prescaler selection bits */
+  async command void HplM16c62pAdc.setPrescaler(uint8_t scale){
+    
+    if(scale == 0x00){ADCON2.BIT.CKS2=0;ADCON1.BIT.CKS1=0;ADCON0.BIT.CKS0=0;} // fAD/4 prescaler
+    else if(scale == 0x01){ADCON2.BIT.CKS2=0;ADCON1.BIT.CKS1=0;ADCON0.BIT.CKS0=1;} // fAD/2 prescaler
+    else if((scale == 0x02) || (scale == 0x03)){ADCON2.BIT.CKS2=0;ADCON1.BIT.CKS1=1;ADCON0.BIT.CKS0=0;} // fAD prescaler
+    else if(scale == 0x04){ADCON2.BIT.CKS2=1;ADCON1.BIT.CKS1=0;ADCON0.BIT.CKS0=0;} // fAD/12 prescaler
+    else if(scale == 0x05){ADCON2.BIT.CKS2=1;ADCON1.BIT.CKS1=0;ADCON0.BIT.CKS0=1;} // fAD/6 prescaler
+    else if((scale == 0x06) || (scale == 0x07)){ADCON2.BIT.CKS2=1;ADCON1.BIT.CKS1=1;ADCON0.BIT.CKS0=0;} // fAD/3 prescaler
+    
+  }
+
+  // Individual bit manipulation. These all clear any pending A/D interrupt.
+  async command void HplM16c62pAdc.enableAdc() {
+    ADCON1.BIT.VCUT = 1; 
+    call McuPowerState.update();
+  }
+  async command void HplM16c62pAdc.disableAdc() {
+    ADCON1.BIT.VCUT = 0; 
+    call McuPowerState.update();
+  }
+  // A/D conversion interrupt control register is ADIC 2009-2-9 by Fan Zhang
+  async command void HplM16c62pAdc.enableInterruption() { ADIC.BIT.ILVL2=0;ADIC.BIT.ILVL1=0;ADIC.BIT.ILVL0=1; }
+  async command void HplM16c62pAdc.disableInterruption() { ADIC.BIT.ILVL2=0;ADIC.BIT.ILVL1=0;ADIC.BIT.ILVL0=0; }
+  async command void HplM16c62pAdc.startConversion() { ADCON0.BIT.ADST=1; } // ADST=6
+  async command void HplM16c62pAdc.resetInterrupt() { } // Clear the ADC interrupt flag
+  /**
+   * Enable continuous sampling, that is repeat sampling mode
+   */
+  async command void HplM16c62pAdc.setContinuous() {  ADCON0.BIT.MD0=0;ADCON0.BIT.MD1=1;  }
+  /**
+   * Disable continuous sampling, enable one-shot sampling mode
+   */
+  async command void HplM16c62pAdc.setSingle() { ADCON0.BIT.MD0=0;ADCON0.BIT.MD1=0; }
+  
+  /* A/D status checks */
+  async command bool HplM16c62pAdc.isEnabled(){       
+    // ADCON1.VCUT control the Vref connection, 0 disable connection, 1 connection
+    return ADCON1.BIT.VCUT; 
+  }
+
+  async command bool HplM16c62pAdc.isStarted() {
+    return ADCON0.BIT.ADST; 
+  }
+  
+  async command bool HplM16c62pAdc.isComplete() {
+    // interrupt flag bit
+    return ADIC.BIT.IR; 
+  }
+  
+  
+  /* A/D interrupt handlers. Signals dataReady event with interrupts enabled */
+  default async event void HplM16c62pAdc.dataReady(uint16_t done) { }
+  M16C_INTERRUPT_HANDLER(M16C_AD)
+  {
+    uint16_t data = call HplM16c62pAdc.getValue();
+    
+    __nesc_enable_interrupt();
+    signal HplM16c62pAdc.dataReady(data);
+  }
+
+  async command bool HplM16c62pAdc.cancel() { 
+    /* This is tricky */
+    atomic
+    {
+           /* To cancel a conversion, first turn off ADEN, then turn off
+              ADSC. We also cancel any pending interrupt.
+              Finally we reenable the ADC.
+           */
+           //ADCON1.VCUT=0;
+           //ADIC.ILVL2=0;ADIC.ILVL1=0;ADIC.ILVL0=0; /* This disable ADC interrupt... */
+           ADCON0.BIT.ADST=0;
+           //ADCON1.VCUT=1;
+           return TRUE;
+     }
+  }
+}
diff --git a/tos/chips/m16c62p/adc/M16c62pAdc.h b/tos/chips/m16c62p/adc/M16c62pAdc.h
new file mode 100755 (executable)
index 0000000..a8d4ba9
--- /dev/null
@@ -0,0 +1,168 @@
+// $Id$
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
+ * MODIFICATIONS.
+ */
+
+// @author Martin Turon <mturon@xbow.com>
+// @author Hu Siquan <husq@xbow.com>
+
+#ifndef __H_M16C62PADC_H__
+#define __H_M16C62PADC_H__
+
+//================== 8 channel 10-bit ADC ==============================
+
+/* Voltage Reference Settings */
+enum {
+    M16c62p_ADC_VREF_OFF = 0, //!< VR+ = AREF   and VR- = GND
+    M16c62p_ADC_VREF_AVCC = 1,//!< VR+ = AVcc   and VR- = GND
+};
+
+/* Voltage Reference Settings */
+enum {
+    M16c62p_ADC_RIGHT_ADJUST = 0,
+    M16c62p_ADC_LEFT_ADJUST = 1,
+};
+
+
+/* ADC Channel Settings */
+enum {
+    M16c62p_ADC_CHL_AN0 = 0,
+    M16c62p_ADC_CHL_AN1,
+    M16c62p_ADC_CHL_AN2,
+    M16c62p_ADC_CHL_AN3,
+    M16c62p_ADC_CHL_AN4,
+    M16c62p_ADC_CHL_AN5,
+    M16c62p_ADC_CHL_AN6,
+    M16c62p_ADC_CHL_AN7,
+    M16c62p_ADC_CHL_AN10 = 8,
+    M16c62p_ADC_CHL_AN11,
+    M16c62p_ADC_CHL_AN12,
+    M16c62p_ADC_CHL_AN13,
+    M16c62p_ADC_CHL_AN14,
+    M16c62p_ADC_CHL_AN15,
+    M16c62p_ADC_CHL_AN16,
+    M16c62p_ADC_CHL_AN17,
+
+};
+
+/* ADC Control Register 0 */
+typedef struct
+{
+    uint8_t ch012   : 3;  //!< Analog Channel and Gain Selection Bits
+    uint8_t md01   : 2;  //!< ADC operation mode select bit
+    uint8_t trg : 1;  //!< Trigger select bit
+    uint8_t adst  : 1;  //!< ADC start flag
+    uint8_t cks0  :1;  //!< Frequency Selection Bit 0
+} M16c62pADCON0_t;
+
+/* ADC Control Register 1 */
+typedef struct
+{
+    uint8_t scan01  : 2;  //!< ADC scan mode select bit
+    uint8_t md2  : 1;  //!< ADC operation mode select bit 1
+    uint8_t bits  : 1;  //!< 8/10-bit mode select bit
+    uint8_t cks1  : 1;  //!< Frequency select bit 1
+    uint8_t vcut  : 1;  //!< Vref connect bit
+    uint8_t opa01  : 2;  //!< External op-amp connection mode bit
+} M16c62pADCON1_t;
+
+/* ADC Control Register 2 */
+typedef struct
+{
+    uint8_t smp  : 1;  //!< ADC method select bit
+    uint8_t adgsel01  : 2;  //!< port group select: 00 select P10 group
+                            //                      01 select NULL
+                            //                      10 select P0 group
+                            //                      11 select P2 group
+    uint8_t bit3  : 1;  //!< reserved bit (always set to 0)
+    uint8_t cks2  : 1;  //!< Frequency select bit 2
+    uint8_t bit5  : 1;  //!< nothing assigned.
+    uint8_t bit6  : 1;  //!< nothing assigned.
+    uint8_t bit7  : 1;  //!< nothing assigned.
+} M16c62pADCON2_t;
+
+/* ADC Prescaler Settings */
+/* Note: each platform must define M16c62p_ADC_PRESCALE to the smallest
+   prescaler which guarantees full A/D precision. */
+enum {
+    M16c62p_ADC_PRESCALE_2 = 1,
+    M16c62p_ADC_PRESCALE_3 = 6,
+    M16c62p_ADC_PRESCALE_4 = 0,
+    M16c62p_ADC_PRESCALE_6 = 5,
+    M16c62p_ADC_PRESCALE_12 = 4,
+
+    // This special value is used to ask the platform for the prescaler
+    // which gives full precision.
+    M16c62p_ADC_PRESCALE = 2,
+};
+
+/* ADC Precision Settings */
+enum {
+    M16c62p_ADC_PRECISION_10BIT = 0,
+    M16c62p_ADC_PRECISION_8BIT,
+};
+
+/* ADC operation mode select bit */
+enum {
+    M16c62p_ADC_ONESHOT_MODE = 0,
+    M16c62p_ADC_REPEAT_MODE,
+};
+
+/* ADC Enable Settings */
+enum {
+    M16c62p_ADC_ENABLE_OFF = 0,
+    M16c62p_ADC_ENABLE_ON,
+};
+
+/* ADC Start Conversion Settings */
+enum {
+    M16c62p_ADC_START_CONVERSION_OFF = 0,
+    M16c62p_ADC_START_CONVERSION_ON,
+};
+
+/* ADC Free Running Select Settings */
+enum {
+    M16c62p_ADC_FREE_RUNNING_OFF = 0,
+    M16c62p_ADC_FREE_RUNNING_ON,
+};
+
+/* ADC Interrupt Flag Settings */
+enum {
+    M16c62p_ADC_INT_FLAG_OFF = 0,
+    M16c62p_ADC_INT_FLAG_ON,
+};
+
+/* ADC Interrupt Enable Settings */
+enum {
+    M16c62p_ADC_INT_ENABLE_OFF = 0,
+    M16c62p_ADC_INT_ENABLE_ON,
+};
+
+
+typedef uint8_t M16c62p_ADCH_t;         //!< ADC data register high
+typedef uint8_t M16c62p_ADCL_t;         //!< ADC data register low
+
+// The resource identifier string for the ADC subsystem
+#define UQ_M16c62pADC_RESOURCE "M16c62padc.resource"
+
+#endif //  __H_M16C62PADC_H_
+
diff --git a/tos/chips/m16c62p/adc/M16c62pAdcC.nc b/tos/chips/m16c62p/adc/M16c62pAdcC.nc
new file mode 100755 (executable)
index 0000000..0e1ec3d
--- /dev/null
@@ -0,0 +1,69 @@
+/// $Id$
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+#include "M16c62pAdc.h"
+
+/**
+ * HAL for the M16c62p A/D conversion susbsystem.
+ *
+ * @author Hu Siquan <husq@xbow.com>
+ * @author David Gay
+ */
+
+configuration M16c62pAdcC
+{
+  provides {
+    interface Resource[uint8_t client];
+    interface M16c62pAdcSingle;
+    interface M16c62pAdcMultiple;
+  }
+  uses interface ResourceConfigure[uint8_t client];
+}
+implementation
+{
+  components M16c62pAdcP, HplM16c62pAdcC, PlatformC, MainC,
+    new RoundRobinArbiterC(UQ_M16c62pADC_RESOURCE) as AdcArbiter,
+    new AsyncStdControlPowerManagerC() as PM;
+
+  Resource = AdcArbiter;
+  ResourceConfigure = AdcArbiter;
+  M16c62pAdcSingle = M16c62pAdcP;
+  M16c62pAdcMultiple = M16c62pAdcP;
+
+  PlatformC.SubInit -> M16c62pAdcP;
+
+  M16c62pAdcP.HplM16c62pAdc -> HplM16c62pAdcC;
+  //M16c62pAdcP.M16c62pCalibrate -> PlatformC;
+
+  PM.AsyncStdControl -> M16c62pAdcP;
+  PM.ResourceDefaultOwner -> AdcArbiter;
+}
diff --git a/tos/chips/m16c62p/adc/M16c62pAdcConfig.nc b/tos/chips/m16c62p/adc/M16c62pAdcConfig.nc
new file mode 100755 (executable)
index 0000000..5323e52
--- /dev/null
@@ -0,0 +1,42 @@
+/* $Id$
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+#include "M16c62pAdc.h"
+
+/**
+ * Clients of higher level must provide this interface to
+ * specify which channel to sample, and with what parameters.
+ *
+ * @author Fan Zang <fanzha@ltu.se>
+ */
+interface M16c62pAdcConfig {
+  /**
+   * Obtain channel.
+   * @return The A/D channel to use. Must be one of the M16c62p_ADC_CHL_xxx
+   *    values from M16c62pAdc.h.
+   */
+  async command uint8_t getChannel();
+
+  /**
+   * Obtain precision setting
+   * @return The reference voltage to use. Must be one of the 
+   *   M16c62p_ADC_CHL_ANxx values from M16c62pAdc.h.
+   */
+  async command uint8_t getPrecision();
+
+  /**
+   * Obtain prescaler value.
+   * @return The prescaler value to use. Must be one of the 
+   *   M16c62p_ADC_PRESCALE_xxx values from M16c62pAdc.h.
+   */
+  async command uint8_t getPrescaler();
+  
+  
+}
diff --git a/tos/chips/m16c62p/adc/M16c62pAdcMultiple.nc b/tos/chips/m16c62p/adc/M16c62pAdcMultiple.nc
new file mode 100755 (executable)
index 0000000..06fa4ba
--- /dev/null
@@ -0,0 +1,119 @@
+/// $Id$
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ * Copyright (c) 2002-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ * Hardware Abstraction Layer interface of Atmega128 for acquiring data
+ * from multiple channels using the ATmega128's free-running mode.
+ * <p>
+ * Because of the possibility that samples may be imprecise after 
+ * switching channels and/or reference voltages, and because there
+ * is a one sample delay on swithcing channels and reference voltages,
+ * M16c62pADCMultiple is complex. Two straightforward uses are:
+ * <ol type="A">
+ * <li>Acquire N samples from channel C:
+ *    <ol>
+ *    <li>call getData to start sampling on channel C at the desired rate
+ *       (note that the choice of prescalers is very limited, so you
+ *       don't have many choices for sampling rate)
+ *    <li>ignore the first dataReady event
+ *    <li>use the results of the next N dataReady() events, return FALSE
+ *       on the last one
+ *    </ol>
+ * <li>Acquire one sample each from channels C1, ..., Cn (this pseudocode
+ *    assumes that none of these channels are differential)
+ *    <ol>
+ *    <li>call getData to start sampling on channel C1
+ *    <li>on the ith dataReady event switch to channel Ci+1 by changing
+ *       *newChannel
+ *    <li>the data passed to the ith dataReady event is for channel Ci-1
+ *       (the data from the first dataReady event is ignored)
+ *    </ol>
+ * </ol>
+ *
+ * @author Hu Siquan <husq@xbow.com>
+ * @author David Gay
+ */        
+
+#include "M16c62pAdc.h"
+
+interface M16c62pAdcMultiple
+{
+  /**
+   * Initiates free-running ADC conversions, with the ability to switch 
+   * channels and reference-voltage with a one sample delay.
+   *
+   * @param channel Initial A/D conversion channel. The channel can 
+   *   be changed in the dataReady event, though these changes happen
+   *   with a one-sample delay (this is a hardware restriction).
+   * @param refVoltage Initial A/D reference voltage. See the
+   *   M16c62p_ADC_VREF_xxx constants in M16c62pADC.h. Like the channel,
+   *   the reference voltage can be changed in the dataReady event with
+   *   a one-sample delay.
+   * @param leftJustify TRUE to place A/D result in high-order bits 
+   *   (i.e., shifted left by 6 bits), low to place it in the low-order bits
+   * @param prescaler Prescaler value for the A/D conversion clock. If you 
+   *  specify M16c62p_ADC_PRESCALE, a prescaler will be chosen that guarantees
+   *  full precision. Other prescalers can be used to get faster conversions. 
+   *  See the ATmega128 manual for details.
+   * @return TRUE if the conversion will be precise, FALSE if it will be 
+   *   imprecise (due to a change in reference voltage, or switching to a
+   *   differential input channel)
+   */
+  async command bool getData(uint8_t channel, uint8_t precision, uint8_t prescaler);
+  
+  /**
+   * Returns the next sample in a free-running conversion. Allow the user
+   * to switch channels and/or reference voltages with a one sample delay.
+   *
+   * @param data a 2 byte unsigned data value sampled by the ADC.
+   * @param precise if this conversion was precise, FALSE if it wasn't 
+   *   (we assume that the second conversion after a change of reference
+   *   voltage or after switching to a differential channel is precise)
+   * @param channel Channel this sample was from.
+   * @param newChannel Change this parameter to switch to a new channel
+   *   for the second next sample.
+   * @param newRefVoltage Change this parameter to change the reference 
+   *   voltage for the second next sample.
+   *
+   * @return TRUE to continue sampling, FALSE to stop.
+   */  
+  async event bool dataReady(uint16_t data, bool precise, uint8_t channel,
+                            uint8_t *newChannel, uint8_t *newRefVoltage);
+
+
+  /* Note: there is no cancel in free-running mode because you cannot tell
+     from a successful (or unsuccessful) cancellation whether there will
+     be another dataReady event. Thus you cannot tell when you can safely
+     reuse the ADC (short of waiting one ADC conversion period, in which
+     case you might as well use the result of dataReady to cancel).
+  */
+}
diff --git a/tos/chips/m16c62p/adc/M16c62pAdcP.nc b/tos/chips/m16c62p/adc/M16c62pAdcP.nc
new file mode 100755 (executable)
index 0000000..ed340b9
--- /dev/null
@@ -0,0 +1,220 @@
+/* $Id$
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ *
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ */
+
+#include "M16c62pAdc.h"
+
+/**
+ * Internal component of the M16c62p A/D HAL.
+ *
+ * @author Fan Zhang
+ */
+
+module M16c62pAdcP
+{
+  provides {
+    interface Init;
+    interface AsyncStdControl;
+    interface M16c62pAdcSingle;
+    interface M16c62pAdcMultiple;
+  }
+  uses {
+    interface HplM16c62pAdc;
+    //interface M16c62pCalibrate;
+  }
+}
+implementation
+{  
+  /* type change from uint8_t to M16c62pADCON0_t, this function is defined at m16c62phardware.h */
+  DEFINE_UNION_CAST(int2ADCON0, uint8_t, M16c62pADCON0_t); // 
+  DEFINE_UNION_CAST(int2ADCON1, uint8_t, M16c62pADCON1_t);
+  DEFINE_UNION_CAST(int2ADCON2, uint8_t, M16c62pADCON2_t);
+  command error_t Init.init() {
+    atomic
+    {
+           M16c62pADCON0_t adcon_0;
+           M16c62pADCON1_t adcon_1;
+           M16c62pADCON2_t adcon_2;
+
+           adcon_0 = int2ADCON0(0x00);
+           adcon_0 = int2ADCON0(0x20);
+           adcon_0 = int2ADCON0(0x01); 
+       
+           call HplM16c62pAdc.setADCON0(adcon_0);
+        call HplM16c62pAdc.setADCON1(adcon_1);
+        call HplM16c62pAdc.setADCON2(adcon_2);
+    }
+    return SUCCESS;
+  }
+
+  /* We enable the A/D when start is called, and disable it when stop is
+     called. This drops A/D conversion latency by a factor of two (but
+     increases idle mode power consumption a little). 
+  */
+  async command error_t AsyncStdControl.start() {
+    atomic call HplM16c62pAdc.enableAdc();
+    return SUCCESS;
+  }
+
+  async command error_t AsyncStdControl.stop() {
+    atomic call HplM16c62pAdc.disableAdc();
+
+    return SUCCESS;
+  }
+
+  /* Return TRUE if switching to 'channel' with reference voltage 'refVoltage'
+     will give a precise result (the first sample after changing reference
+     voltage or switching to/between a differential channel is imprecise)
+  */
+  inline bool isPrecise(uint8_t admux, uint8_t channel, uint8_t refVoltage) {
+    return TRUE;
+  }
+  
+  /**
+   * Indicates a sample has been recorded by the ADC as the result
+   * of a ADC interrupt.
+   *
+   * @param data a 2 byte unsigned data value sampled by the ADC.
+   * @param precise if the conversion precise, FALSE if it wasn't. 
+   */  
+  async event void HplM16c62pAdc.dataReady(uint16_t data) {
+    
+    /* A single sample. Disable the ADC interrupt to avoid starting
+          a new sample at the next "sleep" instruction. */
+       call HplM16c62pAdc.disableInterruption();
+       call HplM16c62pAdc.disableAdc(); 
+       signal M16c62pAdcSingle.dataReady(data, TRUE);
+       
+  }
+
+  /* Start sampling based on request parameters 
+   * one-shot mode default
+   * refVoltage default
+   */
+  void getData(uint8_t channel,uint8_t precision, uint8_t prescaler) {
+    M16c62pADCON0_t adcon0_t;
+    M16c62pADCON1_t adcon1_t;
+    M16c62pADCON2_t adcon2_t;
+
+    if(channel < M16c62p_ADC_CHL_AN10)
+    {
+        adcon2_t.adgsel01 = 0;
+    }
+    else if((channel > M16c62p_ADC_CHL_AN7) && (channel <= M16c62p_ADC_CHL_AN17))
+    {
+        adcon2_t.adgsel01 = 2;
+        channel=channel-8;
+    }
+    adcon0_t.ch012 = channel;
+    
+    adcon0_t.md01 = 0;
+    adcon0_t.trg = 0;
+    adcon0_t.adst = M16c62p_ADC_START_CONVERSION_ON;
+    
+    adcon1_t.md2 = 0;
+    if(precision == M16c62p_ADC_PRECISION_10BIT)     // 10-bit mode
+    {
+        adcon1_t.bits = 1;
+    }
+    else
+    {
+        adcon1_t.bits = 0;
+    }
+    adcon1_t.vcut = M16c62p_ADC_ENABLE_ON;
+    adcon1_t.opa01 = 0;
+    
+    adcon2_t.smp = 1; // sample and hold
+    
+    if(prescaler == 0x00){adcon2_t.cks2=0;adcon1_t.cks1=0;adcon0_t.cks0=0;} // fAD/4 prescaler
+    else if(prescaler == 0x01){adcon2_t.cks2=0;adcon1_t.cks1=0;adcon0_t.cks0=1;} // fAD/2 prescaler
+    else if((prescaler == 0x02) || (prescaler == 0x03)){adcon2_t.cks2=0;adcon1_t.cks1=1;adcon0_t.cks0=0;} // fAD prescaler
+    else if(prescaler == 0x04){adcon2_t.cks2=1;adcon1_t.cks1=0;adcon0_t.cks0=0;} // fAD/12 prescaler
+    else if(prescaler == 0x05){adcon2_t.cks2=1;adcon1_t.cks1=0;adcon0_t.cks0=1;} // fAD/6 prescaler
+    else if((prescaler == 0x06) || (prescaler == 0x07)){adcon2_t.cks2=1;adcon1_t.cks1=1;adcon0_t.cks0=0;} // fAD/3 prescaler
+
+    call HplM16c62pAdc.enableInterruption();
+    
+    call HplM16c62pAdc.setADCON2(adcon2_t);
+    call HplM16c62pAdc.setADCON1(adcon1_t);
+    call HplM16c62pAdc.setADCON0(adcon0_t);
+  }
+
+  async command bool M16c62pAdcSingle.getData(uint8_t channel,
+                                            uint8_t precision, uint8_t prescaler) {
+    atomic
+    {
+               getData(channel, precision, prescaler);
+               return TRUE;
+    }
+  }
+
+  async command bool M16c62pAdcSingle.cancel() 
+  {
+    /* There is no M16c62pAdcMultiple.cancel, for reasons discussed in that
+       interface */
+    return call HplM16c62pAdc.cancel();
+  }
+
+  async command bool M16c62pAdcMultiple.getData(uint8_t channel, uint8_t precision, uint8_t prescaler)
+  {
+    atomic
+    {
+               getData(channel, precision, prescaler);
+
+               return TRUE;
+      }
+  }
+
+  default async event void M16c62pAdcSingle.dataReady(uint16_t data, bool precise) {
+  }
+
+  default async event bool M16c62pAdcMultiple.dataReady(uint16_t data, bool precise, uint8_t channel,
+                                                      uint8_t *newChannel, uint8_t *newRefVoltage) {
+    return FALSE; // stop conversion if we somehow end up here.
+  }
+}
diff --git a/tos/chips/m16c62p/adc/M16c62pAdcPlatform.nc b/tos/chips/m16c62p/adc/M16c62pAdcPlatform.nc
new file mode 100644 (file)
index 0000000..7a50f1b
--- /dev/null
@@ -0,0 +1,6 @@
+interface M16c62pAdcPlatform
+{
+  async command void adcOn();
+  
+  async command void adcOff();
+}
\ No newline at end of file
diff --git a/tos/chips/m16c62p/adc/M16c62pAdcSingle.nc b/tos/chips/m16c62p/adc/M16c62pAdcSingle.nc
new file mode 100755 (executable)
index 0000000..83833e0
--- /dev/null
@@ -0,0 +1,81 @@
+/// $Id$
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ * Copyright (c) 2002-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ * Hardware Abstraction Layer interface of M16c62p for acquiring
+ * a one-shot sampling from a channel.
+ *
+ * @author Fan Zhang <fanzha@ltu.se>
+ */
+
+#include "M16c62pAdc.h"
+
+interface M16c62pAdcSingle
+{
+  /**
+   * Initiates an ADC conversion on a given channel.
+   *
+   * @param channel A/D conversion channel.
+   * @param refVoltage Select reference voltage for A/D conversion. See
+   *   the M16c62p_ADC_VREF_xxx constants in M16c62pADC.h
+   * @param precision 8 to place A/D result in 8 bits, 10 to place it in 
+   *   the 10 bits
+   * @param prescaler Prescaler value for the A/D conversion clock. If you 
+   *  specify M16c62p_ADC_PRESCALE, a prescaler will be chosen that guarantees
+   *  full precision. Other prescalers can be used to get faster conversions. 
+   *  See the M16c62p manual for details.
+   * @return TRUE if the conversion will be precise, FALSE if it will be 
+   *   imprecise (due to a change in refernce voltage, or switching to a
+   *   differential input channel)
+   */
+  async command bool getData(uint8_t channel, uint8_t precision, uint8_t prescaler);
+  
+  /**
+   * Indicates a sample has been recorded by the ADC as the result
+   * of a <code>getData()</code> command.
+   *
+   * @param data a 2 byte unsigned data value sampled by the ADC.
+   * @param precise if the conversion precise, FALSE if it wasn't. This
+   *   values matches the result from the <code>getData</code> call.
+   */  
+  async event void dataReady(uint16_t data, bool precise);
+
+  /**
+   * Cancel an outstanding getData operation. Use with care, to
+   * avoid problems with races between the dataReady event and cancel.
+   * @return TRUE if a conversion was in-progress or an interrupt
+   *   was pending. dataReady will not be signaled. FALSE if the
+   *   conversion was already complete. dataReady will be (or has
+   *   already been) signaled.
+   */
+  async command bool cancel();
+}
diff --git a/tos/chips/m16c62p/adc/WireAdcP.nc b/tos/chips/m16c62p/adc/WireAdcP.nc
new file mode 100755 (executable)
index 0000000..b109519
--- /dev/null
@@ -0,0 +1,37 @@
+/* $Id$
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+/**
+ * Support component for AdcReadClientC and AdcReadNowClientC.
+ *
+ * @author David Gay
+ */
+
+configuration WireAdcP {
+  provides {
+    interface Read<uint16_t>[uint8_t client]; 
+    interface ReadNow<uint16_t>[uint8_t client];
+  }
+  uses {
+    interface M16c62pAdcConfig[uint8_t client];
+    interface Resource[uint8_t client];
+  }
+}
+implementation {
+  components M16c62pAdcC, AdcP,
+    new ArbitratedReadC(uint16_t) as ArbitrateRead;
+
+  Read = ArbitrateRead;
+  ReadNow = AdcP;
+  Resource = ArbitrateRead.Resource;
+  M16c62pAdcConfig = AdcP;     // provide default M16c62pAdcConfig interface
+
+  ArbitrateRead.Service -> AdcP.Read;
+  AdcP.M16c62pAdcSingle -> M16c62pAdcC;
+}
diff --git a/tos/chips/m16c62p/adc/WireAdcStreamP.nc b/tos/chips/m16c62p/adc/WireAdcStreamP.nc
new file mode 100755 (executable)
index 0000000..29a5229
--- /dev/null
@@ -0,0 +1,40 @@
+/* $Id$
+ * Copyright (c) 2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+/**
+ * Support component for AdcReadStreamClientC.
+ *
+ * @author Fan Zhang <fanzha@ltu.se>
+ */
+
+#include "Adc.h"
+
+configuration WireAdcStreamP {
+  provides interface ReadStream<uint16_t>[uint8_t client];
+  uses {
+    interface M16c62pAdcConfig[uint8_t client];
+    interface Resource[uint8_t client];
+  }
+}
+implementation {
+  components M16c62pAdcC, AdcStreamP, PlatformC, MainC,
+    new AlarmMicro32C(), 
+    new ArbitratedReadStreamC(uniqueCount(UQ_ADC_READSTREAM), uint16_t) as ArbitrateReadStream;
+
+  Resource = ArbitrateReadStream;
+  ReadStream = ArbitrateReadStream;
+  M16c62pAdcConfig = AdcStreamP;
+
+  ArbitrateReadStream.Service -> AdcStreamP;
+
+  AdcStreamP.Init <- MainC;
+  AdcStreamP.M16c62pAdcSingle -> M16c62pAdcC;
+  //AdcStreamP.M16c62pCalibrate -> PlatformC;
+  AdcStreamP.Alarm -> AlarmMicro32C;
+}
diff --git a/tos/chips/m16c62p/bits.h b/tos/chips/m16c62p/bits.h
new file mode 100755 (executable)
index 0000000..d91eb85
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef __BITS_H__
+#define __BITS_H__
+
+#define BIT0  0x1
+#define BIT1  0x2
+#define BIT2  0x4
+#define BIT3  0x8
+#define BIT4  0x10
+#define BIT5  0x20
+#define BIT6  0x40
+#define BIT7  0x80
+#define BIT8  0x100
+#define BIT9  0x200
+#define BIT10 0x400
+#define BIT11 0x800
+#define BIT12 0x1000
+#define BIT13 0x2000
+#define BIT14 0x4000
+#define BIT15 0x8000
+#define BIT16 0x10000
+#define BIT17 0x20000
+#define BIT18 0x40000
+#define BIT19 0x80000
+#define BIT20 0x100000
+#define BIT21 0x200000
+#define BIT22 0x400000
+#define BIT23 0x800000
+#define BIT24 0x1000000
+#define BIT25 0x2000000
+#define BIT26 0x4000000
+#define BIT27 0x8000000
+#define BIT28 0x10000000
+#define BIT29 0x20000000
+#define BIT30 0x40000000
+#define BIT31 0x80000000
+
+#endif // __BITS_H__
+
diff --git a/tos/chips/m16c62p/control/M16c62pControl.h b/tos/chips/m16c62p/control/M16c62pControl.h
new file mode 100644 (file)
index 0000000..40bd38c
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * This file includes defines to be used together with the control interfaces
+ * for the M16c/62p mcu.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#ifndef __M16C62P_CONTROL_H__
+#define __M16C62P_CONTROL_H__
+
+#define UQ_M16C62P_STOP_MODE_CONTROL "UQ_M16C62P_STOP_MODE_CONTROL"
+#define UQ_M16C62P_SYSTEM_CLOCK_CONTROL "UQ_M16C62P_SYSTEM_CLOCK_CONTROL"
+
+
+/**
+ * Input to SystemClockControl.minSpeed() and
+ * M16c62pControl.defaultSystemClock().
+ */
+typedef enum
+{
+  M16C62P_DONT_CARE = 0x0,
+  M16C62P_SUB_CLOCK = 0x1,
+  M16C62P_MAIN_CLOCK_DIV_0 = 0x2,
+  M16C62P_MAIN_CLOCK_DIV_2 = 0x4,
+  M16C62P_MAIN_CLOCK_DIV_4 = 0x8,
+  M16C62P_MAIN_CLOCK_DIV_8 = 0x9,
+  M16C62P_MAIN_CLOCK_DIV_16 = 0xc,
+  M16C62P_PLL_CLOCK = 0xd,
+} M16c62pSystemClock;
+
+/**
+ * The different PLL multipliers supported by the M16c/62p mcu.
+ */
+typedef enum
+{
+  M16C62P_PLL_2 = 0x1,
+  M16C62P_PLL_4 = 0x2,
+  M16C62P_PLL_6 = 0x3,
+  M16C62P_PLL_8 = 0x4
+} M16c62pPLLMultiplier;
+
+#endif // __M16C62P_CONTROL_H__
+
diff --git a/tos/chips/m16c62p/control/M16c62pControl.nc b/tos/chips/m16c62p/control/M16c62pControl.nc
new file mode 100755 (executable)
index 0000000..c90c91c
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface to initialize, put the M16c/62p to sleep and default system speed.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "M16c62pControl.h"
+interface M16c62pControl
+{
+  /**
+   * Initializes the mcu.
+   */
+   command error_t init();
+   
+  /**
+   * Sets the default system clock speed.
+   *
+   * @param def Default system speed ( != M16C62P_DONT_CARE)
+   */
+  command error_t defaultSystemClock(M16c62pSystemClock def);
+  
+  /**
+   * Put the mcu to sleep.
+   */
+  async command void sleep();
+}
diff --git a/tos/chips/m16c62p/control/M16c62pControlC.nc b/tos/chips/m16c62p/control/M16c62pControlC.nc
new file mode 100755 (executable)
index 0000000..5e7b990
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Wiring for the M16c62pControlP module.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration M16c62pControlC
+{
+  provides interface M16c62pControl;
+}
+implementation
+{
+  components M16c62pControlP,
+      M16c62pControlPlatformC;
+
+  M16c62pControl = M16c62pControlP;
+  M16c62pControlP.PlatformCtrl -> M16c62pControlPlatformC;
+
+}
diff --git a/tos/chips/m16c62p/control/M16c62pControlP.nc b/tos/chips/m16c62p/control/M16c62pControlP.nc
new file mode 100755 (executable)
index 0000000..dc38041
--- /dev/null
@@ -0,0 +1,349 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Implementation of the Control Interfaces for the M16c/62p mcu.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+
+#include "M16c62pControl.h"
+
+module M16c62pControlP
+{
+  provides interface M16c62pControl;
+  provides interface StopModeControl[uint8_t client];
+  provides interface SystemClockControl[uint8_t client];
+
+  uses interface M16c62pControlPlatform as PlatformCtrl;
+}
+implementation
+{
+  M16c62pSystemClock default_system_clock = M16C62P_MAIN_CLOCK_DIV_0; // Default system clock speed
+  M16c62pSystemClock system_clock = M16C62P_DONT_CARE; 
+  uint8_t client_system_clock[uniqueCount(UQ_M16C62P_SYSTEM_CLOCK_CONTROL)];
+  uint8_t num_system_clock_clients = uniqueCount(UQ_M16C62P_SYSTEM_CLOCK_CONTROL);
+  
+  // Take +1 incase of rest in the division
+  uint8_t client_allow_stop_mode[(uniqueCount(UQ_M16C62P_STOP_MODE_CONTROL)/8) + 1];
+  uint8_t num_allow_stop_mode_clients = uniqueCount(UQ_M16C62P_STOP_MODE_CONTROL);
+  bool update_sleep_mode = false;
+  bool allow_stop_mode = true; // Stop mode enabled/disabled, Default: Enabled.
+  
+  void PLLOn()
+  {
+    uint8_t tmp;
+    uint32_t i;
+
+    CM0.BYTE = 0x08; // Main clock + Sub clock.
+    CM1.BYTE = 0x20; //Clear previous cpu speed setting.
+    PM2.BYTE = 0x00; // PLL > 16MHz (2 waits).
+    tmp = 0x90 + PLL_MULTIPLIER;
+    PLC0.BYTE = tmp; // PLL ON.
+    // Wait for PLL to become stable (50 ms).
+    // TODO (henrik) Make this more efficient when time allows it.For example
+    //               use timers or busy waiting.
+    //               Tried busy waiting but tosboot started to include alot of
+    //               things that it shouldn't which lead to compile errors.
+    for (i = 0; i < 50000 * MAIN_CRYSTAL_SPEED; ++i)
+      asm("nop");
+    CM1.BYTE = 0x22; // PLL as system clock.
+    call PlatformCtrl.PLLOn();
+  }
+
+  void PLLOff()
+  {
+    uint8_t tmp;
+    CLR_BIT(CM1.BYTE, 1); // Main clock
+    tmp = 0x10 + PLL_MULTIPLIER;
+    PLC0.BYTE = tmp; // Turn off PLL clock
+    call PlatformCtrl.PLLOff();
+  }
+  
+  error_t setSystemClock(M16c62pSystemClock set_clock)
+  {
+    M16c62pSystemClock clock = set_clock;
+    atomic
+    {      
+      if (clock == M16C62P_DONT_CARE)
+      {
+        clock = default_system_clock;
+      }
+      
+      PRCR.BYTE = BIT1 | BIT0; // Turn off protection for cpu & clock register.
+      
+      if (system_clock == M16C62P_PLL_CLOCK)
+      {
+        PLLOff();
+      }
+
+      // Set correct system clock speed.
+      if (clock == M16C62P_MAIN_CLOCK_DIV_8)
+      {
+        SET_BIT(CM0.BYTE, 6);
+      }
+      else if (clock >= M16C62P_MAIN_CLOCK_DIV_0 &&
+               clock <= M16C62P_MAIN_CLOCK_DIV_16)
+      { // Main clock divided by 0, 2 ,4 or 16
+        CLR_BIT(CM0.BYTE, 6); // Remove division by 8
+        CLR_FLAG(CM1.BYTE, (0x3 << 6)); // Clear previous cpu speed setting
+        SET_FLAG(CM1.BYTE, ((clock >> 2) << 6)); // New cpu speed
+      }
+      else if (clock == M16C62P_SUB_CLOCK)
+      {
+        SET_BIT(CM0.BYTE, 4); // Sub clock on.
+        SET_BIT(CM0.BYTE, 7); // Sub clock as CPU clock  
+      }
+      else if (clock == M16C62P_PLL_CLOCK)
+      {
+        PLLOn();
+      }
+      // TODO(Henrik) Maybe need to wait for a while to make sure that the
+      //              crystals are stable?
+      CLR_BIT(CM1.BYTE, 5); // Low drive on Xin-Xout.
+      CLR_BIT(CM0.BYTE, 3); // Low drive on XCin-XCout.
+      PRCR.BYTE = 0;           // Turn on protection on all registers.
+      atomic system_clock = set_clock;
+      return SUCCESS;
+    }
+  }
+
+  error_t updateSystemClock()
+  {
+    M16c62pSystemClock clock = M16C62P_DONT_CARE;
+    uint8_t i;
+
+    atomic
+    {
+      for (i = 0; i < num_system_clock_clients; ++i)
+      {
+        if (clock < client_system_clock[i])
+        {
+          clock = client_system_clock[i];
+        }
+      }
+      
+      if (clock == system_clock)
+      {
+        return SUCCESS;
+      }
+      
+      return setSystemClock(clock); 
+    }
+  }
+
+  void initPin(volatile uint8_t *port, volatile uint8_t *port_d, uint8_t pin, uint16_t state)
+  {
+    uint8_t inactive = (state >> (pin*2)) & 0x3;
+    // Turn off protection of PD9
+    PRCR.BYTE = BIT2;
+    switch (inactive)
+    {
+      case M16C_PIN_INACTIVE_DONT_CARE:
+        break;
+      case M16C_PIN_INACTIVE_OUTPUT_LOW:
+        SET_BIT((*port_d), pin);
+        CLR_BIT((*port), pin);
+        break;
+      case M16C_PIN_INACTIVE_OUTPUT_HIGH:
+        SET_BIT((*port_d), pin);
+        SET_BIT((*port), pin);
+        break;
+      case M16C_PIN_INACTIVE_INPUT:
+        CLR_BIT((*port_d), pin);
+        CLR_BIT((*port), pin);
+        break;
+    }
+    PRCR.BYTE = 0;
+  }
+  
+  void initPort(volatile uint8_t *port, volatile uint8_t *port_d, uint16_t state)
+  {
+    initPin(port, port_d, 0, state);
+    initPin(port, port_d, 1, state);
+    initPin(port, port_d, 2, state);
+    initPin(port, port_d, 3, state);
+    initPin(port, port_d, 4, state);
+    initPin(port, port_d, 5, state);
+    initPin(port, port_d, 6, state);
+    initPin(port, port_d, 7, state);
+  }
+  
+  void initPins()
+  {
+    initPort(&P0.BYTE, &PD0.BYTE, PORT_P0_INACTIVE_STATE);
+    initPort(&P1.BYTE, &PD1.BYTE, PORT_P1_INACTIVE_STATE);
+    initPort(&P2.BYTE, &PD2.BYTE, PORT_P2_INACTIVE_STATE);
+    initPort(&P3.BYTE, &PD3.BYTE, PORT_P3_INACTIVE_STATE);
+    initPort(&P4.BYTE, &PD4.BYTE, PORT_P4_INACTIVE_STATE);
+    initPort(&P5.BYTE, &PD5.BYTE, PORT_P5_INACTIVE_STATE);
+    initPort(&P6.BYTE, &PD6.BYTE, PORT_P6_INACTIVE_STATE);
+    initPort(&P7.BYTE, &PD7.BYTE, PORT_P7_INACTIVE_STATE);
+    initPort(&P8.BYTE, &PD8.BYTE, PORT_P8_INACTIVE_STATE);
+    initPort(&P9.BYTE, &PD9.BYTE, PORT_P9_INACTIVE_STATE);
+    initPort(&P10.BYTE, &PD10.BYTE, PORT_P_10_INACTIVE_STATE);
+  }
+  
+  command error_t M16c62pControl.init()
+  {
+    uint8_t i;
+    uint8_t tmp;
+    initPins();
+    PRCR.BYTE = BIT1 | BIT0; // Turn off protection for cpu & clock register.
+
+    PM0.BYTE = BIT7;         // Single Chip mode. No BCLK output.
+    PM1.BYTE = BIT3;         // Expand internal memory, no global wait state.
+    PCLKR.BIT.PCLK0 = 1;     // Set Timer A and B clock bit to F1
+    PCLKR.BIT.PCLK1 = 1;     // Set Timer A and B clock bit to F1
+    
+    tmp = 0x10 + PLL_MULTIPLIER; // Prepare PLL multiplier
+    PLC0.BYTE = tmp; // Set PLL multiplier
+    
+    PRCR.BYTE = 0;
+    // Initialize the clock and stop mode control arrays.
+    for (i = 0; i < num_system_clock_clients; ++i)
+    {
+      client_system_clock[i] = M16C62P_DONT_CARE;
+    }
+    for (i = 0; i < (num_allow_stop_mode_clients/8) + 1; ++i)
+    {
+      client_allow_stop_mode[i] = 0xFF;
+    }
+    return setSystemClock(M16C62P_DONT_CARE);
+  }
+
+  command error_t M16c62pControl.defaultSystemClock(
+      M16c62pSystemClock def)
+  {
+    if (def == M16C62P_DONT_CARE)
+    {
+      return FAIL;
+    }
+    if (def == default_system_clock || system_clock != M16C62P_DONT_CARE)
+    {
+      default_system_clock = def;
+      return SUCCESS;
+    }
+    default_system_clock = def;
+    return setSystemClock(M16C62P_DONT_CARE);
+  }
+
+  void updateSleepMode()
+  {
+    uint8_t i;
+    for (i = 0; i < (num_allow_stop_mode_clients/8) + 1; ++i)
+    {
+      if (client_allow_stop_mode[i] != 0xFF)
+      {
+        allow_stop_mode = false;
+        return;
+      }
+    }
+    allow_stop_mode = true;
+  }
+
+  void waitMode()
+  {
+    __nesc_enable_interrupt();
+    asm ("wait");
+    asm volatile ("" : : : "memory");
+    __nesc_disable_interrupt();
+  }
+
+  void stopMode()
+  {
+    uint8_t cm0_tmp, cm1_tmp;
+    __nesc_enable_interrupt();
+    PRCR.BYTE = 1; // Turn off protection of system clock control registers
+    CLR_BIT(CM2.BYTE, 0);
+    cm0_tmp = CM0.BYTE;
+    cm1_tmp = CM1.BYTE;
+    CM0.BYTE = 0b00001000;
+    asm("bset 0,0x0007"); // Enter stop mode
+    asm("jmp.b MAIN_A");
+    asm("MAIN_A:");
+    asm("nop");
+    asm("nop");
+    asm("nop");
+    asm("nop");
+    asm volatile ("" : : : "memory");
+    __nesc_disable_interrupt();
+    CM0.BYTE = cm0_tmp;
+    CM1.BYTE = cm1_tmp;
+    PRCR.BIT.PRC0 = 0; // Turn on protection of system clock control registers
+  }
+
+  async command void M16c62pControl.sleep()
+  {
+    atomic if (update_sleep_mode)
+    {
+      updateSleepMode();
+    }
+    if (allow_stop_mode && system_clock != M16C62P_PLL_CLOCK)
+    {
+      stopMode();
+    }
+    else
+    {
+      waitMode();
+    }
+  }
+
+  async command void StopModeControl.allowStopMode[uint8_t client](bool allow)
+  {
+    atomic
+    {
+      WRITE_BIT(client_allow_stop_mode[client >> 3], client % 8, allow);
+      if (allow != allow_stop_mode)
+      {
+        update_sleep_mode = true;
+      }
+    }
+  }
+
+  command error_t SystemClockControl.minSpeed[uint8_t client](
+      M16c62pSystemClock speed)
+  {
+    atomic client_system_clock[client] = speed;
+    atomic if (system_clock < speed)
+    {
+      return updateSystemClock();
+    }
+    return SUCCESS;
+  }
+}
diff --git a/tos/chips/m16c62p/control/M16c62pControlPlatform.nc b/tos/chips/m16c62p/control/M16c62pControlPlatform.nc
new file mode 100644 (file)
index 0000000..c48ed1f
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface to signal the platform that the mcu has changed the main clock
+ * speed, PLL is being turned on/off, etc.
+ * Needed so that the platform can take appropriate actions so
+ * that timers can be set to handle the PLL for example.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+interface M16c62pControlPlatform
+{
+  /**
+   * PLL is turned on.
+   */
+  async command void PLLOn();
+
+  /**
+   * PLL is turned off.
+   */
+  async command void PLLOff();
+}
diff --git a/tos/chips/m16c62p/control/StopModeControl.nc b/tos/chips/m16c62p/control/StopModeControl.nc
new file mode 100644 (file)
index 0000000..01d6cd8
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface used by components to signal if it
+ * allows the mcu to go into stop mode.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+interface StopModeControl
+{
+  /**
+   * Tells the mcu if it is allowed to go into stop mode.
+   *
+   * @param allow True if stop mode is allowed.
+   */
+  async command void allowStopMode(bool allow);
+}
diff --git a/tos/chips/m16c62p/control/StopModeControlC.nc b/tos/chips/m16c62p/control/StopModeControlC.nc
new file mode 100644 (file)
index 0000000..b18ca72
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "M16c62pControl.h"
+/**
+ * All components that need to control the mcus sleep
+ * mode should instantiate a component of this configuration.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic configuration StopModeControlC()
+{
+  provides interface StopModeControl;
+}
+implementation
+{
+  enum
+  {
+    CLIENT_ID = unique(UQ_M16C62P_STOP_MODE_CONTROL),
+  };
+
+  components M16c62pControlP;
+
+  StopModeControl = M16c62pControlP.StopModeControl[CLIENT_ID];
+}
diff --git a/tos/chips/m16c62p/control/SystemClockControl.nc b/tos/chips/m16c62p/control/SystemClockControl.nc
new file mode 100644 (file)
index 0000000..330c75f
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface to control the allowed minimum speed of the mcu.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+interface SystemClockControl
+{
+  /**
+   * Control the minimum speed of the mcu.
+   *
+   * @param speed The allowed minimum speed.
+   */
+  command error_t minSpeed(M16c62pSystemClock speed);
+}
diff --git a/tos/chips/m16c62p/control/SystemClockControlC.nc b/tos/chips/m16c62p/control/SystemClockControlC.nc
new file mode 100644 (file)
index 0000000..be97af4
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "M16c62pControl.h"
+
+/**
+ * Every component that needs to control the minimum speed
+ * of the mcu should instantiate a new component of this configuration.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+generic configuration SystemClockControlC()
+{
+  provides interface SystemClockControl;
+}
+implementation
+{
+  enum
+  {
+    CLIENT_ID = unique(UQ_M16C62P_SYSTEM_CLOCK_CONTROL),
+  };
+
+  components M16c62pControlP;
+
+  SystemClockControl = M16c62pControlP.SystemClockControl[CLIENT_ID];
+}
diff --git a/tos/chips/m16c62p/dac/HplM16c62pDac.nc b/tos/chips/m16c62p/dac/HplM16c62pDac.nc
new file mode 100755 (executable)
index 0000000..02a9e0a
--- /dev/null
@@ -0,0 +1,35 @@
+/**
+ * HPL interface to the M16c62p D/A converers. 
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+interface HplM16c62pDac {
+  /**
+   * Sets the D/A value.
+   * @param value The new D/A value
+   */
+  async command void setValue(uint8_t value);
+  
+  /**
+   * Reads the current D/A value.
+   * @return D/A value
+   */
+  async command uint8_t getValue();
+
+  /**
+   * Enables the D/A converter.
+   */
+  async command void enable();
+
+  /**
+   * Disables the D/A converter.
+   */
+  async command void disable();
+
+  /**
+   * Checks the state of the D/A converter.
+   * @return TRUE if the D/A converter is enabled.
+   */
+  async command bool isEnabled();
+}
diff --git a/tos/chips/m16c62p/dac/HplM16c62pDacC.nc b/tos/chips/m16c62p/dac/HplM16c62pDacC.nc
new file mode 100755 (executable)
index 0000000..31b3961
--- /dev/null
@@ -0,0 +1,17 @@
+/**
+ * HPL for the M16c62p D/A conversion susbsystem.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+configuration HplM16c62pDacC {
+  provides interface HplM16c62pDac as Dac0;
+  provides interface HplM16c62pDac as Dac1;
+}
+implementation {
+  components new HplM16c62pDacP(&DA0, 0) as Dac0_, 
+             new HplM16c62pDacP(&DA1, 1) as Dac1_;
+
+  Dac0 = Dac0_;
+  Dac1 = Dac1_;
+}
diff --git a/tos/chips/m16c62p/dac/HplM16c62pDacP.nc b/tos/chips/m16c62p/dac/HplM16c62pDacP.nc
new file mode 100755 (executable)
index 0000000..c99b110
--- /dev/null
@@ -0,0 +1,41 @@
+/**
+ * HPL for the M16c62p A/D conversion susbsystem.
+ *
+ * @author Fan Zhang <fanzha@ltu.se>
+ *
+ */
+
+generic module HplM16c62pDacP(uint16_t da_addr,
+                              uint8_t da_num)
+{
+  provides interface HplM16c62pDac;
+}
+implementation
+{
+#define da (*TCAST(volatile uint8_t* ONE, da_addr))
+
+  async command void HplM16c62pDac.setValue(uint8_t value)
+  {
+    da = value;
+  }
+  
+  async command uint8_t HplM16c62pDac.getValue()
+  {
+    return da;
+  }
+
+  async command void HplM16c62pDac.enable()
+  {
+    SET_BIT(DACON.BYTE, da_num);
+  }
+
+  async command void HplM16c62pDac.disable()
+  {
+    CLR_BIT(DACON.BYTE, da_num);
+  }
+
+  async command bool HplM16c62pDac.isEnabled()
+  {
+    return (READ_BIT(DACON.BYTE, da_num) ? true : false);
+  }
+}
diff --git a/tos/chips/m16c62p/interrupts.h b/tos/chips/m16c62p/interrupts.h
new file mode 100755 (executable)
index 0000000..732152c
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * M16C interrupt id defines.
+ *
+ * @author Per Lindgren
+ * @author Johan Eriksson
+ * @author Johan Nordlander
+ * @author Simon Aittamaa.
+ */
+
+#ifndef M16C_INTERRUPTS_H_
+#define M16C_INTERRUPTS_H_
+
+/* Software interrupts - bound to peripheral hardware */
+
+#define M16C_BRK               0
+#define M16C_INT3              4
+#define M16C_TMRB5             5
+#define M16C_TMRB4             6
+#define M16C_UART1_BCD         6
+#define M16C_TMRB3             7
+#define M16C_UART0_BCD         7
+#define M16C_INT5              8
+#define M16C_SI_O4             8
+#define M16C_INT4              9
+#define M16C_SI_O3             9
+#define M16C_UART2_BCD         10
+#define M16C_DMA0              11
+#define M16C_DMA1              12
+#define M16C_KEY               13
+#define M16C_AD                        14
+#define M16C_UART2_NACK                15
+#define M16C_UART2_ACK         16
+#define M16C_UART0_NACK                17
+#define M16C_UART0_ACK         18
+#define M16C_UART1_NACK                19
+#define M16C_UART1_ACK         20
+#define M16C_TMRA0             21
+#define M16C_TMRA1             22
+#define M16C_TMRA2             23
+#define M16C_TMRA3             24
+#define M16C_TMRA4             25
+#define M16C_TMRB0             26
+#define M16C_TMRB1             27
+#define M16C_TMRB2             28
+#define M16C_INT0              29
+#define M16C_INT1              30
+#define M16C_INT2              31
+
+/* Software interrupts - not bound to peripheral hardware */
+
+#define M16C_SINT0             32
+#define M16C_SINT1             33
+#define M16C_SINT2             34
+#define M16C_SINT3             35
+#define M16C_SINT4             36
+#define M16C_SINT5             37
+#define M16C_SINT6             38
+#define M16C_SINT7             39
+#define M16C_SINT8             40
+#define M16C_SINT9             41
+#define M16C_SINT10            42
+#define M16C_SINT11            43
+#define M16C_SINT12            44
+#define M16C_SINT13            45
+#define M16C_SINT14            46
+#define M16C_SINT15            47
+#define M16C_SINT16            48
+#define M16C_SINT17            49
+#define M16C_SINT18            50
+#define M16C_SINT19            51
+#define M16C_SINT20            52
+#define M16C_SINT21            53
+#define M16C_SINT22            54
+#define M16C_SINT23            55
+#define M16C_SINT24            56
+#define M16C_SINT25            57
+#define M16C_SINT26            58
+#define M16C_SINT27            59
+#define M16C_SINT28            60
+#define M16C_SINT29            61
+#define M16C_SINT30            62
+#define M16C_SINT31            63
+
+/* Interrupt macro */
+#define _M16C_INTERRUPT(id) _vector_##id
+#define M16C_INTERRUPT(id) \
+       void __attribute__((interrupt)) _M16C_INTERRUPT(id)(void)
+
+#endif
+
+
diff --git a/tos/chips/m16c62p/iom16c62p.h b/tos/chips/m16c62p/iom16c62p.h
new file mode 100755 (executable)
index 0000000..658bb7a
--- /dev/null
@@ -0,0 +1,2757 @@
+/****************************************************************
+KPIT Cummins Infosystems Ltd, Pune, India. 1-April-2006.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+*****************************************************************/
+/****************************************************************/
+/*      M16C/60 62P Include File                                */
+/****************************************************************/
+
+#ifndef __IOM16C62P_H__
+#define __IOM16C62P_H__
+
+/*------------------------------------------------------
+    Processor mode register 0  //0x0004
+------------------------------------------------------*/
+union st_pm0 {               /* union PM0                                              */
+  struct {                              /* Bit  Access                                         */
+        unsigned char  PM0_0:1; /* Processor mode bit 0                                */
+        unsigned char  PM0_1:1; /* Processor mode bit 1                                */
+        unsigned char  PM0_2:1; /* R/W mode select bit                                 */
+        unsigned char  PM0_3:1; /* Software reset bit                                  */
+        unsigned char  PM0_4:1; /* Multiplexed bus space select bit 0  */
+        unsigned char  PM0_5:1; /* Multiplexed bus space select bit 1  */
+        unsigned char  PM0_6:1; /* Port P40 to P43 function select bit */
+        unsigned char  PM0_7:1; /* BCLK output disable bit                     */
+  } BIT;                                /*                                                             */
+       unsigned  char BYTE;     /*  Byte Access                                                */
+};                           /*                                                            */
+
+/*------------------------------------------------------
+    Processor mode register 1  //0x0005
+------------------------------------------------------*/
+union st_pm1 {              /* union PM1                                                */
+  struct {                     /* Bit  Access                                           */
+        unsigned char PM1_0:1; /* CS2 area switching bit                */
+        unsigned char PM1_1:1; /* Port P3_4 to P3_7 function select bit */
+        unsigned char PM1_2:1; /* Watch dog timer function select bit   */
+        unsigned char PM1_3:1; /* Intermal reserved area expansion bit  */
+        unsigned char PM1_4:1; /* Memory area expansion bit             */
+        unsigned char PM1_5:1; /* Memory area expansion bit             */
+        unsigned char PM1_6:1; /* Reserved bit                                          */
+        unsigned char PM1_7:1; /* PM17 - Wait bit                                       */
+  } BIT;                               /*                                               */
+        unsigned char BYTE;    /*  Byte Access                                          */
+};                          /*                                                                  */
+
+/*------------------------------------------------------
+    System clock control register 0  //0x0006
+------------------------------------------------------*/
+union st_cm0 {               /* union CM0                                              */
+  struct {                              /* Bit  Access                                         */
+        unsigned char  CM0_0:1; /* Clock output function select bit    */
+        unsigned char  CM0_1:1; /* Clock output function select bit    */
+        unsigned char  CM0_2:1; /* WAIT peripheral function clock stop bit */
+        unsigned char  CM0_3:1; /* Xcin-Xcout drive capacity select bit*/
+        unsigned char  CM0_4:1; /* Port Xc select bit                                  */
+        unsigned char  CM0_5:1; /* Main clock stop bit                                 */
+        unsigned char  CM0_6:1; /* Main clock division select bit 0    */
+        unsigned char  CM0_7:1; /* System clock select bit                     */
+  } BIT;                                /*                                             */
+       unsigned char BYTE;      /*  Byte Access                                        */
+};                           /* system clock control register  0    */
+
+
+/*------------------------------------------------------
+    System clock control register 1 //0x0007
+------------------------------------------------------*/
+union st_cm1 {               /* union CM1                                              */
+  struct {                              /* Bit  Access                                         */
+        unsigned char  CM1_0:1; /* All clock stop control bit                  */
+        unsigned char  CM1_1:1; /* Reserved bit always set to 0                */
+        unsigned char           :1; /* Reserved bit always set to 0            */
+        unsigned char           :1; /* Reserved bit always set to 0            */
+        unsigned char           :1; /* Reserved bit always set to 0            */
+        unsigned char  CM1_5:1; /* Xin-Xouts drive capacity select bit */
+        unsigned char  CM1_6:1; /* Main clock division select bit 1    */
+        unsigned char  CM1_7:1; /* Main clock division select bit 1    */
+  } BIT;                                /*                                         */
+       unsigned char BYTE;      /*  Byte Access                                        */
+};                           /* system clock control register 1     */
+
+
+/*------------------------------------------------------
+    Chip select control register //0x0008
+------------------------------------------------------*/
+union st_csr {               /* union CSR                                              */
+   struct {                     /* Bit  Access                                         */
+        unsigned char  CS0 :1;  /* CS0~ output enable bit                              */
+        unsigned char  CS1 :1;  /* CS1~ output enable bit                              */
+        unsigned char  CS2 :1;  /* CS2~ output enable bit                              */
+        unsigned char  CS3 :1;  /* CS3~ output enable bit                              */
+        unsigned char  CS0W:1;  /* CS0~ wait bit                                       */
+        unsigned char  CS1W:1;  /* CS1~ wait bit                                       */
+        unsigned char  CS2W:1;  /* CS2~ wait bit                                       */
+        unsigned char  CS3W:1;  /* CS3~ wait bit                                       */
+   } BIT;                       /*                                                     */
+        unsigned char BYTE;     /* Byte Access                                         */
+};                           /* Chip select control register           */
+
+/*------------------------------------------------------
+    Address match interrupt enable register //0x0009
+------------------------------------------------------*/
+union st_aier {               /* union AIER                                                    */
+   struct {                      /* Bit  Access                                                */
+        unsigned char  AIER0:1;  /* Address match interrupt0 enable bit*/
+        unsigned char  AIER1:1;  /* Address match interrupt1 enable bit*/
+        unsigned char           :1;  /* Nothing assigned                                       */
+        unsigned char           :1;  /* Nothing assigned                                       */
+        unsigned char           :1;  /* Nothing assigned                                       */
+        unsigned char           :1;  /* Nothing assigned                                       */
+        unsigned char           :1;  /* Nothing assigned                                       */
+        unsigned char           :1;  /* Nothing assigned                                       */
+   } BIT;                        /*                                                            */
+        unsigned char BYTE;      /* Byte Access                                                */
+};                            /* Address match interrupt enable register       */
+
+
+/*------------------------------------------------------
+   Protect register //0x000A
+-----------------------------------------------------*/
+union st_prcr {               /* union PRCR                                                    */
+   struct {                      /* Bit  Access                                                */
+        unsigned char  PRC0:1;   /* Enables writing to system clock control registers 0 & 1 */
+        unsigned char  PRC1:1;   /* Enables writing to processor mode registers 0 & 1 */
+        unsigned char  PRC2:1;   /* Enables writing to port P9 direction register & SI/Oi control register(i=3,4)*/
+        unsigned char  PRC3:1;   /* Enable writting to Power supply detection register 2 and Power supply down detection register */
+        unsigned char          :1;   /* Nothing assigned                                       */
+        unsigned char          :1;   /* Nothing assigned                                       */
+        unsigned char          :1;   /* Nothing assigned                                       */
+        unsigned char          :1;   /* Nothing assigned                                       */
+   } BIT;                        /*                                                            */
+        unsigned char BYTE;      /* Byte Access                                                */
+};                            /* Protect register                                      */
+
+/*------------------------------------------------------
+       Data bank register //0x000B
+------------------------------------------------------*/
+union st_dbr {                /* union DBR                                             */
+   struct {                      /* Bit  Access                                                */
+        unsigned char      :1;   /* Nothing assigned                                   */
+        unsigned char      :1;   /* Nothing assigned                                   */
+        unsigned char  OFS :1;   /* Offset bit                         */
+        unsigned char  BSR0:1;   /* Bank select bit 0                  */
+        unsigned char  BSR1:1;   /* Bank select bit 1                  */
+        unsigned char  BSR2:1;   /* Bank select bit 2                  */
+        unsigned char          :1;   /* Nothing assigned                                       */
+        unsigned char          :1;   /* Nothing assigned                                       */
+   } BIT;                        /*                                                            */
+        unsigned char BYTE;      /* Data bank register                                         */
+};
+
+/*------------------------------------------------------
+       Oscillation stop detection register //0x000C
+------------------------------------------------------*/
+union st_cm2 {                /* union CM2                                              */
+   struct {                      /* Bit  Access                                                 */
+        unsigned char  CM2_0:1;   /* Oscillation stop detection bit     */
+        unsigned char  CM2_1:1;   /* Main clock switch bit              */
+        unsigned char  CM2_2:1;   /* Oscillation stop detection status  */
+        unsigned char  CM2_3:1;   /* Clock monitor bit                  */
+        unsigned char       :1;   /* Nothing assigned                   */
+        unsigned char       :1;   /* Nothing assigned                   */
+        unsigned char           :1;   /* Nothing assigned                                       */
+        unsigned char  CM2_7:1;   /* Operation select bit(when an oscillation stop is detected) */
+   } BIT;                         /*                                                           */
+        unsigned char BYTE;      /* Oscillation stop detection register                                                */
+};
+
+/*------------------------------------------------------
+   Watchdog timer control register //0x000f
+-----------------------------------------------------*/
+union st_wdc {               /* union WDC                                              */
+   struct {                     /* Bit  Access                                                 */
+     unsigned char      B0:1;   /* High-order bit of watchdog timer    */
+     unsigned char      B1:1;   /* High-order bit of watchdog timer    */
+     unsigned char      B2:1;   /* High-order bit of watchdog timer    */
+     unsigned char      B3:1;   /* High-order bit of watchdog timer    */
+     unsigned char      B4:1;   /* High-order bit of watchdog timer    */
+     unsigned char WDC5:1;      /* Cold start / warm start discrimination flag */
+     unsigned char      B6:1;   /* Reserved bit, must always be 0              */
+     unsigned char WDC7:1;   /* Prescaler select bit                           */
+   } BIT;                       /*                                                             */
+     unsigned char BYTE;     /*  Byte Access                                           */
+};                           /* Watchdog timer control register     */
+
+/*------------------------------------------------------
+   Address match interrupt register 0 //0x0010
+-----------------------------------------------------*/
+union st_rmad0 {
+   struct{
+       unsigned char RMAD0L;     /* Address match interrupt register 0 low  8 bit */
+       unsigned char RMAD0M;     /* Address match interrupt register 0 mid  8 bit */
+       unsigned char RMAD0H;     /* Address match interrupt register 0 high 8 bit */
+       unsigned char NC;         /* non use                                       */
+   } BYTE;                       /* Byte access                                   */
+       unsigned long   DWORD;    /* Word Access                                   */
+};                               /* Address match interrupt register 0 32 bit     */
+
+/*------------------------------------------------------
+   Address match interrupt register 1 //0x0014
+-----------------------------------------------------*/
+union st_rmad1 {
+   struct{
+       unsigned char RMAD1L;     /* Address match interrupt register 1 low  8 bit */
+       unsigned char RMAD1M;     /* Address match interrupt register 1 mid  8 bit */
+       unsigned char RMAD1H;     /* Address match interrupt register 1 high 8 bit */
+       unsigned char NC;         /* non use                                       */
+   } BYTE;                       /* Byte access                                   */
+   unsigned long   DWORD;        /*    Word Access                                */
+};                               /* Address match interrupt register 1 32 bit     */
+
+/*------------------------------------------------------
+   Voltage Detection Register 1 //0x0019
+-----------------------------------------------------*/
+union st_vcr1 {               /* union VCR1                                                    */
+   struct {                     /* Bit  Access                                                 */
+     unsigned char       B0:1;  /* Reserved bit,must be 0              */
+     unsigned char       B1:1;  /* Reserved bit,must be 0              */
+     unsigned char       B2:1;  /* Reserved bit,must be 0              */
+     unsigned char VC1_3:1;  /* Voltage down monitor flag           */
+     unsigned char       B4:1;  /* Reserved bit,must be 0                  */
+     unsigned char    B5:1;  /* Reserved bit,must be 0              */
+     unsigned char       B6:1;  /* Reserved bit, must always be 0              */
+     unsigned char    B7:1;  /* Reserved bit,must be 0                         */
+   } BIT;                       /*                                                             */
+     unsigned char BYTE;     /*  Byte Access                                           */
+};                           /* Voltage Detection Register 1     */
+
+/*------------------------------------------------------
+   Voltage Detection Register 2 //0x001A
+-----------------------------------------------------*/
+union st_vcr2 {               /* union VCR2                                                    */
+   struct {                     /* Bit  Access                                                 */
+     unsigned char       B0:1;  /* Reserved bit,must be 0              */
+     unsigned char       B1:1;  /* Reserved bit,must be 0              */
+     unsigned char       B2:1;  /* Reserved bit,must be 0              */
+     unsigned char    B3:1;  /* Reserved bit,must be 0           */
+     unsigned char       B4:1;  /* Reserved bit,must be 0                  */
+     unsigned char    B5:1;  /* Reserved bit,must be 0              */
+     unsigned char VC2_6:1;  /* Reset area monitor bit         */
+     unsigned char VC2_7:1;  /* Voltage down monitor bit                       */
+   } BIT;                       /*                                                             */
+     unsigned char BYTE;     /*  Byte Access                                           */
+};                           /* Voltage Detection Register 1     */
+
+/*------------------------------------------------------
+   Chip select expansion control register//0x001B
+-----------------------------------------------------*/
+union st_cse {               /* union CSE                                              */
+   struct {                     /* Bit  Access                                                 */
+     unsigned char CSE00W:1; /* CS0~ wait expansion bit */
+     unsigned char CSE01W:1; /* CS0~ wait expansion bit */
+     unsigned char CSE10W:1; /* CS1~ wait expansion bit */
+     unsigned char CSE11W:1; /* CS1~ wait expansion bit */
+     unsigned char CSE20W:1; /* CS2~ wait expansion bit */
+     unsigned char CSE21W:1; /* CS2~ wait expansion bit */
+     unsigned char CSE30W:1; /* CS3~ wait expansion bit */
+     unsigned char CSE31W:1; /* CS3~ wait expansion bit */
+   } BIT;                       /*                                                             */
+     unsigned char BYTE;     /*  Byte Access                                           */
+};                           /* Chip select expansion control register    */
+
+/*------------------------------------------------------
+   PLL control register 0 //0x001C
+-----------------------------------------------------*/
+union st_plc0 {               /* union                                                 */
+   struct {                     /* Bit  Access                                                 */
+     unsigned char PLC00:1; /* Programmable counter select bit */
+     unsigned char PLC01:1; /* Programmable counter select bit */
+     unsigned char PLC02:1; /* Programmable counter select bit */
+     unsigned char      :1; /* Nothing assigned */
+     unsigned char      :1; /* Reserved bit,set to one */
+     unsigned char      :1; /* Reserved bit,set to zero */
+     unsigned char      :1; /* Reserved bit,set to zero */
+     unsigned char PLC07:1; /* Operation enable bit */
+   } BIT;                       /*                                                             */
+     unsigned char BYTE;     /*  Byte Access                                           */
+};                           /* PLL control register 0    */
+
+/*------------------------------------------------------
+   Processor mode register 2 //0x001E
+-----------------------------------------------------*/
+union st_pm2 {               /* union                                                                     */
+   struct {                     /* Bit  Access                                                                */
+     unsigned char PM2_0:1; /* Specifying wait when accessing SFR at PLL operation */
+     unsigned char PM2_1:1; /* System clock protective bit */
+     unsigned char PM2_2:1; /* WDT count source protective bit */
+     unsigned char      :1; /* Reserved bit,set to zero */
+     unsigned char      :1; /* Reserved bit,set to zero */
+     unsigned char      :1; /* Nothing assigned */
+     unsigned char      :1; /* Nothing assigned */
+     unsigned char      :1; /* Nothing assigned */
+   } BIT;                       /*                                                             */
+     unsigned char BYTE;     /*  Byte Access                                           */
+};                           /* Processor mode register 2    */
+
+/*------------------------------------------------------
+   Power supply down detection register //0x001F
+-----------------------------------------------------*/
+union st_d4int {               /* union                                                                   */
+   struct {                     /* Bit  Access                                                                */
+     unsigned char D40:1; /* Power supply down detection interrupt enable bit */
+     unsigned char D41:1; /* STOP mode deactivation control bit */
+     unsigned char D42:1; /* Power supply change detection flag */
+     unsigned char D43:1; /* WDT overflow detect flag */
+     unsigned char DF0:1; /* Sampling clock select bit */
+     unsigned char DF1:1; /* Sampling clock select bit */
+     unsigned char    :1; /* Nothing assigned */
+     unsigned char    :1; /* Nothing assigned */
+   } BIT;                       /*                                                             */
+     unsigned char BYTE;     /*  Byte Access                                           */
+};                           /* Power supply down detection register   */
+
+/*------------------------------------------------------
+   DMA0 source pointer //0x0020
+-----------------------------------------------------*/
+union st_sar0 {
+   struct{
+       unsigned char SAR01;     /* DMA0 source pointer low  8 bit                               */
+       unsigned char SAR0M;     /* DMA0 source pointer mid  8 bit                               */
+       unsigned char SAR0H;     /* DMA0 source pointer high 8 bit                               */
+       unsigned char NC;        /* non use                                                                      */
+   } BYTE;                                      /* Byte access                                                                  */
+   unsigned long   DWORD;       /*     Word Access                                                                      */
+};                                                      /* DMA0 source pointer 32 bit                                   */
+
+/*------------------------------------------------------
+   DMA1 source pointer //0x0030
+-----------------------------------------------------*/
+union st_sar1 {
+   struct{
+       unsigned char SAR11;     /* DMA1 source pointer low  8 bit                               */
+       unsigned char SAR1M;     /* DMA1 source pointer mid  8 bit                               */
+       unsigned char SAR1H;     /* DMA1 source pointer high 8 bit                               */
+       unsigned char NC;        /* non use                                                                      */
+   } BYTE;                                      /* Byte access                                                                  */
+   unsigned long   DWORD;       /* Word Access                                                                  */
+};                                              /* DMA1 source pointer 32 bit                                   */
+
+/*------------------------------------------------------
+   DMA0 destination pointer //0x0024
+-----------------------------------------------------*/
+union st_dar0 {                                 /* DMA0 destination pointer 32 bit                              */
+   struct{
+       unsigned char DAR0L;     /* DMA0 destination pointer low  8 bit                  */
+       unsigned char DAR0M;     /* DMA0 destination pointer mid  8 bit          */
+       unsigned char DAR0H;     /* DMA0 destination pointer high 8 bit                  */
+       unsigned char NC;        /* non use                                                                      */
+   } BYTE;                                      /* Byte access                                                                  */
+    unsigned long DWORD;        /* Word Access                                                                  */
+};
+
+/*------------------------------------------------------
+  DMA1 destination pointer //0x0034
+-----------------------------------------------------*/
+union st_dar1 {                                  /* DMA1 destination pointer 32 bit                     */
+   struct{
+       unsigned char DAR1L;     /* DMA1 destination pointer low  8 bit                  */
+       unsigned char DAR1M;     /* DMA1 destination pointer mid  8 bit                  */
+       unsigned char DAR1H;     /* DMA1 destination pointer high 8 bit                  */
+       unsigned char NC;        /* non use                                                                      */
+   } BYTE;                                      /* Byte access                                                                  */
+   unsigned long   DWORD;       /* Word Access                                                                  */
+};
+
+/*------------------------------------------------------
+  DMA0 transfer counter //0x0028
+-----------------------------------------------------*/
+union st_tcr0 {                                 /* DMA0 transfer counter 16 bit                                 */
+   struct{
+       unsigned char TCR0L;     /* DMA0 transfer counter low  8 bit                     */
+       unsigned char TCR0H;     /* DMA0 transfer counter high 8 bit                     */
+   } BYTE;                                      /* Byte access                                                          */
+   unsigned short   WORD;       /* Word Access                                                          */
+};
+
+/*------------------------------------------------------
+  DMA1 transfer counter //0x0038
+-----------------------------------------------------*/
+union st_tcr1 {                                  /* DMA1 transfer counter 16 bit                                */
+   struct{
+       unsigned char TCR1L;     /* DMA1 transfer counter low  8 bit                     */
+       unsigned char TCR1H;     /* DMA1 transfer counter high 8 bit                     */
+   } BYTE;                                      /* Byte access                                                          */
+   unsigned short WORD;             /* Word Access                                                              */
+};
+
+/*------------------------------------------------------
+    DMA0 control register //0x002c
+------------------------------------------------------*/
+union st_dm0con {                     /* DMA0 control register                         */
+   struct{
+     unsigned char    DMBIT:1; /* Transfer unit bit select bit                                 */
+     unsigned char    DMASL:1; /* Repeat transfer mode select bit                      */
+     unsigned char    DMAS :1; /* DMA request bit                                                      */
+     unsigned char    DMAE :1; /* DMA enable bit                                                       */
+     unsigned char    DSD  :1; /* Source address direction select bit          */
+     unsigned char    DAD  :1; /* Destination address direction select bit  */
+     unsigned char        :1;
+     unsigned char         :1;
+   }BIT;
+    unsigned char  BYTE;
+};
+
+/*------------------------------------------------------
+    DMA1 control register //0x003c
+------------------------------------------------------*/
+union st_dm1con {              /*    DMA1 control register union */
+    struct{
+     unsigned char    DMBIT:1; /* Transfer unit bit select bit                                 */
+     unsigned char    DMASL:1; /* Repeat transfer mode select bit                      */
+     unsigned char    DMAS :1; /* DMA request bit                                                      */
+     unsigned char    DMAE :1; /* DMA enable bit                                                       */
+     unsigned char    DSD  :1; /* Source address direction select bit                  */
+     unsigned char    DAD  :1; /* Destination address direction select bit  */
+     unsigned char        :1; /*Nothing assigned */
+     unsigned char         :1; /*Nothing assigned */
+    }BIT;
+    unsigned char  BYTE;
+};
+
+union st_icr {                    /*    interrupt control registers      */
+    struct{
+     unsigned char    ILVL0:1; /* Interrupt priority level select bit */
+     unsigned char    ILVL1:1; /* Interrupt priority level select bit */
+     unsigned char    ILVL2:1; /* Interrupt priority level select bit */
+     unsigned char    IR   :1; /* Interrupt request bit                          */
+     unsigned char    POL  :1; /* Polarity select bit                            */
+     unsigned char         :1; /* Reserved bit, set to 0              */
+     unsigned char        :1; /* Nothing assigned                                        */
+     unsigned char         :1; /* Nothing assigned                                       */
+    }BIT;
+    unsigned char    BYTE;
+};
+
+union st_icr1 {                           /*    interrupt control registers      */
+    struct{
+     unsigned char    ILVL0:1; /* Interrupt priority level select bit */
+     unsigned char    ILVL1:1; /* Interrupt priority level select bit */
+     unsigned char    ILVL2:1; /* Interrupt priority level select bit */
+     unsigned char    IR   :1; /* Interrupt request bit                          */
+     unsigned char         :1; /* Nothing assigned                                       */
+     unsigned char         :1; /* Nothing assigned                                       */
+     unsigned char        :1; /* Nothing assigned                                        */
+     unsigned char         :1; /* Nothing assigned                                       */
+    }BIT;
+    unsigned char    BYTE;
+};
+
+/*------------------------------------------------------
+     bcnic //0x004a
+------------------------------------------------------*/
+union st_bcnic {                                       /*    interrupt control registers*/
+    struct{
+     unsigned char    ILVL0_BCNIC:1;/* Interrupt priority level select bit */
+     unsigned char    ILVL1_BCNIC:1;/* Interrupt priority level select bit */
+     unsigned char    ILVL2_BCNIC:1;/* Interrupt priority level select bit */
+     unsigned char    IR_BCNIC   :1;/* Interrupt request bit */
+     unsigned char                  :1;
+     unsigned char               :1;
+     unsigned char               :1;
+     unsigned char               :1;
+    }BIT;
+    unsigned char    BYTE;
+};
+
+/*------------------------------------------------------
+     dm0ic //0x004b
+------------------------------------------------------*/
+union st_dm0ic {                                       /*    interrupt control registers*/
+    struct{
+     unsigned char    ILVL0_DM0IC:1;/* Interrupt priority level select bit */
+     unsigned char    ILVL1_DM0IC:1;/* Interrupt priority level select bit */
+     unsigned char    ILVL2_DM0IC:1;/* Interrupt priority level select bit */
+     unsigned char    IR_DM0IC   :1;/* Interrupt request bit                      */
+     unsigned char                  :1;
+     unsigned char               :1;
+     unsigned char               :1;
+     unsigned char               :1;
+    }BIT;
+    unsigned char    BYTE;
+};
+
+/*------------------------------------------------------
+    Flash identification register //0x01b4
+------------------------------------------------------*/
+union st_fidr {                           /*    Flash identification register         */
+    struct{
+     unsigned char    FIDR0:1; /* Flash identification value */
+     unsigned char    FIDR1:1; /* Flash identification value */
+     unsigned char         :1; /* Nothing assigned                                                     */
+     unsigned char         :1; /* Nothing assigned                                                     */
+     unsigned char         :1; /* Nothing assigned                             */
+     unsigned char         :1; /* Nothing assigned                          */
+     unsigned char        :1; /* Nothing assigned */
+     unsigned char         :1; /* Nothing assigned */
+    }BIT;
+    unsigned char  BYTE;
+};
+
+/*------------------------------------------------------
+    Flash memory control register 1 //0x01b5
+------------------------------------------------------*/
+union st_fmr1 {                           /*    Flash identification register         */
+    struct{
+     unsigned char         :1; /* Reserved bit   */
+     unsigned char    FMR11:1; /* EW1 mode select bit */
+     unsigned char         :1; /* Reserved bit   */
+     unsigned char         :1; /* Reserved bit   */
+     unsigned char         :1; /* Reserved bit */
+     unsigned char         :1; /* Reserved bit    */
+     unsigned char    FMR16:1; /* Lock bit status flag */
+     unsigned char         :1; /* Reserved bit   */
+    }BIT;
+    unsigned char  BYTE;
+};
+
+/*------------------------------------------------------
+    Flash memory control register 0 //0x01b7
+------------------------------------------------------*/
+union st_fmr0 {                           /*    Flash identification register         */
+    struct{
+     unsigned char    FMR00:1; /* RY/BY~ status flag */
+     unsigned char    FMR01:1; /* EW0 mode select bit */
+     unsigned char    FMR02:1; /* Lock bit disable bit */
+     unsigned char    FMSTP:1; /* Flash memory stop bit */
+     unsigned char         :1; /* Reserved bit */
+     unsigned char    FMR05:1; /* User ROM area select bit */
+     unsigned char    FMR06:1; /* Program status flag */
+     unsigned char    FMR07:1; /* Erase status flag */
+    }BIT;
+    unsigned char  BYTE;
+};
+
+/*------------------------------------------------------
+   Address match interrupt register 2 //0x01b8
+-----------------------------------------------------*/
+union st_rmad2 {
+   struct{
+       unsigned char RMAD2L;     /* Address match interrupt register 2 low  8 bit */
+       unsigned char RMAD2M;     /* Address match interrupt register 2 mid  8 bit */
+       unsigned char RMAD2H;     /* Address match interrupt register 2 high 8 bit */
+       unsigned char NC;         /* non use                                                                       */
+   } BYTE;                                       /* Byte access                                                                   */
+   unsigned long   DWORD;        /*    Word Access                                                                */
+};                                                       /* Address match interrupt register 2 32 bit     */
+
+
+/*------------------------------------------------------
+    Address match interrupt enable register 2 //0x01bb
+------------------------------------------------------*/
+union st_aier2 {                          /* Address match interrupt enable register 2        */
+    struct{
+     unsigned char    AIER20:1; /* Address match interrupt 2 enable bit */
+     unsigned char    AIER21:1; /* Address match interrupt 3 enable bit */
+     unsigned char          :1; /* Nothing assigned */
+     unsigned char          :1; /* Nothing assigned */
+     unsigned char          :1; /* Nothing assigned    */
+     unsigned char          :1; /* Nothing assigned */
+     unsigned char          :1; /* Nothing assigned */
+     unsigned char          :1; /* Nothing assigned */
+    }BIT;
+    unsigned char  BYTE;
+};
+
+/*------------------------------------------------------
+   Address match interrupt register 3 //0x01bc
+-----------------------------------------------------*/
+union st_rmad3 {
+   struct{
+       unsigned char RMAD3L;     /* Address match interrupt register 3 low  8 bit */
+       unsigned char RMAD3M;     /* Address match interrupt register 3 mid  8 bit */
+       unsigned char RMAD3H;     /* Address match interrupt register 3 high 8 bit */
+       unsigned char NC;         /* non use                                                                       */
+   } BYTE;                                       /* Byte access                                                                   */
+   unsigned long   DWORD;        /*    Word Access                                                                */
+};                                                       /* Address match interrupt register 3 32 bit     */
+
+/*------------------------------------------------------
+    Peripheral clock select register //0x025e
+------------------------------------------------------*/
+union st_pclkr {                          /* Peripheral clock select register        */
+    struct{
+     unsigned char    PCLK0 :1; /* TimerA,B clock select bit */
+     unsigned char    PCLK1 :1; /* SI/O clock select bit */
+     unsigned char          :1; /* Reserved bit,set to 0 */
+     unsigned char          :1; /* Reserved bit,set to 0 */
+     unsigned char          :1; /* Reserved bit,set to 0       */
+     unsigned char          :1; /* Reserved bit,set to 0 */
+     unsigned char          :1; /* Reserved bit,set to 0 */
+     unsigned char          :1; /* Reserved bit,set to 0 */
+    }BIT;
+    unsigned char  BYTE;
+};
+
+/*------------------------------------------------------
+    Timer B3,4,5 Count start flag //0x0340
+------------------------------------------------------*/
+union st_tbsr {              /* union tbsr                                             */
+       struct {                 /* Bit  Access                                                 */
+        unsigned char          :1;  /* Nothing Assigned                                        */
+        unsigned char          :1;  /* Nothing Assigned                                        */
+        unsigned char          :1;  /* Nothing Assigned                                        */
+        unsigned char          :1;  /* Nothing Assigned                                        */
+        unsigned char          :1;  /* Nothing Assigned                                        */
+        unsigned char  TB3S:1;  /* Timer B3 count start flag                   */
+        unsigned char  TB4S:1;  /* Timer B4 count start flag                   */
+        unsigned char  TB5S:1;  /* Timer B5 count start flag                   */
+       } BIT;                           /*                                                             */
+       unsigned  char BYTE;     /*  Byte Access                                                */
+};                           /* Timer B3,4,5 Count start flag       */
+
+/*------------------------------------------------------
+   Three-phase PWM control regester 0 //0x0348
+------------------------------------------------------*/
+union st_invc0 {            /* union invc0                                                     */
+       struct {                /* Bit  Access                                                  */
+        unsigned char  INV00:1;/* Effective interrupt output polarity select bit */
+        unsigned char  INV01:1;/* Effective interrupt output specification bit */
+        unsigned char  INV02:1;/* Mode select bit                                              */
+        unsigned char  INV03:1;/* Output control bit                                   */
+        unsigned char  INV04:1;/* Positive and negative phases concurrent L output disable function enable bit */
+        unsigned char  INV05:1;/* Positive and negative phases concurrent L output detect flag */
+        unsigned char  INV06:1;/* Modulation mode select bit                   */
+        unsigned char  INV07:1;/* Software trigger bit                                 */
+       } BIT;                          /*                                                              */
+        unsigned char BYTE;    /*  Byte Access                                                 */
+};                          /*                                                                 */
+
+/*------------------------------------------------------
+    Three-phase PWM control regester 1 //0x0349
+------------------------------------------------------*/
+union st_invc1 {            /* union invc1                                                             */
+       struct {                /* Bit  Access                                                          */
+        unsigned char  INV10:1;/* Timer Ai start trigger signal select bit */
+        unsigned char  INV11:1;/* Timer A1-1,A2-1,A4-1 control bit             */
+        unsigned char  INV12:1;/* Short circuit timer count source select bit*/
+        unsigned char           :1;/* Nothing Assigned                                                 */
+        unsigned char           :1;/* Reserved bit (always 0)                                  */
+        unsigned char           :1;/* Nothing Assigned                                                 */
+        unsigned char           :1;/* Nothing Assigned                                                 */
+        unsigned char           :1;/* Nothing Assigned                                                 */
+       } BIT;                          /*                                                                      */
+       unsigned char BYTE;     /*  Byte Access                                                         */
+};                          /*                                                                         */
+
+/*------------------------------------------------------
+    Three-phase output buffer register 0 //0x034a
+------------------------------------------------------*/
+union st_idb0 {            /* union idb0                                                       */
+       struct {                   /* Bit  Access                                                       */
+        unsigned char  DU0 :1;/* U  phase output buffer 0                              */
+        unsigned char  DUB0:1;/* U~ phase output buffer 0                              */
+        unsigned char  DV0 :1;/* V  phase output buffer 0                              */
+        unsigned char  DVB0:1;/* V~ phase output buffer 0                              */
+        unsigned char  DW0 :1;/* W  phase output buffer 0                              */
+        unsigned char  DWB0:1;/* W~ phase output buffer 0                              */
+        unsigned char          :1;/* Nothing Assigned                                          */
+        unsigned char          :1;/* Nothing Assigned                                          */
+       } BIT;                             /*                                                           */
+       unsigned char BYTE;    /*  Byte Access                                                  */
+};                         /*                                                          */
+
+/*------------------------------------------------------
+    Three-phase output buffer register 1 //0x034b
+------------------------------------------------------*/
+union st_idb1 {            /* union idb1                                                       */
+       struct {                   /* Bit  Access                                                       */
+        unsigned char  DU1 :1;/* U  phase output buffer 1                              */
+        unsigned char  DUB1:1;/* U~ phase output buffer 1                              */
+        unsigned char  DV1 :1;/* V  phase output buffer 1                              */
+        unsigned char  DVB1:1;/* V~ phase output buffer 1                              */
+        unsigned char  DW1 :1;/* W  phase output buffer 1                              */
+        unsigned char  DWB1:1;/* W~ phase output buffer 1                              */
+        unsigned char          :1;/* Nothing Assigned                                          */
+        unsigned char          :1;/* Nothing Assigned                                          */
+       } BIT;                             /*                                                           */
+       unsigned char BYTE;    /*  Byte Access                                                  */
+};                         /*                                                          */
+
+/*----------------------------------------------------------------------------------
+   Timer mode registers  //0x035b,0x035c,0x035d,0x0396,
+                           0x0397,0x0398,0x0399,0x039a,0x039b,0x039c
+---------------------------------------------------------------------------------*/
+union st_tmr {               /* union tmr                                              */
+       struct {                 /* Bit  Access                                                 */
+        unsigned char  TMOD0:1; /* Operation mode select bit                   */
+        unsigned char  TMOD1:1; /* Operation mode select bit                   */
+        unsigned char  MR0      :1; /* Pulse output function select bit        */
+        unsigned char  MR1  :1; /* External trigger select bit                 */
+        unsigned char  MR2  :1; /* Trigger select bit                                  */
+        unsigned char  MR3  :1; /* Must always be "0" in one-shot timer*/
+        unsigned char  TCK0 :1; /* Count source select bit                     */
+        unsigned char  TCK1 :1; /* Count source select bit                     */
+       } BIT;                           /*                                                             */
+       unsigned char BYTE;      /*  Byte Access                                                */
+};
+
+/*------------------------------------------------------
+   Interrupt request cause select register 2  //0x035e
+------------------------------------------------------*/
+union st_ifsr2a {               /* union ifsr2a                                                */
+       struct {                 /* Bit  Access                                 */
+        unsigned char        :1; /* Nothing assigned                   */
+        unsigned char        :1; /* Nothing assigned                   */
+        unsigned char        :1; /* Nothing assigned                   */
+        unsigned char        :1; /* Nothing assigned                   */
+        unsigned char        :1; /* Nothing assigned                   */
+        unsigned char        :1; /* Nothing assigned            */
+        unsigned char IFSR26 :1; /* Interrupt request cause select bit */
+        unsigned char IFSR27 :1; /* Interrupt request cause select bit */
+       } BIT;                           /*                                                             */
+       unsigned char BYTE;      /*  Byte Access                                                */
+};
+
+/*------------------------------------------------------
+Interrupt request cause select register //0x035f
+-----------------------------------------------------*/
+union st_ifsr {              /* union IFSR                                                     */
+       struct {                 /* Bit  Access                                                         */
+        unsigned char  IFSR0:1; /* INT0~ interrupt polarity switching bit  */
+        unsigned char  IFSR1:1; /* INT1~ interrupt polarity switching bit  */
+        unsigned char  IFSR2:1; /* INT2~ interrupt polarity switching bit  */
+        unsigned char  IFSR3:1; /* INT3~ interrupt polarity switching bit  */
+        unsigned char  IFSR4:1; /* INT4~ interrupt polarity switching bit  */
+        unsigned char  IFSR5:1; /* INT5~ interrupt polarity switching bit  */
+        unsigned char  IFSR6:1; /* Interrupt request cause select bit          */
+        unsigned char  IFSR7:1; /* Interrupt request cause select bit          */
+       } BIT;                           /*                                                                     */
+       unsigned char BYTE;      /*  Byte Access                                                        */
+};                           /*                                                                */
+
+/*------------------------------------------------------
+   SI/O4 control registers //0x0360
+------------------------------------------------------*/
+union st_s4c {              /* union S4C                                                       */
+       struct {                        /* Bit  Access                                                          */
+        unsigned char  SM40:1; /* Internal synchronous clock select bit */
+        unsigned char  SM41:1; /* Internal synchronous clock select bit */
+        unsigned char  SM42:1; /* Sout4 output disable bit */
+        unsigned char  SM43:1; /* SI/O4 port select bit */
+        unsigned char  SM44:1; /* CLK polarity select bit */
+        unsigned char  SM45:1; /* Transfer direction select bit */
+        unsigned char  SM46:1; /* Synchronous clock select bit */
+        unsigned char  SM47:1; /* Sout4 initial value set bit */
+       } BIT;                          /*                                                                      */
+       unsigned char BYTE;     /*  Byte Access                                                         */
+};
+
+/*------------------------------------------------------
+   SI/O3 control registers //0x0362
+------------------------------------------------------*/
+union st_s3c {              /* union S3C                                                       */
+       struct {                /* Bit  Access                                                          */
+        unsigned char  SM30:1; /* Internal synchronous clock select bit */
+        unsigned char  SM31:1; /* Internal synchronous clock select bit */
+        unsigned char  SM32:1; /* Sout3 output disable bit */
+        unsigned char  SM33:1; /* SI/O3 port select bit */
+        unsigned char  SM34:1; /* CLK polarity select bit */
+        unsigned char  SM35:1; /* Transfer direction select bit */
+        unsigned char  SM36:1; /* Synchronous clock select bit */
+        unsigned char  SM37:1; /* Sout3 initial value set bit */
+       } BIT;                                  /*                                                                      */
+       unsigned char BYTE;     /*  Byte Access                                                         */
+};                          /*                                                                         */
+
+/*------------------------------------------------------
+   UART0 special mode register 4 //0x036c
+------------------------------------------------------*/
+union st_u0smr4 {              /* union u0smr4                                                         */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char  STAREQ :1; /* Start condition generate bit   */
+        unsigned char  RSTAREQ:1; /* Restart condition generate bit */
+        unsigned char  STPREQ :1; /* Stop condition generate bit    */
+        unsigned char  STSPSEL:1; /* SCL,SDA output select bit      */
+        unsigned char  ACKD   :1; /* ACK data bit                   */
+        unsigned char  ACKC   :1; /* ACK data output enable bit     */
+        unsigned char  SCLHI  :1; /* SCL output stop enable bit     */
+        unsigned char  SWC9   :1; /* Final bit L hold enable bit    */
+       } BIT;                                  /*                                                                      */
+       unsigned char BYTE;     /*  Byte Access                                                         */
+};                          /*                                                                         */
+
+/*------------------------------------------------------
+   UART0 special mode register 3 //0x036d
+------------------------------------------------------*/
+union st_u0smr3 {              /* union u0smr3                                                         */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char         :1; /* Nothing is assigned                */
+        unsigned char  CKPH   :1; /* Clock phase set bit                */
+        unsigned char         :1; /* Nothing is assigned                */
+        unsigned char  NODC   :1; /* Clock output set bit               */
+        unsigned char         :1; /* Nothing is assigned                */
+        unsigned char  DL0    :1; /* SDA0(TxD0) digital delay setup bit */
+        unsigned char  DL1    :1; /* SDA0(TxD0) digital delay setup bit */
+        unsigned char  DL2    :1; /* SDA0(TxD0) digital delay setup bit */
+       } BIT;                                     /*                                                        */
+       unsigned char BYTE;        /*  Byte Access                                               */
+};                             /*                                                           */
+
+/*------------------------------------------------------
+   UART0 special mode register 2 //0x036e
+------------------------------------------------------*/
+union st_u0smr2 {              /* union u0smr2                                                         */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char  IICM2 :1; /* IIC mode selection bit 2 */
+        unsigned char  CSC   :1; /* Clock-synchronous bit    */
+        unsigned char  SWC   :1; /* SCL wait output bit      */
+        unsigned char  ALS   :1; /* SDA output stop bit      */
+        unsigned char  STAC  :1; /* UART0 initialization bit */
+        unsigned char  SWC2  :1; /* SCL wait output bit 2    */
+        unsigned char  SDHI  :1; /* SDA output disable bit   */
+        unsigned char        :1; /* Nothing is assigned      */
+       } BIT;                                     /*                                                        */
+       unsigned char BYTE;        /*  Byte Access                                               */
+};                             /*                                                           */
+
+/*------------------------------------------------------
+   UART0 special mode register  //0x036f
+------------------------------------------------------*/
+union st_u0smr {              /* union u0smr                                                   */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char  IICM:1; /* IIC mode selection bit */
+        unsigned char  ABC :1; /* Arbitration lost detecting flag control bit */
+        unsigned char  BBS :1; /* Bus busy flag */
+        unsigned char      :1; /* Reserved bit,set to 0 */
+        unsigned char  ABSC:1; /* Bus collision detect sampling clock select bit */
+        unsigned char  ACSE:1; /* Auto clear function select bit of transmit enable bit */
+        unsigned char  SSS :1; /* Transmit start condition select bit */
+        unsigned char      :1; /* Nothing is assigned      */
+       } BIT;                                     /*                                                        */
+       unsigned char BYTE;        /*  Byte Access                                               */
+};                             /*                                                           */
+
+/*------------------------------------------------------
+   UART1 special mode register 4 //0x0370
+------------------------------------------------------*/
+union st_u1smr4 {              /* union u1smr4                                                         */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char  STAREQ:1; /* Start condition generate bit */
+        unsigned char  RSTARE:1; /* Restart condition generate bit */
+        unsigned char  STPREQ:1; /* Stop condition generate bit */
+        unsigned char  STSPSE:1; /* SCL,SDA output select bit */
+        unsigned char  ACKD  :1; /* ACK data bit */
+        unsigned char  ACKC  :1; /* ACK data output enable bit */
+        unsigned char  SCLHI :1; /* SCL output stop enable bit */
+        unsigned char  SWC9  :1; /* Final bit L hold enable bit */
+       } BIT;                                     /*                                                        */
+       unsigned char BYTE;        /*  Byte Access                                               */
+};                             /*                                                           */
+
+/*------------------------------------------------------
+   UART1 special mode register 3 //0x0371
+------------------------------------------------------*/
+union st_u1smr3 {              /* union u1smr3                                                         */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char         :1; /* Nothing is assigned                */
+        unsigned char  CKPH   :1; /* Clock phase set bit                */
+        unsigned char         :1; /* Nothing is assigned                */
+        unsigned char  NODC   :1; /* Clock output set bit               */
+        unsigned char         :1; /* Nothing is assigned                */
+        unsigned char  DL0    :1; /* SDA1(TxD1) digital delay setup bit */
+        unsigned char  DL1    :1; /* SDA1(TxD1) digital delay setup bit */
+        unsigned char  DL2    :1; /* SDA1(TxD1) digital delay setup bit */
+       } BIT;                                     /*                                                        */
+       unsigned char BYTE;        /*  Byte Access                                               */
+};                             /*                                                           */
+
+/*------------------------------------------------------
+   UART1 special mode register 2 //0x0372
+------------------------------------------------------*/
+union st_u1smr2 {              /* union u1smr2                                                         */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char  IICM2 :1; /* IIC mode selection bit 2 */
+        unsigned char  CSC   :1; /* Clock-synchronous bit    */
+        unsigned char  SWC   :1; /* SCL wait output bit      */
+        unsigned char  ALS   :1; /* SDA output stop bit      */
+        unsigned char  STAC  :1; /* UART0 initialization bit */
+        unsigned char  SWC2  :1; /* SCL wait output bit 2    */
+        unsigned char  SDHI  :1; /* SDA output disable bit   */
+        unsigned char        :1; /* Nothing is assigned      */
+       } BIT;                                     /*                                                        */
+       unsigned char BYTE;        /*  Byte Access                                               */
+};                             /*                                                           */
+
+/*------------------------------------------------------
+   UART1 special mode register  //0x0373
+------------------------------------------------------*/
+union st_u1smr {              /* union u1smr                                                   */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char  IICM:1; /* IIC mode selection bit */
+        unsigned char  ABC :1; /* Arbitration lost detecting flag control bit */
+        unsigned char  BBS :1; /* Bus busy flag */
+        unsigned char      :1; /* Reserved bit,set to 0 */
+        unsigned char  ABSC:1; /* Bus collision detect sampling clock select bit */
+        unsigned char  ACSE:1; /* Auto clear function select bit of transmit enable bit */
+        unsigned char  SSS :1; /* Transmit start condition select bit */
+        unsigned char      :1; /* Nothing is assigned      */
+       } BIT;                                     /*                                                        */
+       unsigned char BYTE;        /*  Byte Access                                               */
+};                             /*                                                           */
+
+/*------------------------------------------------------
+   UART2 special mode register 4 //0x0374
+------------------------------------------------------*/
+union st_u2smr4 {              /* union u1smr4                                                         */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char  STAREQ:1; /* Start condition generate bit */
+        unsigned char  RSTARE:1; /* Restart condition generate bit */
+        unsigned char  STPREQ:1; /* Stop condition generate bit */
+        unsigned char  STSPSE:1; /* SCL,SDA output select bit */
+        unsigned char  ACKD  :1; /* ACK data bit */
+        unsigned char  ACKC  :1; /* ACK data output enable bit */
+        unsigned char  SCLHI :1; /* SCL output stop enable bit */
+        unsigned char  SWC9  :1; /* Final bit L hold enable bit */
+       } BIT;                                     /*                                                        */
+       unsigned char BYTE;        /*  Byte Access                                               */
+};                             /*                                                           */
+
+/*------------------------------------------------------
+    UART2 special mode register 3 //0x0375
+------------------------------------------------------*/
+union st_u2smr3 {              /* union U2SMR3                                                 */
+       struct {                   /* Bit  Access                                                       */
+        unsigned char         :1; /* Nothing is assigned                */
+        unsigned char   CKPH  :1; /* Clock phase set bit                */
+        unsigned char         :1; /* Nothing is assigned                */
+        unsigned char   NODC  :1; /* Clock output set bit               */
+        unsigned char         :1; /* Nothing is assigned                */
+        unsigned char   DL0   :1; /* SDA digital delay setup bit                       */
+        unsigned char   DL1   :1; /* SDA digital delay setup bit                       */
+        unsigned char   DL2   :1; /* SDA digital delay setup bit                       */
+       } BIT;                          /*                                                              */
+       unsigned char BYTE;     /*  Byte Access                                                 */
+};                          /*                                                                 */
+
+/*------------------------------------------------------
+    UART2 special mode register 2 //0x0376
+------------------------------------------------------*/
+union st_u2smr2 {            /* union U2SMR2                                                   */
+       struct {                     /* Bit  Access                                                     */
+        unsigned char  IICM2:1; /* IIC mode selection bit 2                            */
+        unsigned char  CSC  :1; /* Clock-synchronous bit                                       */
+        unsigned char  SWC  :1; /* SCL wait output bit                                         */
+        unsigned char  ALS  :1; /* SDA output stop bit                                         */
+        unsigned char  STAC :1; /* UART2 initialization bit                            */
+        unsigned char  SWC2 :1; /* SCL wait output bit 2                                       */
+        unsigned char  SDHI :1; /* SDA output disable bit                                      */
+        unsigned char       :1; /* Nothing is assigned         */
+       } BIT;                               /*                                                                 */
+       unsigned char BYTE;      /*  Byte Access                                                        */
+};                           /*                                                                */
+
+/*------------------------------------------------------
+    UART2 special mode register //0x0377
+------------------------------------------------------*/
+union st_u2smr {             /* union U2SMR                                                                    */
+       struct {                 /* Bit  Access                                                                 */
+        unsigned char  IICM :1; /* IIC mode selection bit                                              */
+        unsigned char  ABC  :1; /* Arbitration lost detecting flag control bit */
+        unsigned char  BBS  :1; /* Reserved bit,set to 0                                                       */
+        unsigned char       :1; /* SCLL sync output enable bit                                 */
+        unsigned char  ABSCS:1; /* Bus collision detect sampling clock select bit */
+        unsigned char  ACSE :1; /* Auto clear function select bit of transmit enable bit */
+        unsigned char  SSS  :1; /* Transmit start condition select bit                 */
+        unsigned char       :1; /* Nothing is assigned                                 */
+       } BIT;                           /*                                                                                     */
+       unsigned char BYTE;      /*  Byte Access                                                                */
+};                           /*                                                                        */
+
+/*------------------------------------------------------
+    UART2 transmit/receive mode register //0x0378
+------------------------------------------------------*/
+union st_u2mr {                  /* union U2MR                                                         */
+       struct {                      /* Bit  Access                                                    */
+        unsigned char  SMD0_U2MR :1; /* Serial I/O mode select bit                     */
+        unsigned char  SMD1_U2MR :1; /* Serial I/O mode select bit                     */
+        unsigned char  SMD2_U2MR :1; /* Serial I/O mode select bit                     */
+        unsigned char  CKDIR_U2MR:1; /* Internal/external clock select bit             */
+        unsigned char  STPS_U2MR :1; /* Stop bit length select bit                     */
+        unsigned char  PRY_U2MR  :1; /* Odd/even parity select bit                     */
+        unsigned char  PRYE_U2MR :1; /* Parity enable bit                                              */
+        unsigned char  IOPOL_U2MR:1; /* TxD RxD I/O polarity reverse bit               */
+       } BIT;                                    /*                                                                                    */
+       unsigned char BYTE;           /*  Byte Access                                                   */
+};
+
+/*------------------------------------------------------
+    UART2 Transmit buffer register 16 bit //0x037a
+------------------------------------------------------*/
+union st_u2tb {                                 /* UART2 Transmit buffer register 16 bit ; Use "MOV" instruction when writing to this register. */
+   struct{
+       unsigned char U2TBL;     /* UART2 Transmit buffer register low  8 bit    */
+       unsigned char U2TBH;     /* UART2 Transmit buffer register high 8 bit    */
+   } BYTE;                                      /* Byte access                                                                  */
+   unsigned short   WORD;       /* Word Access                                                                  */
+};
+
+/*------------------------------------------------------
+    UART2 transmit/receive control register 0//0x037c
+------------------------------------------------------*/
+union st_u2c0 {                /* union U2C0                                                           */
+       struct {                        /* Bit  Access                                                          */
+        unsigned char  CLK0 :1;        /* BRG count source select bit                          */
+        unsigned char  CLK1 :1;        /* BRG count source select bit                          */
+        unsigned char  CRS  :1;        /* CTS~/RTS~ function select bit                        */
+        unsigned char  TXEPT:1;        /* Transmit register empty flag                         */
+        unsigned char  CRD  :1;        /* CTS~/RTS~ disable bit                                        */
+        unsigned char           :1;    /* Nothing Assigned                                                     */
+        unsigned char  CKPOL:1;        /* CLK polarity select bit                                      */
+        unsigned char  UFORM:1;        /* Transfer format select bit                           */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;         /* Byte Access                                                              */
+};                                                             /* UART2 transmit/receive control register 0*/
+
+/*------------------------------------------------------
+    UART2 transmit/receive control register 1 //0x037d
+-----------------------------------------------------*/
+union st_u2c1 {                /* union U2C1                                                           */
+       struct {                        /* Bit  Access                                                          */
+        unsigned char  TE_U2C1:1;      /* Transmit enable bit                                          */
+        unsigned char  TI_U2C1:1;      /* Transmit buffer empty flag                           */
+        unsigned char  RE_U2C1:1;      /* Receive enable bit                                           */
+        unsigned char  RI_U2C1:1;      /* Receive complete flag                                        */
+        unsigned char  U2IRS  :1;      /* UART2 transmit interrupt cause select bit*/
+        unsigned char  U2RRM  :1;      /* UART2 continuous receive mode enable bit */
+        unsigned char  U2LCH  :1;      /* Data logic select bit                                        */
+        unsigned char  U2ERE  :1;      /* Error signal output enable bit                       */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;         /* Byte Access                                                              */
+};                                                             /*UART2 transmit/receive control register 1 */
+
+/*------------------------------------------------------
+    UART2 receive buffer registers //0x037e
+------------------------------------------------------*/
+union st_u2rb {                                /* UART2 receive buffer register */
+    struct {                                           /*  Bit  Access */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /* Nothing assigned                                     */
+        unsigned char                  :1;             /* Nothing assigned                                     */
+        unsigned char  ABT_U2RB:1;     /* Arbitration lost detecting flag  */
+        unsigned char  OER_U2RB:1;     /* Overrun error flag                           */
+        unsigned char  FER_U2RB:1;     /* Framing error flag                           */
+        unsigned char  PER_U2RB:1;     /* Parity error flag                            */
+        unsigned char  SUM_U2RB:1;     /* Error sum flag                                       */
+    }BIT;
+    struct{
+        unsigned char    U2RBL;        /* Low  8 bit                                           */
+        unsigned char    U2RBH;        /* High 8 bit                                           */
+    }BYTE;
+    unsigned short  WORD;
+};
+
+/*------------------------------------------------------
+    Count start flag //0x0380
+------------------------------------------------------*/
+union st_tabsr {               /* union TABSR                                                          */
+       struct {                        /* Bit  Access                                                          */
+     unsigned char     TA0S:1;         /* Timer A0 count start flag                            */
+     unsigned char     TA1S:1;         /* Timer A1 count start flag                            */
+     unsigned char     TA2S:1;         /* Timer A2 count start flag                            */
+     unsigned char     TA3S:1;         /* Timer A3 count start flag                            */
+     unsigned char     TA4S:1;         /* Timer A4 count start flag                            */
+     unsigned char     TB0S:1;         /* Timer B0 count start flag                            */
+     unsigned char     TB1S:1;         /* Timer B1 count start flag                            */
+     unsigned char     TB2S:1;         /* Timer B2 count start flag                            */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;         /* Byte Access                                                              */
+};                                                             /*UART2 transmit/receive control register 1 */
+
+/*------------------------------------------------------
+    Clock prescaler reset flag //0x0381
+------------------------------------------------------*/
+union st_cpsrf {              /* union CPSRF                                                           */
+struct {      /* Bit  Access                                                           */
+     unsigned char             :1;   /*                                                                                        */
+     unsigned char             :1;   /*                                                                                        */
+     unsigned char             :1;   /*                                                                                        */
+     unsigned char             :1;   /*                                                                                        */
+     unsigned char             :1;   /*                                                                                        */
+     unsigned char             :1;   /*                                                                                        */
+     unsigned char             :1;   /*                                                                                        */
+     unsigned char     CPSR:1;   /* Clock prescaler reset flag                                 */
+        } BIT;           /*                                                                            */
+     unsigned char BYTE;      /* Byte Access                                                           */
+};                            /* Watchdog timer start register                         */
+
+/*------------------------------------------------------
+    One-shot start flag //0x0382
+------------------------------------------------------*/
+union st_onsf {                /* union ONSF                                                           */
+       struct {                        /* Bit  Access                                                          */
+        unsigned char   TA0OS:1;       /* Timer A0 one-shot start flag                         */
+        unsigned char   TA1OS:1;       /* Timer A1 one-shot start flag                         */
+        unsigned char   TA2OS:1;       /* Timer A2 one-shot start flag                         */
+        unsigned char   TA3OS:1;       /* Timer A3 one-shot start flag                         */
+        unsigned char   TA4OS:1;       /* Timer A4 one-shot start flag                         */
+        unsigned char   TAZIE:1;       /* Z phase input enable bit                             */
+        unsigned char  TA0TGL:1;       /* Timer A0 event/trigger select bit            */
+        unsigned char  TA0TGH:1;       /* Timer A0 event/trigger select bit            */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;         /* Byte Access                                                              */
+};                                                             /*UART2 transmit/receive control register 1 */
+
+/*------------------------------------------------------
+    Trigger select register //0x0383
+------------------------------------------------------*/
+union st_trgsr {               /* union TRGSR                                                          */
+               struct {                /* Bit  Access                                                          */
+        unsigned char  TA1TGL:1;       /* Timer A1 event/trigger select bit            */
+        unsigned char  TA1TGH:1;       /* Timer A1 event/trigger select bit            */
+        unsigned char  TA2TGL:1;       /* Timer A2 event/trigger select bit            */
+        unsigned char  TA2TGH:1;       /* Timer A2 event/trigger select bit            */
+        unsigned char  TA3TGL:1;       /* Timer A3 event/trigger select bit            */
+        unsigned char  TA3TGH:1;       /* Timer A3 event/trigger select bit            */
+        unsigned char  TA4TGL:1;       /* Timer A4 event/trigger select bit            */
+        unsigned char  TA4TGH:1;       /* Timer A4 event/trigger select bit            */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;             /* Byte Access                                                          */
+};                                                             /*UART2 transmit/receive control register 1 */
+
+/*------------------------------------------------------
+    Timer B2 special mode register //0x039e
+------------------------------------------------------*/
+union st_tb2sc {               /* union tb2sc                                                           */
+               struct {                /* Bit  Access                                                           */
+        unsigned char  PWCON :1;       /* Timer B2 reload timing switching bit      */
+        unsigned char  IVPCR1:1;       /* Three phase output port NMI control bit 1 */
+        unsigned char        :1;       /* Nothing is assigned                           */
+        unsigned char        :1;       /* Nothing is assigned                               */
+        unsigned char        :1;       /* Nothing is assigned                               */
+        unsigned char        :1;       /* Nothing is assigned                               */
+        unsigned char        :1;       /* Nothing is assigned                               */
+        unsigned char        :1;       /* Nothing is assigned                               */
+       } BIT;                                  /*                                                                               */
+       unsigned char BYTE;         /* Byte Access                                                              */
+};                                                             /*UART2 transmit/receive control register 1 */
+
+/*------------------------------------------------------
+    UART0 transmit/receive mode register //0x03a0
+------------------------------------------------------*/
+union st_u0mr {                  /* union U0MR                                                         */
+       struct {                      /* Bit  Access                                                    */
+        unsigned char  SMD0_U0MR :1; /* Serial I/O mode select bit                     */
+        unsigned char  SMD1_U0MR :1; /* Serial I/O mode select bit                     */
+        unsigned char  SMD2_U0MR :1; /* Serial I/O mode select bit                     */
+        unsigned char  CKDIR_U0MR:1; /* Internal/external clock select bit     */
+        unsigned char  STPS_U0MR :1; /* Stop bit length select bit                     */
+        unsigned char  PRY_U0MR  :1; /* Odd/even parity select bit                     */
+        unsigned char  PRYE_U0MR :1; /* Parity enable bit                                              */
+        unsigned char  IOPOL_U0MR :1; /* TxD,RxD I/O polarity reverse bit              */
+       } BIT;                                    /*                                                                            */
+       unsigned char BYTE;           /* Byte Access                                                    */
+};
+
+/*------------------------------------------------------
+    UART0 transmit/receive mode register //0x03a2
+------------------------------------------------------*/
+union st_u0tb {                                /* UART0 Transmit buffer register 16 bit ; Use "MOV" instruction when writing to this register. */
+   struct{
+       unsigned char U0TBL;     /* UART0 Transmit buffer register low  8 bit    */
+       unsigned char U0TBH;     /* UART0 Transmit buffer register high 8 bit    */
+   } BYTE;                                      /* Byte access                                                                  */
+   unsigned short   WORD;       /* Word Access                                                                  */
+};
+
+/*------------------------------------------------------
+    UARTi transmit/receive control register 0 //0x03a4
+------------------------------------------------------*/
+union st_u0c0 {                /* union U0C0                                                           */
+       struct {                        /* Bit  Access                                                          */
+        unsigned char  CLK0 :1;        /* BRG count source select bit                          */
+        unsigned char  CLK1 :1;        /* BRG count source select bit                          */
+        unsigned char  CRS  :1;        /* CTS~/RTS~ function select bit                        */
+        unsigned char  TXEPT:1;        /* Transmit register empty flag                         */
+        unsigned char  CRD  :1;        /* CTS~/RTS~ disable bit                                        */
+        unsigned char  NCH  :1;        /* Data output select bit                                       */
+        unsigned char  CKPOL:1;        /* CLK polarity select bit                                      */
+        unsigned char  UFORM:1;        /* Transfer format select bit                           */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;         /* Byte Access                                                              */
+};                                                             /*UARTi transmit/receive control register 0 */
+
+/*------------------------------------------------------
+    UART0 transmit/receive control register 1 //0x03a5
+------------------------------------------------------*/
+union st_u0c1 {             /* union U0C1                                                                      */
+       struct {                /* Bit  Access                                                                  */
+        unsigned char  TE     :1;      /* Transmit enable bit                                                  */
+        unsigned char  TI     :1;      /* Transmit buffer empty flag                                   */
+        unsigned char  RE     :1;      /* Receive enable bit                                                   */
+        unsigned char  RI     :1;      /* Receive complete flag                                                */
+        unsigned char         :1;      /* Nothing Assigned                                                             */
+        unsigned char         :1;      /* Nothing Assigned                                                             */
+        unsigned char  U0LCH  :1;      /* Data logic select bit */
+        unsigned char  U0ERE  :1;      /* Error signal output enable bit */
+       } BIT;                          /*                                                                                      */
+       unsigned char BYTE;     /* Byte Access                                                                  */
+};                                                     /*UART0 transmit/receive control register 1     */
+
+/*------------------------------------------------------
+    UART0 receive buffer register //0x03a6
+------------------------------------------------------*/
+union st_u0rb {                                                /*  UART0 receive buffer register       */
+    struct {                                           /*  Bit  Access                                         */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /* Nothing assigned                                     */
+        unsigned char                  :1;             /* Nothing assigned                                     */
+        unsigned char  ABT_U0RB:1;     /* Arbitration lost detecting flag      */
+        unsigned char  OER_U0RB:1;     /* Overrun error flag                           */
+        unsigned char  FER_U0RB:1;     /* Framing error flag                           */
+        unsigned char  PER_U0RB:1;     /* Parity error flag                            */
+        unsigned char  SUM_U0RB:1;     /* Error sum flag                                       */
+    }BIT;
+    struct{
+     unsigned char U0RBL;              /* Low  8 bit                                           */
+     unsigned char U0RBH;           /* High 8 bit                                              */
+    }BYTE;
+    unsigned short  WORD;
+};
+
+/*------------------------------------------------------
+    UART1 transmit/receive mode register //0x03a8
+------------------------------------------------------*/
+union st_u1mr {                  /* union U1MR                                                         */
+       struct {                          /* Bit  Access                                                        */
+        unsigned char  SMD0_U1MR  :1; /* Serial I/O mode select bit                    */
+        unsigned char  SMD1_U1MR  :1; /* Serial I/O mode select bit                    */
+        unsigned char  SMD2_U1MR  :1; /* Serial I/O mode select bit                    */
+        unsigned char  CKDIR_U1MR :1; /* Internal/external clock select bit    */
+        unsigned char  STPS_U1MR  :1; /* Stop bit length select bit                    */
+        unsigned char  PRY_U1MR   :1; /* Odd/even parity select bit                    */
+        unsigned char  PRYE_U1MR  :1; /* Parity enable bit                                             */
+        unsigned char  IOPOL_U1MR :1; /* TxD,RxD I/O polarity reverse bit                      */
+       } BIT;                                    /*                                                                            */
+       unsigned char BYTE;           /* Byte Access                                                    */
+};
+
+/*------------------------------------------------------
+    UART1 transmit buffer register //0x03aa
+------------------------------------------------------*/
+union st_u1tb {                                 /* UART1 Transmit buffer register 16 bit ; Use "MOV" instruction when writing to this register. */
+   struct{
+       unsigned char U1TBL;     /* UART1 Transmit buffer register low  8 bit    */
+       unsigned char U1TBH;     /* UART1 Transmit buffer register high 8 bit    */
+   } BYTE;                                      /* Byte access                                                                  */
+   unsigned short   WORD;       /* Word Access                                                                  */
+};
+
+/*------------------------------------------------------
+     UART1 transmit/receive control register 0 //0x03ac
+------------------------------------------------------*/
+union st_u1c0 {                /* union UCR                                                            */
+       struct {                        /* Bit  Access                                                          */
+        unsigned char  CLK0 :1;        /* BRG count source select bit                          */
+        unsigned char  CLK1 :1;        /* BRG count source select bit                          */
+        unsigned char  CRS  :1;        /* CTS~/RTS~ function select bit                        */
+        unsigned char  TXEPT:1;        /* Transmit register empty flag                         */
+        unsigned char  CRD  :1;        /* CTS~/RTS~ disable bit                                        */
+        unsigned char  NCH  :1;        /* Data output select bit                                       */
+        unsigned char  CKPOL:1;        /* CLK polarity select bit                                      */
+        unsigned char  UFORM:1;        /* Transfer format select bit                           */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;         /* Byte Access                                                              */
+};                                                             /*UARTi transmit/receive control register 0 */
+
+/*------------------------------------------------------
+     UART1 transmit/receive control register 1 //0x03ad
+------------------------------------------------------*/
+union st_u1c1 {             /* union U1C1                                                                      */
+       struct {                /* Bit  Access                                                                  */
+        unsigned char  TE:1;   /* Transmit enable bit                                                  */
+        unsigned char  TI:1;   /* Transmit buffer empty flag                                   */
+        unsigned char  RE:1;   /* Receive enable bit                                                   */
+        unsigned char  RI:1;   /* Receive complete flag                                                */
+        unsigned char    :1;   /*                                                                                      */
+        unsigned char    :1;   /*                                                                                      */
+        unsigned char    :1;   /*                                                                                      */
+        unsigned char    :1;   /*                                                                                      */
+       } BIT;                          /*                                                                                  */
+        unsigned char BYTE;    /* Byte Access                                                              */
+};                                                     /*UART1 transmit/receive control register 1     */
+
+/*------------------------------------------------------
+     UART1 receive buffer register //0x03ae
+------------------------------------------------------*/
+union st_u1rb {                                                /* UART1 receive buffer register */
+    struct {                                           /*  Bit  Access */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /*  Receive data                                */
+        unsigned char                  :1;             /* Nothing assigned                                     */
+        unsigned char                  :1;             /* Nothing assigned                                     */
+        unsigned char  ABT_U1RB:1;     /* Arbitration lost detecting flag      */
+        unsigned char  OER_U1RB:1;     /* Overrun error flag                           */
+        unsigned char  FER_U1RB:1;     /* Framing error flag                           */
+        unsigned char  PER_U1RB:1;     /* Parity error flag                            */
+        unsigned char  SUM_U1RB:1;     /* Error sum flag                                       */
+    }BIT;
+    struct{
+     unsigned char U1RBL;           /* Low  8 bit                                              */
+     unsigned char U1RBH;           /* High 8 bit                                              */
+    }BYTE;
+    unsigned short  WORD;
+};
+
+/*------------------------------------------------------
+    UART transmit/receive control register 2 //0x03b0
+------------------------------------------------------*/
+union st_ucon {                /* union UCON                                                           */
+       struct {                        /* Bit  Access                                                          */
+        unsigned char  U0IRS :1;       /* UART0 transmit interrupt cause select bit*/
+        unsigned char  U1IRS :1;       /* UART1 transmit interrupt cause select bit*/
+        unsigned char  U0RRM :1;       /* UART0 continuous receive mode enable bit */
+        unsigned char  U1RRM :1;       /* UART1 continuous receive mode enable bit */
+        unsigned char  CLKMD0:1;       /* CLK/CLKS select bit 0                                        */
+        unsigned char  CLKMD1:1;       /* CLK/CLKS select bit 1                                        */
+        unsigned char  RCSP  :1;       /* Separate CTS~/RTS~ bit                       */
+        unsigned char        :1;       /*                                                                                      */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;        /* Byte Access                                                               */
+};                                                             /*UART transmit/receive control register 2  */
+
+/*------------------------------------------------------
+    DMA0 request cause select register //0x03b8
+------------------------------------------------------*/
+union st_dm0sl {                         /*    DMAi request cause select registers                     */
+    struct{
+     unsigned char    DSEL0:1;/* DMA request cause select bit                          */
+     unsigned char    DSEL1:1;/* DMA request cause select bit                          */
+     unsigned char    DSEL2:1;/* DMA request cause select bit                          */
+     unsigned char    DSEL3:1;/* DMA request cause select bit                          */
+     unsigned char         :1;
+     unsigned char         :1;
+     unsigned char    DMS  :1;/* DMA request cause expansion bit                       */
+     unsigned char    DSR  :1;/* Software DMA request bit                                      */
+    }BIT;
+     unsigned char  BYTE;
+};
+
+/*------------------------------------------------------
+    DMA1 request cause select register //0x03ba
+------------------------------------------------------*/
+union st_dm1sl {                          /*    DMAi request cause select registers    */
+    struct{
+     unsigned char    DSEL0:1; /* DMA request cause select bit                                 */
+     unsigned char    DSEL1:1; /* DMA request cause select bit                                 */
+     unsigned char    DSEL2:1; /* DMA request cause select bit                                 */
+     unsigned char    DSEL3:1; /* DMA request cause select bit                                 */
+     unsigned char                :1;
+     unsigned char        :1;
+     unsigned char    DMS  :1; /* DMA request cause expansion bit                      */
+     unsigned char    DSR  :1; /* Software DMA request bit                                     */
+    }BIT;
+    unsigned char  BYTE;
+};
+
+/*------------------------------------------------------
+    CRC data register //0x03bc
+------------------------------------------------------*/
+union st_crcd {                                 /* CRC data register 16 bit                                     */
+   struct{
+       unsigned char CRCDL;     /* CRC data register low  8 bit                                 */
+       unsigned char CRCDH;     /* CRC data register high 8 bit                                 */
+   } BYTE;                                      /* Byte access                                                                  */
+   unsigned short   WORD;    /* Word Access                                                                     */
+};
+
+/*------------------------------------------------------
+    A/D register 0 //0x03c0
+------------------------------------------------------*/
+union st_ad0 {                          /* A/D register 0 16 bit                                               */
+   struct{
+       unsigned char AD0L;      /* A/D register 0 low  8 bit                                   */
+       unsigned char AD0H;      /* A/D register 0 high 8 bit                                   */
+   }BYTE;                                       /* Byte access                                                         */
+   unsigned short   WORD;       /* Word Access                                                         */
+};
+
+/*------------------------------------------------------
+    A/D register 1 //0x03c2
+------------------------------------------------------*/
+ union st_ad1 {                                 /* A/D register 1 16 bit                                               */
+   struct{
+       unsigned char AD1L;      /* A/D register 1 low  8 bit                                   */
+       unsigned char AD1H;      /* A/D register 1 high 8 bit                                   */
+   } BYTE;                                      /* Byte access                                                         */
+   unsigned short   WORD;       /* Word Access                                                         */
+};
+
+/*------------------------------------------------------
+    A/D register 2 //0x03c4
+------------------------------------------------------*/
+union st_ad2 {                          /* A/D register 2 16 bit                                               */
+  struct{
+       unsigned char AD2L;      /* A/D register 2 low  8 bit                                   */
+       unsigned char AD2H;      /* A/D register 2 high 8 bit                                   */
+  } BYTE;                                       /* Byte access                                                         */
+  unsigned short   WORD;        /* Word Access                                                         */
+};
+
+/*------------------------------------------------------
+    A/D register 3 //0x03c6
+------------------------------------------------------*/
+union st_ad3 {                      /* A/D register 3 16 bit                                           */
+  struct{
+       unsigned char AD3L;      /* A/D register 3 low  8 bit                                   */
+       unsigned char AD3H;      /* A/D register 3 high 8 bit                                   */
+  } BYTE;                                       /* Byte access                                                         */
+       unsigned short   WORD;   /* Word Access                                                         */
+};
+
+/*------------------------------------------------------
+    A/D register 4 //0x03c8
+------------------------------------------------------*/
+union st_ad4 {                      /* A/D register 4 16 bit                                           */
+  struct{
+       unsigned char AD4L;      /* A/D register 4 low  8 bit                                   */
+       unsigned char AD4H;      /* A/D register 4 high 8 bit                                   */
+  } BYTE;                                   /* Byte access                                                                     */
+  unsigned short   WORD;        /* Word Access                                                         */
+};
+
+/*------------------------------------------------------
+    A/D register 5 //0x03ca
+------------------------------------------------------*/
+union st_ad5 {                          /* A/D register 5 16 bit                                               */
+  struct{
+       unsigned char AD5L;      /* A/D register 5 low  8 bit                                   */
+       unsigned char AD5H;      /* A/D register 5 high 8 bit                                   */
+  } BYTE;                                       /* Byte access                                                                 */
+       unsigned short   WORD;   /* Word Access                                                                 */
+};
+
+/*------------------------------------------------------
+    A/D register 6 //0x03cc
+------------------------------------------------------*/
+union st_ad6 {                          /* A/D register 6 16 bit                                               */
+   struct{
+       unsigned char AD6L;      /* A/D register 6 low  8 bit                                   */
+       unsigned char AD6H;      /* A/D register 6 high 8 bit                                   */
+   } BYTE;                                      /* Byte access                                                         */
+   unsigned short   WORD;       /* Word Access                                                         */
+ };
+
+/*------------------------------------------------------
+    A/D register 7 //0x03ce
+------------------------------------------------------*/
+union st_ad7 {                          /* A/D register 7 16 bit                                               */
+   struct{
+       unsigned char AD7L;      /* A/D register 7 low  8 bit                                   */
+       unsigned char AD7H;      /* A/D register 7 high 8 bit                                   */
+   } BYTE;                                      /* Byte access                                                         */
+   unsigned short   WORD;       /* Word Access                                                         */
+ };
+
+/*------------------------------------------------------
+    A/D control register 2 //0x03d4
+------------------------------------------------------*/
+union st_adcon2 {                              /* union ADCON2                                         */
+    struct {                                   /*  Bit  Access                                         */
+        unsigned char     SMP     :1;      /* A/D conversion method select bit */
+        unsigned char     ADGSEL0 :1;          /* Reserved bit (Always set to 0 )  */
+        unsigned char     ADGSEL1 :1;          /* Reserved bit (Always set to 0 )  */
+        unsigned char                 :1;              /* Reserved bit (Always set to 0 )  */
+        unsigned char     CKS2    :1;          /* Nothing Assigned.                    */
+        unsigned char                 :1;              /* Nothing Assigned.                    */
+        unsigned char                 :1;              /* Nothing Assigned.                    */
+        unsigned char                 :1;              /* Nothing Assigned.                    */
+       } BIT;
+    unsigned char   BYTE;              /*  Byte Access                                         */
+};
+
+/*------------------------------------------------------
+    A/D control register 0  //0x03d6
+------------------------------------------------------*/
+union st_adcon0 {                      /* union ADCON0                                                         */
+       struct {                        /* Bit  Access                                                          */
+        unsigned char  CH0 :1;         /* Analog input pin select bit                          */
+        unsigned char  CH1 :1;         /* Analog input pin select bit                          */
+        unsigned char  CH2 :1;         /* Analog input pin select bit                          */
+        unsigned char  MD0 :1;         /* A/D operation mode select bit 0                      */
+        unsigned char  MD1 :1;         /* A/D operation mode select bit 0                      */
+        unsigned char  TRG :1;         /* Trigger select bit                                           */
+        unsigned char  ADST:1;         /* A/D conversion start flag                            */
+        unsigned char  CKS0:1;         /* Frequency select bit 0                                       */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;         /* Byte Access                                                              */
+};                                                             /*A/D control register 0                                        */
+
+
+/*------------------------------------------------------
+   A/D control register 1 //0x03d7
+------------------------------------------------------*/
+union st_adcon1 {                      /* union ADCON1                                                         */
+       struct {                        /* Bit  Access                                                          */
+        unsigned char  SCAN0:1;        /* A/D sweep pin select bit                             */
+        unsigned char  SCAN1:1;        /* A/D sweep pin select bit                             */
+        unsigned char  MD2  :1;        /* A/D operation mode select bit 1                      */
+        unsigned char  BITS :1;        /* 8/10-bit mode select bit                             */
+        unsigned char  CKS1 :1;        /* Frequency select bit 1                                       */
+        unsigned char  VCUT :1;        /* Vref connect bit                                                     */
+        unsigned char  OPA0 :1;        /* External op-amp connection mode bit          */
+        unsigned char  OPA1 :1;        /* External op-amp connection mode bit          */
+       } BIT;                                  /*                                                                              */
+       unsigned char BYTE;         /* Byte Access                                                              */
+};                                                             /*A-D control register 1                                        */
+
+
+/*------------------------------------------------------
+    D/A control register //0x03dc
+------------------------------------------------------*/
+union st_dacon{               /* union DACON                                                   */
+       struct {                  /* Bit  Access                                                */
+        unsigned char  DA0E :1;  /* D/A0 output enable bit                         */
+        unsigned char  DA1E :1;  /* D/A1 output enable bit                     */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+       } BIT;                            /*                                                            */
+       unsigned char BYTE;       /* Byte Access                                                */
+};                            /* D/A control register                          */
+
+/*------------------------------------------------------
+    Port P14 control register //0x03de
+------------------------------------------------------*/
+union st_pc14{                /* union pc14                                            */
+       struct {                  /* Bit  Access                                                */
+        unsigned char  P140 :1;  /* Port P14_0 register */
+        unsigned char  P141 :1;  /* Port P14_1 register */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+        unsigned char  pd140:1;  /* Port P14_0 direction register */
+        unsigned char  pd141:1;  /* Port P14_1 direction register */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+        unsigned char           :1;  /* Nothing Assigned                                       */
+       } BIT;                            /*                                                            */
+       unsigned char BYTE;       /* Byte Access                                                */
+};                            /* Port P14 control register                             */
+
+/*------------------------------------------------------
+    Pull-up control register 3 //0x03df
+------------------------------------------------------*/
+union st_pur3{               /* union pur3                                             */
+       struct {                  /* Bit  Access                                                */
+        unsigned char  PU30:1;  /* P11_0 to P11_3 pull-up */
+        unsigned char  PU31:1;  /* P11_4 to P11_7 pull-up */
+        unsigned char  PU32:1;  /* P12_0 to P12_3 pull-up */
+        unsigned char  PU33:1;  /* P12_4 to P12_7 pull-up */
+        unsigned char  PU34:1;  /* P13_0 to P13_3 pull-up */
+        unsigned char  PU35:1;  /* P13_4 to P13_7 pull-up */
+        unsigned char  PU36:1;  /* P14_0,P14_1 pull-up */
+        unsigned char  PU37:1;  /* P11 to P14 effective bit */
+       } BIT;                            /*                                                            */
+       unsigned char BYTE;       /* Byte Access                                                */
+};                            /* Pull-up control register 3                            */
+
+/*------------------------------------------------------
+    Port P0 register //0x03e0
+------------------------------------------------------*/
+union st_p0 {               /* union P0                                                */
+       struct {                /* Bit  Access                                          */
+        unsigned char  P0_0:1; /* Port P00 register                            */
+        unsigned char  P0_1:1; /* Port P01 register                            */
+        unsigned char  P0_2:1; /* Port P02 register                            */
+        unsigned char  P0_3:1; /* Port P03 register                            */
+        unsigned char  P0_4:1; /* Port P04 register                            */
+        unsigned char  P0_5:1; /* Port P05 register                            */
+        unsigned char  P0_6:1; /* Port P06 register                            */
+        unsigned char  P0_7:1; /* Port P07 register                            */
+       } BIT;                          /*                                                          */
+       unsigned char BYTE;     /*  Byte Access                                         */
+};                          /*                                                             */
+
+/*------------------------------------------------------
+    Port P1 register //0x03e1
+------------------------------------------------------*/
+union st_p1 {              /* union P1                                 */
+       struct {                   /* Bit  Access                                       */
+        unsigned char  P1_0:1;/* Port P10 register                             */
+        unsigned char  P1_1:1;/* Port P11 register                             */
+        unsigned char  P1_2:1;/* Port P12 register                             */
+        unsigned char  P1_3:1;/* Port P13 register                             */
+        unsigned char  P1_4:1;/* Port P14 register                             */
+        unsigned char  P1_5:1;/* Port P15 register                             */
+        unsigned char  P1_6:1;/* Port P16 register                             */
+        unsigned char  P1_7:1;/* Port P17 register                             */
+       } BIT;                         /*                                                       */
+       unsigned char BYTE;    /*  Byte Access                                  */
+};                         /*                                                          */
+
+/*------------------------------------------------------
+    Port P0 direction register //0x03e2
+------------------------------------------------------*/
+union st_pd0 {              /* union PD0                                       */
+       struct {                /* Bit  Access                                          */
+        unsigned char  PD0_0:1;/* Port P00 direction register          */
+        unsigned char  PD0_1:1;/* Port P01 direction register          */
+        unsigned char  PD0_2:1;/* Port P02 direction register          */
+        unsigned char  PD0_3:1;/* Port P03 direction register          */
+        unsigned char  PD0_4:1;/* Port P04 direction register          */
+        unsigned char  PD0_5:1;/* Port P05 direction register          */
+        unsigned char  PD0_6:1;/* Port P06 direction register          */
+        unsigned char  PD0_7:1;/* Port P07 direction register          */
+       } BIT;                          /*                                                              */
+       unsigned char BYTE;     /*  Byte Access                                         */
+};                          /*                                                                 */
+
+
+/*------------------------------------------------------
+    Port P1 direction register //0x03e3
+------------------------------------------------------*/
+union st_pd1 {              /* union PD1                          */
+       struct {                /* Bit  Access                             */
+        unsigned char  PD1_0:1;/* Port P10 direction register */
+        unsigned char  PD1_1:1;/* Port P11 direction register */
+        unsigned char  PD1_2:1;/* Port P12 direction register */
+        unsigned char  PD1_3:1;/* Port P13 direction register */
+        unsigned char  PD1_4:1;/* Port P14 direction register */
+        unsigned char  PD1_5:1;/* Port P15 direction register */
+        unsigned char  PD1_6:1;/* Port P16 direction register */
+        unsigned char  PD1_7:1;/* Port P17 direction register */
+       } BIT;                          /*                                                 */
+       unsigned char BYTE;     /*  Byte Access                            */
+};                          /*                                                        */
+
+/*------------------------------------------------------
+    Port P2 register //0x03e4
+------------------------------------------------------*/
+union st_p2 {              /* union P2                             */
+       struct {                   /* Bit  Access                                   */
+        unsigned char  P2_0:1;/* Port P20 register                         */
+        unsigned char  P2_1:1;/* Port P21 register                     */
+        unsigned char  P2_2:1;/* Port P22 register                     */
+        unsigned char  P2_3:1;/* Port P23 register                     */
+        unsigned char  P2_4:1;/* Port P24 register                     */
+        unsigned char  P2_5:1;/* Port P25 register                     */
+        unsigned char  P2_6:1;/* Port P26 register                     */
+        unsigned char  P2_7:1;/* Port P27 register                     */
+       } BIT;                             /*                                               */
+       unsigned char BYTE;    /*  Byte Access                          */
+};                         /*                                                  */
+
+/*------------------------------------------------------
+    Port P3 register //0x03e5
+------------------------------------------------------*/
+union st_p3 {              /* union P3                             */
+       struct {                   /* Bit  Access                                   */
+        unsigned char  P3_0:1;/* Port P30 register                         */
+        unsigned char  P3_1:1;/* Port P31 register                     */
+        unsigned char  P3_2:1;/* Port P32 register                     */
+        unsigned char  P3_3:1;/* Port P33 register                     */
+        unsigned char  P3_4:1;/* Port P34 register                     */
+        unsigned char  P3_5:1;/* Port P35 register                     */
+        unsigned char  P3_6:1;/* Port P36 register                     */
+        unsigned char  P3_7:1;/* Port P37 register                     */
+       } BIT;                             /*                                               */
+       unsigned char BYTE;    /*  Byte Access                          */
+};                         /*                                                  */
+
+/*------------------------------------------------------
+    Port P2 direction register //0x03e6
+------------------------------------------------------*/
+union st_pd2 {              /* union PD2                          */
+       struct {                    /* Bit  Access                                 */
+        unsigned char  PD2_0:1;/* Port P20 direction register */
+        unsigned char  PD2_1:1;/* Port P21 direction register */
+        unsigned char  PD2_2:1;/* Port P22 direction register */
+        unsigned char  PD2_3:1;/* Port P23 direction register */
+        unsigned char  PD2_4:1;/* Port P24 direction register */
+        unsigned char  PD2_5:1;/* Port P25 direction register */
+        unsigned char  PD2_6:1;/* Port P26 direction register */
+        unsigned char  PD2_7:1;/* Port P27 direction register */
+               } BIT;                      /*                                             */
+       unsigned char BYTE;     /*  Byte Access                            */
+};                          /*                                                        */
+
+
+/*------------------------------------------------------
+    Port P3 direction register //0x03e7
+------------------------------------------------------*/
+union st_pd3 {              /* union PD3                          */
+       struct {                    /* Bit  Access                                 */
+        unsigned char  PD3_0:1;/* Port P30 direction register */
+        unsigned char  PD3_1:1;/* Port P31 direction register */
+        unsigned char  PD3_2:1;/* Port P32 direction register */
+        unsigned char  PD3_3:1;/* Port P33 direction register */
+        unsigned char  PD3_4:1;/* Port P34 direction register */
+        unsigned char  PD3_5:1;/* Port P35 direction register */
+        unsigned char  PD3_6:1;/* Port P36 direction register */
+        unsigned char  PD3_7:1;/* Port P37 direction register */
+       } BIT;                          /*                                                 */
+       unsigned char BYTE;     /*  Byte Access                            */
+};                          /*                                                        */
+
+/*------------------------------------------------------
+    Port P4 register //0x03e8
+------------------------------------------------------*/
+union st_p4 {              /* union P4                             */
+       struct {                   /* Bit  Access                                   */
+        unsigned char  P4_0:1;/* Port P40 register                         */
+        unsigned char  P4_1:1;/* Port P41 register                     */
+        unsigned char  P4_2:1;/* Port P42 register                     */
+        unsigned char  P4_3:1;/* Port P43 register                     */
+        unsigned char  P4_4:1;/* Port P44 register                     */
+        unsigned char  P4_5:1;/* Port P45 register                     */
+        unsigned char  P4_6:1;/* Port P46 register                     */
+        unsigned char  P4_7:1;/* Port P47 register                     */
+       } BIT;                             /*                                               */
+       unsigned char BYTE;    /*  Byte Access                          */
+};                         /*                                                  */
+
+/*------------------------------------------------------
+    Port P5 register //0x03e9
+------------------------------------------------------*/
+union st_p5 {              /* union P5                             */
+       struct {                   /* Bit  Access                                   */
+        unsigned char  P5_0:1;/* Port P50 register                         */
+        unsigned char  P5_1:1;/* Port P51 register                     */
+        unsigned char  P5_2:1;/* Port P52 register                     */
+        unsigned char  P5_3:1;/* Port P53 register                     */
+        unsigned char  P5_4:1;/* Port P54 register                     */
+        unsigned char  P5_5:1;/* Port P55 register                     */
+        unsigned char  P5_6:1;/* Port P56 register                     */
+        unsigned char  P5_7:1;/* Port P57 register                     */
+       } BIT;                         /*                                                   */
+       unsigned char BYTE;    /*  Byte Access                          */
+};                         /*                                                  */
+
+
+/*------------------------------------------------------
+    Port P4 direction register //0x03ea
+------------------------------------------------------*/
+union st_pd4 {              /* union PD4                          */
+       struct {                /* Bit  Access                             */
+        unsigned char  PD4_0:1;/* Port P40 direction register */
+        unsigned char  PD4_1:1;/* Port P41 direction register */
+        unsigned char  PD4_2:1;/* Port P42 direction register */
+        unsigned char  PD4_3:1;/* Port P43 direction register */
+        unsigned char  PD4_4:1;/* Port P44 direction register */
+        unsigned char  PD4_5:1;/* Port P45 direction register */
+        unsigned char  PD4_6:1;/* Port P46 direction register */
+        unsigned char  PD4_7:1;/* Port P47 direction register */
+       } BIT;                          /*                                                 */
+       unsigned char BYTE;     /*  Byte Access                            */
+};                          /*                                                        */
+
+
+
+/*------------------------------------------------------
+    Port P5 direction register //0x03eb
+------------------------------------------------------*/
+union st_pd5 {              /* union PD5                          */
+       struct {                /* Bit  Access                             */
+        unsigned char  PD5_0:1;/* Port P50 direction register */
+        unsigned char  PD5_1:1;/* Port P51 direction register */
+        unsigned char  PD5_2:1;/* Port P52 direction register */
+        unsigned char  PD5_3:1;/* Port P53 direction register */
+        unsigned char  PD5_4:1;/* Port P54 direction register */
+        unsigned char  PD5_5:1;/* Port P55 direction register */
+        unsigned char  PD5_6:1;/* Port P56 direction register */
+        unsigned char  PD5_7:1;/* Port P57 direction register */
+       } BIT;                          /*                                                 */
+       unsigned char BYTE;     /*  Byte Access                            */
+};                          /*                                                        */
+
+/*------------------------------------------------------
+    Port P6 register //0x03ec
+------------------------------------------------------*/
+union st_p6 {              /* union P6                             */
+       struct {                   /* Bit  Access                                   */
+        unsigned char  P6_0:1;/* Port P60 register                         */
+        unsigned char  P6_1:1;/* Port P61 register                     */
+        unsigned char  P6_2:1;/* Port P62 register                     */
+        unsigned char  P6_3:1;/* Port P63 register                     */
+        unsigned char  P6_4:1;/* Port P64 register                     */
+        unsigned char  P6_5:1;/* Port P65 register                     */
+        unsigned char  P6_6:1;/* Port P66 register                     */
+        unsigned char  P6_7:1;/* Port P67 register                     */
+       } BIT;                         /*                                                   */
+       unsigned char BYTE;    /*  Byte Access                          */
+};                         /*                                                  */
+
+/*------------------------------------------------------
+    Port P7 register //0x03ed
+------------------------------------------------------*/
+union st_p7 {              /* union P7                             */
+       struct {               /* Bit  Access                               */
+        unsigned char  P7_0:1;/* Port P70 register                         */
+        unsigned char  P7_1:1;/* Port P71 register                     */
+        unsigned char  P7_2:1;/* Port P72 register                     */
+        unsigned char  P7_3:1;/* Port P73 register                     */
+        unsigned char  P7_4:1;/* Port P74 register                     */
+        unsigned char  P7_5:1;/* Port P75 register                     */
+        unsigned char  P7_6:1;/* Port P76 register                     */
+        unsigned char  P7_7:1;/* Port P77 register                     */
+       } BIT;                             /*                                               */
+       unsigned char BYTE;    /*  Byte Access                          */
+};                         /*                                                  */
+
+
+/*------------------------------------------------------
+    Port P6 direction register //0x03ee
+------------------------------------------------------*/
+union st_pd6 {              /* union PD6                          */
+       struct {                /* Bit  Access                             */
+        unsigned char  PD6_0:1;/* Port P60 direction register */
+        unsigned char  PD6_1:1;/* Port P61 direction register */
+        unsigned char  PD6_2:1;/* Port P62 direction register */
+        unsigned char  PD6_3:1;/* Port P63 direction register */
+        unsigned char  PD6_4:1;/* Port P64 direction register */
+        unsigned char  PD6_5:1;/* Port P65 direction register */
+        unsigned char  PD6_6:1;/* Port P66 direction register */
+        unsigned char  PD6_7:1;/* Port P67 direction register */
+       } BIT;                          /*                                                 */
+       unsigned char BYTE;     /*  Byte Access                            */
+};                          /*                                                        */
+
+
+/*------------------------------------------------------
+    Port P7 direction register //0x03ef
+------------------------------------------------------*/
+union st_pd7 {              /* union PD7                          */
+       struct {                /* Bit  Access                             */
+        unsigned char  PD7_0:1;/* Port P70 direction register */
+        unsigned char  PD7_1:1;/* Port P71 direction register */
+        unsigned char  PD7_2:1;/* Port P72 direction register */
+        unsigned char  PD7_3:1;/* Port P73 direction register */
+        unsigned char  PD7_4:1;/* Port P74 direction register */
+        unsigned char  PD7_5:1;/* Port P75 direction register */
+        unsigned char  PD7_6:1;/* Port P76 direction register */
+        unsigned char  PD7_7:1;/* Port P77 direction register */
+               } BIT;                      /*                                             */
+       unsigned char BYTE;     /*  Byte Access                            */
+};                          /*                                                        */
+
+/*------------------------------------------------------
+    Port P8 register //0x03f0
+------------------------------------------------------*/
+union st_p8 {              /* union P8                             */
+       struct {                   /* Bit  Access                                   */
+        unsigned char  P8_0:1;/* Port P80 register                         */
+        unsigned char  P8_1:1;/* Port P81 register                     */
+        unsigned char  P8_2:1;/* Port P82 register                     */
+        unsigned char  P8_3:1;/* Port P83 register                     */
+        unsigned char  P8_4:1;/* Port P84 register                     */
+        unsigned char  P8_5:1;/* Port P85 register                     */
+        unsigned char  P8_6:1;/* Port P86 register                     */
+        unsigned char  P8_7:1;/* Port P87 register                     */
+       } BIT;                         /*                                                   */
+       unsigned char BYTE;    /*  Byte Access                          */
+};                         /*                                                  */
+
+/*------------------------------------------------------
+    Port P9 register //0x03f1
+------------------------------------------------------*/
+union st_p9 {              /* union P9                             */
+       struct {                   /* Bit  Access                                   */
+        unsigned char  P9_0:1;/* Port P90 register                         */
+        unsigned char  P9_1:1;/* Port P91 register                     */
+        unsigned char  P9_2:1;/* Port P92 register                     */
+        unsigned char  P9_3:1;/* Port P93 register                     */
+        unsigned char  P9_4:1;/* Port P94 register                     */
+        unsigned char  P9_5:1;/* Port P95 register                     */
+        unsigned char  P9_6:1;/* Port P96 register                     */
+        unsigned char  P9_7:1;/* Port P97 register                     */
+       } BIT;                             /*                                               */
+       unsigned char BYTE;    /*  Byte Access                          */
+};                         /*                                                  */
+
+/*------------------------------------------------------
+    Port P8 direction register //0x03f2
+------------------------------------------------------*/
+union st_pd8 {              /* union PD8                          */
+       struct {                /* Bit  Access                             */
+        unsigned char  PD8_0:1;/* Port P80 direction register */
+        unsigned char  PD8_1:1;/* Port P81 direction register */
+        unsigned char  PD8_2:1;/* Port P82 direction register */
+        unsigned char  PD8_3:1;/* Port P83 direction register */
+        unsigned char  PD8_4:1;/* Port P84 direction register */
+        unsigned char           :1;/* Nothing assigned                    */
+        unsigned char  PD8_6:1;/* Port P86 direction register */
+        unsigned char  PD8_7:1;/* Port P87 direction register */
+       } BIT;                          /*                                                 */
+       unsigned char BYTE;     /*  Byte Access                            */
+};                          /*                                                        */
+
+
+/*------------------------------------------------------
+    Port P9 direction register //0x03f3
+------------------------------------------------------*/
+union st_pd9 {              /* union PD9                          */
+       struct {                /* Bit  Access                             */
+        unsigned char  PD9_0:1;/* Port P90 direction register */
+        unsigned char  PD9_1:1;/* Port P91 direction register */
+        unsigned char  PD9_2:1;/* Port P92 direction register */
+        unsigned char  PD9_3:1;/* Port P93 direction register */
+        unsigned char  PD9_4:1;/* Port P94 direction register */
+        unsigned char  PD9_5:1;/* Port P95 direction register */
+        unsigned char  PD9_6:1;/* Port P96 direction register */
+        unsigned char  PD9_7:1;/* Port P97 direction register */
+       } BIT;                          /*                                                 */
+       unsigned char BYTE;     /*  Byte Access                            */
+};                          /*                                                        */
+
+/*------------------------------------------------------
+    Port P10 register //0x03f4
+------------------------------------------------------*/
+union st_p10 {              /* union P10                                                               */
+       struct {                /* Bit  Access                                                          */
+        unsigned char  P10_0:1;/* Port P100 register                                                   */
+        unsigned char  P10_1:1;/* Port P101 register                                                   */
+        unsigned char  P10_2:1;/* Port P102 register                                                   */
+        unsigned char  P10_3:1;/* Port P103 register                                                   */
+        unsigned char  P10_4:1;/* Port P104 register                                                   */
+        unsigned char  P10_5:1;/* Port P105 register                                                   */
+        unsigned char  P10_6:1;/* Port P106 register                                                   */
+        unsigned char  P10_7:1;/* Port P107 register                                                   */
+       } BIT;                          /*                                                                              */
+       unsigned char BYTE;     /*  Byte Access                                                         */
+};                          /*                                                         */
+
+/*------------------------------------------------------
+    Port P11 register //0x03f5
+------------------------------------------------------*/
+union st_p11 {              /* union P11                                                               */
+       struct {                /* Bit  Access                                                          */
+        unsigned char  P11_0:1;/* Port P110 register                                                   */
+        unsigned char  P11_1:1;/* Port P111 register                                                   */
+        unsigned char  P11_2:1;/* Port P112 register                                                   */
+        unsigned char  P11_3:1;/* Port P113 register                                                   */
+        unsigned char  P11_4:1;/* Port P114 register                                                   */
+        unsigned char  P11_5:1;/* Port P115 register                                                   */
+        unsigned char  P11_6:1;/* Port P116 register                                                   */
+        unsigned char  P11_7:1;/* Port P117 register                                                   */
+       } BIT;                          /*                                                                              */
+       unsigned char BYTE;     /*  Byte Access                                                         */
+};                          /*                                                         */
+
+/*------------------------------------------------------
+    Port P10 direction register //0x03f6
+------------------------------------------------------*/
+union st_pd10 {              /* union PD10                                                     */
+       struct {                 /* Bit  Access                                                                 */
+        unsigned char  PD10_0:1;/* Port P100 direction register                                */
+        unsigned char  PD10_1:1;/* Port P101 direction register                                */
+        unsigned char  PD10_2:1;/* Port P102 direction register                                */
+        unsigned char  PD10_3:1;/* Port P103 direction register                                */
+        unsigned char  PD10_4:1;/* Port P104 direction register                                */
+        unsigned char  PD10_5:1;/* Port P105 direction register                                */
+        unsigned char  PD10_6:1;/* Port P106 direction register                                */
+        unsigned char  PD10_7:1;/* Port P107 direction register                                */
+       } BIT;                           /*                                                                             */
+               char BYTE;           /*  Byte Access                                                    */
+};                           /*                                                                                */
+
+/*------------------------------------------------------
+    Port P11 direction register //0x03f7
+------------------------------------------------------*/
+union st_pd11 {              /* union PD11                                                     */
+       struct {                 /* Bit  Access                                                                 */
+        unsigned char  PD11_0:1;/* Port P110 direction register                                */
+        unsigned char  PD11_1:1;/* Port P111 direction register                                */
+        unsigned char  PD11_2:1;/* Port P112 direction register                                */
+        unsigned char  PD11_3:1;/* Port P113 direction register                                */
+        unsigned char  PD11_4:1;/* Port P114 direction register                                */
+        unsigned char  PD11_5:1;/* Port P115 direction register                                */
+        unsigned char  PD11_6:1;/* Port P116 direction register                                */
+        unsigned char  PD11_7:1;/* Port P117 direction register                                */
+       } BIT;                           /*                                                                             */
+               char BYTE;           /*  Byte Access                                                    */
+};                           /*                                                                                */
+
+/*------------------------------------------------------
+    Port P12 register //0x03f8
+------------------------------------------------------*/
+union st_p12 {              /* union P12                                                               */
+       struct {                /* Bit  Access                                                          */
+        unsigned char  P12_0:1;/* Port P120 register                                                   */
+        unsigned char  P12_1:1;/* Port P121 register                                                   */
+        unsigned char  P12_2:1;/* Port P122 register                                                   */
+        unsigned char  P12_3:1;/* Port P123 register                                                   */
+        unsigned char  P12_4:1;/* Port P124 register                                                   */
+        unsigned char  P12_5:1;/* Port P125 register                                                   */
+        unsigned char  P12_6:1;/* Port P126 register                                                   */
+        unsigned char  P12_7:1;/* Port P127 register                                                   */
+       } BIT;                          /*                                                                              */
+       unsigned char BYTE;     /*  Byte Access                                                         */
+};                          /*                                                         */
+
+/*------------------------------------------------------
+    Port P13 register //0x03f9
+------------------------------------------------------*/
+union st_p13 {              /* union P13                                                               */
+       struct {                /* Bit  Access                                                          */
+        unsigned char  P13_0:1;/* Port P130 register                                                   */
+        unsigned char  P13_1:1;/* Port P131 register                                                   */
+        unsigned char  P13_2:1;/* Port P132 register                                                   */
+        unsigned char  P13_3:1;/* Port P133 register                                                   */
+        unsigned char  P13_4:1;/* Port P134 register                                                   */
+        unsigned char  P13_5:1;/* Port P135 register                                                   */
+        unsigned char  P13_6:1;/* Port P136 register                                                   */
+        unsigned char  P13_7:1;/* Port P137 register                                                   */
+       } BIT;                          /*                                                                              */
+       unsigned char BYTE;     /*  Byte Access                                                         */
+};                          /*                                                         */
+
+/*------------------------------------------------------
+    Port P12 direction register //0x03fa
+------------------------------------------------------*/
+union st_pd12 {              /* union PD12                                                     */
+       struct {                 /* Bit  Access                                                                 */
+        unsigned char  PD12_0:1;/* Port P120 direction register                                */
+        unsigned char  PD12_1:1;/* Port P121 direction register                                */
+        unsigned char  PD12_2:1;/* Port P122 direction register                                */
+        unsigned char  PD12_3:1;/* Port P123 direction register                                */
+        unsigned char  PD12_4:1;/* Port P124 direction register                                */
+        unsigned char  PD12_5:1;/* Port P125 direction register                                */
+        unsigned char  PD12_6:1;/* Port P126 direction register                                */
+        unsigned char  PD12_7:1;/* Port P127 direction register                                */
+       } BIT;                           /*                                                                             */
+               char BYTE;           /*  Byte Access                                                    */
+};                           /*                                                                                */
+
+/*------------------------------------------------------
+    Port P13 direction register //0x03fb
+------------------------------------------------------*/
+union st_pd13 {              /* union PD13                                                     */
+       struct {                 /* Bit  Access                                                                 */
+        unsigned char  PD13_0:1;/* Port P130 direction register                                */
+        unsigned char  PD13_1:1;/* Port P131 direction register                                */
+        unsigned char  PD13_2:1;/* Port P132 direction register                                */
+        unsigned char  PD13_3:1;/* Port P133 direction register                                */
+        unsigned char  PD13_4:1;/* Port P134 direction register                                */
+        unsigned char  PD13_5:1;/* Port P135 direction register                                */
+        unsigned char  PD13_6:1;/* Port P136 direction register                                */
+        unsigned char  PD13_7:1;/* Port P137 direction register                                */
+       } BIT;                           /*                                                                             */
+               char BYTE;           /*  Byte Access                                                    */
+};                           /*                                                                                */
+
+/*------------------------------------------------------
+    Pull-up control register 0 //0x03fc
+------------------------------------------------------*/
+union st_pur0 {            /* union PUR0                                                               */
+       struct {               /* Bit  Access                                                                   */
+        unsigned char  PU00:1;/* P00 to P03 pull-up                                                    */
+        unsigned char  PU01:1;/* P04 to P07 pull-up                                                    */
+        unsigned char  PU02:1;/* P10 to P13 pull-up                                                    */
+        unsigned char  PU03:1;/* P14 to P17 pull-up                                                    */
+        unsigned char  PU04:1;/* P20 to P23 pull-up                                                    */
+        unsigned char  PU05:1;/* P24 to P27 pull-up                                                    */
+        unsigned char  PU06:1;/* P30 to P33 pull-up                                                    */
+        unsigned char  PU07:1;/* P34 to P37 pull-up                                                    */
+       } BIT;                         /*                                                                                       */
+       unsigned char BYTE;    /*  Byte Access                                                                  */
+};                         /*                                                                                  */
+
+/*------------------------------------------------------
+    Pull-up control register 1 //0x03fd
+------------------------------------------------------*/
+union st_pur1 {            /* union PUR1                                                               */
+       struct {                   /* Bit  Access                                                                       */
+        unsigned char  PU10:1;/* P40 to P43 pull-up                                                    */
+        unsigned char  PU11:1;/* P44 to P47 pull-up                                                    */
+        unsigned char  PU12:1;/* P50 to P53 pull-up                                                    */
+        unsigned char  PU13:1;/* P54 to P57 pull-up                                                    */
+        unsigned char  PU14:1;/* P60 to P63 pull-up                                                    */
+        unsigned char  PU15:1;/* P64 to P67 pull-up                                                    */
+        unsigned char  PU16:1;/* P70 to P73 pull-up (Except P70,P71 ; P70,P71 -> N-channel open drain ports)*/
+        unsigned char  PU17:1;/* P74 to P77 pull-up                                                    */
+       } BIT;                         /*                                                                                       */
+       unsigned char BYTE;    /*  Byte Access                                                                  */
+};                         /*                                                                                  */
+
+/*------------------------------------------------------
+    Pull-up control register 2 //0x03fe
+------------------------------------------------------*/
+union st_pur2 {            /* union PUR2                                                       */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char  PU20:1;/* P80 to P83 pull-up                                                    */
+        unsigned char  PU21:1;/* P84 to P87 pull-up (Except P85)                               */
+        unsigned char  PU22:1;/* P90 to P93 pull-up                                                    */
+        unsigned char  PU23:1;/* P94 to P97 pull-up                                                    */
+        unsigned char  PU24:1;/* P100 to P103 pull-up                                                  */
+        unsigned char  PU25:1;/* P104 to P107 pull-up                                                  */
+        unsigned char          :1;/* Nothing assigned                                                          */
+        unsigned char          :1;/* Nothing assigned                                                          */
+       } BIT;                             /*                                                                           */
+       unsigned char BYTE;    /*  Byte Access                                                                  */
+};                         /*                                                                                  */
+
+/*------------------------------------------------------
+    Port control register //0x03ff
+------------------------------------------------------*/
+union st_pcr {             /* union PCR2                                                       */
+       struct {                   /* Bit  Access                                                               */
+        unsigned char  PCR0:1;/* Port P1 control register                                              */
+        unsigned char          :1;/* Nothing assigned                                                          */
+        unsigned char          :1;/* Nothing assigned                                                          */
+        unsigned char          :1;/* Nothing assigned                                                          */
+        unsigned char          :1;/* Nothing assigned                                                          */
+        unsigned char          :1;/* Nothing assigned                                                          */
+        unsigned char          :1;/* Nothing assigned                                                          */
+        unsigned char          :1;/* Nothing assigned                                                          */
+       } BIT;                             /*                                                                           */
+       unsigned char BYTE;    /*  Byte Access                                                                  */
+};                         /*                                                                                  */
+
+
+
+
+/* Processor mode register 0 */
+#define PM0   (*(volatile union st_pm0 *)(0x0004))
+
+/* Processor mode register 1 */
+#define PM1   (*(volatile union st_pm1 *)(0x0005))
+
+/* System clock control register 0 */
+#define CM0   (*(volatile union st_cm0 *)(0x0006))
+
+/* System clock control register 1 */
+#define CM1   (*(volatile union st_cm1 *)(0x0007))
+
+/* Chip select control register */
+#define CSR   (*(volatile union st_csr *)(0x0008))
+
+/* Address match interrupt enable register */
+#define AIER  (*(volatile union st_aier *)(0x0009))
+
+/* Protect register */
+#define PRCR  (*(volatile union st_prcr *)(0x000A))
+
+/* Data bank register */
+#define DBR  (*(volatile union st_dbr *)(0x000B))
+
+/* Oscillation stop detection register */
+#define CM2  (*(volatile union st_cm2 *)(0x000C))
+
+/* Watchdog timer start register */
+#define WDTS  (*(volatile char *)(0x000E))
+
+/* Watchdog timer control register */
+#define WDC  (*(volatile union st_wdc *)(0x000F))
+
+/* Address match interrupt register 0 */
+#define RMAD0 (*(volatile union st_rmad0 *)(0x0010))
+
+/* Address match interrupt register 1 */
+#define RMAD1 (*(volatile union st_rmad1 *)(0x0014))
+
+/* Voltage detection register 1 */
+#define VCR1 (*(volatile union st_vcr1 *)(0x0019))
+
+/* Voltage detection register 2 */
+#define VCR2 (*(volatile union st_vcr2 *)(0x001A))
+
+/* Chip select expansion control register */
+#define CSE (*(volatile union st_cse *)(0x001B))
+
+/* PLC control register 0 */
+#define PLC0 (*(volatile union st_plc0 *)(0x001C))
+
+/* Processor mode register 2 */
+#define PM2 (*(volatile union st_pm2 *)(0x001E))
+
+/* Power supply down detection register */
+#define D4INT (*(volatile union st_d4int *)(0x001F))
+
+/* DMA0 source pointer */
+#define SAR0  (*(volatile union st_sar0 *)(0x0020))
+
+/* DMA0 destination pointer */
+#define DAR0  (*(volatile union st_dar0 *)(0x0024))
+
+/* DMA0 transfer counter */
+#define TCR0  (*(volatile union st_tcr0  *)(0x0028))
+
+ /* DMA0 control register */
+#define DM0CON (*(volatile union st_dm0con  *)(0x002C))
+
+/* DMA1 source pointer */
+#define SAR1  (*(volatile union st_sar1 *)(0x0030))
+
+/* DMA1 destination pointer */
+#define DAR1  (*(volatile union st_dar1 *)(0x0034))
+
+ /* DMA1 transfer counter */
+#define TCR1  (*(volatile union st_tcr1 *)(0x0038))
+
+/* DMA1 control register */
+#define DM1CON  (*(volatile union st_dm1con *)(0x003c))
+
+
+/* INT3~ interrupt control register */
+#define INT3IC  (*(volatile union st_icr *)(0x0044))
+
+/* Timer B5 interrupt control register */
+#define TB5IC  (*(volatile union st_icr1 *)(0x0045))
+
+/* Timer B4 interrupt control register */
+#define TB4IC (*(volatile union st_icr1 *)(0x0046))
+
+/* Timer B3 interrupt control register */
+#define TB3IC (*(volatile union st_icr1 *)(0x0047))
+
+/* UART1 BUS collision detection interrupt control register */
+#define U1BCNIC  (*(volatile union st_icr1 *)(0x0046))
+
+/* UART0 BUS collision detection interrupt control register */
+#define U0BCNIC  (*(volatile union st_icr1 *)(0x0047))
+
+/* SI/O4 interrupt control register */
+#define S4IC  (*(volatile union st_icr *)(0x0048))
+
+/* SI/O3 interrupt control register */
+#define S3IC  (*(volatile union st_icr *)(0x0049))
+
+/* INT5~ interrupt control register */
+#define INT5IC  (*(volatile union st_icr *)(0x0048))
+
+/* INT4~ interrupt control register */
+#define INT4IC  (*(volatile union st_icr *)(0x0049))
+
+/* Bus collision detection interrupt control register */
+#define BCNIC  (*(volatile union st_bcnic *)(0x004a))
+
+/* DMA0 interrupt control register */
+#define DM0IC  (*(volatile union st_dm0ic *)(0x004b))
+
+/* DMA1 interrupt control register */
+#define DM1IC  (*(volatile union st_icr1 *)(0x004c))
+
+/* Key input interrupt control register */
+#define KUPIC  (*(volatile union st_icr1 *)(0x004D))
+
+/* A/D conversion interrupt control register */
+#define ADIC  (*(volatile union st_icr1 *)(0x004E))
+
+/* UART2 transmit interrupt control register */
+#define S2TIC  (*(volatile union st_icr1 *)(0x004F))
+
+/* UART2 receive interrupt control register */
+#define S2RIC  (*(volatile union st_icr1 *)(0x0050))
+
+/* UART0 transmit interrupt control register */
+#define S0TIC  (*(volatile union st_icr1 *)(0x0051))
+
+/* UART0 receive interrupt control register */
+#define S0RIC  (*(volatile union st_icr1 *)(0x0052))
+
+/* UART1 transmit interrupt control register */
+#define S1TIC (*(volatile union st_icr1 *)(0x0053))
+
+/* UART1 receive interrupt control register */
+#define S1RIC  (*(volatile union st_icr1 *)(0x0054))
+
+/* Timer A0 interrupt control register */
+#define TA0IC  (*(volatile union st_icr1 *)(0x0055))
+
+/* Timer A1 interrupt control register */
+#define TA1IC  (*(volatile union st_icr1 *)(0x0056))
+
+/* Timer A2 interrupt control register */
+#define TA2IC (*(volatile union st_icr1 *)(0x0057))
+
+/* Timer A3 interrupt control register */
+#define TA3IC  (*(volatile union st_icr1 *)(0x0058))
+
+/* Timer A4 interrupt control register */
+#define TA4IC  (*(volatile union st_icr1 *)(0x0059))
+
+/* Timer B0 interrupt control register */
+#define TB0IC  (*(volatile union st_icr1 *)(0x005A))
+
+/* Timer B1 interrupt control register */
+#define TB1IC  (*(volatile union st_icr1 *)(0x005B))
+
+/* Timer B2 interrupt control register */
+#define TB2IC  (*(volatile union st_icr1 *)(0x005C))
+
+/* INT0~ interrupt control register */
+#define INT0IC (*(volatile union st_icr *)(0x005D))
+
+/* INT1~ interrupt control register */
+#define INT1IC  (*(volatile union st_icr *)(0x005E))
+
+/* INT2~ interrupt control register */
+#define INT2IC  (*(volatile union st_icr *)(0x005F))
+
+/* Flash identification register */
+#define FIDR  (*(volatile union st_fidr *)(0x01b4))
+
+/* Flash memory control register 1 */
+#define FMR1  (*(volatile union st_fmr1 *)(0x01b5))
+
+/* Flash memory control register 0 */
+#define FMR0  (*(volatile union st_fmr0 *)(0x01b7))
+
+/* Address match interrupt register 2 */
+#define RMAD2  (*(volatile union st_rmad2 *)(0x01b8))
+
+/* Address match interrupt enable register 2 */
+#define AIER2  (*(volatile union st_aier2 *)(0x01bb))
+
+/* Address match interrupt register 3 */
+#define RMAD3  (*(volatile union st_rmad3 *)(0x01bc))
+
+/* Peripheral clock select register */
+#define PCLKR  (*(volatile union st_pclkr *)(0x025e))
+
+/* Timer B3,4,5 count start flag */
+#define TBSR  (*(volatile union st_tbsr *)(0x0340))
+
+
+/********************************************************
+*   declare  SFR short                                  *
+********************************************************/
+/*--------------------------------------------------------
+    Timer registers : Read and write data in 16-bit units.
+--------------------------------------------------------*/
+
+/* Timer A1-1 register */
+#define TA1_1  (*(volatile unsigned short *)(0x0342))
+
+/* Timer A2-1 register */
+#define TA2_1  (*(volatile unsigned short *)(0x0344))
+
+/* Timer A4-1 register */
+#define TA4_1  (*(volatile unsigned short *)(0x0346))
+
+/* Three-phase PWM control regester 0 */
+#define INVC0  (*(volatile union st_invc0 *)(0x0348))
+
+ /* Three-phase PWM control register 1 */
+#define INVC1  (*(volatile union st_invc1 *)(0x0349))
+
+/* Three-phase output buffer register 0 */
+#define IDB0  (*(volatile union st_idb0 *)(0x034a))
+
+/* Three-phase output buffer register 1 */
+#define IDB1  (*(volatile union st_idb1 *)(0x034b))
+
+/*------------------------------------------------------
+     Dead time timer ; Use "MOV" instruction when writing to this register.
+------------------------------------------------------*/
+/* Dead time timer */
+#define DTT  (*(volatile unsigned char *)(0x034c))
+
+/*------------------------------------------------------------------
+   Timer B2 interrupt occurrences frequency set counter
+   ; Use "MOV" instruction when writing to this register.
+-------------------------------------------------------------------*/
+/* Timer B2 interrupt occurrences frequency set counter */
+#define ICTB2  (*(volatile unsigned char *)(0x034d))
+
+
+/* Timer B3 register */
+#define TB3  (*(volatile unsigned short *)(0x0350))
+
+/* Timer B4 register */
+#define TB4  (*(volatile unsigned short *)(0x0352))
+
+/* Timer B5 register */
+#define TB5  (*(volatile unsigned short *)(0x0354))
+
+/* Timer B3 mode register */
+#define TB3MR  (*(volatile union st_tmr *)(0x035b))
+
+/* Timer B4 mode register */
+#define TB4MR  (*(volatile union st_tmr *)(0x035c))
+
+/* Timer B5 mode register */
+#define TB5MR  (*(volatile union st_tmr *)(0x035d))
+
+/* Interrupt request cause select register 2 */
+#define IFSR2A  (*(volatile union st_ifsr2a *)(0x035e))
+
+/* Interrupt cause select register */
+#define IFSR  (*(volatile union st_ifsr *)(0x035f))
+
+/* SI/O3i transmit/receive register (i=3,4)*/
+#define S3TRR  (*(volatile unsigned char *)(0x0360))
+
+/* SI/O3 control register */
+#define S3C  (*(volatile union st_s3c *)(0x0362))
+
+
+/* SI/O3 bit rate generator (Use "MOV" instruction when writing to these registers)*/
+#define S3BRG  (*(volatile unsigned char *)(0x0363))
+
+
+/* SI/O4 transmit/receive register */
+#define S4TRR  (*(volatile unsigned char *)(0x0364))
+
+/* SI/O4 control register */
+#define S4C  (*(volatile union st_s4c *)(0x0366))
+
+/* SI/O4 bit rate generator */
+#define S4BRG  (*(volatile unsigned char *)(0x0367))
+
+/* UART0 special mode register 4 */
+#define U0SMR4  (*(volatile union st_u0smr4 *)(0x036c))
+
+/* UART0 special mode register 3 */
+#define U0SMR3  (*(volatile union st_u0smr3 *)(0x036d))
+
+
+/* UART0 special mode register 2 */
+#define U0SMR2  (*(volatile union st_u0smr2 *)(0x036e))
+
+/* UART0 special mode register  */
+#define U0SMR  (*(volatile union st_u0smr *)(0x036f))
+
+/* UART1 special mode register 4 */
+#define U1SMR4  (*(volatile union st_u1smr4 *)(0x0370))
+
+/* UART1 special mode register 3 */
+#define U1SMR3  (*(volatile union st_u1smr3 *)(0x0371))
+
+/* UART1 special mode register 2 */
+#define U1SMR2  (*(volatile union st_u1smr2 *)(0x0372))
+
+/* UART1 special mode register  */
+#define U1SMR  (*(volatile union st_u1smr *)(0x0373))
+
+/* UART2 special mode register 4  */
+#define U2SMR4  (*(volatile union st_u2smr4 *)(0x0374))
+
+/* UART2 special mode register 3 */
+#define U2SMR3  (*(volatile union st_u2smr3 *)(0x0375))
+
+
+/* UART2 special mode register 2 */
+#define U2SMR2  (*(volatile union st_u2smr2 *)(0x0376))
+
+/* UART2 special mode register */
+#define U2SMR  (*(volatile union st_u2smr *)(0x0377))
+
+/* UART2 transmit/receive mode register */
+#define U2MR  (*(volatile union st_u2mr *)(0x0378))
+
+/* UART2 bit rate generator */
+#define U2BRG  (*(volatile unsigned char *)(0x0379))
+
+/* UART2 transmit buffer register */
+#define U2TB  (*(volatile union st_u2tb *)(0x037a))
+
+/* UART2 transmit/receive control register 0 */
+//#pragma ADDRESS     u2c0_addr   037cH
+#define U2C0  (*(volatile union st_u2c0 *)(0x037c))
+
+/* UART2 transmit/receive control register 1 */
+#define U2C1  (*(volatile union st_u2c1 *)(0x037d))
+
+/* UART2 receive buffer register */
+#define U2RB  (*(volatile union st_u2rb *)(0x037e))
+
+/* Count start flag */
+#define TABSR  (*(volatile union st_tabsr *)(0x0380))
+
+/* Clock prescaler reset flag */
+#define CPSRF  (*(volatile union st_cpsrf *)(0x0381))
+
+
+/* One-shot start flag */
+#define ONSF  (*(volatile union st_onsf *)(0x0382))
+
+
+/* Trigger select register */
+#define TRGSR  (*(volatile union st_trgsr *)(0x0383))
+
+
+/* Up/down flag (Use "MOV" instruction when writing to this register.)*/
+#define UDF  (*(volatile unsigned char *)(0x0384))
+
+/* Timer A0 register */
+#define TA0 (*(volatile unsigned short  *)(0x0386))
+
+/* Timer A1 register */
+#define TA1 (*(volatile unsigned short  *)(0x0388))
+
+/* Timer A2 register */
+#define TA2 (*(volatile unsigned short  *)(0x038a))
+
+/* Timer A3 register */
+#define TA3 (*(volatile unsigned short  *)(0x038c))
+
+/* Timer A4 register */
+#define TA4 (*(volatile unsigned short  *)(0x038e))
+
+/* Timer B0 register */
+#define TB0 (*(volatile unsigned short  *)(0x0390))
+
+/* Timer B1 register */
+#define TB1 (*(volatile unsigned short  *)(0x0392))
+
+/* Timer B2 register */
+#define TB2 (*(volatile unsigned short  *)(0x0394))
+
+
+
+ /* Timer A0 mode register */
+#define TA0MR  (*(volatile union st_tmr *)(0x0396))
+
+/* Timer A1 mode register */
+#define TA1MR  (*(volatile union st_tmr *)(0x0397))
+
+/* Timer A2 mode register */
+#define TA2MR  (*(volatile union st_tmr *)(0x0398))
+
+/* Timer A3 mode register */
+#define TA3MR  (*(volatile union st_tmr *)(0x0399))
+
+/* Timer A4 mode register */
+#define TA4MR  (*(volatile union st_tmr *)(0x039A))
+
+/* Timer B0 mode register */
+#define TB0MR  (*(volatile union st_tmr *)(0x039b))
+
+/* Timer B1 mode register */
+#define TB1MR  (*(volatile union st_tmr *)(0x039c))
+
+/* Timer B2 mode register */
+#define TB2MR  (*(volatile union st_tmr *)(0x039d))
+
+/* Timer B2 special mode register */
+#define TB2SC  (*(volatile union st_tb2sc *)(0x039e))
+
+/* UART0 transmit/receive mode register */
+#define U0MR  (*(volatile union st_u0mr *)(0x03a0))
+
+/* UART0 bit rate generator (Use "MOV" instruction when writing to these registers.)*/
+#define U0BRG  (*(volatile unsigned char *)(0x03a1))
+
+/* UART0 transmit buffer register */
+#define U0TB  (*(volatile union st_u0tb *)(0x03a2))
+
+/* UART0 transmit/receive control register 0 */
+#define U0C0  (*(volatile union st_u0c0 *)(0x03a4))
+
+ /* UART0 transmit/receive control register 1 */
+#define U0C1  (*(volatile union st_u0c1 *)(0x03a5))
+
+/* UART0 receive buffer register */
+#define U0RB  (*(volatile union st_u0rb *)(0x03a6))
+
+/* UART1 transmit/receive mode register */
+#define U1MR  (*(volatile union st_u1mr *)(0x03a8))
+
+/* UART1 bit rate generator */
+#define U1BRG  (*(volatile unsigned char *)(0x03a9))
+
+ /* UART1 transmit buffer register */
+#define U1TB  (*(volatile union st_u1tb *)(0x03aa))
+
+/* UART1 transmit/receive control register 0 */
+#define U1C0  (*(volatile union st_u1c0 *)(0x03ac))
+
+ /* UART1 transmit/receive control register 1 */
+#define U1C1  (*(volatile union st_u1c1 *)(0x03ad))
+
+ /* UART1 receive buffer register */
+#define U1RB  (*(volatile union st_u1rb *)(0x03ae))
+
+/* UART transmit/receive control register 2 */
+#define UCON  (*(volatile union st_ucon *)(0x03b0))
+
+/* DMA0 cause select register */
+#define DM0SL  (*(volatile union st_dm0sl *)(0x03b8))
+
+/* DMA1 cause select register */
+#define DM1SL  (*(volatile union st_dm1sl *)(0x03ba))
+
+/* CRC data register */
+#define CRCD  (*(volatile union st_crcd *)(0x03bc))
+
+/* CRC input register */
+#define CRCIN  (*(volatile unsigned char *)(0x03be))
+
+/* A/D register 0 */
+#define AD0  (*(volatile union st_ad0 *)(0x03c0))
+
+/* A/D register 1 */
+#define AD1  (*(volatile union st_ad1 *)(0x03c2))
+
+/* A/D register 2 */
+#define AD2  (*(volatile union st_ad2 *)(0x03c4))
+
+/* A/D register 3 */
+#define AD3  (*(volatile union st_ad3 *)(0x03c6))
+
+/* A/D register 4 */
+#define AD4  (*(volatile union st_ad4 *)(0x03c8))
+
+/* A/D register 5 */
+#define AD5  (*(volatile union st_ad5 *)(0x03ca))
+
+/* A/D register 6 */
+#define AD6  (*(volatile union st_ad6 *)(0x03cc))
+
+ /* A/D register 7 */
+#define AD7  (*(volatile union st_ad7 *)(0x03ce))
+
+/* A/D control register 2 */
+#define ADCON2  (*(volatile union st_adcon2 *)(0x03d4))
+
+/* A/D control register 0 */
+#define ADCON0  (*(volatile union st_adcon0 *)(0x03d6))
+
+/* A/D control register 1 */
+#define ADCON1  (*(volatile union st_adcon1 *)(0x03d7))
+
+/* D/A register 0 */
+#define DA0  (*(volatile unsigned char *)(0x03d8))
+
+/* D/A register 1 */
+#define DA1  (*(volatile unsigned char *)(0x03da))
+
+/* D/A control register */
+#define DACON  (*(volatile union st_dacon *)(0x03dc))
+
+/* Port P14 control register */
+#define PC14  (*(volatile union st_pc14 *)(0x03de))
+
+/* Pull-up control register 3 */
+#define PUR3  (*(volatile union st_pur3 *)(0x03df))
+
+
+/* Port P0 register */
+#define P0  (*(volatile union st_p0 *)(0x03e0))
+
+/* Port P1 register */
+#define P1  (*(volatile union st_p1 *)(0x03e1))
+
+/* Port P0 direction register */
+#define PD0  (*(volatile union st_pd0 *)(0x03e2))
+
+/* Port P1 direction register */
+#define PD1  (*(volatile union st_pd1 *)(0x03e3))
+
+/* Port P2 register */
+#define P2  (*(volatile union st_p2 *)(0x03e4))
+
+/* Port P3 register */
+#define P3  (*(volatile union st_p3 *)(0x03e5))
+
+/* Port P2 direction register */
+#define PD2  (*(volatile union st_pd2 *)(0x03e6))
+
+/* Port P3 direction register */
+#define PD3  (*(volatile union st_pd3 *)(0x03e7))
+
+
+ /* Port P4 register */
+#define P4  (*(volatile union st_p4 *)(0x03e8))
+
+/* Port P5 register */
+#define P5  (*(volatile union st_p5 *)(0x03e9))
+
+/* Port P4 direction register */
+#define PD4  (*(volatile union st_pd4 *)(0x03ea))
+
+/* Port P5 direction register */
+#define PD5  (*(volatile union st_pd5 *)(0x03eb))
+
+/* Port P6 register */
+#define P6  (*(volatile union st_p6 *)(0x03ec))
+
+/* Port P7 register */
+#define P7  (*(volatile union st_p7 *)(0x03ed))
+
+/* Port P6 direction register */
+#define PD6  (*(volatile union st_pd6 *)(0x03ee))
+
+/* Port P7 direction register */
+#define PD7  (*(volatile union st_pd7 *)(0x03ef))
+
+/* Port P8 register */
+#define P8  (*(volatile union st_p8 *)(0x03f0))
+
+/* Port P9 register */
+#define P9  (*(volatile union st_p9 *)(0x03f1))
+
+/* Port P8 direction register */
+#define PD8  (*(volatile union st_pd8 *)(0x03f2))
+
+/* Port P9 direction register */
+#define PD9  (*(volatile union st_pd9 *)(0x03f3))
+
+/* Port P10 register */
+#define P10  (*(volatile union st_p10 *)(0x03f4))
+
+/* Port P11 register */
+#define P11  (*(volatile union st_p11 *)(0x03f5))
+
+/* Port P10 direction register */
+#define PD10  (*(volatile union st_pd10 *)(0x03f6))
+
+/* Port P11 direction register */
+#define PD11  (*(volatile union st_pd11 *)(0x03f7))
+
+/* Port P12 register */
+#define P12  (*(volatile union st_p12 *)(0x03f8))
+
+/* Port P13 register */
+#define P13  (*(volatile union st_p13 *)(0x03f9))
+
+/* Port P12 direction register */
+#define PD12  (*(volatile union st_pd12 *)(0x03fa))
+
+/* Port P13 direction register */
+#define PD13  (*(volatile union st_pd13 *)(0x03f7))
+
+ /* Pull-up control register 0 */
+#define PUR0  (*(volatile union st_pur0 *)(0x03fc))
+
+/* Pull-up control register 1 */
+#define PUR1  (*(volatile union st_pur1 *)(0x03fd))
+
+ /* Pull-up control register 2 */
+#define PUR2  (*(volatile union st_pur2 *)(0x03fe))
+
+/* Port control register */
+#define PCR  (*(volatile union st_pcr *)(0x03ff))
+
+
+#endif /* __IOM16C62P_H__ */
+
diff --git a/tos/chips/m16c62p/m16c62phardware.h b/tos/chips/m16c62p/m16c62phardware.h
new file mode 100755 (executable)
index 0000000..d85c2de
--- /dev/null
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Some M16c/62p needed macros and defines.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Fan Zhang <fanzha@ltu.se>
+ */
+
+#ifndef __M16C62PHARDWARE_H__
+#define __M16C62PHARDWARE_H__
+
+#include "interrupts.h"
+#include "iom16c62p.h"
+#include "bits.h"
+#include "uart/M16c62pUart.h"
+#include "pins/M16c62pPin.h"
+
+#define true 1
+#define false 0
+
+//Bit operators using bit number
+#define _BV(bit)  (1 << bit)
+#define SET_BIT(port, bit)    ((port) |= _BV(bit))
+#define CLR_BIT(port, bit)    ((port) &= ~_BV(bit))
+#define READ_BIT(port, bit)   (((port) & _BV(bit)) != 0)
+#define FLIP_BIT(port, bit)   ((port) ^= _BV(bit))
+#define WRITE_BIT(port, bit, value) \
+  if (value) SET_BIT((port), (bit)); \
+    else CLR_BIT((port), (bit))
+
+// Bit operators using bit flag mask
+#define SET_FLAG(port, flag)  ((port) |= (flag))
+#define CLR_FLAG(port, flag)  ((port) &= ~(flag))
+#define READ_FLAG(port, flag) ((port) & (flag))
+
+// We need slightly different defs than M16C_INTERRUPT
+// for interrupt handlers.
+#define M16C_INTERRUPT_HANDLER(id) \
+  M16C_INTERRUPT(id) @atomic_hwevent() @C()
+// The mov instruction should be used when clearing the interrupt flag.
+// More information can be found in the manual for the MCU.
+inline void clear_interrupt(uint16_t interrupt_addr)
+{
+  atomic
+  {
+  uint8_t tmp = (*TCAST(volatile uint8_t* ONE, interrupt_addr));
+  CLR_BIT(tmp, 3);
+  asm("mov.w %[interrupt_addr], a0\n\t"
+      "mov.b %[tmp], [a0]"
+      :
+      : [tmp] "r" (tmp) , [interrupt_addr] "r" (interrupt_addr)
+      : "a0");
+  }
+}
+
+typedef uint8_t mcu_power_t @combine("ecombine");
+
+mcu_power_t mcombine(mcu_power_t m1, mcu_power_t m2)
+{
+  return (m1 < m2) ? m1: m2;
+}
+
+enum
+{
+  M16C62P_POWER_WAIT        = 1,
+  M16C62P_POWER_STOP        = 2,
+};
+
+inline void __nesc_enable_interrupt(void) { asm("fset i"); }
+inline void __nesc_disable_interrupt(void) { asm("fclr i"); }
+
+// Macro to create union casting functions.
+#define DEFINE_UNION_CAST(func_name, from_type, to_type) \
+  to_type func_name(from_type x_type) { \
+    union {from_type f_type; to_type t_type;} c_type = {f_type:x_type}; return c_type.t_type; }
+
+typedef uint16_t __nesc_atomic_t;
+
+#ifndef NESC_BUILD_BINARY
+/**
+ * Start atomic section.
+ */
+inline __nesc_atomic_t __nesc_atomic_start(void) @spontaneous()
+{
+  __nesc_atomic_t result;
+  // Disable interrupts
+  __nesc_disable_interrupt();
+  // Save the flag register (FLG)
+  asm volatile ("stc flg, %0": "=r"(result): : "%flg");
+  asm volatile("" : : : "memory"); // ensure atomic section effect visibility
+  return result;
+}
+
+/**
+ * End atomic section.
+ */
+inline void __nesc_atomic_end(__nesc_atomic_t original_FLG) @spontaneous()
+{
+  // Restore the flag register (FLG)
+  asm volatile("" : : : "memory"); // ensure atomic section effect visibility
+  asm volatile ("ldc %0, flg": : "r"(original_FLG): "%flg");
+}
+#endif
+
+// If the platform doesnt have defined any main crystal speed it will
+// get a default value of 16MHz
+#ifndef MAIN_CRYSTAL_SPEED
+#define MAIN_CRYSTAL_SPEED 16 /*MHZ*/
+#endif
+
+// If the PLL_MULTIPLIER is not defined it will be default to M16C62P_PLL_2.
+#ifndef PLL_MULTIPLIER
+#define PLL_MULTIPLIER M16C62P_PLL_2
+#endif
+
+// Default inactive pin states
+#ifndef PORT_P0_INACTIVE_STATE
+#define PORT_P0_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P1_INACTIVE_STATE
+#define PORT_P1_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P2_INACTIVE_STATE
+#define PORT_P2_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P3_INACTIVE_STATE
+#define PORT_P3_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P4_INACTIVE_STATE
+#define PORT_P4_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P5_INACTIVE_STATE
+#define PORT_P5_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P6_INACTIVE_STATE
+#define PORT_P6_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P7_INACTIVE_STATE
+#define PORT_P7_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P8_INACTIVE_STATE
+#define PORT_P8_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P9_INACTIVE_STATE
+#define PORT_P9_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#ifndef PORT_P_10_INACTIVE_STATE
+#define PORT_P_10_INACTIVE_STATE M16C_PIN_INACTIVE_DONT_CARE
+#endif
+
+#endif  // __M16C62PHARDWARE_H__
diff --git a/tos/chips/m16c62p/pins/HplM16c62pGeneralIOC.nc b/tos/chips/m16c62p/pins/HplM16c62pGeneralIOC.nc
new file mode 100755 (executable)
index 0000000..439143e
--- /dev/null
@@ -0,0 +1,308 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+ /*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ * 
+ * @author Martin Turon <mturon@xbow.com>
+ */
+/**
+ * The HplM16c62pGeneralIOC configuration provides GeneralIO interfaces for all
+ * the M16c/62p's pins.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "iom16c62p.h"
+
+configuration HplM16c62pGeneralIOC
+{
+  // provides all the ports as raw ports
+  provides
+  {
+    interface GeneralIO as PortP00;
+    interface GeneralIO as PortP01;
+    interface GeneralIO as PortP02;
+    interface GeneralIO as PortP03;
+    interface GeneralIO as PortP04;
+    interface GeneralIO as PortP05;
+    interface GeneralIO as PortP06;
+    interface GeneralIO as PortP07;
+
+    interface GeneralIO as PortP10;
+    interface GeneralIO as PortP11;
+    interface GeneralIO as PortP12;
+    interface GeneralIO as PortP13;
+    interface GeneralIO as PortP14;
+    interface GeneralIO as PortP15;
+    interface GeneralIO as PortP16;
+    interface GeneralIO as PortP17;
+
+    interface GeneralIO as PortP20;
+    interface GeneralIO as PortP21;
+    interface GeneralIO as PortP22;
+    interface GeneralIO as PortP23;
+    interface GeneralIO as PortP24;
+    interface GeneralIO as PortP25;
+    interface GeneralIO as PortP26;
+    interface GeneralIO as PortP27;
+
+    interface GeneralIO as PortP30;
+    interface GeneralIO as PortP31;
+    interface GeneralIO as PortP32;
+    interface GeneralIO as PortP33;
+    interface GeneralIO as PortP34;
+    interface GeneralIO as PortP35;
+    interface GeneralIO as PortP36;
+    interface GeneralIO as PortP37;
+
+    interface GeneralIO as PortP40;
+    interface GeneralIO as PortP41;
+    interface GeneralIO as PortP42;
+    interface GeneralIO as PortP43;
+    interface GeneralIO as PortP44;
+    interface GeneralIO as PortP45;
+    interface GeneralIO as PortP46;
+    interface GeneralIO as PortP47;
+
+    interface GeneralIO as PortP50;
+    interface GeneralIO as PortP51;
+    interface GeneralIO as PortP52;
+    interface GeneralIO as PortP53;
+    interface GeneralIO as PortP54;
+    interface GeneralIO as PortP55;
+    interface GeneralIO as PortP56;
+    interface GeneralIO as PortP57;
+  
+    interface GeneralIO as PortP60;
+    interface GeneralIO as PortP61;
+    interface GeneralIO as PortP62;
+    interface GeneralIO as PortP63;
+    interface GeneralIO as PortP64;
+    interface GeneralIO as PortP65;
+    interface GeneralIO as PortP66;
+    interface GeneralIO as PortP67;
+  
+    interface GeneralIO as PortP70;
+    interface GeneralIO as PortP71;
+    interface GeneralIO as PortP72;
+    interface GeneralIO as PortP73;
+    interface GeneralIO as PortP74;
+    interface GeneralIO as PortP75;
+    interface GeneralIO as PortP76;
+    interface GeneralIO as PortP77;
+  
+    interface GeneralIO as PortP80;
+    interface GeneralIO as PortP81;
+    interface GeneralIO as PortP82;
+    interface GeneralIO as PortP83;
+    interface GeneralIO as PortP84;
+    interface GeneralIO as PortP85;
+    interface GeneralIO as PortP86;
+    interface GeneralIO as PortP87;
+  
+    interface GeneralIO as PortP90;
+    interface GeneralIO as PortP91;
+    interface GeneralIO as PortP92;
+    interface GeneralIO as PortP93;
+    interface GeneralIO as PortP94;
+    interface GeneralIO as PortP95;
+    interface GeneralIO as PortP96;
+    interface GeneralIO as PortP97;
+    interface GeneralIO as PortP100;
+    interface GeneralIO as PortP101;
+    interface GeneralIO as PortP102;
+    interface GeneralIO as PortP103;
+    interface GeneralIO as PortP104;
+    interface GeneralIO as PortP105;
+    interface GeneralIO as PortP106;
+    interface GeneralIO as PortP107;
+  
+  }
+}
+implementation
+{
+  components 
+    new HplM16c62pGeneralIOPortP((uint16_t)&P0.BYTE, (uint16_t)&PD0.BYTE) as PortP0,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P1.BYTE, (uint16_t)&PD1.BYTE) as PortP1,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P2.BYTE, (uint16_t)&PD2.BYTE) as PortP2,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P3.BYTE, (uint16_t)&PD3.BYTE) as PortP3,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P4.BYTE, (uint16_t)&PD4.BYTE) as PortP4,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P5.BYTE, (uint16_t)&PD5.BYTE) as PortP5,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P6.BYTE, (uint16_t)&PD6.BYTE) as PortP6,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P7.BYTE, (uint16_t)&PD7.BYTE) as PortP7,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P8.BYTE, (uint16_t)&PD8.BYTE) as PortP8,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P9.BYTE, (uint16_t)&PD9.BYTE) as PortP9,
+    new HplM16c62pGeneralIOPortP((uint16_t)&P10.BYTE, (uint16_t)&PD10.BYTE) as PortP_10;
+
+  PortP00 = PortP0.Pin0;
+  PortP01 = PortP0.Pin1;
+  PortP02 = PortP0.Pin2;
+  PortP03 = PortP0.Pin3;
+  PortP04 = PortP0.Pin4;
+  PortP05 = PortP0.Pin5;
+  PortP06 = PortP0.Pin6;
+  PortP07 = PortP0.Pin7;
+
+  PortP10 = PortP1.Pin0;
+  PortP11 = PortP1.Pin1;
+  PortP12 = PortP1.Pin2;
+  PortP13 = PortP1.Pin3;
+  PortP14 = PortP1.Pin4;
+  PortP15 = PortP1.Pin5;
+  PortP16 = PortP1.Pin6;
+  PortP17 = PortP1.Pin7;
+
+  PortP20 = PortP2.Pin0;
+  PortP21 = PortP2.Pin1;
+  PortP22 = PortP2.Pin2;
+  PortP23 = PortP2.Pin3;
+  PortP24 = PortP2.Pin4;
+  PortP25 = PortP2.Pin5;
+  PortP26 = PortP2.Pin6;
+  PortP27 = PortP2.Pin7;
+
+  PortP30 = PortP3.Pin0;
+  PortP31 = PortP3.Pin1;
+  PortP32 = PortP3.Pin2;
+  PortP33 = PortP3.Pin3;
+  PortP34 = PortP3.Pin4;
+  PortP35 = PortP3.Pin5;
+  PortP36 = PortP3.Pin6;
+  PortP37 = PortP3.Pin7;
+
+  PortP40 = PortP4.Pin0;
+  PortP41 = PortP4.Pin1;
+  PortP42 = PortP4.Pin2;
+  PortP43 = PortP4.Pin3;
+  PortP44 = PortP4.Pin4;
+  PortP45 = PortP4.Pin5;
+  PortP46 = PortP4.Pin6;
+  PortP47 = PortP4.Pin7;
+
+  PortP50 = PortP5.Pin0;
+  PortP51 = PortP5.Pin1;
+  PortP52 = PortP5.Pin2;
+  PortP53 = PortP5.Pin3;
+  PortP54 = PortP5.Pin4;
+  PortP55 = PortP5.Pin5;
+  PortP56 = PortP5.Pin6;
+  PortP57 = PortP5.Pin7;
+
+  PortP60 = PortP6.Pin0;
+  PortP61 = PortP6.Pin1;
+  PortP62 = PortP6.Pin2;
+  PortP63 = PortP6.Pin3;
+  PortP64 = PortP6.Pin4;
+  PortP65 = PortP6.Pin5;
+  PortP66 = PortP6.Pin6;
+  PortP67 = PortP6.Pin7;
+
+  PortP70 = PortP7.Pin0;
+  PortP71 = PortP7.Pin1;
+  PortP72 = PortP7.Pin2;
+  PortP73 = PortP7.Pin3;
+  PortP74 = PortP7.Pin4;
+  PortP75 = PortP7.Pin5;
+  PortP76 = PortP7.Pin6;
+  PortP77 = PortP7.Pin7;
+
+  PortP80 = PortP8.Pin0;
+  PortP81 = PortP8.Pin1;
+  PortP82 = PortP8.Pin2;
+  PortP83 = PortP8.Pin3;
+  PortP84 = PortP8.Pin4;
+  PortP85 = PortP8.Pin5;
+  PortP86 = PortP8.Pin6;
+  PortP87 = PortP8.Pin7;
+  
+  components 
+    new HplM16c62pGeneralIOPinPRC2P() as PortP90W,
+    new HplM16c62pGeneralIOPinPRC2P() as PortP91W,
+    new HplM16c62pGeneralIOPinPRC2P() as PortP92W,
+    new HplM16c62pGeneralIOPinPRC2P() as PortP93W,
+    new HplM16c62pGeneralIOPinPRC2P() as PortP94W,
+    new HplM16c62pGeneralIOPinPRC2P() as PortP95W,
+    new HplM16c62pGeneralIOPinPRC2P() as PortP96W,
+    new HplM16c62pGeneralIOPinPRC2P() as PortP97W;
+
+  PortP90W -> PortP9.Pin0;
+  PortP91W -> PortP9.Pin1;
+  PortP92W -> PortP9.Pin2;
+  PortP93W -> PortP9.Pin3;
+  PortP94W -> PortP9.Pin4;
+  PortP95W -> PortP9.Pin5;
+  PortP96W -> PortP9.Pin6;
+  PortP97W -> PortP9.Pin7;
+  
+  PortP90 = PortP90W;
+  PortP91 = PortP91W;
+  PortP92 = PortP92W;
+  PortP93 = PortP93W;
+  PortP94 = PortP94W;
+  PortP95 = PortP95W;
+  PortP96 = PortP96W;
+  PortP97 = PortP97W;
+
+  PortP100 = PortP_10.Pin0;
+  PortP101 = PortP_10.Pin1;
+  PortP102 = PortP_10.Pin2;
+  PortP103 = PortP_10.Pin3;
+  PortP104 = PortP_10.Pin4;
+  PortP105 = PortP_10.Pin5;
+  PortP106 = PortP_10.Pin6;
+  PortP107 = PortP_10.Pin7;
+}
diff --git a/tos/chips/m16c62p/pins/HplM16c62pGeneralIOPinP.nc b/tos/chips/m16c62p/pins/HplM16c62pGeneralIOPinP.nc
new file mode 100755 (executable)
index 0000000..bcaf970
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ */
+  
+/**
+ * Generic pin access for pins mapped into I/O space.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Martin Turon <mturon@xbow.com>
+ * @author David Gay <dgay@intel-research.net>
+ */
+generic module HplM16c62pGeneralIOPinP (uint16_t port_addr, 
+                                uint16_t ddr_addr, 
+                                uint16_t bit)
+{
+  provides interface GeneralIO as IO;
+}
+implementation
+{
+#define port (*TCAST(volatile uint8_t* ONE, port_addr))
+#define ddr (*TCAST(volatile uint8_t* ONE, ddr_addr))
+
+  inline async command bool IO.get()        { return READ_BIT (port, bit); }
+  inline async command void IO.set()        { SET_BIT  (port, bit); }
+  inline async command void IO.clr()        { CLR_BIT  (port, bit); }
+  inline async command void IO.toggle()     { atomic FLIP_BIT (port, bit); }
+    
+  inline async command void IO.makeInput()  { CLR_BIT  (ddr, bit);  }
+  inline async command bool IO.isInput()    { return !READ_BIT(ddr, bit); }
+  inline async command void IO.makeOutput() { SET_BIT  (ddr, bit);  }
+  inline async command bool IO.isOutput()   { return READ_BIT(ddr, bit); }
+}
+
diff --git a/tos/chips/m16c62p/pins/HplM16c62pGeneralIOPinPRC2P.nc b/tos/chips/m16c62p/pins/HplM16c62pGeneralIOPinPRC2P.nc
new file mode 100755 (executable)
index 0000000..bea643e
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+  
+/**
+ * Generic pin access for pins on the P9 port. The PD9 register
+ * is locked by the PRC2 bit in the PRCR register so it needs
+ * to be unlocked before each access.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic module HplM16c62pGeneralIOPinPRC2P()
+{
+  provides interface GeneralIO as IO;
+  uses interface GeneralIO as Wrap;
+}
+implementation
+{
+
+  inline async command bool IO.get()        { return call Wrap.get(); }
+  inline async command void IO.set()        { call Wrap.set(); }
+  inline async command void IO.clr()        { call Wrap.clr(); }
+  inline async command void IO.toggle()     { call Wrap.toggle(); }
+    
+  inline async command void IO.makeInput() 
+  {
+    atomic
+    {
+         PRCR.BYTE = BIT2;
+         call Wrap.makeInput();
+    }
+  }
+  
+  inline async command bool IO.isInput()    { return call Wrap.isInput(); }
+  inline async command void IO.makeOutput()
+  {
+    atomic
+    {
+      PRCR.BYTE = BIT2;
+         call Wrap.makeOutput();
+    }
+  }
+  
+  inline async command bool IO.isOutput()   { return call Wrap.isOutput(); }
+}
+
diff --git a/tos/chips/m16c62p/pins/HplM16c62pGeneralIOPortP.nc b/tos/chips/m16c62p/pins/HplM16c62pGeneralIOPortP.nc
new file mode 100755 (executable)
index 0000000..05c2270
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ */
+  
+/**
+ * Generic component to expose a full 8-bit port of GPIO pins.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Martin Turon <mturon@xbow.com>
+ */
+
+generic configuration HplM16c62pGeneralIOPortP(uint16_t port_addr,
+                                               uint16_t ddr_addr)
+{
+  // provides all the ports as raw ports
+  provides
+  {
+    interface GeneralIO as Pin0;
+    interface GeneralIO as Pin1;
+    interface GeneralIO as Pin2;
+    interface GeneralIO as Pin3;
+    interface GeneralIO as Pin4;
+    interface GeneralIO as Pin5;
+    interface GeneralIO as Pin6;
+    interface GeneralIO as Pin7;
+  }
+}
+implementation
+{
+  components 
+    new HplM16c62pGeneralIOPinP (port_addr, ddr_addr, 0) as Bit0,
+    new HplM16c62pGeneralIOPinP (port_addr, ddr_addr, 1) as Bit1,
+    new HplM16c62pGeneralIOPinP (port_addr, ddr_addr, 2) as Bit2,
+    new HplM16c62pGeneralIOPinP (port_addr, ddr_addr, 3) as Bit3,
+    new HplM16c62pGeneralIOPinP (port_addr, ddr_addr, 4) as Bit4,
+    new HplM16c62pGeneralIOPinP (port_addr, ddr_addr, 5) as Bit5,
+    new HplM16c62pGeneralIOPinP (port_addr, ddr_addr, 6) as Bit6,
+    new HplM16c62pGeneralIOPinP (port_addr, ddr_addr, 7) as Bit7;
+
+  Pin0 = Bit0;
+  Pin1 = Bit1;
+  Pin2 = Bit2;
+  Pin3 = Bit3;
+  Pin4 = Bit4;
+  Pin5 = Bit5;
+  Pin6 = Bit6;
+  Pin7 = Bit7;
+}
diff --git a/tos/chips/m16c62p/pins/HplM16c62pInterrupt.nc b/tos/chips/m16c62p/pins/HplM16c62pInterrupt.nc
new file mode 100755 (executable)
index 0000000..0959f3b
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* "Copyright (c) 2000-2003 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/**
+ * Interface to control an M16c/62p external pin interrupt.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Joe Polastre
+ * @author Martin Turon
+ */
+
+interface HplM16c62pInterrupt
+{
+  /**
+   * Enables M16c/62p hardware interrupt on a particular port.
+   */
+  async command void enable();
+
+  /** 
+   * Disables M16c/62p hardware interrupt on a particular port.
+   */
+  async command void disable();
+
+  /** 
+   * Clears the M16c/62p Interrupt Pending Flag for a particular port.
+   */
+  async command void clear();
+
+  /** 
+   * Gets the current value of the input voltage of a port.
+   *
+   * @return TRUE if the pin is set high, FALSE if it is set low.
+   */
+  async command bool getValue();
+
+  /** 
+   * Sets whether the edge should be high to low or low to high.
+   * @param TRUE if the interrupt should be triggered on a low to high
+   *        edge transition, false for interrupts on a high to low transition.
+   */
+  async command void edge(bool low_to_high);
+
+  /**
+   * Sets the edge mode to both edges.
+   */
+  async command void bothEdges();
+  
+  /**
+   * Signaled when an interrupt occurs on a port.
+   */
+  async event void fired();
+}
diff --git a/tos/chips/m16c62p/pins/HplM16c62pInterruptC.nc b/tos/chips/m16c62p/pins/HplM16c62pInterruptC.nc
new file mode 100755 (executable)
index 0000000..8c82ca2
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ * @author Martin Turon <mturon@xbow.com>
+ */
+/**
+ * This component providing access to all external pin interrupts on M16c/62P.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+configuration HplM16c62pInterruptC
+{
+  provides
+  {
+    interface HplM16c62pInterrupt as Int0;
+    interface HplM16c62pInterrupt as Int1;
+    interface HplM16c62pInterrupt as Int2;
+    interface HplM16c62pInterrupt as Int3;
+    interface HplM16c62pInterrupt as Int4;
+    interface HplM16c62pInterrupt as Int5;
+  }
+}
+implementation
+{
+  components 
+    HplM16c62pInterruptSigP as IrqVector,
+    new HplM16c62pInterruptPinP((uint16_t)&INT0IC, 0) as IntPin0,
+    new HplM16c62pInterruptPinP((uint16_t)&INT1IC, 1) as IntPin1,
+    new HplM16c62pInterruptPinP((uint16_t)&INT2IC, 2) as IntPin2,
+    new HplM16c62pInterruptPinP((uint16_t)&INT3IC, 3) as IntPin3,
+    new HplM16c62pInterruptPinP((uint16_t)&INT4IC, 4) as IntPin4,
+    new HplM16c62pInterruptPinP((uint16_t)&INT5IC, 5) as IntPin5;
+  
+  Int0 = IntPin0;
+  Int1 = IntPin1;
+  Int2 = IntPin2;
+  Int3 = IntPin3;
+  Int4 = IntPin4;
+  Int5 = IntPin5;
+
+  IntPin0.IrqSignal -> IrqVector.IntSig0;
+  IntPin1.IrqSignal -> IrqVector.IntSig1;
+  IntPin2.IrqSignal -> IrqVector.IntSig2;
+  IntPin3.IrqSignal -> IrqVector.IntSig3;
+  IntPin4.IrqSignal -> IrqVector.IntSig4;
+  IntPin5.IrqSignal -> IrqVector.IntSig5;
+}
+
diff --git a/tos/chips/m16c62p/pins/HplM16c62pInterruptPinP.nc b/tos/chips/m16c62p/pins/HplM16c62pInterruptPinP.nc
new file mode 100755 (executable)
index 0000000..871c7d9
--- /dev/null
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ * @author Martin Turon <mturon@xbow.com>
+ */
+/**
+ * Interrupt interface access for interrupt capable GPIO pins.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+generic module HplM16c62pInterruptPinP (uint16_t ctrl_addr, uint8_t edgebit)
+{
+  provides interface HplM16c62pInterrupt as Irq;
+  uses interface HplM16c62pInterruptSig as IrqSignal;
+}
+implementation
+{
+#define ctrl  (*TCAST(volatile uint8_t * ONE, ctrl_addr))
+
+  inline async command bool Irq.getValue() { return READ_BIT(ctrl, 3); }
+  inline async command void Irq.clear()    { clear_interrupt(ctrl_addr); }
+  inline async command void Irq.disable()  { CLR_BIT(ctrl, 0); }
+  
+  inline async command void Irq.enable()
+  {
+    if (edgebit > 3)
+    {
+      SET_BIT(IFSR.BYTE, (edgebit+2));
+    }
+    SET_BIT(ctrl, 0);
+
+  }
+
+  inline async command void Irq.edge(bool low_to_high)
+  {
+    CLR_BIT(IFSR.BYTE, edgebit); // use edge mode
+    // and select rising vs falling
+    if (low_to_high)
+    {
+      SET_BIT(ctrl, 4);
+    }
+    else
+    {
+      CLR_BIT(ctrl, 4);
+    }
+  }
+
+  inline async command void Irq.bothEdges()
+  {
+    SET_BIT(IFSR.BYTE, edgebit);
+    CLR_BIT(ctrl, 4);
+  }
+
+  /** 
+   * Forward the external interrupt event.
+   */
+  async event void IrqSignal.fired()
+  {
+    call Irq.clear();
+    signal Irq.fired();
+  }
+
+  default async event void Irq.fired() { }
+}
diff --git a/tos/chips/m16c62p/pins/HplM16c62pInterruptSig.nc b/tos/chips/m16c62p/pins/HplM16c62pInterruptSig.nc
new file mode 100755 (executable)
index 0000000..a35138b
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ *  Copyright (c) 2004-2005 Crossbow Technology, Inc.
+ *  All rights reserved.
+ *
+ *  Permission to use, copy, modify, and distribute this software and its
+ *  documentation for any purpose, without fee, and without written
+ *  agreement is hereby granted, provided that the above copyright
+ *  notice, the (updated) modification history and the author appear in
+ *  all copies of this source code.
+ *
+ *  Permission is also granted to distribute this software under the
+ *  standard BSD license as contained in the TinyOS distribution.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+ *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ *  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS 
+ *  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
+ *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA, 
+ *  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
+ *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
+ *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
+ *  THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+/**
+ * Interface to an M16c/62p external pin interrupt that exposes just the
+ * interrupt vector routine for easy linking to generic components (see
+ * HplM16c62pInterrupt for the full interface).
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Martin Turon <mturon@xbow.com>
+ * @see HplM16c62pInterrupt
+ */
+interface HplM16c62pInterruptSig
+{
+  /**
+   * Signaled when an interrupt occurs on a pin
+   */
+  async event void fired();
+}
+
diff --git a/tos/chips/m16c62p/pins/HplM16c62pInterruptSigP.nc b/tos/chips/m16c62p/pins/HplM16c62pInterruptSigP.nc
new file mode 100755 (executable)
index 0000000..6454691
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ * @author Martin Turon <mturon@xbow.com>
+ */
+/**
+ * Interrupt interface access for interrupt capable GPIO pins.
+ * Exposes just the interrupt vector routine for 
+ * easy linking to generic components.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+module HplM16c62pInterruptSigP
+{
+  provides interface HplM16c62pInterruptSig as IntSig0;
+  provides interface HplM16c62pInterruptSig as IntSig1;
+  provides interface HplM16c62pInterruptSig as IntSig2;
+  provides interface HplM16c62pInterruptSig as IntSig3;
+  provides interface HplM16c62pInterruptSig as IntSig4;
+  provides interface HplM16c62pInterruptSig as IntSig5;
+}
+implementation
+{
+  default async event void IntSig0.fired() { }
+  M16C_INTERRUPT_HANDLER(M16C_INT0)
+  {
+    signal IntSig0.fired();
+  }
+
+  default async event void IntSig1.fired() { }
+  M16C_INTERRUPT_HANDLER(M16C_INT1)
+  {
+    signal IntSig1.fired();
+  }
+
+  default async event void IntSig2.fired() { }
+  M16C_INTERRUPT_HANDLER(M16C_INT2)
+  {
+    signal IntSig2.fired();
+  }
+
+  default async event void IntSig3.fired() { }
+  M16C_INTERRUPT_HANDLER(M16C_INT3)
+  {
+    signal IntSig3.fired();
+  }
+
+  default async event void IntSig4.fired() { }
+  M16C_INTERRUPT_HANDLER(M16C_INT4)
+  {
+    signal IntSig4.fired();
+  }
+
+  default async event void IntSig5.fired() { }
+  M16C_INTERRUPT_HANDLER(M16C_INT5)
+  {
+    signal IntSig5.fired();
+  }
+
+}
diff --git a/tos/chips/m16c62p/pins/M16c62pInterruptC.nc b/tos/chips/m16c62p/pins/M16c62pInterruptC.nc
new file mode 100755 (executable)
index 0000000..b5b3be5
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* "Copyright (c) 2000-2005 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * @author Joe Polastre
+ * @author Martin Turon
+ */
+/**
+ * Creates a HIL interrupt component from a M16c/62p interrupt.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+generic module M16c62pInterruptC()
+{
+  provides interface GpioInterrupt;
+  uses interface HplM16c62pInterrupt;
+}
+implementation {
+  async command error_t GpioInterrupt.enableRisingEdge()
+  {
+    atomic
+    {
+      call HplM16c62pInterrupt.disable();
+      call HplM16c62pInterrupt.edge(true);
+      call HplM16c62pInterrupt.clear();
+      call HplM16c62pInterrupt.enable();
+    }
+    return SUCCESS;
+  }
+
+  async command error_t GpioInterrupt.enableFallingEdge()
+  {
+    atomic
+    {
+      call HplM16c62pInterrupt.disable();
+      call HplM16c62pInterrupt.edge(false);
+      call HplM16c62pInterrupt.clear();
+      call HplM16c62pInterrupt.enable();
+    }
+    return SUCCESS;
+  }
+
+  async command error_t GpioInterrupt.disable()
+  {
+    atomic
+    {
+      call HplM16c62pInterrupt.disable();
+      call HplM16c62pInterrupt.clear();
+    }
+    return SUCCESS;
+  }
+
+  async event void HplM16c62pInterrupt.fired()
+  {
+    signal GpioInterrupt.fired();
+  }
+
+  default async event void GpioInterrupt.fired() { }
+}
diff --git a/tos/chips/m16c62p/pins/M16c62pPin.h b/tos/chips/m16c62p/pins/M16c62pPin.h
new file mode 100644 (file)
index 0000000..e4bb8e1
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * M16c62p pin defines and enums.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+
+#ifndef __M16C62P_PIN_H__
+#define __M16C62P_PIN_H__
+
+enum
+{
+  M16C_PIN_INACTIVE_DONT_CARE = 0,
+  M16C_PIN_INACTIVE_OUTPUT_LOW = 1,
+  M16C_PIN_INACTIVE_OUTPUT_HIGH = 2,
+  M16C_PIN_INACTIVE_INPUT = 3
+};
+
+#define M16C_PORT_INACTIVE_STATE(p0, p1, p2, p3, p4, p5, p6, p7) p0 | (p1 << 2) | \
+                                                          (p2 << 4) | (p3 << 6) | \
+                                                          (p4 << 8) | (p5 << 10) | \
+                                                         (p6 << 12) | (p7 << 14)
+
+#endif  // __M16C62P_PIN_H__ 
diff --git a/tos/chips/m16c62p/printf/elib.c b/tos/chips/m16c62p/printf/elib.c
new file mode 100644 (file)
index 0000000..7106e1c
--- /dev/null
@@ -0,0 +1,491 @@
+/****************************************************************
+  KPIT Cummins Infosystems Ltd, Pune, India. 1-April-2006.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+ *****************************************************************/
+
+/*
+   Written By:
+   Shrirang Khishti <shrirangk@kpitcummins.com>.
+
+   This is a smaller version of printf
+   Positive points about this function
+   1. Reduces code size considerably ,very useful in embedded applications
+   2. No malloc calls are used
+   3. Supports almost all the functionalities of GNU std printf routine.
+   4. If user dont want float_support in this customized printf
+   just undef macro float_support
+ */
+
+#include <stdarg.h>
+#include <string.h>
+
+
+int left_val,right_val;
+
+#define condition *format!='f'&&*format!='d'&&*format!='c'&&*format!='s'&&*format!='l'&&*format!='u'&&*format!='\0'&&*format!=' '&&*format!='i'&&*format!='x'&&*format!='X'&&*format!='o'&&*format!='%'&&*format!='p'
+
+#define float_support
+
+long temp_arr[]={100000,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
+
+
+/**
+ * @fn void shutdown(void)
+ * @brief Shutsdown the MCU by placing it in an eternal loop
+ *
+ */
+void
+shutdown(void) 
+{
+  for(;;)
+    ;
+}
+
+
+/**
+ * @fn
+ * @brief 
+ *
+ * @param c
+ */
+int
+_putchar(int c)
+{     
+  /* Convert CR to CR/LF */
+  if (c == '\n')
+    lowlevel_putc('\r');
+  lowlevel_putc(c);
+
+  return c;
+}
+
+
+/**
+ * @fn void _puts(const char *tempStr)
+ * @brief Prints a NULL-erminated string on UART 1
+ *
+ * @param s The string to output
+ *
+ */
+int
+_puts(const char *s)
+{
+  while( *s != '\0' )
+    _putchar(*s++);
+  
+  _putchar('\n');
+
+  return 0;
+}
+
+
+/**
+ * @fn void strrev(char *str)
+ * @brief Reverses a string
+ *
+ * @param str The string to reverse
+ */
+void
+strrev(char *str)
+{
+  char *temp, c;
+  int len=strlen(str) ;
+  temp = str + len -1;
+
+  while(str < temp ) {
+
+    c = *str;
+    *str = *temp;
+
+    *temp = c;
+    str++;
+    temp--;
+  }
+}
+
+static void print_hex_oct( long int temp_var,int div,int corr_factor,int ret_val,int sign,int *cntr_val)
+{
+  unsigned long int i=1,i1,temp=temp_var;
+  int cntr=0,neg_flag=0;
+  char s1[40];
+
+  if(sign==1&&temp_var<0)
+  {
+    temp=-temp_var;
+    neg_flag=1;
+  }
+  if(temp==0)
+    s1[cntr++]='0';
+  while(temp>0)
+  {
+    i1=temp%div;
+    temp=temp/div;
+    if(i1<=9)
+      s1[cntr]=i1+'0';
+    else
+      s1[cntr]=i1+corr_factor-9;
+    cntr++;
+  }
+
+  while((left_val-(right_val>cntr?right_val:cntr+neg_flag))>0)
+  {
+    _putchar(' ');
+    left_val--;
+               (*cntr_val)++;
+       }
+
+       while(right_val-cntr>0)
+       {
+               s1[cntr++]='0';
+       }
+
+       if(neg_flag==1)
+       s1[cntr++]='-';
+
+       s1[cntr]='\0';
+       strrev(s1);
+       _puts(s1);
+       (*cntr_val)+=strlen(s1);
+}
+
+
+#ifdef float_support
+static void float_print(long double f1,long double f2,int multi,int *cntr_val)
+{
+       int i=1,temp,cntr=0,i1,neg_flag=0;
+       char s1[10];
+
+        if(f1<0)
+        {
+                f1=f1*-1;
+                neg_flag=1;
+                f2=f1;
+        }
+        temp=(int)f1;
+
+        f1=f1-temp;
+     f1=f1*multi;
+
+     temp=f1;
+
+     if(temp==0)
+       s1[cntr++]='0';
+     while(temp>0)
+     {
+         i1=temp%10;
+         temp=temp/10;
+         s1[cntr]=i1+0x30;
+         cntr++;
+     }
+
+     while(right_val<9&&(right_val -cntr)>0)
+          s1[cntr++]='0';
+          s1[cntr]='.';
+          cntr++;
+
+          temp=(int)f2;
+        if(temp==0)
+               s1[cntr++]='0';
+        while(temp>0)
+        {
+             i1=temp%10;
+             temp=temp/10;
+             s1[cntr]=i1+0x30;
+             cntr++;
+        }
+
+        while(left_val-- -cntr>0)
+               {
+                       _putchar(' ');
+                       (*cntr_val)++;
+               }
+                       if(neg_flag==1)
+           s1[cntr++]='-';
+           s1[cntr]='\0';
+           cntr--;
+               strrev(s1);
+       _puts(s1);
+               (*cntr_val)+=strlen(s1);
+               neg_flag=0;
+}
+
+#endif // float_support
+
+static int format_val(char *temp,long float_flag,int *cntr_val,int flag)
+{
+left_val=0;
+right_val=0;
+       if(*temp=='\0'&&flag==1)
+       {
+               right_val=3;
+               return 0;
+       }
+       while(*temp!='.'&&*temp!='\0')
+       {
+               if(*temp<'0'||*temp>'9')
+               {
+                       while(*temp)
+                       {
+                               _putchar(*temp++);
+                               (*cntr_val)++;
+                       }
+                       return -1;
+               }
+               else
+               left_val=left_val*10+*temp-'0';
+        temp++;
+       }
+    if(*temp)
+               temp++;
+               else
+               return left_val;
+       while(*temp)
+       {
+       if(*temp<'0'||*temp>'9')
+       {
+       while(*temp)
+               {
+                       _putchar(*temp++);
+                       (*cntr_val)++;
+               }
+       return -1;
+       }
+       else
+       right_val=right_val*10+*temp-'0';
+     temp++;
+       }
+
+return 0;
+}
+
+
+/**
+ * @fn int _printf(const char *format, ...)
+ * @brief Prints a formatted string on UART1
+ *
+ * @param format The string
+ */
+int _printf(const char *format, ...)
+{
+   int format_cntr=0;
+   char temp_str[20];
+   int return_flag=0,cntr_val;
+   long double f1,f2;
+   char *str_temp;
+   int *cntr=&cntr_val;
+
+   va_list ap;
+   va_start(ap, format);
+   *cntr=0;
+   while(*format) {
+     temp_str[format_cntr]='\0';
+     if(*format=='%')
+     {
+       *format++;
+       while(*format==' ')
+       {
+        format++;
+        _putchar(' ');
+       }
+       while(condition)
+
+       {
+        temp_str[format_cntr++]=*format++;
+       }
+       temp_str[format_cntr]='\0';
+       if(*format=='%')
+       {
+        _putchar('%');
+        (*cntr)++;
+        format_cntr=0;
+        format++;
+        continue;
+       }
+
+       /************** print unsigned ****************/
+       else if(*format=='u')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1)
+
+          print_hex_oct(va_arg(ap,unsigned int),10,0,return_flag,0,cntr);
+
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+       }
+       /*********** Print Integer Values **************/
+       else if(*format=='d'||*format=='i')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+
+        if(return_flag!=-1)
+
+          print_hex_oct(va_arg(ap,int),10,0,return_flag,1,cntr);
+
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+
+       }
+
+       /*********** Print hex,Octal values ******************/
+       else if(*format=='x'||*format=='X'||*format=='o'||*format=='p')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1) {
+
+          if(*format=='x'||*format=='p')
+            print_hex_oct(va_arg(ap,unsigned int),16,0x60,return_flag,0,cntr);
+          else if(*format=='X')
+            print_hex_oct(va_arg(ap,unsigned int),16,0x40,return_flag,0,cntr);
+          else
+            print_hex_oct(va_arg(ap,unsigned int),8,0,return_flag,0,cntr);
+        }
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+       }
+
+       /************ Character printing ****************88*/
+       else if(*format=='c')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1)
+        {
+          while(return_flag-->1)
+          {
+            _putchar(' ');
+            (*cntr)++;
+          }
+          _putchar(va_arg(ap,int));
+          (*cntr)+=2;
+        }
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+       }
+
+       /*************** Print String *****************/
+       else if(*format=='s')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1)
+        {
+          str_temp=va_arg(ap,char*);
+
+          while((return_flag--  -(int) strlen(str_temp))>0)
+          {
+            _putchar(' ');
+            (*cntr)++;
+
+          }
+          _puts(str_temp);
+          (*cntr)+=strlen(str_temp);
+        }
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+
+       }
+       /*************** Print floating point number *****************/
+       else if(*format=='f'||(*format=='l'&&*(format+1)=='f'))
+       {
+
+        return_flag=format_val(temp_str,1,cntr,1);
+        if(return_flag!=-1)
+        {
+          if(*format=='l')
+          {
+            f1=va_arg(ap,long double);
+            format+=2;
+          }
+          else
+          {
+            f1=va_arg(ap,double);
+            format++;
+          }
+          f2=f1;
+#ifdef float_support
+          right_val++;
+          float_print(f1,f2,temp_arr[right_val%10],cntr);
+#endif
+        }
+        else
+        {
+          _putchar(*format++);
+          (*cntr)++;
+        }
+        format_cntr=0;
+        continue;
+       }
+       else if(*format=='l'&&((*(format+1)=='d')||(*(format+1)=='u')))
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+
+        if((return_flag=-1)&&(*(format+1)=='d'))
+        {
+          print_hex_oct(va_arg(ap,long int),10,0x00,return_flag,1,cntr);
+        }
+
+        else if((return_flag=-1)&&(*(format+1)=='u'))
+        {
+          print_hex_oct(va_arg(ap,unsigned long int),10,0x00,return_flag,0,cntr);
+        }
+
+        else
+        {
+          _putchar(*format);
+          _putchar(*(format+1));
+          (*cntr)+=2;
+        }
+        format+=2;
+        format_cntr=0;
+        continue;
+       }
+       else
+       {
+        _puts(temp_str);
+        format_cntr=0;
+        continue;
+       }
+     }
+     _putchar(*format++);
+
+     (*cntr)++;
+   }
+   va_end(ap);
+   return cntr_val;
+}
+
+
+
diff --git a/tos/chips/m16c62p/printf/m16c62p_printf.h b/tos/chips/m16c62p/printf/m16c62p_printf.h
new file mode 100644 (file)
index 0000000..96a8d9d
--- /dev/null
@@ -0,0 +1,481 @@
+/****************************************************************
+  KPIT Cummins Infosystems Ltd, Pune, India. 1-April-2006.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+ *****************************************************************/
+
+/*
+   Written By:
+   Shrirang Khishti <shrirangk@kpitcummins.com>.
+
+   This is a smaller version of printf
+   Positive points about this function
+   1. Reduces code size considerably ,very useful in embedded applications
+   2. No malloc calls are used
+   3. Supports almost all the functionalities of GNU std printf routine.
+   4. If user dont want float_support in this customized printf
+   just undef macro float_support
+ */
+
+#ifndef  __M16C62P_PRINTF_H__
+#define __M16C62P_PRINTF_H__
+#include <stdarg.h>
+#include <string.h>
+
+#define printf _printf
+
+int left_val,right_val;
+
+#define condition *format!='f'&&*format!='d'&&*format!='c'&&*format!='s'&&*format!='l'&&*format!='u'&&*format!='\0'&&*format!=' '&&*format!='i'&&*format!='x'&&*format!='X'&&*format!='o'&&*format!='%'&&*format!='p'
+
+#define float_support
+
+long temp_arr[]={100000,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
+
+
+/**
+ * @fn
+ * @brief 
+ *
+ * @param c
+ */
+int
+_putchar(int c)
+{     
+  /* Convert CR to CR/LF */
+  if (c == '\n')
+    lowlevel_putc('\r');
+  lowlevel_putc(c);
+
+  return c;
+}
+
+
+/**
+ * @fn void _puts(const char *tempStr)
+ * @brief Prints a NULL-erminated string on UART 1
+ *
+ * @param s The string to output
+ *
+ */
+int
+_puts(const char *s)
+{
+  while( *s != '\0' )
+    _putchar(*s++);
+
+  return 0;
+}
+
+
+/**
+ * @fn void strrev(char *str)
+ * @brief Reverses a string
+ *
+ * @param str The string to reverse
+ */
+void
+strrev(char *str)
+{
+  char *temp, c;
+  int len=strlen(str) ;
+  temp = str + len -1;
+
+  while(str < temp ) {
+
+    c = *str;
+    *str = *temp;
+
+    *temp = c;
+    str++;
+    temp--;
+  }
+}
+
+
+static void print_hex_oct( long int temp_var,int _div,int corr_factor,int ret_val,int sign,int *cntr_val)
+{
+  unsigned long int i=1,i1,temp=temp_var;
+  int cntr=0,neg_flag=0;
+  char s1[40];
+
+  if(sign==1&&temp_var<0)
+  {
+    temp=-temp_var;
+    neg_flag=1;
+  }
+  if(temp==0)
+    s1[cntr++]='0';
+  while(temp>0)
+  {
+    i1=temp%_div;
+    temp=temp/_div;
+    if(i1<=9)
+      s1[cntr]=i1+'0';
+    else
+      s1[cntr]=i1+corr_factor-9;
+    cntr++;
+  }
+
+  while((left_val-(right_val>cntr?right_val:cntr+neg_flag))>0)
+  {
+    _putchar(' ');
+    left_val--;
+               (*cntr_val)++;
+       }
+
+       while(right_val-cntr>0)
+       {
+               s1[cntr++]='0';
+       }
+
+       if(neg_flag==1)
+       s1[cntr++]='-';
+
+       s1[cntr]='\0';
+       strrev(s1);
+       _puts(s1);
+       (*cntr_val)+=strlen(s1);
+}
+
+
+#ifdef float_support
+static void float_print(long double f1,long double f2,int multi,int *cntr_val)
+{
+       int i=1,temp,cntr=0,i1,neg_flag=0;
+       char s1[10];
+
+        if(f1<0)
+        {
+                f1=f1*-1;
+                neg_flag=1;
+                f2=f1;
+        }
+        temp=(int)f1;
+
+        f1=f1-temp;
+     f1=f1*multi;
+
+     temp=f1;
+
+     if(temp==0)
+       s1[cntr++]='0';
+     while(temp>0)
+     {
+         i1=temp%10;
+         temp=temp/10;
+         s1[cntr]=i1+0x30;
+         cntr++;
+     }
+
+     while(right_val<9&&(right_val -cntr)>0)
+          s1[cntr++]='0';
+          s1[cntr]='.';
+          cntr++;
+
+          temp=(int)f2;
+        if(temp==0)
+               s1[cntr++]='0';
+        while(temp>0)
+        {
+             i1=temp%10;
+             temp=temp/10;
+             s1[cntr]=i1+0x30;
+             cntr++;
+        }
+
+        while(left_val-- -cntr>0)
+               {
+                       _putchar(' ');
+                       (*cntr_val)++;
+               }
+                       if(neg_flag==1)
+           s1[cntr++]='-';
+           s1[cntr]='\0';
+           cntr--;
+               strrev(s1);
+       _puts(s1);
+               (*cntr_val)+=strlen(s1);
+               neg_flag=0;
+}
+
+#endif // float_support
+
+static int format_val(char *temp,long float_flag,int *cntr_val,int flag)
+{
+left_val=0;
+right_val=0;
+       if(*temp=='\0'&&flag==1)
+       {
+               right_val=3;
+               return 0;
+       }
+       while(*temp!='.'&&*temp!='\0')
+       {
+               if(*temp<'0'||*temp>'9')
+               {
+                       while(*temp)
+                       {
+                               _putchar(*temp++);
+                               (*cntr_val)++;
+                       }
+                       return -1;
+               }
+               else
+               left_val=left_val*10+*temp-'0';
+        temp++;
+       }
+    if(*temp)
+               temp++;
+               else
+               return left_val;
+       while(*temp)
+       {
+       if(*temp<'0'||*temp>'9')
+       {
+       while(*temp)
+               {
+                       _putchar(*temp++);
+                       (*cntr_val)++;
+               }
+       return -1;
+       }
+       else
+       right_val=right_val*10+*temp-'0';
+     temp++;
+       }
+
+return 0;
+}
+
+
+/**
+ * @fn int _printf(const char *format, ...)
+ * @brief Prints a formatted string on UART1
+ *
+ * @param format The string
+ */
+int _printf(const char *format, ...)
+{
+   int format_cntr=0;
+   char temp_str[20];
+   int return_flag=0,cntr_val;
+   long double f1,f2;
+   char *str_temp;
+   int *cntr=&cntr_val;
+
+   va_list ap;
+   va_start(ap, format);
+   *cntr=0;
+   while(*format) {
+     temp_str[format_cntr]='\0';
+     if(*format=='%')
+     {
+       *format++;
+       while(*format==' ')
+       {
+        format++;
+        _putchar(' ');
+       }
+       while(condition)
+
+       {
+        temp_str[format_cntr++]=*format++;
+       }
+       temp_str[format_cntr]='\0';
+       if(*format=='%')
+       {
+        _putchar('%');
+        (*cntr)++;
+        format_cntr=0;
+        format++;
+        continue;
+       }
+
+       /************** print unsigned ****************/
+       else if(*format=='u')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1)
+
+          print_hex_oct(va_arg(ap,unsigned int),10,0,return_flag,0,cntr);
+
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+       }
+       /*********** Print Integer Values **************/
+       else if(*format=='d'||*format=='i')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+
+        if(return_flag!=-1)
+
+          print_hex_oct(va_arg(ap,int),10,0,return_flag,1,cntr);
+
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+
+       }
+
+       /*********** Print hex,Octal values ******************/
+       else if(*format=='x'||*format=='X'||*format=='o'||*format=='p')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1) {
+
+          if(*format=='x'||*format=='p')
+            print_hex_oct(va_arg(ap,unsigned int),16,0x60,return_flag,0,cntr);
+          else if(*format=='X')
+            print_hex_oct(va_arg(ap,unsigned int),16,0x40,return_flag,0,cntr);
+          else
+            print_hex_oct(va_arg(ap,unsigned int),8,0,return_flag,0,cntr);
+        }
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+       }
+
+       /************ Character printing ****************88*/
+       else if(*format=='c')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1)
+        {
+          while(return_flag-->1)
+          {
+            _putchar(' ');
+            (*cntr)++;
+          }
+          _putchar(va_arg(ap,int));
+          (*cntr)+=2;
+        }
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+       }
+
+       /*************** Print String *****************/
+       else if(*format=='s')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1)
+        {
+          str_temp=va_arg(ap,char*);
+
+          while((return_flag--  -(int) strlen(str_temp))>0)
+          {
+            _putchar(' ');
+            (*cntr)++;
+
+          }
+          _puts(str_temp);
+          (*cntr)+=strlen(str_temp);
+        }
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+
+       }
+       /*************** Print floating point number *****************/
+       else if(*format=='f'||(*format=='l'&&*(format+1)=='f'))
+       {
+
+        return_flag=format_val(temp_str,1,cntr,1);
+        if(return_flag!=-1)
+        {
+          if(*format=='l')
+          {
+            f1=va_arg(ap,long double);
+            format+=2;
+          }
+          else
+          {
+            f1=va_arg(ap,double);
+            format++;
+          }
+          f2=f1;
+#ifdef float_support
+          right_val++;
+          float_print(f1,f2,temp_arr[right_val%10],cntr);
+#endif
+        }
+        else
+        {
+          _putchar(*format++);
+          (*cntr)++;
+        }
+        format_cntr=0;
+        continue;
+       }
+       else if(*format=='l'&&((*(format+1)=='d')||(*(format+1)=='u')))
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+
+        if((return_flag=-1)&&(*(format+1)=='d'))
+        {
+          print_hex_oct(va_arg(ap,long int),10,0x00,return_flag,1,cntr);
+        }
+
+        else if((return_flag=-1)&&(*(format+1)=='u'))
+        {
+          print_hex_oct(va_arg(ap,unsigned long int),10,0x00,return_flag,0,cntr);
+        }
+
+        else
+        {
+          _putchar(*format);
+          _putchar(*(format+1));
+          (*cntr)+=2;
+        }
+        format+=2;
+        format_cntr=0;
+        continue;
+       }
+       else
+       {
+        _puts(temp_str);
+        format_cntr=0;
+        continue;
+       }
+     }
+     _putchar(*format++);
+
+     (*cntr)++;
+   }
+   va_end(ap);
+   return cntr_val;
+}
+
+
+#endif // __M16C62P_PRINTF_H__
+
diff --git a/tos/chips/m16c62p/timer/HplM16c62pTimer.nc b/tos/chips/m16c62p/timer/HplM16c62pTimer.nc
new file mode 100755 (executable)
index 0000000..a762e2c
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ */
+
+/**
+ * Basic interface to the hardware timers on the M16C/62p.
+ * This interface provides four major groups of functionality:<ol>
+ *      <li>Timer Value: get/set current time
+ *      <li>Interrupt event, occurs when the timer under- or overflows.
+ *      <li>Control of Interrupt: enableInterrupt/disableInterrupt/clearInterrupt...
+ *      <li>Timer Initialization: turn on/off clock source
+ * </ol>
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Martin Turon <mturon@xbow.com>
+ */
+#include "M16c62pTimer.h"
+
+interface HplM16c62pTimer
+{
+  /**
+   * Turn on the clock.
+   */
+  async command void on();
+  
+  /**
+   * Turn off the clock.
+   */
+  async command void off();
+
+  /**
+   * Check if the clock is on.
+   */
+  async command bool isOn();
+
+  /** 
+   * Get the current time.
+   * @return  the current time.
+   */
+  async command uint16_t get();
+
+  /** 
+   * Set the current time.
+   * @param t the time to set.
+   */
+  async command void set( uint16_t t );
+
+  /**
+   * Signalled on timer interrupt.
+   */
+  async event void fired();
+
+  /**
+   * Clear the interrupt flag.
+   */
+  async command void clearInterrupt();
+
+  /**
+   * Enable the interrupts.
+   */
+  async command void enableInterrupt();
+
+  /**
+   * Turns off interrupts.
+   */
+  async command void disableInterrupt();
+
+  /** 
+   * Checks if an interrupt has occured.
+   * @return TRUE if interrupt has triggered.
+   */
+  async command bool testInterrupt();
+
+  /** 
+   * Checks if interrupts are on.
+   * @return TRUE if interrups are enabled.
+   */
+  async command bool isInterruptOn();
+  
+  /**
+   * Turn stop mode on/off while the timer is on.
+   * @param allow If true the mcu can go into stop mode while
+   *              timer is on if false the mcu can only use
+   *              wait mode while timer is on.
+   */
+  async command void allowStopMode(bool allow);
+}
diff --git a/tos/chips/m16c62p/timer/HplM16c62pTimerACtrl.nc b/tos/chips/m16c62p/timer/HplM16c62pTimerACtrl.nc
new file mode 100755 (executable)
index 0000000..2151e99
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface for controlling the mode of a TimerA.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "M16c62pTimer.h"
+
+interface HplM16c62pTimerACtrl
+{
+  /**
+   * Sets the timer to timer mode.
+   *
+   * @param settings The settings for the timer mode.
+   */
+  async command void setTimerMode(st_timer settings);
+
+  /**
+   * Sets the timer to counter mode.
+   *
+   * @param settings The settings for the counter mode.
+   */
+  async command void setCounterMode(sta_counter settings);
+
+  /**
+   * Sets the timer to one-shot mode.
+   *
+   * @param settings The settings for the one-shot mode.
+   */
+  async command void setOneShotMode(sta_one_shot settings);
+  
+  /**
+   * Starts the timer if in one-shot mode.
+   */
+  async command void oneShotFire();
+}
diff --git a/tos/chips/m16c62p/timer/HplM16c62pTimerACtrlP.nc b/tos/chips/m16c62p/timer/HplM16c62pTimerACtrlP.nc
new file mode 100755 (executable)
index 0000000..72b8579
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Implementation of the HplM16c62pTimerACtrl interface.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "M16c62pTimer.h"
+
+generic module HplM16c62pTimerACtrlP (uint8_t timer,
+                                      uint16_t mode_addr,
+                                      uint16_t taitg_addr,
+                                      uint8_t taitg_start_bit)
+{
+  provides interface HplM16c62pTimerACtrl as TimerACtrl;
+}
+implementation
+{
+#define mode (*TCAST(volatile uint8_t* ONE, mode_addr))
+#define taitg (*TCAST(volatile uint8_t* ONE, taitg_addr))
+  inline void UDFBit(uint16_t bit, uint16_t value)
+  {
+    uint8_t tmp = UDF;
+    WRITE_BIT(tmp, bit, value);
+    // Move tmp variable into UDF (adress 0x0384)
+    asm("mov.b %0,(0x0384)" : : "r"(tmp) );
+  }
+  
+  inline void setTAiTG(uint8_t flag)
+  {
+    CLR_FLAG(taitg, 0x03 << taitg_start_bit);
+    SET_FLAG(taitg, flag << taitg_start_bit);
+  }
+
+  async command void TimerACtrl.setTimerMode(st_timer settings)
+  {
+    uint8_t flags = 0;
+    // If timer nr > 1 set "Two-phase pulse signal" bit to zero.
+    if (timer > 1)
+    {
+      UDFBit(timer + 3, 0);
+    }
+    flags = settings.output_pulse << 2 | settings.gate_func << 3 | settings.count_src << 6;
+    mode = flags;
+  }
+
+  async command void TimerACtrl.setCounterMode(sta_counter settings)
+  {
+    uint8_t flags;
+    uint8_t TAiTG;
+    mode = 1;
+    flags = settings.operation_type << 6;
+    if (settings.two_phase_pulse_mode && timer > 1)
+    {
+      uint8_t tmp = timer; // Used to remove left shift warning
+      // Set flags
+      flags |= 0x04 | settings.two_phase_processing << 7;
+      // If two-phase signal procressing is desired UDF TAiP bit must be set.
+      UDFBit(timer + 3, 1);
+      // Set TAiTGH and TAiTGL in TRGSR to "00b" (TAiIN pin input).
+      if (tmp == 0)
+        tmp = 1; // This line will never be executed because tmp is always > 1
+      CLR_FLAG(TRGSR.BYTE, 0x03 << ((tmp - 1) * 2));
+      TAiTG = 0x00;
+    }
+    else
+    {
+      flags |= settings.output_pulse << 2 | settings.count_rising_edge << 3 |
+          settings.up_down_switch << 4;
+      // If two-phase signal procressing is not desired UDF TAiP bit must be cleared.
+      // Note this is only availible for timers A2, A3 and A4
+      if (timer > 1)
+      {
+        UDFBit(timer + 3, 0);
+      }
+      UDFBit(timer, settings.up_count);
+      TAiTG = settings.event_source;
+    }
+    setTAiTG(TAiTG);
+    mode |= flags;
+  }
+
+  async command void TimerACtrl.setOneShotMode(sta_one_shot settings)
+  {
+    uint8_t flags;
+    mode = 0x02;
+    flags = settings.output_pulse << 2 | settings.ext_trigger_rising_edge << 3 | settings.trigger << 4 | settings.count_src << 6;
+    setTAiTG(settings.TAiTG_trigger_source);
+    mode |= flags;
+  }
+
+  async command void TimerACtrl.oneShotFire()
+  {
+    SET_BIT(ONSF.BYTE, timer);
+  }
+}
diff --git a/tos/chips/m16c62p/timer/HplM16c62pTimerBCtrl.nc b/tos/chips/m16c62p/timer/HplM16c62pTimerBCtrl.nc
new file mode 100755 (executable)
index 0000000..e7c5984
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+* Interface for controlling the mode of a TimerB.
+* Precaution when using timer mode, read M16c62pTimer.h for more information.
+*
+* @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+*/
+
+#include "M16c62pTimer.h"
+
+interface HplM16c62pTimerBCtrl
+{
+  /** 
+   * Sets the timer to timer mode.
+   *
+   * @param settings The settings for the timer mode.
+   */
+  async command void setTimerMode(st_timer settings);
+
+  /** 
+   * Sets the timer to counter mode.
+   *
+   * @param settings The settings for the counter mode.
+   */
+  async command void setCounterMode(stb_counter settings);
+}
diff --git a/tos/chips/m16c62p/timer/HplM16c62pTimerBCtrlP.nc b/tos/chips/m16c62p/timer/HplM16c62pTimerBCtrlP.nc
new file mode 100755 (executable)
index 0000000..ab59f19
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Implementation of the HplM16c62pTimerBCtrl interface.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "M16c62pTimer.h"
+
+generic module HplM16c62pTimerBCtrlP (uint16_t mode_addr)
+{
+  provides interface HplM16c62pTimerBCtrl as TimerBCtrl;
+}
+implementation
+{
+#define mode (*TCAST(volatile uint8_t* ONE, mode_addr))
+  async command void TimerBCtrl.setTimerMode(st_timer settings)
+  {
+    mode = settings.count_src << 6;
+  }
+
+  async command void TimerBCtrl.setCounterMode(stb_counter settings)
+  {
+    mode = 1 | settings.count_polarity << 2 | settings.event_source << 7;
+  }
+}
diff --git a/tos/chips/m16c62p/timer/HplM16c62pTimerC.nc b/tos/chips/m16c62p/timer/HplM16c62pTimerC.nc
new file mode 100755 (executable)
index 0000000..d7f07da
--- /dev/null
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interfaces to all the M16c/62p timers and controls.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration HplM16c62pTimerC
+{
+  provides
+  {
+    interface HplM16c62pTimer as TimerA0;
+    interface HplM16c62pTimer as TimerA1;
+    interface HplM16c62pTimer as TimerA2;
+    interface HplM16c62pTimer as TimerA3;
+    interface HplM16c62pTimer as TimerA4;
+
+    interface HplM16c62pTimerACtrl as TimerA0Ctrl;
+    interface HplM16c62pTimerACtrl as TimerA1Ctrl;
+    interface HplM16c62pTimerACtrl as TimerA2Ctrl;
+    interface HplM16c62pTimerACtrl as TimerA3Ctrl;
+    interface HplM16c62pTimerACtrl as TimerA4Ctrl; 
+
+    interface HplM16c62pTimer as TimerB0;
+    interface HplM16c62pTimer as TimerB1;
+    interface HplM16c62pTimer as TimerB2;
+    interface HplM16c62pTimer as TimerB3;
+    interface HplM16c62pTimer as TimerB4;
+    interface HplM16c62pTimer as TimerB5;
+
+    interface HplM16c62pTimerBCtrl as TimerB0Ctrl;
+    interface HplM16c62pTimerBCtrl as TimerB1Ctrl;
+    interface HplM16c62pTimerBCtrl as TimerB2Ctrl;
+    interface HplM16c62pTimerBCtrl as TimerB3Ctrl;
+    interface HplM16c62pTimerBCtrl as TimerB4Ctrl;
+    interface HplM16c62pTimerBCtrl as TimerB5Ctrl;
+  }
+}
+implementation 
+{
+  components
+    HplM16c62pTimerInterruptP as IrqVector,
+    new HplM16c62pTimerP((uint16_t)&TA0, (uint16_t)&TA0IC, (uint16_t)&TABSR, 0) as TimerA0_,
+    new HplM16c62pTimerP((uint16_t)&TA1, (uint16_t)&TA1IC, (uint16_t)&TABSR, 1) as TimerA1_,
+    new HplM16c62pTimerP((uint16_t)&TA2, (uint16_t)&TA2IC, (uint16_t)&TABSR, 2) as TimerA2_,
+    new HplM16c62pTimerP((uint16_t)&TA3, (uint16_t)&TA3IC, (uint16_t)&TABSR, 3) as TimerA3_,
+    new HplM16c62pTimerP((uint16_t)&TA4, (uint16_t)&TA4IC, (uint16_t)&TABSR, 4) as TimerA4_,
+
+    new HplM16c62pTimerACtrlP(0, (uint16_t)&TA0MR, (uint16_t)&ONSF,  6) as TimerA0Ctrl_,
+    new HplM16c62pTimerACtrlP(1, (uint16_t)&TA1MR, (uint16_t)&TRGSR, 0) as TimerA1Ctrl_,
+    new HplM16c62pTimerACtrlP(2, (uint16_t)&TA2MR, (uint16_t)&TRGSR, 2) as TimerA2Ctrl_,
+    new HplM16c62pTimerACtrlP(3, (uint16_t)&TA3MR, (uint16_t)&TRGSR, 4) as TimerA3Ctrl_,
+    new HplM16c62pTimerACtrlP(4, (uint16_t)&TA4MR, (uint16_t)&TRGSR, 6) as TimerA4Ctrl_,
+
+    new HplM16c62pTimerP((uint16_t)&TB0, (uint16_t)&TB0IC, (uint16_t)&TABSR, 5) as TimerB0_,
+    new HplM16c62pTimerP((uint16_t)&TB1, (uint16_t)&TB1IC, (uint16_t)&TABSR, 6) as TimerB1_,
+    new HplM16c62pTimerP((uint16_t)&TB2, (uint16_t)&TB2IC, (uint16_t)&TABSR, 7) as TimerB2_,
+    new HplM16c62pTimerP((uint16_t)&TB3, (uint16_t)&TB3IC, (uint16_t)&TBSR,  5) as TimerB3_,
+    new HplM16c62pTimerP((uint16_t)&TB4, (uint16_t)&TB4IC, (uint16_t)&TBSR,  6) as TimerB4_,
+    new HplM16c62pTimerP((uint16_t)&TB5, (uint16_t)&TB5IC, (uint16_t)&TBSR,  7) as TimerB5_,
+
+    new HplM16c62pTimerBCtrlP((uint16_t)&TB0MR) as TimerB0Ctrl_,
+    new HplM16c62pTimerBCtrlP((uint16_t)&TB1MR) as TimerB1Ctrl_,
+    new HplM16c62pTimerBCtrlP((uint16_t)&TB2MR) as TimerB2Ctrl_,
+    new HplM16c62pTimerBCtrlP((uint16_t)&TB3MR) as TimerB3Ctrl_,
+    new HplM16c62pTimerBCtrlP((uint16_t)&TB4MR) as TimerB4Ctrl_,
+    new HplM16c62pTimerBCtrlP((uint16_t)&TB5MR) as TimerB5Ctrl_,
+    
+    new StopModeControlC() as TimerA0StopModeControl,
+    new StopModeControlC() as TimerA1StopModeControl,
+    new StopModeControlC() as TimerA2StopModeControl,
+    new StopModeControlC() as TimerA3StopModeControl,
+    new StopModeControlC() as TimerA4StopModeControl,
+
+    new StopModeControlC() as TimerB0StopModeControl,
+    new StopModeControlC() as TimerB1StopModeControl,
+    new StopModeControlC() as TimerB2StopModeControl,
+    new StopModeControlC() as TimerB3StopModeControl,
+    new StopModeControlC() as TimerB4StopModeControl,
+    new StopModeControlC() as TimerB5StopModeControl;
+    
+
+  TimerA0 = TimerA0_;
+  TimerA1 = TimerA1_;
+  TimerA2 = TimerA2_;
+  TimerA3 = TimerA3_;
+  TimerA4 = TimerA4_;
+  
+  TimerA0_.StopModeControl -> TimerA0StopModeControl;
+  TimerA1_.StopModeControl -> TimerA1StopModeControl;
+  TimerA2_.StopModeControl -> TimerA2StopModeControl;
+  TimerA3_.StopModeControl -> TimerA3StopModeControl;
+  TimerA4_.StopModeControl -> TimerA4StopModeControl;
+
+  TimerB0 = TimerB0_;
+  TimerB1 = TimerB1_;
+  TimerB2 = TimerB2_;
+  TimerB3 = TimerB3_;
+  TimerB4 = TimerB4_;
+  TimerB5 = TimerB5_;
+  
+  TimerB0_.StopModeControl -> TimerB0StopModeControl;
+  TimerB1_.StopModeControl -> TimerB1StopModeControl;
+  TimerB2_.StopModeControl -> TimerB2StopModeControl;
+  TimerB3_.StopModeControl -> TimerB3StopModeControl;
+  TimerB4_.StopModeControl -> TimerB4StopModeControl;
+  TimerB5_.StopModeControl -> TimerB5StopModeControl;
+
+  TimerA0_.IrqSignal -> IrqVector.TimerA0;
+  TimerA1_.IrqSignal -> IrqVector.TimerA1;
+  TimerA2_.IrqSignal -> IrqVector.TimerA2;
+  TimerA3_.IrqSignal -> IrqVector.TimerA3;
+  TimerA4_.IrqSignal -> IrqVector.TimerA4;
+
+  TimerB0_.IrqSignal -> IrqVector.TimerB0;
+  TimerB1_.IrqSignal -> IrqVector.TimerB1;
+  TimerB2_.IrqSignal -> IrqVector.TimerB2;
+  TimerB3_.IrqSignal -> IrqVector.TimerB3;
+  TimerB4_.IrqSignal -> IrqVector.TimerB4;
+  TimerB5_.IrqSignal -> IrqVector.TimerB5;
+
+  TimerA0Ctrl = TimerA0Ctrl_;
+  TimerA1Ctrl = TimerA1Ctrl_;
+  TimerA2Ctrl = TimerA2Ctrl_;
+  TimerA3Ctrl = TimerA3Ctrl_;
+  TimerA4Ctrl = TimerA4Ctrl_;
+
+  TimerB0Ctrl = TimerB0Ctrl_;
+  TimerB1Ctrl = TimerB1Ctrl_;
+  TimerB2Ctrl = TimerB2Ctrl_;
+  TimerB3Ctrl = TimerB3Ctrl_;
+  TimerB4Ctrl = TimerB4Ctrl_;
+  TimerB5Ctrl = TimerB5Ctrl_;
+}
diff --git a/tos/chips/m16c62p/timer/HplM16c62pTimerInterrupt.nc b/tos/chips/m16c62p/timer/HplM16c62pTimerInterrupt.nc
new file mode 100755 (executable)
index 0000000..e373a29
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface for interrupt signal from a timer.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+interface HplM16c62pTimerInterrupt
+{
+  /** 
+   * Signal when an overflow/underflow interrupt occurs on a timer.
+   */  
+  async event void fired();
+}
+
diff --git a/tos/chips/m16c62p/timer/HplM16c62pTimerInterruptP.nc b/tos/chips/m16c62p/timer/HplM16c62pTimerInterruptP.nc
new file mode 100755 (executable)
index 0000000..4268976
--- /dev/null
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * All timer interrupt vector handlers.
+ * These are wired in HplM16c62pTimerC.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+module HplM16c62pTimerInterruptP
+{
+  provides interface HplM16c62pTimerInterrupt as TimerA0;
+  provides interface HplM16c62pTimerInterrupt as TimerA1;
+  provides interface HplM16c62pTimerInterrupt as TimerA2;
+  provides interface HplM16c62pTimerInterrupt as TimerA3;
+  provides interface HplM16c62pTimerInterrupt as TimerA4;
+  provides interface HplM16c62pTimerInterrupt as TimerB0;
+  provides interface HplM16c62pTimerInterrupt as TimerB1;
+  provides interface HplM16c62pTimerInterrupt as TimerB2;
+  provides interface HplM16c62pTimerInterrupt as TimerB3;
+  provides interface HplM16c62pTimerInterrupt as TimerB4;
+  provides interface HplM16c62pTimerInterrupt as TimerB5;
+}
+implementation
+{
+  default async event void TimerA0.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRA0)
+  {
+    signal TimerA0.fired();
+  }
+
+  default async event void TimerA1.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRA1)
+  {
+    signal TimerA1.fired();
+  }
+
+  default async event void TimerA2.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRA2)
+  {
+    signal TimerA2.fired();
+  }
+
+  default async event void TimerA3.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRA3)
+  {
+    signal TimerA3.fired();
+  }
+
+  default async event void TimerA4.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRA4)
+  {
+    signal TimerA4.fired();
+  }
+
+  default async event void TimerB0.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRB0)
+  {
+    signal TimerB0.fired();
+  }
+
+  default async event void TimerB1.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRB1)
+  {
+    signal TimerB1.fired();
+  }
+
+  default async event void TimerB2.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRB2)
+  {
+    signal TimerB2.fired();
+  }
+
+  default async event void TimerB3.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRB3)
+  {
+    signal TimerB3.fired();
+  }
+
+  default async event void TimerB4.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRB4)
+  {
+    signal TimerB4.fired();
+  }
+
+  default async event void TimerB5.fired() { } 
+  M16C_INTERRUPT_HANDLER(M16C_TMRB5)
+  {
+    signal TimerB5.fired();
+  }
+
+}
diff --git a/tos/chips/m16c62p/timer/HplM16c62pTimerP.nc b/tos/chips/m16c62p/timer/HplM16c62pTimerP.nc
new file mode 100755 (executable)
index 0000000..eef8fb1
--- /dev/null
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Implementation of a generic HplM16c62pTimer interface.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+generic module HplM16c62pTimerP (uint16_t timer_addr,
+                                 uint16_t interrupt_addr,
+                                 uint16_t start_addr,
+                                 uint8_t start_bit)
+{
+  provides interface HplM16c62pTimer as Timer;
+
+  uses interface HplM16c62pTimerInterrupt as IrqSignal;
+  uses interface StopModeControl;
+}
+implementation
+{
+#define timer (*TCAST(volatile uint16_t* ONE, timer_addr))
+#define start (*TCAST(volatile uint8_t* ONE, start_addr))
+#define interrupt (*TCAST(volatile uint8_t* ONE, interrupt_addr))
+
+  bool allow_stop_mode = false;
+
+  async command uint16_t Timer.get() { return timer; }
+  
+  async command void Timer.set( uint16_t t )
+  {
+    // If the timer is on it must be turned off, else the value will
+    // only be written to the reload register.
+    atomic
+    {
+      if(call Timer.isOn())
+      {
+        call Timer.off();
+        timer = t;
+        call Timer.on();
+      }
+      else
+      {
+        timer = t;
+      }
+    }
+  }
+
+  // When the timer is turned on in one-shot mode on TimerA
+  // the timer also needs an trigger event to start counting.
+  async command void Timer.on()
+  { 
+    atomic if (!allow_stop_mode)
+    {
+      call StopModeControl.allowStopMode(false);
+    }
+    SET_BIT(start, start_bit); 
+  }
+  
+  async command void Timer.off()
+  { 
+    CLR_BIT(start, start_bit);
+    atomic if (!allow_stop_mode)
+    {
+      call StopModeControl.allowStopMode(true);
+    }
+  }
+  
+  async command bool Timer.isOn() { return READ_BIT(start, start_bit); }
+  async command void Timer.clearInterrupt() { clear_interrupt(interrupt_addr); }
+  async command void Timer.enableInterrupt() { SET_BIT(interrupt, 0); }
+  async command void Timer.disableInterrupt() { CLR_BIT(interrupt, 0); }
+  async command bool Timer.testInterrupt() { return READ_BIT(interrupt, 3); }
+  async command bool Timer.isInterruptOn() { return READ_BIT(interrupt, 0); }
+
+  async command void Timer.allowStopMode(bool allow)
+  {
+    allow_stop_mode = allow;
+  }
+  // Forward the timer interrupt event.  
+  async event void IrqSignal.fired() { signal Timer.fired(); }
+
+  default async event void Timer.fired() { } 
+}
diff --git a/tos/chips/m16c62p/timer/M16c62pAlarm16C.nc b/tos/chips/m16c62p/timer/M16c62pAlarm16C.nc
new file mode 100755 (executable)
index 0000000..7202894
--- /dev/null
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Build a TEP102 16bits Alarm from a counter and a M16c62p hardware timers.
+ * Use the counter to get the "current time" and the hw timer to count down the
+ * remaining time for the alarm to be fired.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic module M16c62pAlarm16C(typedef precision_tag)
+{
+  provides interface Alarm<precision_tag, uint16_t> as Alarm @atmostonce();
+
+  uses interface HplM16c62pTimer as ATimer; // Alarm Timer
+  uses interface Counter<precision_tag, uint16_t>;
+}
+implementation
+{
+  uint16_t alarm = 0;
+  async command uint16_t Alarm.getNow()
+  {
+    return call Counter.get();
+  }
+
+  async command uint16_t Alarm.getAlarm()
+  {
+    return alarm;
+  }
+
+  async command bool Alarm.isRunning()
+  {
+    return call ATimer.isInterruptOn();
+  }
+
+  async command void Alarm.stop()
+  {
+    atomic
+    {
+      call ATimer.off();
+      call ATimer.disableInterrupt();
+    }
+  }
+
+  async command void Alarm.start( uint16_t dt ) 
+  {
+    call Alarm.startAt( call Alarm.getNow(), dt);
+  }
+
+  async command void Alarm.startAt( uint16_t t0, uint16_t dt )
+  {
+    atomic
+    {
+      uint16_t now, elapsed, expires;
+
+      now = call Alarm.getNow();
+      elapsed = now - t0;
+        
+      if (elapsed >= dt)
+      {
+        expires = 0;
+      }
+      else
+      {
+        expires = dt - elapsed - 1;
+      }
+        
+      call ATimer.off();
+      call ATimer.set(expires);
+      call ATimer.clearInterrupt();
+      call ATimer.enableInterrupt();
+      call ATimer.on();
+    }
+  }
+
+  async event void ATimer.fired()
+  {
+    call Alarm.stop();
+    signal Alarm.fired();
+  }
+
+  async event void Counter.overflow() {}
+}
diff --git a/tos/chips/m16c62p/timer/M16c62pAlarm32C.nc b/tos/chips/m16c62p/timer/M16c62pAlarm32C.nc
new file mode 100755 (executable)
index 0000000..2e94821
--- /dev/null
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Build a TEP102 32bit Alarm from a counter and two M16c62p hardware timers.
+ * Use the counter to get the "current time" and the hw timer to count down the
+ * remaining time for the alarm to be fired.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic module M16c62pAlarm32C(typedef precision_tag)
+{
+  provides interface Alarm<precision_tag, uint32_t> as Alarm @atmostonce();
+
+  uses interface HplM16c62pTimer as ATimerLow; // Alarm Timer low bits
+  uses interface HplM16c62pTimer as ATimerHigh; // Alarm Timer high bits
+  uses interface Counter<precision_tag, uint32_t>;
+}
+implementation
+{
+  uint32_t alarm = 0;
+
+  async command uint32_t Alarm.getNow()
+  {
+    return call Counter.get();
+  }
+
+  async command uint32_t Alarm.getAlarm()
+  {
+    atomic return alarm;
+  }
+
+  async command bool Alarm.isRunning()
+  {
+      return call ATimerLow.isInterruptOn() || call ATimerHigh.isInterruptOn();
+  }
+
+  async command void Alarm.stop()
+  {
+    atomic
+    {
+      call ATimerLow.off();
+      call ATimerLow.disableInterrupt();
+      call ATimerHigh.off();
+      call ATimerHigh.disableInterrupt();
+    }
+  }
+
+  async command void Alarm.start( uint32_t dt ) 
+  {
+    call Alarm.startAt( call Alarm.getNow(), dt);
+  }
+
+  async command void Alarm.startAt( uint32_t t0, uint32_t dt )
+  {
+    atomic
+    {
+      uint32_t now, elapsed, expires;
+
+      now = call Alarm.getNow();
+      elapsed = now - t0;
+        
+      if (elapsed >= dt)
+      {
+        expires = 0;
+      }
+      else
+      {
+        expires = dt - elapsed - 1;
+      }
+      
+      alarm = expires;
+
+      call Alarm.stop();
+      
+      if (expires <= 0xFFFF)
+      {
+        call ATimerLow.set((uint16_t)expires);
+        call ATimerLow.clearInterrupt();
+        call ATimerLow.enableInterrupt();
+        call ATimerLow.on();
+      }
+      else
+      {
+        uint16_t high_bits;
+
+        high_bits = expires >> 16;
+        call ATimerHigh.set(high_bits-1);
+        call ATimerHigh.clearInterrupt();
+        call ATimerHigh.enableInterrupt();
+        call ATimerHigh.on();
+        call ATimerLow.set(0xFFFF);
+        call ATimerLow.on();
+      }
+    }
+  }
+
+  async event void ATimerLow.fired()
+  {
+    call Alarm.stop();
+    signal Alarm.fired();
+  }
+  
+  async event void ATimerHigh.fired()
+  {
+    atomic
+    {
+      uint16_t remaining;
+      
+      call Alarm.stop();
+      
+      // All the high bits should have been cleared so only the
+      // low should remain.
+      remaining = (uint16_t)(alarm & 0xFFFF);
+      if (remaining != 0)
+      {
+        call ATimerLow.set(remaining);
+        call ATimerLow.clearInterrupt();
+        call ATimerLow.enableInterrupt();
+        call ATimerLow.on();
+      }
+      else
+      {
+        signal Alarm.fired();
+      }
+    }
+  }
+  async event void Counter.overflow() {}
+}
diff --git a/tos/chips/m16c62p/timer/M16c62pCounter16C.nc b/tos/chips/m16c62p/timer/M16c62pCounter16C.nc
new file mode 100755 (executable)
index 0000000..9c97329
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Build a TEP102 16bits Counter from an M16c/62p hardware timer.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic module M16c62pCounter16C(typedef precision_tag)
+{
+  provides interface Counter<precision_tag, uint16_t> as Counter;
+  uses interface HplM16c62pTimer as Timer;
+}
+implementation
+{
+  async command uint16_t Counter.get()
+  {
+    // The timer counts down so the time needs to be inverted.
+    return (0xFFFF) - call Timer.get();
+  }
+
+  async command bool Counter.isOverflowPending()
+  {
+    return call Timer.testInterrupt();
+  }
+
+  async command void Counter.clearOverflow()
+  {
+    call Timer.clearInterrupt();
+  }
+
+  async event void Timer.fired()
+  {
+    signal Counter.overflow();
+  }
+}
+
diff --git a/tos/chips/m16c62p/timer/M16c62pCounter32C.nc b/tos/chips/m16c62p/timer/M16c62pCounter32C.nc
new file mode 100755 (executable)
index 0000000..fb5c3b8
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Build a TEP102 32 bit Counter from two M16c/62p hardware timers.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic module M16c62pCounter32C(typedef precision_tag)
+{
+  provides interface Counter<precision_tag, uint32_t> as Counter;
+  uses interface HplM16c62pTimer as TimerLow;
+  uses interface HplM16c62pTimer as TimerHigh;
+}
+implementation
+{
+  async command uint32_t Counter.get()
+  {
+    uint32_t time = 0;
+    atomic
+    {
+      time = (((uint32_t)call TimerHigh.get()) << 16) + call TimerLow.get();
+    }
+    // The timers count down so the time needs to be inverted.
+    return (0xFFFFFFFF) - time;
+  }
+
+  async command bool Counter.isOverflowPending()
+  {
+    return call TimerHigh.testInterrupt();
+  }
+
+  async command void Counter.clearOverflow()
+  {
+    call TimerHigh.clearInterrupt();
+  }
+
+  async event void TimerHigh.fired()
+  {
+    signal Counter.overflow();
+  }
+
+  async event void TimerLow.fired() {}
+}
+
diff --git a/tos/chips/m16c62p/timer/M16c62pTimer.h b/tos/chips/m16c62p/timer/M16c62pTimer.h
new file mode 100755 (executable)
index 0000000..9f6786b
--- /dev/null
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+ /**
+  * This file contains structures and defines used together with timer
+  * interfaces and control.
+  * 
+  * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+  */
+
+#ifndef __M16C62PTIMER_H__
+#define __M16C62PTIMER_H__
+/*
+ * Precations when using Timer A1 and Timer A2.
+ * Read hardware manual page 139.
+ *
+ * Precations when using Timer B2.
+ * Read hardware manual page 156.
+ */
+
+enum
+{
+  TMR_TIMER_MODE,
+  TMR_COUNTER_MODE,
+  TMR_ONE_SHOT_MODE
+};
+
+
+/* Timer mode */
+typedef struct
+{
+  uint8_t output_pulse:1; // TAiMR: MR0 . TAiOUT pin is a pulse output pin if bit is set. No effect on TimerB.
+  uint8_t gate_func:2;    // TAiMR: MR1, MR2 [ NO_GATE | TAiIN_LOW | TAiIN_HIGH ] . No effect on TimerB.
+  uint8_t count_src:2;    // T*iMR: TCK0, TCK1 [ F1_2 | F8 | F32 | FC32 ]
+} st_timer;
+
+// "gate_func"
+enum
+{
+  M16C_TMR_TMR_GF_NO_GATE    = 0x0,
+  M16C_TMR_TMR_GF_TAiIN_LOW  = 0x2,
+  M16C_TMR_TMR_GF_TAiIN_HIGH = 0x3
+};
+
+
+/* TimerA Counter mode */
+typedef struct
+{
+  uint8_t two_phase_pulse_mode:1;   // Use two phase mode, only available for timers A2, A3 and A4, will be ignored else.
+  // Flags active in two-phase mode
+  uint8_t two_phase_processing:1;   // TAiMR: TCK1 [ NORMAL | MULTIPLY_BY_4 ] Only active for Timer A3.
+
+  // Flags active when not using two-phase mode.
+  uint8_t output_pulse:1;           // TAIMR: MR0 . TAiOUT is N-channel open drain output when bit is set.
+  uint8_t count_rising_edge:1;      // TAiMR: MR1 . Active when event_trigger = TAiIN
+  uint8_t up_down_switch:1;         // TAiMR: MR2 [ UDF | TAiOUT ]
+  uint8_t up_count:1;               // UDF: TAiUD . Active when up_down_switch = UDF
+  uint8_t event_source:2;           // ONSF/TRGS: TAiTG [ TAiIN | TB2 | TA_PREV | TA_NEXT ]
+
+  // Flags active in both modes
+  uint8_t operation_type:1;         // TAiMR: TCK0 [ RELOAD | FREE_RUN ]
+} sta_counter;
+
+// "operation_type"
+enum
+{
+  M16C_TMR_CTR_OT_RELOAD   = 0x0,
+  M16C_TMR_CTR_OT_FREE_RUN = 0x1
+};
+
+// "up_down_switch"
+enum
+{
+  M16C_TMR_CTR_UDS_UDF    = 0x0,
+  M16C_TMR_CTR_UDS_TAiOUT = 0x1
+};
+
+// "two_phase_processing"
+enum
+{
+  M16C_TMR_CTR_TPP_NORMAL        = 0x0,
+  M16C_TMR_CTR_TPP_MULTIPLY_BY_4 = 0x1
+};
+
+
+/* TimerA one shot mode. */
+typedef struct
+{
+  uint8_t output_pulse:1;           // TAiMR: MR0 . TAiOUT pin is a pulse output pin if bit is set.
+  uint8_t ext_trigger_rising_edge:1;// TAiMR: MR1 . Trigger on rising edge of input signal to TAiIN if bit is set. Active when TAiTG = 00b.
+  uint8_t trigger:1;                // TAiMR: MR2 [ TAiOS | TAiTG ]
+  uint8_t count_src:2;              // TAiMR: TCK0, TCK1 [ F1_2 | F8 | F32 | FC32 ]
+  uint8_t TAiTG_trigger_source:2;   // ONSF/TRGS: TAiTG [ TAiIN | TB2 | TA_PREV | TA_NEXT ]. Active if trigger = TAiTG
+} sta_one_shot;
+
+// "trigger"
+enum
+{
+  M16C_TMRA_OS_T_TAiOS = 0x00,
+  M16C_TMRA_OS_T_TAiTG = 0x01
+};
+
+
+
+/* TimerB Counter mode. */
+typedef struct
+{
+  uint8_t count_polarity:2;   // TBiMR: MR0, MR1 [ EXT_FALLING_EDGE | EXT_RISING_EDGE | EXT_BOTH ] . Effective if event_source = TBiIN.
+  uint8_t event_source:1;     // TBiMR: TCK1 [ TBiIN | TBj ] . j = i-1, except j = 2 if i = 0 and j = 5 if i = 3.
+} stb_counter;
+
+// "counter_polarity"
+enum
+{
+  M16C_TMRB_CTR_CP_EXT_FALLING_EDGE = 0x0,
+  M16C_TMRB_CTR_CP_EXT_RISING_EDGE  = 0x1,
+  M16C_TMRB_CTR_CP_EXT_BOTH         = 0x2,
+};
+
+// "event_source"
+enum
+{
+  M16C_TMRB_CTR_ES_TBiIN = 0x0,
+  M16C_TMRB_CTR_ES_TBj   = 0x1
+};
+
+
+/* Common settings */
+
+// TimerA One Shot "TAiTG_trigger_source" , TimerA Counter "event_source"
+enum
+{
+  M16C_TMRA_TES_TAiIN   = 0x0,
+  M16C_TMRA_TES_TB2     = 0x1,
+  M16C_TMRA_TES_TA_PREV = 0x2,
+  M16C_TMRA_TES_TA_NEXT = 0x3
+};
+
+// TimerA/B, TimerA One Shot : "count_src"
+enum 
+{
+  M16C_TMR_CS_F1_2 = 0x0,
+  M16C_TMR_CS_F8   = 0x1,
+  M16C_TMR_CS_F32  = 0x2,
+  M16C_TMR_CS_FC32 = 0x3
+};
+
+#endif  // __M16C62PTMR_H__
diff --git a/tos/chips/m16c62p/timer/M16c62pTimerAInitC.nc b/tos/chips/m16c62p/timer/M16c62pTimerAInitC.nc
new file mode 100755 (executable)
index 0000000..9b0743b
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Initialize an M16c/62p TimerA to a particular mode. Expected to be
+ * used at boot time.
+ * @param mode The desired mode of the timer.
+ * @param count_src Count source if applicable.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#include "M16c62pTimer.h"
+
+generic module M16c62pTimerAInitC(uint8_t mode,
+                                  uint8_t count_src,
+                                  uint16_t reload,
+                                  bool enable_interrupt,
+                                  bool start,
+                                  bool allow_stop_mode)
+{
+  provides interface Init @atleastonce();
+  uses interface HplM16c62pTimerACtrl as TimerCtrl;
+  uses interface HplM16c62pTimer as Timer;
+}
+implementation
+{
+  command error_t Init.init()
+  {
+    st_timer timer = {0};
+    sta_counter counter = {0};
+    sta_one_shot one_shot = {0};
+
+    atomic
+    {
+      call Timer.allowStopMode(allow_stop_mode);
+      if (mode == TMR_TIMER_MODE)
+      {
+        timer.gate_func = M16C_TMR_TMR_GF_NO_GATE;
+        timer.count_src = count_src;
+
+        call TimerCtrl.setTimerMode(timer);
+        call Timer.set(reload);
+      }
+      else if (mode == TMR_COUNTER_MODE)
+      {
+        // 'tmp' only used for avoiding "large integer
+        // implicitly truncated to unsigned type" warning 
+        counter.event_source = count_src;
+
+        call TimerCtrl.setCounterMode(counter);
+        call Timer.set(reload);
+      }
+      else if (mode == TMR_ONE_SHOT_MODE)
+      {
+        one_shot.trigger = M16C_TMRA_OS_T_TAiOS;
+        one_shot.count_src = count_src;
+        call TimerCtrl.setOneShotMode(one_shot);
+      }
+      if (enable_interrupt)
+      {
+        call Timer.enableInterrupt();
+      }
+      if (start)
+      {
+        call Timer.on();
+      }
+
+    }
+    return SUCCESS;
+  }
+
+  async event void Timer.fired() {}
+}
diff --git a/tos/chips/m16c62p/timer/M16c62pTimerBInitC.nc b/tos/chips/m16c62p/timer/M16c62pTimerBInitC.nc
new file mode 100755 (executable)
index 0000000..ccd606b
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Initialize an M16c/62p TimerB to a particular mode. Expected to be
+ * used at boot time.
+ * @param mode The desired mode of the timer.
+ * @param count_src Count source if applicable.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+generic module M16c62pTimerBInitC(uint8_t mode,
+                                  uint8_t count_src,
+                                  uint16_t reload,
+                                  bool enable_interrupt,
+                                  bool start,
+                                  bool allow_stop_mode)
+{
+  provides interface Init @atleastonce();
+  uses interface HplM16c62pTimerBCtrl as TimerCtrl;
+  uses interface HplM16c62pTimer as Timer;
+}
+implementation
+{
+  command error_t Init.init()
+  {
+    uint8_t tmp;
+    error_t ret = SUCCESS;
+    st_timer timer = {0};
+    stb_counter counter = {0};
+
+    atomic
+    {
+      call Timer.allowStopMode(allow_stop_mode);
+      if (mode == TMR_TIMER_MODE)
+      {
+        timer.gate_func = M16C_TMR_TMR_GF_NO_GATE;
+        timer.count_src = count_src;
+
+        call TimerCtrl.setTimerMode(timer);
+        call Timer.set(reload);
+      }
+      else if (mode == TMR_COUNTER_MODE)
+      {
+        // 'tmp' only used for avoiding "large integer
+        // implicitly truncated to unsigned type" warning 
+        tmp =  count_src & 1; 
+        counter.event_source = tmp;
+
+        call TimerCtrl.setCounterMode(counter);
+        call Timer.set(reload);
+      }
+      else
+      {
+        ret = FAIL;
+      }
+      if (enable_interrupt)
+      {
+        call Timer.enableInterrupt();
+      }
+      if (start)
+      {
+        call Timer.on();
+      }
+    }
+    return ret;
+  }
+
+  async event void Timer.fired() {}
+}
diff --git a/tos/chips/m16c62p/uart/HplM16c62pUart.nc b/tos/chips/m16c62p/uart/HplM16c62pUart.nc
new file mode 100755 (executable)
index 0000000..5df085d
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * Copyright (c) 2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCH ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * HPL interface for a M16c/62p uart.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Alec Woo <awoo@archrock.com>
+ * @author Jonathan Hui <jhui@archrock.com>
+ */
+#include "M16c62pUart.h"
+interface HplM16c62pUart {
+  async command void on();
+  async command void off();
+  async command error_t setSpeed(uart_speed_t speed);
+  async command uart_speed_t getSpeed();
+  async command void setParity(uart_parity_t parity);
+  async command uart_parity_t getParity();
+  async command void setStopBits(uart_stop_bits_t stop_bits);
+  async command uart_stop_bits_t getStopBits();
+  async command error_t enableTxInterrupt();
+  async command error_t disableTxInterrupt();
+  async command error_t enableRxInterrupt();
+  async command error_t disableRxInterrupt();
+  async command bool isTxEmpty();
+  async command bool isRxEmpty();
+  async command void tx( uint8_t data );
+  async event void txDone();
+  async command uint8_t rx();
+  async event void rxDone( uint8_t data );
+
+}
diff --git a/tos/chips/m16c62p/uart/HplM16c62pUartC.nc b/tos/chips/m16c62p/uart/HplM16c62pUartC.nc
new file mode 100755 (executable)
index 0000000..c549e11
--- /dev/null
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ *
+ * @author Martin Turon <mturon@xbow.com>
+ * @author David Gay
+ */
+
+/**
+ * The M16c/62p uart ports.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration HplM16c62pUartC
+{
+  provides
+  {
+    interface AsyncStdControl as Uart0TxControl;
+    interface AsyncStdControl as Uart0RxControl;
+    interface HplM16c62pUart as HplUart0;
+    
+    interface AsyncStdControl as Uart1TxControl;
+    interface AsyncStdControl as Uart1RxControl;
+    interface HplM16c62pUart as HplUart1;
+
+    interface AsyncStdControl as Uart2TxControl;
+    interface AsyncStdControl as Uart2RxControl;
+    interface HplM16c62pUart as HplUart2;
+  }
+}
+implementation
+{
+  components
+      HplM16c62pGeneralIOC as IOs,
+      HplM16c62pUartInterruptP as Irqs,
+      new HplM16c62pUartP(0,
+                          (uint16_t)&U0TB.BYTE.U0TBL,
+                          (uint16_t)&U0RB.BYTE.U0RBL,
+                          (uint16_t)&U0BRG,
+                          (uint16_t)&U0MR.BYTE,
+                          (uint16_t)&U0C0.BYTE,
+                          (uint16_t)&U0C1.BYTE,
+                          (uint16_t)&S0TIC.BYTE,
+                          (uint16_t)&S0RIC.BYTE) as HplUart0P,
+      new HplM16c62pUartP(1,
+                          (uint16_t)&U1TB.BYTE.U1TBL,
+                          (uint16_t)&U1RB.BYTE.U1RBL,
+                          (uint16_t)&U1BRG,
+                          (uint16_t)&U1MR.BYTE,
+                          (uint16_t)&U1C0.BYTE,
+                          (uint16_t)&U1C1.BYTE,
+                          (uint16_t)&S1TIC.BYTE,
+                          (uint16_t)&S1RIC.BYTE) as HplUart1P,
+      new HplM16c62pUartP(2,
+                          (uint16_t)&U2TB.BYTE.U2TBL,
+                          (uint16_t)&U2RB.BYTE.U2RBL,
+                          (uint16_t)&U2BRG,
+                          (uint16_t)&U2MR.BYTE,
+                          (uint16_t)&U2C0.BYTE,
+                          (uint16_t)&U2C1.BYTE,
+                          (uint16_t)&S2TIC.BYTE,
+                          (uint16_t)&S2RIC.BYTE) as HplUart2P;
+
+  components new StopModeControlC() as Uart0StopModeControl,
+             new StopModeControlC() as Uart1StopModeControl,
+             new StopModeControlC() as Uart2StopModeControl;
+  
+  Uart0TxControl = HplUart0P.UartTxControl;
+  Uart0RxControl = HplUart0P.UartRxControl;
+  HplUart0 = HplUart0P.HplUart;
+  HplUart0P.TxIO -> IOs.PortP63;
+  HplUart0P.RxIO -> IOs.PortP62;
+  HplUart0P.Irq -> Irqs.Uart0;
+  HplUart0P.StopModeControl -> Uart0StopModeControl;
+
+  Uart1TxControl = HplUart1P.UartTxControl;
+  Uart1RxControl = HplUart1P.UartRxControl;
+  HplUart1 = HplUart1P.HplUart;
+  HplUart1P.TxIO -> IOs.PortP67;
+  HplUart1P.RxIO -> IOs.PortP66;
+  HplUart1P.Irq -> Irqs.Uart1;
+  HplUart1P.StopModeControl -> Uart1StopModeControl;
+  
+  Uart2TxControl = HplUart2P.UartTxControl;
+  Uart2RxControl = HplUart2P.UartRxControl;
+  HplUart2 = HplUart2P.HplUart;
+  HplUart2P.TxIO -> IOs.PortP70;
+  HplUart2P.RxIO -> IOs.PortP71;
+  HplUart2P.Irq -> Irqs.Uart2;
+  HplUart2P.StopModeControl -> Uart2StopModeControl;
+  
+}
diff --git a/tos/chips/m16c62p/uart/HplM16c62pUartInterrupt.nc b/tos/chips/m16c62p/uart/HplM16c62pUartInterrupt.nc
new file mode 100755 (executable)
index 0000000..44206f5
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface for interrupt signals from a uart.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+interface HplM16c62pUartInterrupt
+{
+  /** 
+   * Signal when an tx interrupt occurs.
+   */  
+  async event void tx();
+
+  /** 
+   * Signal when an rx interrupt occurs.
+   */  
+  async event void rx();
+}
+
diff --git a/tos/chips/m16c62p/uart/HplM16c62pUartInterruptP.nc b/tos/chips/m16c62p/uart/HplM16c62pUartInterruptP.nc
new file mode 100755 (executable)
index 0000000..64fad63
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * All uart interrupt vector handlers.
+ * These are wired in HplM16c62pUartC.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+module HplM16c62pUartInterruptP
+{
+  provides interface HplM16c62pUartInterrupt as Uart0;
+  provides interface HplM16c62pUartInterrupt as Uart1;
+  provides interface HplM16c62pUartInterrupt as Uart2;
+}
+implementation
+{
+  default async event void Uart0.tx() { } 
+  M16C_INTERRUPT_HANDLER(M16C_UART0_NACK)
+  {
+    signal Uart0.tx();
+  }
+
+  default async event void Uart0.rx() { } 
+  M16C_INTERRUPT_HANDLER(M16C_UART0_ACK)
+  {
+    signal Uart0.rx();
+  }
+
+
+  default async event void Uart1.tx() { } 
+  M16C_INTERRUPT_HANDLER(M16C_UART1_NACK)
+  {
+    signal Uart1.tx();
+  }
+
+  default async event void Uart1.rx() { } 
+  M16C_INTERRUPT_HANDLER(M16C_UART1_ACK)
+  {
+    signal Uart1.rx();
+  }
+
+
+  default async event void Uart2.tx() { } 
+  M16C_INTERRUPT_HANDLER(M16C_UART2_NACK)
+  {
+    signal Uart2.tx();
+  }
+
+  default async event void Uart2.rx() { } 
+  M16C_INTERRUPT_HANDLER(M16C_UART2_ACK)
+  {
+    signal Uart2.rx();
+  }
+}
diff --git a/tos/chips/m16c62p/uart/HplM16c62pUartP.nc b/tos/chips/m16c62p/uart/HplM16c62pUartP.nc
new file mode 100755 (executable)
index 0000000..3059a5f
--- /dev/null
@@ -0,0 +1,372 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCH ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+/**
+ * @author Alec Woo <awoo@archrock.com>
+ * @author Jonathan Hui <jhui@archrock.com>
+ */
+
+/*
+ * Copyright (c) 2004-2005 Crossbow Technology, Inc.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO 
+ * ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL 
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 
+ * DAMAGE. 
+ *
+ * CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS 
+ * ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR 
+ * MODIFICATIONS.
+ */
+/** 
+ * @author Martin Turon <mturon@xbow.com>
+ * @author David Gay
+ */
+
+
+/**
+ * Generic HPL module for a Uart port on the M16c/62p MCU.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#include "M16c62pUart.h"
+generic module HplM16c62pUartP(uint8_t uartNr,
+                               uint16_t tx_addr,
+                               uint16_t rx_addr,
+                               uint16_t brg_addr,
+                               uint16_t mode_addr,
+                               uint16_t ctrl0_addr,
+                               uint16_t ctrl1_addr,
+                               uint16_t txInterrupt_addr,
+                               uint16_t rxInterrupt_addr)
+{
+  provides interface AsyncStdControl as UartTxControl;
+  provides interface AsyncStdControl as UartRxControl;
+  provides interface HplM16c62pUart as HplUart;
+  
+  uses interface GeneralIO as TxIO;
+  uses interface GeneralIO as RxIO;
+  uses interface HplM16c62pUartInterrupt as Irq;
+  uses interface StopModeControl;
+
+}
+implementation
+{
+#define txBuf (*TCAST(volatile uint8_t* ONE, tx_addr))
+#define rxBuf (*TCAST(volatile uint8_t* ONE, rx_addr))
+#define txInterrupt (*TCAST(volatile uint8_t* ONE, txInterrupt_addr))
+#define rxInterrupt (*TCAST(volatile uint8_t* ONE, rxInterrupt_addr))
+#define brg (*TCAST(volatile uint8_t* ONE, brg_addr))
+#define mode (*TCAST(volatile uint8_t* ONE, mode_addr))
+#define ctrl0 (*TCAST(volatile uint8_t* ONE, ctrl0_addr))
+#define ctrl1 (*TCAST(volatile uint8_t* ONE, ctrl1_addr))
+
+  enum {
+    ON,
+    OFF
+  };
+
+  uint8_t state = OFF;
+  uart_speed_t current_speed = TOS_UART_57600;
+  
+  async command void HplUart.on()
+  {
+    // Set 8 bit transfer
+    SET_BIT(mode, 0);
+    SET_BIT(mode, 2);
+    
+    //no cts/rts.
+    SET_BIT(ctrl0, 4);
+    atomic switch (current_speed)
+    {
+      case TOS_UART_1200:
+        SET_BIT(ctrl0, 0);
+        CLR_BIT(ctrl0, 1);
+        break;
+      case TOS_UART_9600:
+      case TOS_UART_57600:
+        CLR_BIT(ctrl0, 0);
+        CLR_BIT(ctrl0, 1);
+        break;
+      default:
+        break;
+    }
+    call StopModeControl.allowStopMode(false);
+    atomic state = ON;
+  }
+  
+  async command void HplUart.off()
+  {
+    CLR_BIT(mode, 0);
+    CLR_BIT(mode, 2);
+    call StopModeControl.allowStopMode(true);
+    atomic state = OFF;
+  }
+
+
+  async command error_t HplUart.setSpeed(uart_speed_t speed)
+  {
+    atomic if (state != OFF)
+    {
+      return FAIL;
+    }
+    
+    switch (speed)
+    {
+      // TODO(henrik) These values are based on a mcu that runs on MAIN_CRYSTAL_SPEED and doesn't
+      //              consider if the PLL is on which they should.
+      case TOS_UART_1200:
+        brg = (uint8_t)(((MAIN_CRYSTAL_SPEED * 1000000.0 / (128.0 * 1200.0))+ 0.5) - 1.0);
+        break;
+      case TOS_UART_9600:
+       brg = (uint8_t)(((MAIN_CRYSTAL_SPEED * 1000000.0 / (16.0 * 9600.0))+ 0.5) - 1.0);
+       break;
+      case TOS_UART_57600:
+        brg = (uint8_t)(((MAIN_CRYSTAL_SPEED * 1000000.0 / (16.0 * 57600.0))+ 0.5) - 1.0);
+        break;
+      default:
+        break;
+    }
+    atomic current_speed = speed;
+    return SUCCESS;
+  }
+  
+  async command uart_speed_t HplUart.getSpeed()
+  {
+    atomic return current_speed;
+  }
+  
+  async command void HplUart.setParity(uart_parity_t parity)
+  {
+    switch (parity)
+    {
+      case TOS_UART_PARITY_NONE:
+        CLR_BIT(mode, 6);
+        break;
+      case TOS_UART_PARITY_EVEN:
+        SET_BIT(mode, 6);
+        SET_BIT(mode, 5);
+        break;
+      case TOS_UART_PARITY_ODD:
+        SET_BIT(mode, 6);
+        CLR_BIT(mode, 5);
+        break;
+      default:
+        break;
+    }
+  }
+  
+  async command uart_parity_t HplUart.getParity()
+  {
+    if (READ_BIT(mode, 6) && READ_BIT(mode, 5))
+    {
+      return TOS_UART_PARITY_EVEN;
+    }
+    else if (READ_BIT(mode, 6))
+    {
+      return TOS_UART_PARITY_ODD;
+    }
+    else
+    {
+      return TOS_UART_PARITY_NONE;
+    }
+  }
+  
+  async command void HplUart.setStopBits(uart_stop_bits_t stop_bits)
+  {
+    switch (stop_bits)
+    {
+      case TOS_UART_STOP_BITS_1:
+        CLR_BIT(mode, 4);
+        break;
+      case TOS_UART_STOP_BITS_2:
+        SET_BIT(mode, 4);
+        break;
+      default:
+        break;
+    }
+  }
+  
+  async command uart_stop_bits_t HplUart.getStopBits()
+  {
+    if (READ_BIT(mode, 4))
+    {
+      return TOS_UART_STOP_BITS_2;
+    }
+    else
+    {
+      return TOS_UART_STOP_BITS_1;
+    }
+  }
+    
+
+  async command error_t UartTxControl.start()
+  {
+    call TxIO.makeOutput();
+    SET_BIT(ctrl1, 0);
+    return SUCCESS;
+  }
+
+  async command error_t UartTxControl.stop()
+  {
+    call TxIO.makeInput();
+    CLR_BIT(ctrl1, 0);
+    return SUCCESS;
+  }
+
+  async command error_t UartRxControl.start()
+  {
+    call RxIO.makeInput();
+    SET_BIT(ctrl1, 2);
+    return SUCCESS;
+  }
+
+  async command error_t UartRxControl.stop()
+  {
+    CLR_BIT(ctrl1, 2);
+    return SUCCESS;
+  }
+  
+  async command error_t HplUart.enableTxInterrupt()
+  {
+    atomic
+    {
+      clear_interrupt(txInterrupt_addr);
+      SET_BIT(ctrl1, 1);
+      CLR_BIT(UCON.BYTE, uartNr);
+      SET_BIT(txInterrupt, 0);
+    }
+    return SUCCESS;
+  }
+  
+  async command error_t HplUart.disableTxInterrupt()
+  {
+    CLR_BIT(txInterrupt, 0);
+    return SUCCESS;
+  }
+  
+  async command error_t HplUart.enableRxInterrupt()
+  { 
+    atomic
+    {
+      clear_interrupt(rxInterrupt_addr);
+      SET_BIT(rxInterrupt, 0);
+    }
+    return SUCCESS;
+  }
+
+  async command error_t HplUart.disableRxInterrupt()
+  {
+    CLR_BIT(rxInterrupt, 0);
+    return SUCCESS;
+  }
+  
+  async command bool HplUart.isTxEmpty()
+  {
+    return READ_BIT(ctrl1, 1);
+  }
+
+  async command bool HplUart.isRxEmpty()
+  {
+    return !READ_BIT(ctrl1, 3);
+  }
+  
+  async command uint8_t HplUart.rx()
+  {
+    return rxBuf;
+  }
+
+  async command void HplUart.tx(uint8_t data)
+  {
+      txBuf = data;
+  }
+  
+  async event void Irq.rx() 
+  {
+    if (!call HplUart.isRxEmpty()) {
+      signal HplUart.rxDone(call HplUart.rx());
+    }
+  }
+  
+  async event void Irq.tx()
+  {
+    signal HplUart.txDone();
+  }
+  
+  default async event void HplUart.txDone() {} 
+  default async event void HplUart.rxDone(uint8_t data) {}
+}
diff --git a/tos/chips/m16c62p/uart/M16c62pUart.h b/tos/chips/m16c62p/uart/M16c62pUart.h
new file mode 100644 (file)
index 0000000..23fa284
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * M16c62p UART typedefs.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#ifndef __M16C62P_UART_H__
+#define __M16C62P_UART_H__
+
+
+typedef enum {
+  TOS_UART_1200,
+  TOS_UART_9600,
+  TOS_UART_57600,
+} uart_speed_t;
+
+typedef enum {
+  TOS_UART_OFF,
+  TOS_UART_RONLY,
+  TOS_UART_TONLY,
+  TOS_UART_DUPLEX
+} uart_duplex_t;
+
+typedef enum {
+  TOS_UART_PARITY_NONE,
+  TOS_UART_PARITY_EVEN,
+  TOS_UART_PARITY_ODD
+}uart_parity_t;
+
+typedef enum {
+  TOS_UART_STOP_BITS_1,
+  TOS_UART_STOP_BITS_2
+} uart_stop_bits_t;
+
+
+#endif  // __M16C62P_UART_H__
\ No newline at end of file
diff --git a/tos/chips/m16c62p/uart/M16c62pUartC.nc b/tos/chips/m16c62p/uart/M16c62pUartC.nc
new file mode 100755 (executable)
index 0000000..6c2fb1c
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCH ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+/**
+ * @author Alec Woo <awoo@archrock.com>
+ * @author Jonathan Hui <jhui@archrock.com>
+ */
+
+/**
+ * HAL of the M16c/62p uarts.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration M16c62pUartC
+{
+  provides interface UartByte as Uart0Byte;
+  provides interface UartStream as Uart0Stream;
+  provides interface UartControl as Uart0Control;
+  
+  provides interface UartByte as Uart1Byte;
+  provides interface UartStream as Uart1Stream;
+  provides interface UartControl as Uart1Control;
+  
+  provides interface UartByte as Uart2Byte;
+  provides interface UartStream as Uart2Stream;
+  provides interface UartControl as Uart2Control;
+  
+  uses interface Counter<TMicro, uint16_t>;
+}
+
+implementation
+{
+  components HplM16c62pUartC as HplUartC;
+  
+  components new M16c62pUartP() as Uart0P;
+  Uart0Byte = Uart0P;
+  Uart0Stream = Uart0P;
+  Uart0Control = Uart0P;
+  Uart0P.Counter = Counter;
+  
+  Uart0P.HplUartTxControl -> HplUartC.Uart0TxControl;
+  Uart0P.HplUartRxControl -> HplUartC.Uart0RxControl;
+  Uart0P.HplUart -> HplUartC.HplUart0;
+  
+  components new M16c62pUartP() as Uart1P;
+  Uart1Byte = Uart1P;
+  Uart1Stream = Uart1P;
+  Uart1Control = Uart1P;
+  Uart1P.Counter = Counter;
+  
+  Uart1P.HplUartTxControl -> HplUartC.Uart1TxControl;
+  Uart1P.HplUartRxControl -> HplUartC.Uart1RxControl;
+  Uart1P.HplUart -> HplUartC.HplUart1;
+
+  components new M16c62pUartP() as Uart2P;
+  Uart2Byte = Uart2P;
+  Uart2Stream = Uart2P;
+  Uart2Control = Uart2P;
+  Uart2P.Counter = Counter;
+  
+  Uart2P.HplUartTxControl -> HplUartC.Uart2TxControl;
+  Uart2P.HplUartRxControl -> HplUartC.Uart2RxControl;
+  Uart2P.HplUart -> HplUartC.HplUart2;
+  
+}
diff --git a/tos/chips/m16c62p/uart/M16c62pUartP.nc b/tos/chips/m16c62p/uart/M16c62pUartP.nc
new file mode 100755 (executable)
index 0000000..9a63033
--- /dev/null
@@ -0,0 +1,377 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCH ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ *
+ */
+
+/**
+ * Generic HAL uart for M16c/62p.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Alec Woo <awoo@archrock.com>
+ * @author Jonathan Hui <jhui@archrock.com>
+ * @author Philip Levis <pal@cs.stanford.edu>
+ */
+
+#include <Timer.h>
+#include "M16c62pUart.h"
+
+generic module M16c62pUartP()
+{  
+  provides interface UartByte;
+  provides interface UartStream;
+  provides interface UartControl;
+  
+  uses interface AsyncStdControl as HplUartTxControl;
+  uses interface AsyncStdControl as HplUartRxControl;
+  uses interface HplM16c62pUart as HplUart;
+  uses interface Counter<TMicro, uint16_t>;
+  
+}
+implementation
+{ 
+  norace uint16_t m_tx_len, m_rx_len;
+  norace uint8_t *m_tx_buf, *m_rx_buf;
+  norace uint16_t m_tx_pos, m_rx_pos;
+  norace uint16_t m_byte_time = 68;
+  norace uint8_t m_rx_intr;
+  norace uint8_t m_tx_intr;
+  uart_duplex_t mode = TOS_UART_OFF;
+
+  async command error_t UartStream.enableReceiveInterrupt()
+  {
+    if (mode == TOS_UART_TONLY)
+    {
+      return FAIL;
+    }
+    
+    atomic
+    {
+      m_rx_intr = 3;
+      call HplUart.enableRxInterrupt();
+    }
+    return SUCCESS;
+  }
+
+  async command error_t UartStream.disableReceiveInterrupt()
+  {
+    if (mode == TOS_UART_TONLY)
+    {
+      return FAIL;
+    }
+    atomic
+    {
+      call HplUart.disableRxInterrupt();
+      m_rx_intr = 0;
+    }
+    return SUCCESS;
+  }
+
+  async command error_t UartStream.receive( uint8_t* buf, uint16_t len )
+  {
+    if (mode == TOS_UART_TONLY)
+    {
+      return FAIL;
+    }
+    
+    if ( len == 0 )
+      return FAIL;
+    atomic
+    {
+      if ( m_rx_buf )
+       return EBUSY;
+      m_rx_buf = buf;
+      m_rx_len = len;
+      m_rx_pos = 0;
+      m_rx_intr |= 1;
+      call HplUart.enableRxInterrupt();
+    }
+    
+    return SUCCESS;
+    
+  }
+
+  async event void HplUart.rxDone( uint8_t data ) 
+  {
+
+    if ( m_rx_buf ) 
+    {
+      m_rx_buf[ m_rx_pos++ ] = data;
+      if ( m_rx_pos >= m_rx_len ) 
+      {
+           uint8_t* buf = m_rx_buf;
+           atomic
+        {
+             m_rx_buf = NULL;
+             if(m_rx_intr != 3)
+          {
+               call HplUart.disableRxInterrupt();
+               m_rx_intr = 0;
+             }
+           }  
+           signal UartStream.receiveDone( buf, m_rx_len, SUCCESS );
+      }
+    }
+    else 
+    {
+      signal UartStream.receivedByte( data );
+    }    
+  }
+
+  async command error_t UartStream.send( uint8_t *buf, uint16_t len)
+  {
+    if (mode == TOS_UART_RONLY)
+    {
+      return FAIL;
+    }
+    if ( len == 0 )
+      return FAIL;
+    else if ( m_tx_buf )
+      return EBUSY;
+    
+    m_tx_len = len;
+    m_tx_buf = buf;
+    m_tx_pos = 0;
+    m_tx_intr = 1;
+    call HplUart.enableTxInterrupt();
+    call HplUart.tx( buf[ m_tx_pos++ ] );
+    
+    return SUCCESS;
+    
+  }
+
+  async event void HplUart.txDone() 
+  {
+    
+    if ( m_tx_pos < m_tx_len ) 
+    {
+      call HplUart.tx( m_tx_buf[ m_tx_pos++ ] );
+    }
+    else 
+    {
+      uint8_t* buf = m_tx_buf;
+      m_tx_buf = NULL;
+      m_tx_intr = 0;
+      call HplUart.disableTxInterrupt();
+      signal UartStream.sendDone( buf, m_tx_len, SUCCESS );
+    }
+    
+  }
+
+  async command error_t UartByte.send( uint8_t byte )
+  {
+    if (mode == TOS_UART_RONLY)
+    {
+      return FAIL;
+    }
+    if(m_tx_intr)
+      return FAIL;
+
+    call HplUart.tx( byte );
+    while ( !call HplUart.isTxEmpty() );
+    return SUCCESS;
+  }
+  
+  async command error_t UartByte.receive( uint8_t * byte, uint8_t timeout)
+  {
+    uint16_t timeout_micro = m_byte_time * timeout + 1;
+    uint16_t start;
+    
+    if (mode == TOS_UART_TONLY)
+    {
+      return FAIL;
+    }
+    
+    if(m_rx_intr)
+      return FAIL;
+
+    start = call Counter.get();
+    while ( call HplUart.isRxEmpty() ) 
+    {
+      if ( ( (uint16_t)call Counter.get() - start ) >= timeout_micro )
+           return FAIL;
+    }
+    *byte = call HplUart.rx();
+    
+    return SUCCESS;
+    
+  }
+  
+  async command error_t UartControl.setSpeed(uart_speed_t speed)
+  {
+    return call HplUart.setSpeed(speed);
+  }
+
+  async command uart_speed_t UartControl.speed()
+  {
+    return call HplUart.getSpeed();
+  }
+  
+  async command error_t UartControl.setDuplexMode(uart_duplex_t duplex)
+  {
+    if (mode == TOS_UART_OFF)
+    {
+      call HplUart.disableTxInterrupt();
+      call HplUart.disableRxInterrupt();
+      m_rx_intr = 0;
+      m_tx_intr = 0;
+    }
+    switch (duplex)
+    {
+      case TOS_UART_OFF:
+        call HplUart.disableTxInterrupt();
+        call HplUart.disableRxInterrupt();
+        call HplUartTxControl.stop();
+        call HplUartRxControl.stop();
+        call HplUart.off();
+        return SUCCESS;
+        break;
+      case TOS_UART_RONLY:
+        call HplUart.disableTxInterrupt();
+        call HplUartTxControl.stop();
+        call HplUart.on();
+        call HplUartRxControl.start();
+        call HplUart.enableRxInterrupt();
+        break;
+      case TOS_UART_TONLY:
+        call HplUart.disableRxInterrupt();
+        call HplUartRxControl.stop();
+        call HplUart.on();
+        call HplUartTxControl.start();
+        break;
+      case TOS_UART_DUPLEX:
+        call HplUart.on();
+        call HplUartTxControl.start();
+        call HplUartRxControl.start();
+        call HplUart.enableRxInterrupt();
+        break;
+      default:
+        break;
+    }
+    
+    return SUCCESS;
+  }
+
+  async command uart_duplex_t UartControl.duplexMode()
+  {
+    atomic return mode;
+  }
+  
+  async command error_t UartControl.setParity(uart_parity_t parity)
+  {
+    if (mode != TOS_UART_OFF)
+    {
+      return FAIL;
+    }
+    call HplUart.setParity(parity);
+    return SUCCESS;
+  }
+
+  async command uart_parity_t UartControl.parity()
+  {
+    return call HplUart.getParity();
+  }
+  
+  async command error_t UartControl.setStop()
+  {
+    if (mode != TOS_UART_OFF)
+    {
+      return FAIL;
+    }
+    call HplUart.setStopBits(TOS_UART_STOP_BITS_2);
+    return SUCCESS;
+  }
+
+  async command error_t UartControl.setNoStop()
+  {
+    if (mode != TOS_UART_OFF)
+    {
+      return FAIL;
+    }
+    call HplUart.setStopBits(TOS_UART_STOP_BITS_1);
+    return SUCCESS;
+  }
+
+  async command bool UartControl.stopBits()
+  {
+    if (call HplUart.getStopBits() == TOS_UART_STOP_BITS_2)
+    {
+      return true;
+    }
+    else
+    {
+      return false;
+    }
+  }
+  
+  
+  
+  async event void Counter.overflow() {}
+
+  default async event void UartStream.sendDone( uint8_t* buf, uint16_t len, error_t error ){}
+  default async event void UartStream.receivedByte( uint8_t byte ){}
+  default  async event void UartStream.receiveDone( uint8_t* buf, uint16_t len, error_t error ){}
+
+}
diff --git a/tos/chips/mma7261qt/HplMMA7261QT.h b/tos/chips/mma7261qt/HplMMA7261QT.h
new file mode 100644 (file)
index 0000000..06f8e0d
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * MMA7261QT gSelect defines.
+ *
+ * @author Henrik Makitaavola
+ */
+
+#ifndef __HPLMMA7261QT_H__
+#define  __HPLMMA7261QT_H__
+
+typedef enum mm7261qt_gselect {
+  MMA7261QT_GSELECT_2_5G=0, //most sensitive
+  MMA7261QT_GSELECT_3_3G=1,
+  MMA7261QT_GSELECT_6_7G=2,
+  MMA7261QT_GSELECT_10_0G=3, //least sensitive
+} mm7261qt_gselect_t;
+
+#endif
+
diff --git a/tos/chips/mma7261qt/HplMMA7261QTControl.nc b/tos/chips/mma7261qt/HplMMA7261QTControl.nc
new file mode 100644 (file)
index 0000000..7f3e149
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * MMA7261QT control interface.
+ *
+ * @author Henrik Makitaavola
+ */
+#include "HplMMA7261QT.h"
+
+interface HplMMA7261QTControl
+{
+  async command void on();
+  async command void off();
+  async command void gSelect( mm7261qt_gselect_t val);
+}
diff --git a/tos/chips/mma7261qt/HplMMA7261QTControlC.nc b/tos/chips/mma7261qt/HplMMA7261QTControlC.nc
new file mode 100644 (file)
index 0000000..aee31a0
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * MMA7261QT control component.
+ *
+ * @author Henrik Makitaavola
+ */
+
+configuration HplMMA7261QTControlC
+{
+  provides interface HplMMA7261QTControl;
+}
+implementation
+{
+  components HplMMA7261QTControlP, HplMMA7261QTC;
+  
+  HplMMA7261QTControlP.Sleep -> HplMMA7261QTC.Sleep;
+  HplMMA7261QTControlP.GSelect1 -> HplMMA7261QTC.GSelect1;
+  HplMMA7261QTControlP.GSelect2 -> HplMMA7261QTC.GSelect2;
+  
+  HplMMA7261QTControl = HplMMA7261QTControlP;
+}
diff --git a/tos/chips/mma7261qt/HplMMA7261QTControlP.nc b/tos/chips/mma7261qt/HplMMA7261QTControlP.nc
new file mode 100644 (file)
index 0000000..79b4d41
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * MMA7261QT control.
+ *
+ * @author Henrik Makitaavola
+ */
+#include "HplMMA7261QT.h"
+
+module HplMMA7261QTControlP
+{
+  provides interface HplMMA7261QTControl;
+  
+  uses interface GeneralIO as Sleep;
+  uses interface GeneralIO as GSelect1;
+  uses interface GeneralIO as GSelect2;
+}
+implementation
+{
+  async command void HplMMA7261QTControl.on()
+  {
+    call Sleep.set();
+    call GSelect1.clr();
+    call GSelect2.clr();
+
+  }
+  
+  async command void HplMMA7261QTControl.off()
+  {
+    call GSelect1.clr();
+    call GSelect2.clr();
+    call Sleep.clr();
+  }
+  
+  async command void HplMMA7261QTControl.gSelect( mm7261qt_gselect_t val)
+  {
+    if(val & 1)
+      call GSelect1.set();
+    else 
+      call GSelect1.clr();
+
+    if(val & 2)
+      call GSelect2.set();
+    else
+      call GSelect2.clr();
+  }
+}
diff --git a/tos/chips/mma7261qt/HplMMA7261QTReaderC.nc b/tos/chips/mma7261qt/HplMMA7261QTReaderC.nc
new file mode 100644 (file)
index 0000000..a9bdb26
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * MMA7261QT reader.
+ *
+ * @author Henrik Makitaavola
+ */
+
+configuration HplMMA7261QTReaderC
+{
+  provides interface Read<uint16_t> as AccelX;
+  provides interface Read<uint16_t> as AccelY;
+  provides interface Read<uint16_t> as AccelZ;
+}
+implementation
+{
+  components HplMMA7261QTC;
+  
+  AccelX = HplMMA7261QTC.AccelX;
+  AccelY = HplMMA7261QTC.AccelY;
+  AccelZ = HplMMA7261QTC.AccelZ;
+}
index dbe70912c8d3879cddceb49ee2eae600afcb85fe..57c6d393aaefcb522c22cc0738cb56df82d14e24 100644 (file)
@@ -64,7 +64,7 @@ implementation {
   };
     
   mcu_power_t getPowerState() {
-    mcu_power_t pState = MSP430_POWER_LPM3;
+    mcu_power_t pState = MSP430_POWER_LPM4;
     // TimerA, USART0, USART1 check
     if ((((TACCTL0 & CCIE) ||
          (TACCTL1 & CCIE) ||
@@ -78,7 +78,7 @@ implementation {
 #endif
 #ifdef __MSP430_HAS_I2C__
         // registers end in "nr" to prevent nesC race condition detection
-       || ((U0CTLnr & I2CEN) && (I2CTCTLnr & SSEL1) &&
+        || ((U0CTLnr & I2CEN) && (I2CTCTLnr & SSEL1) &&
             (I2CDCTLnr & I2CBUSY) && (U0CTLnr & SYNC) && (U0CTLnr & I2C))
 #endif
        )
index 7bc24f87ba6918540151e09ab2bd93b621de56f3..a7f623865782e034497c650cd07825ea98949ec8 100644 (file)
@@ -93,7 +93,8 @@ implementation {
     call SingleChannel.getData[client]();
   }
 
-  command error_t ReadStream.postBuffer[uint8_t c](uint16_t *buf, uint16_t n) {
+  error_t postBuffer(uint8_t c, uint16_t *buf, uint16_t n)
+  {
     if (n < sizeof(struct list_entry_t))
       return ESIZE;
     atomic
@@ -111,6 +112,10 @@ implementation {
     return SUCCESS;
   }
 
+  command error_t ReadStream.postBuffer[uint8_t c](uint16_t *buf, uint16_t n) {
+    return postBuffer(c, buf, n);
+  }
+
   task void readStreamDone() {
     uint8_t c = client;
     uint32_t actualPeriod = period;
@@ -204,8 +209,12 @@ implementation {
       msp430adc12_channel_config_t config = *call AdcConfigure.getConfiguration[c]();
       config.sampcon_ssel = SAMPCON_SOURCE_SMCLK; // assumption: SMCLK runs at 1 MHz
       config.sampcon_id = SAMPCON_CLOCK_DIV_1; 
-      call SingleChannel.configureMultiple[c]( &config, pos, count, period);
-      call SingleChannel.getData[c]();
+      if (call SingleChannel.configureMultiple[c]( &config, pos, count, period) == SUCCESS)
+        call SingleChannel.getData[c]();
+      else {
+        postBuffer(c, pos, count);
+        post readStreamFail();
+      }
     }
   }
 
index 54c9c3464511c7b7d7668c88bd2ed470cf08051b..b8ba9d0dd42c3e1757467f88d8e3476089e576ab 100644 (file)
@@ -54,46 +54,43 @@ implementation
   MSP430REG_NORACE(ADC12IE);
   MSP430REG_NORACE(ADC12IV);
 
-  // SFRs are accessed directly or cast to a pointer, both works fine
-  // (we don't access all SFRs directly, because that would result in
-  // much higher memory footprint)
+  DEFINE_UNION_CAST(int2adc12ctl0,adc12ctl0_t,uint16_t)
+  DEFINE_UNION_CAST(int2adc12ctl1,adc12ctl1_t,uint16_t)
+  DEFINE_UNION_CAST(adc12ctl0cast2int,uint16_t,adc12ctl0_t)
+  DEFINE_UNION_CAST(adc12ctl1cast2int,uint16_t,adc12ctl1_t)
+  DEFINE_UNION_CAST(adc12memctl2int,uint8_t,adc12memctl_t)
+  DEFINE_UNION_CAST(int2adc12memctl,adc12memctl_t,uint8_t)
   
   async command void HplAdc12.setCtl0(adc12ctl0_t control0){
-    ADC12CTL0 = *((uint16_t*) &control0); 
+    ADC12CTL0 = adc12ctl0cast2int(control0); 
   }
   
   async command void HplAdc12.setCtl1(adc12ctl1_t control1){
-    ADC12CTL1 = *((uint16_t*) &control1); 
+    ADC12CTL1 = adc12ctl1cast2int(control1); 
   }
   
   async command adc12ctl0_t HplAdc12.getCtl0(){ 
-    return *((adc12ctl0_t*) &ADC12CTL0); 
+    return int2adc12ctl0(ADC12CTL0); 
   }
   
   async command adc12ctl1_t HplAdc12.getCtl1(){
-    return *((adc12ctl1_t*) &ADC12CTL1); 
+    return int2adc12ctl1(ADC12CTL1); 
   }
   
-  async command void HplAdc12.setMCtl(uint8_t i, adc12memctl_t memControl){
-    uint8_t *memCtlPtr = (uint8_t*) ADC12MCTL;
-    memCtlPtr += i;
-    *memCtlPtr = *(uint8_t*)&memControl; 
+  async command void HplAdc12.setMCtl(uint8_t i, adc12memctl_t memCtl){
+    ADC12MCTL[i] = adc12memctl2int(memCtl);
   }
    
   async command adc12memctl_t HplAdc12.getMCtl(uint8_t i){
-    adc12memctl_t x = {inch: 0, sref: 0, eos: 0 };    
-    uint8_t *memCtlPtr = (uint8_t*) ADC12MCTL;
-    memCtlPtr += i;
-    x = *(adc12memctl_t*) memCtlPtr;
-    return x;
+    return int2adc12memctl(ADC12MCTL[i]);
   }  
   
   async command uint16_t HplAdc12.getMem(uint8_t i){
-    return *((uint16_t*) ADC12MEM + i);
+    return ADC12MEM[i];
   }
 
   async command void HplAdc12.setIEFlags(uint16_t mask){ ADC12IE = mask; } 
-  async command uint16_t HplAdc12.getIEFlags(){ return (uint16_t) ADC12IE; } 
+  async command uint16_t HplAdc12.getIEFlags(){ return ADC12IE; } 
   
   async command void HplAdc12.resetIFGs(){ 
     ADC12IV = 0; 
@@ -118,7 +115,7 @@ implementation
     ADC12CTL0 |= ENC; 
   }
     
-  async command bool HplAdc12.isBusy(){ return ADC12CTL1 & ADC12BUSY; }
+  async command bool HplAdc12.isBusy(){ return (ADC12CTL1 & ADC12BUSY); }
 
   TOSH_SIGNAL(ADC_VECTOR) {
     signal HplAdc12.conversionDone(ADC12IV);
index 0ce8a5450799aa351bee46ebf8407da3ba35afbc..e9e7f68e869dd8f07bee73dbd5bb08d86d407252 100644 (file)
@@ -63,7 +63,11 @@ module Msp430Adc12ImplP @safe()
 }
 implementation
 { 
-#warning Accessing TimerA for ADC12 
+
+#ifdef ADC12_TIMERA_ENABLED
+  #warning Accessing TimerA for ADC12 
+#endif
+
   enum {
     SINGLE_DATA = 1,
     SINGLE_DATA_REPEAT = 2,
@@ -218,6 +222,10 @@ implementation
   {
     error_t result = ERESERVE;
 #ifdef ADC12_CHECK_ARGS
+#ifndef ADC12_TIMERA_ENABLED
+    if (jiffies>0) 
+      return EINVAL;
+#endif
     if (!config || jiffies == 1 || jiffies == 2)
       return EINVAL;
 #endif
@@ -266,6 +274,10 @@ implementation
   {
     error_t result = ERESERVE;
 #ifdef ADC12_CHECK_ARGS
+#ifndef ADC12_TIMERA_ENABLED
+    if (jiffies>0) 
+      return EINVAL;
+#endif
     if (!config || !buf || !length || jiffies == 1 || jiffies == 2)
       return EINVAL;
 #endif
@@ -323,6 +335,10 @@ implementation
   {
     error_t result = ERESERVE;
 #ifdef ADC12_CHECK_ARGS
+#ifndef ADC12_TIMERA_ENABLED
+    if (jiffies>0) 
+      return EINVAL;
+#endif
     if (!config || !buf || !length || length > 16 || jiffies == 1 || jiffies == 2)
       return EINVAL;
 #endif
@@ -379,7 +395,7 @@ implementation
   {
     atomic {
       if (call ADCArbiterInfo.userId() == id){
-        if (state & MULTIPLE_DATA_REPEAT && !resultBufferStart)
+        if ((state & MULTIPLE_DATA_REPEAT) && !resultBufferStart)
           return EINVAL;
         if (state & ADC_BUSY)
           return EBUSY;
@@ -402,6 +418,10 @@ implementation
   {
     error_t result = ERESERVE;
 #ifdef ADC12_CHECK_ARGS
+#ifndef ADC12_TIMERA_ENABLED
+    if (jiffies>0) 
+      return EINVAL;
+#endif
     if (!config || !memctl || !numMemctl || numMemctl > 15 || !numSamples || 
         !buf || jiffies == 1 || jiffies == 2 || numSamples % (numMemctl+1) != 0)
       return EINVAL;
@@ -554,7 +574,7 @@ implementation
       case MULTI_CHANNEL:
         {
           uint16_t i = 0, k;
-          resultBuffer = resultBufferStart;
+          resultBuffer = resultBufferStart + resultBufferIndex;
           do {
             *resultBuffer++ = call HplAdc12.getMem(i);
           } while (++i < numChannels);
@@ -566,7 +586,7 @@ implementation
             resultBufferIndex = 0;
             signal MultiChannel.dataReady[clientID](resultBuffer, 
                 overflow ? k : resultBufferLength);
-          } else call HplAdc12.enableConversion();
+          }
         }
         break;
       case MULTIPLE_DATA:
index 38ff00c7551d7671f3d9a572fb92eef98985ebad..aff85f6f9ee0f11f42e45cc32395209b9ffb4a3a 100644 (file)
@@ -75,7 +75,9 @@ interface Msp430Adc12MultiChannel
    * numSamples = (numMemctl+1) * 2
    *
    * @param jiffies Sampling period in terms of clock ticks of "sampcon_ssel"
-   * and input divider "sampcon_id".
+   * and input divider "sampcon_id". Samples are taken equally-spaced in
+   * time iterating round-robin over the channels (different channels are  
+   * not sampled simultaneously but one after another).
    *
    * @return SUCCESS means that the ADC was configured successfully and
    * <code>getData()</code> can be called to start the conversion.
index e1df33a4311051fd523730b90e1dff25c85025ff..267e214ee72f66b1ead6b4c0d3da6f92189f62ca 100644 (file)
  * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
  * ========================================================================
  */
-#include <Timer.h>
-module Msp430RefVoltGeneratorP
-{
-  provides interface SplitControl as RefVolt_1_5V;
-  provides interface SplitControl as RefVolt_2_5V;
+
+module Msp430RefVoltGeneratorP {
+  provides {
+    interface SplitControl as RefVolt_1_5V;
+    interface SplitControl as RefVolt_2_5V;
+  }
+  
   uses {
     interface HplAdc12;
     interface Timer<TMilli> as SwitchOnTimer;
     interface Timer<TMilli> as SwitchOffTimer;
   }
-} implementation {
   
-  enum
-  {
-    GENERATOR_OFF,
-    REFERENCE_1_5V_PENDING, 
-    REFERENCE_2_5V_PENDING,
-    REFERENCE_1_5V_STABLE,
-    REFERENCE_2_5V_STABLE,
-  };
+} 
 
-  uint8_t state;
+implementation {
+  
+  typedef enum  {
+    // DO NOT CHANGE ANY OF THE CONSTANTS BELOW!
+    GENERATOR_OFF = 0,
+      
+    REFERENCE_1_5V_STABLE = 1,
+    REFERENCE_2_5V_STABLE = 2,
 
-  error_t switchOn(uint8_t level)
-  {
-    atomic {
-      if (call HplAdc12.isBusy())
-        return FAIL;
-      else {
-        adc12ctl0_t ctl0 = call HplAdc12.getCtl0();
-        ctl0.enc = 0;
-        call HplAdc12.setCtl0(ctl0);
-        ctl0.refon = 1;
-        if (level == REFERENCE_1_5V_PENDING)
-          ctl0.r2_5v = 0;
-        else
-          ctl0.r2_5v = 1;
-        call HplAdc12.setCtl0(ctl0);
-        return SUCCESS;
-      }
-    }
+    REFERENCE_1_5V_ON_PENDING = 3,
+    REFERENCE_2_5V_ON_PENDING = 4,
+
+    REFERENCE_1_5V_OFF_PENDING = 5,
+    REFERENCE_2_5V_OFF_PENDING = 6,
+
+  } state_t;
+
+  state_t m_state;
+
+  /***************** Prototypes ****************/
+  error_t switchOn(uint8_t level);
+  error_t switchOff();
+  void signalStartDone(state_t state, error_t result);
+  void signalStopDone(state_t state, error_t result);
+  error_t start(state_t targetState);
+  error_t stop(state_t nextState);
+  
+  /***************** SplitControl Commands ****************/
+  command error_t RefVolt_1_5V.start() {
+    return start(REFERENCE_1_5V_STABLE);
   }
-    
-  error_t switchOff()
-  {
-    atomic {
-      if (call HplAdc12.isBusy())
-        return FAIL;
-      else {
-        adc12ctl0_t ctl0 = call HplAdc12.getCtl0();
-        ctl0.enc = 0;
-        call HplAdc12.setCtl0(ctl0);
-        ctl0.refon = 0;
-        call HplAdc12.setCtl0(ctl0);
-        return SUCCESS;
+
+  command error_t RefVolt_2_5V.start() {
+    return start(REFERENCE_2_5V_STABLE);
+  }
+
+  command error_t RefVolt_1_5V.stop() {
+    return stop(REFERENCE_1_5V_OFF_PENDING);
+  }
+
+  command error_t RefVolt_2_5V.stop() {
+    return stop(REFERENCE_2_5V_OFF_PENDING);
+  }
+
+  error_t start(state_t targetState){
+    error_t result;
+
+    if (m_state == REFERENCE_1_5V_STABLE || m_state == REFERENCE_2_5V_STABLE) {
+      if (targetState == m_state) {
+        result = EALREADY;
+      } else if ((result = switchOn(targetState)) == SUCCESS) {
+        m_state = targetState;
+        signalStartDone(targetState, SUCCESS);
       }
-    }
-  }  
-    
-  command error_t RefVolt_1_5V.start()
-  {
-    switch (state)
-    {
-      case REFERENCE_1_5V_STABLE:
+    } else if (m_state == GENERATOR_OFF) {
+      if ((result = switchOn(targetState)) == SUCCESS) {
+        call SwitchOnTimer.startOneShot(STABILIZE_INTERVAL);
+        m_state = targetState + 2; // +2 turns "XXX_STABLE" state into a "XXX_ON_PENDING" state 
+      }
+    } else if (m_state == REFERENCE_1_5V_OFF_PENDING || m_state == REFERENCE_2_5V_OFF_PENDING) {
+      if ((result = switchOn(targetState)) == SUCCESS) {
+        // there is a pending stop() call
+        state_t oldState = m_state;
         call SwitchOffTimer.stop();
-        signal RefVolt_1_5V.startDone(SUCCESS);
-        return SUCCESS;
-      case GENERATOR_OFF:
-        if (switchOn(REFERENCE_1_5V_PENDING) == SUCCESS){
-          call SwitchOnTimer.startOneShot(STABILIZE_INTERVAL);
-          state = REFERENCE_1_5V_PENDING;
-          return SUCCESS;
-        } else
-          return FAIL;
-      case REFERENCE_2_5V_STABLE:
-        if (switchOn(REFERENCE_1_5V_PENDING) == SUCCESS){
-          call SwitchOffTimer.stop();
-          state = REFERENCE_1_5V_STABLE;
-          signal RefVolt_1_5V.startDone(SUCCESS);
-          return SUCCESS;
-        } else
-          return FAIL;         
-      case REFERENCE_1_5V_PENDING:
-        // fall through
-      case REFERENCE_2_5V_PENDING:
-        // fall through
-      default:
-        // illegal state
-        return FAIL;
-    }
+        m_state = targetState;
+        signalStopDone(oldState, FAIL);
+        signalStartDone(targetState, SUCCESS);
+      }
+    } else if (m_state == targetState + 2) // starting already?
+      result = SUCCESS;
+    else
+      result = EBUSY;
+
+    return result;
   }
 
-  command error_t RefVolt_1_5V.stop()
-  {
-    switch (state)
-    {
-      case REFERENCE_1_5V_PENDING:
-        // fall through
-      case REFERENCE_2_5V_PENDING:
-        if (switchOff() == SUCCESS){
-          call SwitchOnTimer.stop();
-          state = GENERATOR_OFF;
-          if (state == REFERENCE_1_5V_PENDING)
-            signal RefVolt_1_5V.stopDone(SUCCESS);
-          else
-            signal RefVolt_2_5V.stopDone(SUCCESS);
-          return SUCCESS;
-        } else 
-          return FAIL;
-      case REFERENCE_1_5V_STABLE:
-        // fall through
-      case REFERENCE_2_5V_STABLE:
+  error_t stop(state_t nextState){
+    error_t result;
+
+    if (m_state == GENERATOR_OFF)
+      result = EALREADY;
+    else if (m_state == REFERENCE_1_5V_STABLE || m_state == REFERENCE_2_5V_STABLE) {
+      if ((result = switchOff()) == SUCCESS) {
+        m_state = nextState; // m_state becomes a "XXX_OFF_PENDING" state 
         call SwitchOffTimer.startOneShot(SWITCHOFF_INTERVAL);
-        return SUCCESS;
-      case GENERATOR_OFF:
-        // fall through
-      default:
-        // illegal state
-        return FAIL;
-    }
+      }
+    } else if (m_state == REFERENCE_1_5V_ON_PENDING || m_state == REFERENCE_2_5V_ON_PENDING) {
+      if ((result = switchOff()) == SUCCESS) {
+        // there is a pending start() call
+        state_t oldState = m_state;
+        call SwitchOnTimer.stop();
+        m_state = GENERATOR_OFF;
+        signalStartDone(oldState, FAIL);
+        signalStopDone(nextState, SUCCESS);
+      }
+    } else if (m_state == nextState) // stopping already?
+      result = SUCCESS;
+    else
+      result = EBUSY;
+
+    return result;
   }
 
-  command error_t RefVolt_2_5V.start()
-  {
-    switch (state)
-    {
-      case REFERENCE_2_5V_STABLE:
-        call SwitchOffTimer.stop();
-        signal RefVolt_2_5V.startDone(SUCCESS);
-        return SUCCESS;
-      case GENERATOR_OFF:
-        if (switchOn(REFERENCE_2_5V_PENDING) == SUCCESS){
-          call SwitchOnTimer.startOneShot(STABILIZE_INTERVAL);
-          state = REFERENCE_2_5V_PENDING;
-          return SUCCESS;
-        } else
-          return FAIL;
-      case REFERENCE_1_5V_STABLE:
-        if (switchOn(REFERENCE_2_5V_PENDING) == SUCCESS){
-          call SwitchOffTimer.stop();
-          state = REFERENCE_2_5V_STABLE;
-          signal RefVolt_2_5V.startDone(SUCCESS);
-          return SUCCESS;
-        } else
-          return FAIL;         
-      case REFERENCE_2_5V_PENDING:
-        // fall through
-      case REFERENCE_1_5V_PENDING:
-        // fall through
-      default:
-        // illegal state
-        return FAIL;
-    }
+  void signalStartDone(state_t state, error_t result){
+    if (state == REFERENCE_1_5V_STABLE || state == REFERENCE_1_5V_ON_PENDING)
+      signal RefVolt_1_5V.startDone(result);
+    else
+      signal RefVolt_2_5V.startDone(result);
   }
-  
-  command error_t RefVolt_2_5V.stop()
-  {
-    switch (state)
-    {
-      case REFERENCE_2_5V_PENDING:
-        // fall through
-      case REFERENCE_1_5V_PENDING:
-        if (switchOff() == SUCCESS){
-          call SwitchOnTimer.stop();
-          state = GENERATOR_OFF;
-          if (state == REFERENCE_2_5V_PENDING)
-            signal RefVolt_2_5V.stopDone(SUCCESS);
-          else
-            signal RefVolt_1_5V.stopDone(SUCCESS);
-          return SUCCESS;
-        } else 
-          return FAIL;
-      case REFERENCE_2_5V_STABLE:
-        // fall through
-      case REFERENCE_1_5V_STABLE:
-        call SwitchOffTimer.startOneShot(SWITCHOFF_INTERVAL);
-        return SUCCESS;
-      case GENERATOR_OFF:
-        // fall through
-      default:
-        // illegal state
-        return FAIL;
-    }
+
+  void signalStopDone(state_t state, error_t result){
+    if (state == REFERENCE_1_5V_STABLE || state == REFERENCE_1_5V_OFF_PENDING)
+      signal RefVolt_1_5V.stopDone(result);
+    else
+      signal RefVolt_2_5V.stopDone(result);
   }
 
-  event void SwitchOnTimer.fired() 
-  {
-    switch (state)
-    {
-      case REFERENCE_1_5V_PENDING:
-        state = REFERENCE_1_5V_STABLE;
+  /***************** Timer Events ******************/
+  event void SwitchOnTimer.fired() {
+    switch (m_state) {
+      case REFERENCE_1_5V_ON_PENDING:
+        m_state = REFERENCE_1_5V_STABLE;
         signal RefVolt_1_5V.startDone(SUCCESS);
         break;
-      case REFERENCE_2_5V_PENDING:
-         state = REFERENCE_2_5V_STABLE;
+        
+      case REFERENCE_2_5V_ON_PENDING:
+         m_state = REFERENCE_2_5V_STABLE;
         signal RefVolt_2_5V.startDone(SUCCESS);
         break;
-      case REFERENCE_1_5V_STABLE:
-        // fall through
-      case GENERATOR_OFF:
-        // fall through
-      case REFERENCE_2_5V_STABLE:
-        // fall through
+        
       default:
-        // illegal state
         return;
     }
   }
     
-  event void SwitchOffTimer.fired() 
-  {
-    switch (state)
-    {
+  event void SwitchOffTimer.fired() {
+    switch (m_state) {
       case REFERENCE_1_5V_STABLE:
         if (switchOff() == SUCCESS){
-          state = GENERATOR_OFF;
+          m_state = GENERATOR_OFF;
           signal RefVolt_1_5V.stopDone(SUCCESS);
-        } else
+          
+        } else {
           call SwitchOffTimer.startOneShot(SWITCHOFF_INTERVAL);
+        }
         break;
+        
       case REFERENCE_2_5V_STABLE:
-        if (switchOff() == SUCCESS){
-          state = GENERATOR_OFF;
+        if (switchOff() == SUCCESS) {
+          m_state = GENERATOR_OFF;
           signal RefVolt_2_5V.stopDone(SUCCESS);
-        } else
+          
+        } else {
           call SwitchOffTimer.startOneShot(SWITCHOFF_INTERVAL);
+        }
         break;
-      case GENERATOR_OFF:
-        // fall through
-      case REFERENCE_1_5V_PENDING:
-        // fall through
-      case REFERENCE_2_5V_PENDING:
-        // fall through
+        
       default:
-        // illegal state
-        return;
+        break;
     }
   }
+  
+  /**************** HplAdc12 Events ***************/
+  async event void HplAdc12.conversionDone(uint16_t iv) {
+  }
 
-  async event void HplAdc12.conversionDone(uint16_t iv){}
+  /**************** Functions ****************/
+  error_t switchOn(uint8_t level) {
+    atomic {
+      if (call HplAdc12.isBusy()) {
+        return EBUSY;
+        
+      } else {
+        adc12ctl0_t ctl0 = call HplAdc12.getCtl0();
+        ctl0.enc = 0;
+        call HplAdc12.setCtl0(ctl0);
+        ctl0.refon = 1;
+        
+        // This is why we don't change the enum at the top
+        ctl0.r2_5v = level - 1;  
+        call HplAdc12.setCtl0(ctl0);
+        return SUCCESS;
+      }
+    }
+  }
+  
+  error_t switchOff() {
+    atomic {
+      if (call HplAdc12.isBusy()) {
+        return EBUSY;
+        
+      } else {
+        adc12ctl0_t ctl0 = call HplAdc12.getCtl0();
+        ctl0.enc = 0;
+        call HplAdc12.setCtl0(ctl0);
+        ctl0.refon = 0;
+        call HplAdc12.setCtl0(ctl0);
+        return SUCCESS;
+      }
+    }
+  }  
+  
+  /***************** Defaults ****************/
 
   default event void RefVolt_1_5V.startDone(error_t error){}
   default event void RefVolt_2_5V.startDone(error_t error){}
index 16a9fb5f3b96c8a3748c5cb94bd859269051e3f7..1ec121ac158ecbe7c8457ef8a04435cb85223b51 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Clock initialization for msp430's with the newer basic clock +, sometimes
  * referred to as basic clock 2.  Derived from the Msp430ClockP for the
  * original basic clock peripheral (chips/msp430/clock/Msp430ClockP.nc), with
  * some refinements suggested by TI in ther example code, filename
  * MSP430x261x_dco_flashcal.c.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "Msp430Timer.h"
 
 generic module Msp430ClockP(uint16_t TARGET_DCO_KHZ, uint16_t ACLK_KHZ) @safe()
@@ -81,7 +81,7 @@ implementation
     TACCTL2 = CM_1 + CCIS_1 + CAP;     /* Capture on rising ACLK */
     TACTL = TASSEL_2 + MC_2 + TACLR;   /* Continuous mode, source SMCLK */
    }
-    
+
   command void Msp430ClockInit.defaultInitClocks()
   {
     const unsigned int divider = TARGET_DCO_KHZ / 1000;
@@ -120,7 +120,7 @@ implementation
   {
     call Msp430ClockInit.defaultSetupDcoCalibrate();
   }
-  
+
   default event void Msp430ClockInit.initClocks()
   {
     call Msp430ClockInit.defaultInitClocks();
index e0d9cbac33096f04a3e01bf87254d6791db5e223..e5406c5b1e93e691345e7a135c97d759d8658705 100644 (file)
@@ -220,7 +220,7 @@ void __nesc_atomic_end(__nesc_atomic_t reenable_interrupts);
 
 #ifndef NESC_BUILD_BINARY
 /* @spontaneous() functions should not be included when NESC_BUILD_BINARY
-   is #defined, to avoid duplicate functions definitions wheb binary
+   is #defined, to avoid duplicate functions definitions when binary
    components are used. Such functions do need a prototype in all cases,
    though. */
 __nesc_atomic_t __nesc_atomic_start(void) @spontaneous() @safe()
@@ -239,5 +239,24 @@ void __nesc_atomic_end(__nesc_atomic_t reenable_interrupts) @spontaneous() @safe
 }
 #endif
 
+/* Floating-point network-type support.
+   These functions must convert to/from a 32-bit big-endian integer that follows
+   the layout of Java's java.lang.float.floatToRawIntBits method.
+   Conveniently, for the MSP430 family, this is a straight byte copy...
+*/
+
+typedef float nx_float __attribute__((nx_base_be(afloat)));
+
+inline float __nesc_ntoh_afloat(const void *COUNT(sizeof(float)) source) @safe() {
+  float f;
+  memcpy(&f, source, sizeof(float));
+  return f;
+}
+
+inline float __nesc_hton_afloat(void *COUNT(sizeof(float)) target, float value) @safe() {
+  memcpy(target, &value, sizeof(float));
+  return value;
+}
+
 #endif//_H_msp430hardware_h
 
index b7f6681c2661894a8f07274372106003f2fe5dbf..5e272b39ca5aab434bd4678990a14c8e2d88bcf5 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000-2005 The Regents of the University of California.  
+ * Copyright (c) 2000-2005 The Regents of the University of California.
  * All rights reserved.
  *
  * Copyright (c) 2008, Titanium Mirror, Inc.
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Modified from the original HplMsp430GeneralIOP to provide resistor enable
  * support available on some msp430 parts.
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "msp430regtypes.h"
 
 generic module HplMsp430GeneralIORenP(
index 9051fc4054b56bdd9c9626474c9555089f6b3c50..e2247fad343baefb1ba36174495a74ee717bbca1 100644 (file)
@@ -30,9 +30,10 @@ generic configuration Msp430ClockC(uint16_t TARGET_DCO_KHZ, uint16_t ACLK_KHZ)
 }
 implementation
 {
-  components new Msp430ClockP(TARGET_DCO_KHZ, ACLK_KHZ), Msp430TimerC;
+  components new Msp430ClockP(TARGET_DCO_KHZ, ACLK_KHZ), Msp430TimerC, McuSleepC;
 
   Init = Msp430ClockP;
   Msp430ClockInit = Msp430ClockP;
+  McuSleepC.McuPowerOverride -> Msp430ClockP;
 }
 
index 82e776c0763387feb9e79a10027329ea41229072..7d081ab6edb1f3c0d25e5837274986d9891454b5 100644 (file)
@@ -31,6 +31,7 @@ generic module Msp430ClockP(uint16_t TARGET_DCO_KHZ, uint16_t ACLK_KHZ) @safe()
 {
   provides interface Init;
   provides interface Msp430ClockInit;
+  provides interface McuPowerOverride;
 }
 implementation
 {
@@ -56,6 +57,9 @@ implementation
     TARGET_DCO_DELTA = (TARGET_DCO_KHZ / ACLK_KHZ) * ACLK_CALIB_PERIOD,
   };
 
+  async command mcu_power_t McuPowerOverride.lowestState() {
+    return MSP430_POWER_LPM3;
+  }
 
   command void Msp430ClockInit.defaultSetupDcoCalibrate()
   {
index 548aecc301f9918be6d1f178f1a9d3871433008d..52355369c72ac061da5169356856f51e9594088c 100644 (file)
@@ -65,7 +65,7 @@ implementation
       ccis : 0,  // capture/compare input select
       clld : 0,  // TBCL1 loads on write to TBCCR1
       cap : 1,   // compare mode
-      scs : 1,   // synchronous capture mode
+      scs : 0,   // non synchronous capture mode
       ccie : 0,  // capture compare interrupt enable
     };
     return CC2int(x);
index 5a50349cd6c45b3350df9c57b044e40e5350e72c..08d543b3d93338378086d0fbad5cf958a8051bb8 100644 (file)
@@ -306,5 +306,35 @@ msp430_i2c_union_config_t msp430_i2c_default_config = {
   } 
 };
 
+typedef uint8_t uart_speed_t;
+typedef uint8_t uart_parity_t;
+typedef uint8_t uart_duplex_t;
+
+enum {
+  TOS_UART_1200   = 0,
+  TOS_UART_1800   = 1,
+  TOS_UART_2400   = 2,
+  TOS_UART_4800   = 3,
+  TOS_UART_9600   = 4,
+  TOS_UART_19200  = 5,
+  TOS_UART_38400  = 6,
+  TOS_UART_57600  = 7,
+  TOS_UART_76800  = 8,
+  TOS_UART_115200 = 9,
+  TOS_UART_230400 = 10
+};
+
+enum {
+  TOS_UART_OFF,
+  TOS_UART_RONLY,
+  TOS_UART_TONLY,
+  TOS_UART_DUPLEX
+};
+
+enum {
+  TOS_UART_PARITY_NONE,
+  TOS_UART_PARITY_EVEN,
+  TOS_UART_PARITY_ODD
+};
 
 #endif//_H_Msp430Usart_h
index 59dc4346af2497db1d7c182384106a97ebe12fa3..f1e343de50f5651c9cfb7a5e6f91616d613d4291 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Generic async configuration interface.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
 
index 8bebd13258c86c5cd339628664b1b46c31194782..05917df9b41d2a5b3fd4ab90151bd6137ef10b27 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Provides HPL access to both registers and interrupts of all USCI devices on
  * a supported msp430 processor.  The interfaces available are created
  *
  * 'A' devices offer UART, LIN, IrDA and SPI modes of operation.  'B' devices
  * are limited to SPI and I2C modes.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration HplMsp430UsciC {
   provides {
 #if defined(__MSP430_HAS_USCI_AB0__) || defined(__MSP430_HAS_USCI__)
index 6b73960ec708c493a9524f13aa27f9e9782401de..b5cb0c85209b4cb125022f04ddbdeeaa978d4ac9 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Interrupt interface for USCI peripherals.  Although A and B devices have
  * different interrupt sets since B only support I2C, we use a single set for
  * both so that upper layers need not deal with the different sets.  This is
  * critical in the case of SPI communications, which is supported by both A
  * and B devices.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "Msp430Usci.h"
 
 interface HplMsp430UsciInt {
index 9e69649cd7701f039c4fa3e132a562e394d956bd..dff680fd7ddb43cda8720126fc0705772c64fbf4 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HPL interrupt interface for the USCI0 peripheral.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "Msp430Usci.h"
 #include "msp430hardware.h"
 
@@ -100,7 +100,7 @@ implementation
       signal IntB.i2cStop();
     }
   }
-  
+
   /* This interrupt vector signals transmit events.  USCI_A0 can receive events
    * for UART and SPI modes, while USCI_B0 can receive events for I2C and SPI
    * modes.
index 2b9b1d4fa052a57766677ff98330b624e1ecc5ea..720031034ccd8dc9858527c5f8206cdaf4cac6f4 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HPL interrupt interface for the USCI1 peripheral.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "Msp430Usci.h"
 #include "msp430hardware.h"
 
@@ -93,7 +93,7 @@ implementation
       signal IntB.i2cStop();
     }
   }
-  
+
   /* This interrupt vector signals transmit events.  USCI_A1 can receive events
    * for UART and SPI modes, while USCI_B1 can receive events for I2C and SPI
    * modes.
index 1d80fdaf25647464b8ae519a8fe3f577742d1251..cf49708ada3b8bda03da1acbb913a1f5f93b01d0 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HPL interface to a USCI peripheral device in UART mode.
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "Msp430Usci.h"
 
 interface HplMsp430UsciReg {
index b46a1c4f35815b51fdc7fbc83a5914007fe2c1c4..3dcaf9caae90fe48973316cf5252b931de175f0a 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * HPL register interface to USCI peripherals.  The interface abstracts the
  * differences between pysical devices (aka addresses) such that a user of
  * the interface can equally use any USCI device, providing the device
  * provides the necessary capabilities.  For example, I2C is only available
  * on USCI_Bx ports.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "Msp430Usci.h"
 #include "msp430hardware.h"
 
index 9f166521bf76c4d2531982212ee9981476368cf3..b3c284f2e46912c9d30df1a4b9641b5ddc9128b8 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * This configuration provides the interface for using USCI_A0 in its SPI
  * mode.
@@ -50,7 +50,7 @@
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #if !defined(__MSP430_HAS_USCI_AB0__)
 #error "Target does not have a USCI_A0 peripheral (SPI)"
 #endif
index dbd008220be9ca39ef13aa7019eed1492c86d81e..8da9619f3a17b7a1d495dbc81600f7ff8c650c54 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * This configuration provides the interface for using USCI_B0 in its SPI
  * mode.
@@ -50,7 +50,7 @@
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #if !defined(__MSP430_HAS_USCI_AB0__)
 #error "Target does not have a USCI_B0 peripheral (SPI)"
 #endif
index 5fc73fc23356aaf98e7a07844636a5efc83f9589..f06cc414c431e6aea06cc5a3c45b104516c8a56c 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * This configuration provides the interface for using USCI_B1 in its SPI
  * mode.
@@ -50,7 +50,7 @@
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #if !defined(__MSP430_HAS_USCI_AB1__)
 #error "Target does not have a USCI_B1 peripheral (SPI)"
 #endif
index 142edb7b9f9996a8a15b1ad96a759a2b8b2a8c73..ee57284498a5af9aa07129981ca83904113cd7d0 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Spi implementation using a USCI device.  When being used as a SPI slave, the
  * CSn interface should be wired to the chip select driven by the SPI master so
@@ -38,7 +38,7 @@
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 generic module Msp430SpiP(uint16_t blockSize) {
   provides {
     interface SpiByte;
@@ -302,7 +302,7 @@ implementation {
 
   default async command const msp430_usci_spi_t* Configure.get()
   {
-    const static msp430_usci_spi_t def = { 
+    const static msp430_usci_spi_t def = {
       ctl0: UCSYNC | UCMODE_0 | UCMST, /* 3-pin SPI mode 0, LSB first */
       ctl1: UCSWRST | UCSSEL_3,                /* SPI clock source is SMCLK */
       brx: 10,                 /* SPI clock=SMCLK/10; ~105KHz if SMCLK=1MHz */
index c411445485b6b7ac95d809fb61811fe20a62d478..bbdf8a45877f44598c414ba4951b8ba9722dc7fb 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * This configuration provides the interface for using USCI_A0 in its UART
  * mode.
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #if !defined(__MSP430_HAS_USCI_AB0__)
 #error "Target does not have a USCI_A0 peripheral (UART)"
 #endif
index 67c0a02fbea56e5ee3de86fbeb4e6b431afa528c..67a917c3bab2acd9c074c9d4c1c5e43150c05949 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * This configuration provides the interface for using USCI_A1 in its UART
  * mode.
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #if !defined(__MSP430_HAS_USCI_AB0__)
 #error "Target does not have a USCI_A1 peripheral (UART)"
 #endif
index a4bec07698e521599d379e4c4634fb885e8d296a..72df1df0c1827f63ef14f7836a5927aaa43b3828 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Uart implementation using a USCI device.
  *
@@ -35,7 +35,7 @@
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 generic module Msp430UartP() {
   provides {
     interface UartStream;
@@ -256,7 +256,7 @@ implementation {
 
   default async command const msp430_usci_uart_t* Configure.get()
   {
-    const static msp430_usci_uart_t def = { 
+    const static msp430_usci_uart_t def = {
       ctl0: UCMODE_0,          /* async, lsb first, 8N1 */
       ctl1: UCSWRST | UCSSEL_3,        /* clock uart from SMCLK */
       brx: UBRX_1MHZ_115200,
index 94e54cf5cc054fe753f14fda36c7b2e8909a245c..88e4c90198b48e7470c6ea56f09d2cc6d503dfdb 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Header definitions for the USCI peripheral in newer msp430 processors.
  * A USCI peripheral provides two communications devices, denoted A and B.
  *
  * A devices offer UART, LIN, IrDA and SPI modes of operation.  B parts are
  * limited to SPI and I2C modes.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #ifndef MSP430_USCI_h
 #define MSP430_USCI_h
 
index ed89b1e3ef0eefe73b603a5be268e1066204dcf8..cf4ee6eeea608502c3732a5ff78d23c63112de5e 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Defines the USCI_A0 peripheral.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration Msp430UsciA0C {
   provides {
     interface HplMsp430UsciReg as Registers;
index efff0cdec2226d66bc599caa8c4498eb9e1ddf97..800300d3df14418d903ba082599f9888f69c4ef1 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Defines the USCI_A1 peripheral.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration Msp430UsciA1C {
   provides {
     interface HplMsp430UsciReg as Registers;
index 371d22bdc0039e0bed73ae1e207e2133b20b4244..12f821ef4f8a1b2885881ed5f4619c29cf343def 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Defines the USCI_B0 peripheral.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration Msp430UsciB0C {
   provides {
     interface HplMsp430UsciReg as Registers;
index 20ea176d6c4385b95e6587072912c1665618a07d..81b5e60751685f6b4edbc310ffc8ce6e05f45cef 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Defines the USCI_B1 peripheral.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration Msp430UsciB1C {
   provides {
     interface HplMsp430UsciReg as Registers;
index 30dcff6d5f371647b34fec58cca18597e59d502f..eaa2129bcf66a19168668cb6df7544951c741043 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Interrupt dispatch for USCI_Ax and USCI_Bx devices.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 generic module Msp430UsciIntDispatchP() @safe() {
   provides interface HplMsp430UsciInt as Interrupts[uint8_t id];
   uses {
index 78abf87c996850b584695c22b19e2ee7acced9b1..f8ddab13948123b44743413a68aabeb027c30268 100644 (file)
@@ -45,8 +45,6 @@
  * @author Brano Kusy (branislav.kusy@gmail.com)
  * @version October 25, 2007
  */
-#include "SCCB.h"
-#include "OV7649.h"
 #include "PXA27XQuickCaptInt.h"
 #include "DMA.h"
 #include "dmaArray.h"
@@ -150,7 +148,6 @@ implementation
 
     async command void HplPXA27XQuickCaptInt.disableQuick()
     {
-        led_clr();//call LED_PIN.clr();
         CICR0 &= ~(CICR0_EN);
         CISR |= CISR_CQD;
     } 
@@ -172,11 +169,8 @@ implementation
 
     command error_t HplPXA27XQuickCaptInt.setImageSize(uint16_t sizeX, uint16_t sizeY, uint8_t colorType)
     {
-        //was: if (sizeX > 2048 || sizeY > 2048)
-    if (sizeX > 320 || sizeY > 240) 
-            return FAIL;
-
-    
+    if (sizeX > 2048 || sizeY > 2048)
+      return FAIL;
 
     // (1) - Set the Quick Capture Interface Size
     //was: call HplPXA27XQuickCaptInt.disableQuick();
@@ -218,13 +212,11 @@ implementation
       
         //atomic{printfUART(">>>>>>>>>>>>>>> PPID_CIF_Irq.fired() >>>>>>>>>>>\n", "");}
         volatile uint32_t tempCISR;
-        call Leds.led0Toggle();
 
         atomic {  tempCISR = CISR; }
         // Start-Of-Frame
         if ((tempCISR & CISR_SOF) && (~(CICR0) & CICR0_SOFM)) {
             atomic CISR |= CISR_SOF;
-            led_set();//call LED_PIN.set();
             signal HplPXA27XQuickCaptInt.startOfFrame();
             // this disables CIF after the current frame capture is done 
             CICR0 |= CICR0_DIS;                
@@ -232,7 +224,6 @@ implementation
         // End-Of-Frame
         if ((tempCISR & CISR_EOF) && (~(CICR0) & CICR0_EOFM)) {
             atomic CISR |= CISR_EOF;
-            led_clr();//call LED_PIN.clr();
             signal HplPXA27XQuickCaptInt.endOfFrame();
             return;           
         }
index d501b66525a78a102ab404439b9991b97a4660f1..2822db87289a1e56e589b8d7b0212f70ece3bda3 100644 (file)
@@ -58,7 +58,7 @@ typedef struct {
 #define MAX_DESC_TRANSFER  8184                // max is 8K-1, CIF requires a multiple of 8    //8192
 
 // ----------------------------------------------
-#define DescArray_NBR_DESC         20//8
+#define DescArray_NBR_DESC         100//8
 #define DescArray_BYTE_ALLIGNMENT  16
 #define DescArray_BUFFER_SIZE      (DescArray_NBR_DESC*sizeof(DMADescriptor_t) + DescArray_BYTE_ALLIGNMENT)
 
index 912a7b1c13d9d3264c76d8578c14bc52a9d13af5..e7168f1b02c09fd0eea345cefe3af54e9d00972a 100644 (file)
@@ -98,8 +98,8 @@ implementation
 
   async command uint32_t I2C.getIDBR() { 
     switch(dev) {
-    case 0: return IDBR; break;
-    case 1: return PIDBR; break;
+    case 0: return IDBR;
+    case 1: return PIDBR;
     default: return 0;
     }
   }
@@ -115,8 +115,8 @@ implementation
 
   async command uint32_t I2C.getICR() { 
     switch(dev) {
-    case 0: return ICR; break;
-    case 1: return PICR; break;
+    case 0: return ICR;
+    case 1: return PICR;
     default: return 0;
     }
   }
@@ -131,8 +131,8 @@ implementation
 
  async command uint32_t I2C.getISR() { 
     switch(dev) {
-    case 0: return ISR; break;
-    case 1: return PISR; break;
+    case 0: return ISR;
+    case 1: return PISR;
     default: return 0;
     }
   }
index faa7f9cff1ce4e9d1dedb1ac98838bba07c85543..8eead3b6d818253b27ee44034e12b0bfa93e6ca2 100644 (file)
@@ -55,5 +55,5 @@ implementation
 
   HplPXA27xSSPP.Init[2] <- PlatformP.InitL1;
 
-  HplPXA27xSSPP.SSP2Irq -> HplPXA27xInterrupM.PXA27xIrq[PPID_SSP2];
+  HplPXA27xSSPP.SSP2Irq -> HplPXA27xInterruptM.PXA27xIrq[PPID_SSP2];
 }
diff --git a/tos/chips/rf230/ActiveMessageConfig.nc b/tos/chips/rf230/ActiveMessageConfig.nc
deleted file mode 100644 (file)
index e47f0e8..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-interface ActiveMessageConfig
-{
-       /**
-        * This command is called when the message first enters the radio stack
-        * via the Send.send command. This should clear the packet if the user
-        * forgot to do so (or return EINVAL to be strict).
-        */
-       command error_t checkPacket(message_t* msg);
-}
diff --git a/tos/chips/rf230/ActiveMessageLayerC.nc b/tos/chips/rf230/ActiveMessageLayerC.nc
deleted file mode 100644 (file)
index f635a9c..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-module ActiveMessageLayerC
-{
-       provides
-       {
-               interface AMSend[am_id_t id];
-               interface Receive[am_id_t id];
-               interface Receive as Snoop[am_id_t id]; 
-       }
-       uses
-       {
-               interface Send as SubSend;
-               interface Receive as SubReceive;
-               interface AMPacket;
-               interface ActiveMessageConfig as Config;
-       }
-}
-
-implementation
-{
-/*----------------- Send -----------------*/
-
-       command error_t AMSend.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len)
-       {
-               error_t error;
-
-               error = call Config.checkPacket(msg);
-               if( error != SUCCESS )
-                       return error;
-
-               call AMPacket.setSource(msg, call AMPacket.address());
-               call AMPacket.setGroup(msg, call AMPacket.localGroup());
-               call AMPacket.setType(msg, id);
-               call AMPacket.setDestination(msg, addr);
-
-               return call SubSend.send(msg, len);
-       }
-
-       inline event void SubSend.sendDone(message_t* msg, error_t error)
-       {
-               signal AMSend.sendDone[call AMPacket.type(msg)](msg, error);
-       }
-
-       inline command error_t AMSend.cancel[am_id_t id](message_t* msg)
-       {
-               return call SubSend.cancel(msg);
-       }
-
-       default event void AMSend.sendDone[am_id_t id](message_t* msg, error_t error)
-       {
-       }
-
-       inline command uint8_t AMSend.maxPayloadLength[am_id_t id]()
-       {
-               return call SubSend.maxPayloadLength();
-       }
-
-       inline command void* AMSend.getPayload[am_id_t id](message_t* msg, uint8_t len)
-       {
-               return call SubSend.getPayload(msg, len);
-       }
-
-/*----------------- Receive -----------------*/
-
-       event message_t* SubReceive.receive(message_t* msg, void* payload, uint8_t len)
-       {
-               am_id_t type = call AMPacket.type(msg);
-
-               msg = call AMPacket.isForMe(msg) 
-                       ? signal Receive.receive[type](msg, payload, len)
-                       : signal Snoop.receive[type](msg, payload, len);
-
-               return msg;
-       }
-
-       default event message_t* Receive.receive[am_id_t id](message_t* msg, void* payload, uint8_t len)
-       {
-               return msg;
-       }
-
-       default event message_t* Snoop.receive[am_id_t id](message_t* msg, void* payload, uint8_t len)
-       {
-               return msg;
-       }
-}
diff --git a/tos/chips/rf230/CsmaConfig.nc b/tos/chips/rf230/CsmaConfig.nc
deleted file mode 100644 (file)
index 9d45376..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-interface CsmaConfig
-{
-       /**
-        * This command is called when the message is transmitted to
-        * check if it needs software clear channel assesment.
-        */
-       async command bool requiresSoftwareCCA(message_t* msg);
-}
diff --git a/tos/chips/rf230/CsmaLayerC.nc b/tos/chips/rf230/CsmaLayerC.nc
deleted file mode 100644 (file)
index e0ddc26..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration CsmaLayerC
-{
-       provides
-       {
-               interface RadioSend;
-       }
-       uses
-       {
-               interface RadioSend as SubSend;
-               interface RadioCCA as SubCCA;
-
-               interface CsmaConfig as Config;
-       }
-}
-
-implementation
-{
-       components CsmaLayerP;
-
-       RadioSend = CsmaLayerP;
-       SubSend = CsmaLayerP;
-       SubCCA = CsmaLayerP;
-       Config = CsmaLayerP;
-}
diff --git a/tos/chips/rf230/CsmaLayerP.nc b/tos/chips/rf230/CsmaLayerP.nc
deleted file mode 100644 (file)
index 5bd1aa4..0000000
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-#include <RadioAssert.h>
-
-module CsmaLayerP
-{
-       provides
-       {
-               interface RadioSend;
-       }
-
-       uses
-       {
-               interface CsmaConfig as Config;
-
-               interface RadioSend as SubSend;
-               interface RadioCCA as SubCCA;
-       }
-}
-
-implementation
-{
-       tasklet_norace message_t *txMsg;
-
-       tasklet_norace uint8_t state;
-       enum
-       {
-               STATE_READY = 0,
-               STATE_CCA_WAIT = 1,
-               STATE_SEND = 2,
-       };
-
-       tasklet_async event void SubSend.ready()
-       {
-               if( state == STATE_READY )
-                       signal RadioSend.ready();
-       }
-
-       tasklet_async command error_t RadioSend.send(message_t* msg)
-       {
-               error_t error;
-
-               if( state == STATE_READY )
-               {
-                       if( call Config.requiresSoftwareCCA(msg) )
-                       {
-                               txMsg = msg;
-
-                               if( (error = call SubCCA.request()) == SUCCESS )
-                                       state = STATE_CCA_WAIT;
-                       }
-                       else if( (error = call SubSend.send(msg)) == SUCCESS )
-                               state = STATE_SEND;
-               }
-               else
-                       error = EBUSY;
-
-               return error;
-       }
-
-       tasklet_async event void SubCCA.done(error_t error)
-       {
-               ASSERT( state == STATE_CCA_WAIT );
-
-               if( error == SUCCESS && (error = call SubSend.send(txMsg)) == SUCCESS )
-                       state = STATE_SEND;
-               else
-               {
-                       state = STATE_READY;
-                       signal RadioSend.sendDone(EBUSY);
-               }
-       }
-
-       tasklet_async event void SubSend.sendDone(error_t error)
-       {
-               ASSERT( state == STATE_SEND );
-
-               state = STATE_READY;
-               signal RadioSend.sendDone(error);
-       }
-}
diff --git a/tos/chips/rf230/DummyConfig.nc b/tos/chips/rf230/DummyConfig.nc
deleted file mode 100644 (file)
index c76631e..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-interface DummyConfig
-{
-       /**
-        * We need to put something here, but this is not going to get called
-        */
-       async command void nothing();
-}
diff --git a/tos/chips/rf230/DummyLayerC.nc b/tos/chips/rf230/DummyLayerC.nc
deleted file mode 100644 (file)
index e3c55de..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-generic configuration DummyLayerC()
-{
-       provides
-       {
-               interface SplitControl;
-               interface Send;
-               interface Receive;
-               interface LowPowerListening;
-
-               interface RadioState;
-               interface RadioSend;
-               interface RadioReceive;
-               interface RadioCCA;
-
-               interface DummyConfig as UnconnectedConfig;
-       }
-
-       uses 
-       {
-               interface RadioState as SubState;
-               interface RadioSend as SubRadioSend;
-               interface RadioReceive as SubRadioReceive;
-               interface RadioCCA as SubRadioCCA;
-               interface SplitControl as SubControl;
-               interface Send as SubSend;
-               interface Receive as SubReceive;
-
-               interface DummyConfig as Config;
-       }
-}
-
-implementation
-{
-       RadioState = SubState;
-       RadioSend = SubRadioSend;
-       RadioReceive = SubRadioReceive;
-       RadioCCA = SubRadioCCA;
-
-       SplitControl = SubControl;
-       Send = SubSend;
-       Receive = SubReceive;
-
-       Config = UnconnectedConfig;
-
-       components DummyLayerP;
-       LowPowerListening = DummyLayerP.LowPowerListening;
-}
diff --git a/tos/chips/rf230/DummyLayerP.nc b/tos/chips/rf230/DummyLayerP.nc
deleted file mode 100644 (file)
index 8ce3261..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-module DummyLayerP
-{
-       provides interface LowPowerListening;
-}
-
-implementation
-{
-       command void LowPowerListening.setLocalSleepInterval(uint16_t sleepIntervalMs) { }
-
-       command uint16_t LowPowerListening.getLocalSleepInterval() { return 0; }
-  
-       command void LowPowerListening.setLocalDutyCycle(uint16_t dutyCycle) { }
-  
-       command uint16_t LowPowerListening.getLocalDutyCycle() { return 10000; }
-  
-       command void LowPowerListening.setRxSleepInterval(message_t *msg, uint16_t sleepIntervalMs) { }
-  
-       command uint16_t LowPowerListening.getRxSleepInterval(message_t *msg) { return 0; }
-  
-       command void LowPowerListening.setRxDutyCycle(message_t *msg, uint16_t dutyCycle) { }
-  
-       command uint16_t LowPowerListening.getRxDutyCycle(message_t *msg) { return 10000; }
-  
-       command uint16_t LowPowerListening.dutyCycleToSleepInterval(uint16_t dutyCycle) { return 0; }
-
-       command uint16_t LowPowerListening.sleepIntervalToDutyCycle(uint16_t sleepInterval) { return 10000; }
-}
diff --git a/tos/chips/rf230/IEEE154NetworkLayerC.nc b/tos/chips/rf230/IEEE154NetworkLayerC.nc
deleted file mode 100644 (file)
index 2cfd690..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration IEEE154NetworkLayerC
-{
-       provides
-       {
-               interface SplitControl;
-               interface Send;
-               interface Receive;
-       }
-       uses
-       {
-               interface SplitControl as SubControl;
-               interface Send as SubSend;
-               interface Receive as SubReceive;
-       }
-}
-
-implementation
-{
-       components IEEE154NetworkLayerP, IEEE154PacketC;
-
-       SplitControl = SubControl;
-
-       Send = IEEE154NetworkLayerP;
-       Receive = IEEE154NetworkLayerP;
-
-       SubSend = IEEE154NetworkLayerP;
-       SubReceive = IEEE154NetworkLayerP;
-
-       IEEE154NetworkLayerP.IEEE154Packet -> IEEE154PacketC;
-}
diff --git a/tos/chips/rf230/IEEE154NetworkLayerP.nc b/tos/chips/rf230/IEEE154NetworkLayerP.nc
deleted file mode 100644 (file)
index f4abf63..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-module IEEE154NetworkLayerP
-{
-       provides
-       {
-               interface Send;
-               interface Receive;
-               interface Receive as NonTinyosReceive[uint8_t network];
-       }
-
-       uses
-       {
-               interface Send as SubSend;
-               interface Receive as SubReceive;
-
-               interface IEEE154Packet;
-       }
-}
-
-implementation
-{
-#ifndef TINYOS_6LOWPAN_NETWORK_ID
-#define TINYOS_6LOWPAN_NETWORK_ID 0x3f
-#endif
-
-       command error_t Send.send(message_t* msg, uint8_t len)
-       {
-               call IEEE154Packet.set6LowPan(msg, TINYOS_6LOWPAN_NETWORK_ID);
-               return call SubSend.send(msg, len);
-       }
-
-       command error_t Send.cancel(message_t* msg)
-       {
-               return call SubSend.cancel(msg);
-       }
-
-       command uint8_t Send.maxPayloadLength()
-       {
-               return call SubSend.maxPayloadLength();
-       }
-
-       command void* Send.getPayload(message_t* msg, uint8_t len)
-       {
-               return call SubSend.getPayload(msg, len);
-       }
-  
-       event void SubSend.sendDone(message_t* msg, error_t error)
-       {
-               signal Send.sendDone(msg, error);
-       }
-  
-       event message_t *SubReceive.receive(message_t *msg, void *payload, uint8_t len)
-       {
-               uint8_t network = call IEEE154Packet.get6LowPan(msg);
-               if( network == TINYOS_6LOWPAN_NETWORK_ID )
-                       return signal Receive.receive(msg, payload, len);
-               else
-                       return signal NonTinyosReceive.receive[network](msg, payload, len);
-       }
-
-       default event message_t *NonTinyosReceive.receive[uint8_t network](message_t *msg, void *payload, uint8_t len)
-       {
-               return msg;
-       }
-}
diff --git a/tos/chips/rf230/IEEE154Packet.h b/tos/chips/rf230/IEEE154Packet.h
deleted file mode 100644 (file)
index 62fe16b..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#ifndef __IEEE154PACKET_H__
-#define __IEEE154PACKET_H__
-
-typedef nx_struct ieee154_header_t
-{
-       nxle_uint8_t length;
-       nxle_uint16_t fcf;
-       nxle_uint8_t dsn;
-       nxle_uint16_t destpan;
-       nxle_uint16_t dest;
-       nxle_uint16_t src;
-
-// I-Frame 6LowPAN interoperability byte
-#ifndef TFRAMES_ENABLED        
-       nxle_uint8_t network;
-#endif
-
-       nxle_uint8_t type;
-} ieee154_header_t;
-
-// the actual radio driver might not use this
-typedef nx_struct ieee154_footer_t
-{ 
-       nxle_uint16_t crc;
-} ieee154_footer_t;
-
-enum ieee154_fcf_enums {
-       IEEE154_FCF_FRAME_TYPE = 0,
-       IEEE154_FCF_SECURITY_ENABLED = 3,
-       IEEE154_FCF_FRAME_PENDING = 4,
-       IEEE154_FCF_ACK_REQ = 5,
-       IEEE154_FCF_INTRAPAN = 6,
-       IEEE154_FCF_DEST_ADDR_MODE = 10,
-       IEEE154_FCF_SRC_ADDR_MODE = 14,
-};
-
-enum ieee154_fcf_type_enums {
-       IEEE154_TYPE_BEACON = 0,
-       IEEE154_TYPE_DATA = 1,
-       IEEE154_TYPE_ACK = 2,
-       IEEE154_TYPE_MAC_CMD = 3,
-       IEEE154_TYPE_MASK = 7,
-};
-
-enum iee154_fcf_addr_mode_enums {
-       IEEE154_ADDR_NONE = 0,
-       IEEE154_ADDR_SHORT = 2,
-       IEEE154_ADDR_EXT = 3,
-       IEEE154_ADDR_MASK = 3,
-};
-
-#endif//__IEEE154PACKET_H__
diff --git a/tos/chips/rf230/IEEE154Packet.nc b/tos/chips/rf230/IEEE154Packet.nc
deleted file mode 100644 (file)
index fd17174..0000000
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <IEEE154Packet.h>
-#include <message.h>
-
-/**
- * This interface encapsulates IEEE 802.15.4 intrapan data frames with 
- * 16-bit destination pan, source and destination addresses. It also 
- * supports 6LowPan interoperability mode, and acknowledgement frames.
- * Note, that this interface does not support the CRC-16 value, which
- * should be verified before the data can be trusted.
- */
-interface IEEE154Packet
-{
-       /**
-        * Returns the IEEE 802.15.4 header including the length field.
-        */
-       async command ieee154_header_t* getHeader(message_t* msg);
-
-       /**
-        * Returns the raw value (unadjusted) of the length field
-        */
-       async command uint8_t getLength(message_t* msg);
-
-       /**
-        * Sets the length field
-        */
-       async command void setLength(message_t* msg, uint8_t length);
-
-       /**
-        * Returns the frame control field. This method should not be used, 
-        * isDataFrame and isAckFrame should be used instead.
-        */
-       async command uint16_t getFCF(message_t* msg);
-
-       /**
-        * Sets the frame control field. This method should not be used, 
-        * createDataFrame and createAckFrame should be used instead.
-        */
-       async command void setFCF(message_t* msg, uint16_t fcf);
-
-       /**
-        * Returns TRUE if the message is a data frame supported by 
-        * this interface (based on the value of the FCF).
-        */
-       async command bool isDataFrame(message_t* msg);
-
-       /**
-        * Sets the FCF to create a data frame supported by this interface.
-        * You may call setAckRequired and setFramePending commands after this.
-        */
-       async command void createDataFrame(message_t* msg);
-
-       /**
-        * Returns TRUE if the message is an acknowledgement frame supported
-        * by this interface (based on the value of the FCF).
-        */
-       async command bool isAckFrame(message_t* msg);
-
-       /**
-        * Sets the FCF to create an acknowledgement frame supported by
-        * this interface. You may call setFramePending after this.
-        */
-       async command void createAckFrame(message_t* msg);
-
-       /**
-        * Creates an acknowledgement packet for the given data packet.
-        * This also sets the DSN value. The data message must be a 
-        * data frame, the ack message will be overwritten.
-        */
-       async command void createAckReply(message_t* data, message_t* ack);
-
-       /**
-        * Returns TRUE if the acknowledgement packet corresponds to the
-        * data packet. The data message must be a data packet.
-        */
-       async command bool verifyAckReply(message_t* data, message_t* ack);
-
-       /**
-        * Returns TRUE if the ACK required field is set in the FCF.
-        */
-       async command bool getAckRequired(message_t* msg);
-
-       /**
-        * Sets the ACK required field in the FCF, should never be set
-        * for acknowledgement frames.
-        */
-       async command void setAckRequired(message_t* msg, bool ack);
-
-       /**
-        * Returns TRUE if the frame pending field is set in the FCF.
-        */
-       async command bool getFramePending(message_t* msg);
-
-       /**
-        * Sets the frame pending field in the FCF.
-        */
-       async command void setFramePending(message_t* msg, bool pending);
-
-       /**
-        * Returns the data sequence number
-        */
-       async command uint8_t getDSN(message_t* msg);
-
-       /**
-        * Sets the data sequence number
-        */
-       async command void setDSN(message_t* msg, uint8_t dsn);
-
-       /**
-        * returns the destination PAN id, values <= 255 are tinyos groups,
-        * valid only for data frames
-        */
-       async command uint16_t getDestPan(message_t* msg);
-
-       /**
-        * Sets the destination PAN id, valid only for data frames
-        */
-       async command void setDestPan(message_t* msg, uint16_t pan);
-
-       /**
-        * Returns the destination address, valid only for data frames
-        */
-       async command uint16_t getDestAddr(message_t* msg);
-
-       /**
-        * Sets the destination address, valid only for data frames
-        */
-       async command void setDestAddr(message_t* msg, uint16_t addr);
-
-       /**
-        * Returns the source address, valid only for data frames
-        */
-       async command uint16_t getSrcAddr(message_t* msg);
-
-       /**
-        * Sets the source address, valid only for data frames
-        */
-       async command void setSrcAddr(message_t* msg, uint16_t addr);
-
-#ifndef TFRAMES_ENABLED
-
-       /**
-        * Returns the value of the 6LowPan network field.
-        */
-       async command uint8_t get6LowPan(message_t* msg);
-
-       /**
-        * Sets the value of the 6LowPan network field.
-        */
-       async command void set6LowPan(message_t* msg, uint8_t network);
-
-#endif
-
-       /**
-        * Returns the active message type of the message
-        */
-       async command am_id_t getType(message_t* msg);
-
-       /**
-        * Sets the active message type
-        */
-       async command void setType(message_t* msg, am_id_t type);
-
-       /**
-        * Returns TRUE if the packet is a data packet, the ACK_REQ field
-        * is set and the destination address is not the broadcast address.
-        */
-       async command bool requiresAckWait(message_t* msg);
-
-       /**
-        * Returns TRUE if the packet is a data packet, the ACK_REQ field
-        * is set and the destionation address is this node.
-        */
-       async command bool requiresAckReply(message_t* msg);
-}
diff --git a/tos/chips/rf230/IEEE154PacketC.nc b/tos/chips/rf230/IEEE154PacketC.nc
deleted file mode 100644 (file)
index 2ea8ffe..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration IEEE154PacketC
-{
-       provides
-       {
-               interface IEEE154Packet;
-               interface AMPacket;
-       }
-}
-
-implementation
-{
-       components IEEE154PacketP, ActiveMessageAddressC;
-       IEEE154PacketP.ActiveMessageAddress -> ActiveMessageAddressC;
-
-       IEEE154Packet = IEEE154PacketP;
-       AMPacket = IEEE154PacketP;
-}
diff --git a/tos/chips/rf230/IEEE154PacketP.nc b/tos/chips/rf230/IEEE154PacketP.nc
deleted file mode 100644 (file)
index cb89824..0000000
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <IEEE154Packet.h>
-
-module IEEE154PacketP
-{
-       provides 
-       {
-               interface IEEE154Packet;
-               interface AMPacket;
-       }
-
-       uses interface ActiveMessageAddress;
-}
-
-implementation
-{
-/*----------------- IEEE154Packet -----------------*/
-
-       enum
-       {
-               IEEE154_DATA_FRAME_MASK = (IEEE154_TYPE_MASK << IEEE154_FCF_FRAME_TYPE) 
-                       | (1 << IEEE154_FCF_INTRAPAN) 
-                       | (IEEE154_ADDR_MASK << IEEE154_FCF_DEST_ADDR_MODE) 
-                       | (IEEE154_ADDR_MASK << IEEE154_FCF_SRC_ADDR_MODE),
-
-               IEEE154_DATA_FRAME_VALUE = (IEEE154_TYPE_DATA << IEEE154_FCF_FRAME_TYPE) 
-                       | (1 << IEEE154_FCF_INTRAPAN) 
-                       | (IEEE154_ADDR_SHORT << IEEE154_FCF_DEST_ADDR_MODE) 
-                       | (IEEE154_ADDR_SHORT << IEEE154_FCF_SRC_ADDR_MODE),
-
-               IEEE154_ACK_FRAME_LENGTH = 5,   // includes the FCF, DSN and FCS
-               IEEE154_ACK_FRAME_MASK = (IEEE154_TYPE_MASK << IEEE154_FCF_FRAME_TYPE), 
-               IEEE154_ACK_FRAME_VALUE = (IEEE154_TYPE_ACK << IEEE154_FCF_FRAME_TYPE),
-       };
-
-       inline ieee154_header_t* getHeader(message_t* msg)
-       {
-               return (ieee154_header_t*)(msg->data - sizeof(ieee154_header_t));
-       }
-
-       inline async command ieee154_header_t* IEEE154Packet.getHeader(message_t* msg)
-       {
-               return getHeader(msg);
-       }
-
-       inline async command uint8_t IEEE154Packet.getLength(message_t* msg)
-       {
-               return getHeader(msg)->length;
-       }
-
-       inline async command void IEEE154Packet.setLength(message_t* msg, uint8_t length)
-       {
-               getHeader(msg)->length = length;
-       }
-
-       inline async command uint16_t IEEE154Packet.getFCF(message_t* msg)
-       {
-               return getHeader(msg)->fcf;
-       }
-
-       inline async command void IEEE154Packet.setFCF(message_t* msg, uint16_t fcf)
-       {
-               getHeader(msg)->fcf = fcf;
-       }
-
-       inline async command bool IEEE154Packet.isDataFrame(message_t* msg)
-       {
-               return (getHeader(msg)->fcf & IEEE154_DATA_FRAME_MASK) == IEEE154_DATA_FRAME_VALUE;
-       }
-
-       inline async command void IEEE154Packet.createDataFrame(message_t* msg)
-       {
-               getHeader(msg)->fcf = IEEE154_DATA_FRAME_VALUE;
-       }
-
-       inline async command bool IEEE154Packet.isAckFrame(message_t* msg)
-       {
-               return (getHeader(msg)->fcf & IEEE154_ACK_FRAME_MASK) == IEEE154_ACK_FRAME_VALUE;
-       }
-
-       inline async command void IEEE154Packet.createAckFrame(message_t* msg)
-       {
-               ieee154_header_t* header = getHeader(msg);
-
-               header->length = IEEE154_ACK_FRAME_LENGTH;
-               header->fcf = IEEE154_ACK_FRAME_VALUE;
-       }
-
-       inline async command void IEEE154Packet.createAckReply(message_t* data, message_t* ack)
-       {
-               ieee154_header_t* header = getHeader(ack);
-
-               header->length = IEEE154_ACK_FRAME_LENGTH;
-               header->fcf = IEEE154_ACK_FRAME_VALUE;
-               header->dsn = getHeader(data)->dsn;
-       }
-
-       inline async command bool IEEE154Packet.verifyAckReply(message_t* data, message_t* ack)
-       {
-               ieee154_header_t* header = getHeader(ack);
-
-               return header->dsn == getHeader(data)->dsn
-                       && (header->fcf & IEEE154_ACK_FRAME_MASK) == IEEE154_ACK_FRAME_VALUE;
-       }
-
-       inline async command bool IEEE154Packet.getAckRequired(message_t* msg)
-       {
-               return getHeader(msg)->fcf & (1 << IEEE154_FCF_ACK_REQ);
-       }
-
-       inline async command void IEEE154Packet.setAckRequired(message_t* msg, bool ack)
-       {
-               if( ack )
-                       getHeader(msg)->fcf |= (1 << IEEE154_FCF_ACK_REQ);
-               else
-                       getHeader(msg)->fcf &= ~(uint16_t)(1 << IEEE154_FCF_ACK_REQ);
-       }
-
-       inline async command bool IEEE154Packet.getFramePending(message_t* msg)
-       {
-               return getHeader(msg)->fcf & (1 << IEEE154_FCF_FRAME_PENDING);
-       }
-
-       inline async command void IEEE154Packet.setFramePending(message_t* msg, bool pending)
-       {
-               if( pending )
-                       getHeader(msg)->fcf |= (1 << IEEE154_FCF_FRAME_PENDING);
-               else
-                       getHeader(msg)->fcf &= ~(uint16_t)(1 << IEEE154_FCF_FRAME_PENDING);
-       }
-
-       inline async command uint8_t IEEE154Packet.getDSN(message_t* msg)
-       {
-               return getHeader(msg)->dsn;
-       }
-
-       inline async command void IEEE154Packet.setDSN(message_t* msg, uint8_t dsn)
-       {
-               getHeader(msg)->dsn = dsn;
-       }
-
-       inline async command uint16_t IEEE154Packet.getDestPan(message_t* msg)
-       {
-               return getHeader(msg)->destpan;
-       }
-
-       inline async command void IEEE154Packet.setDestPan(message_t* msg, uint16_t pan)
-       {
-               getHeader(msg)->destpan = pan;
-       }
-
-       inline async command uint16_t IEEE154Packet.getDestAddr(message_t* msg)
-       {
-               return getHeader(msg)->dest;
-       }
-
-       inline async command void IEEE154Packet.setDestAddr(message_t* msg, uint16_t addr)
-       {
-               getHeader(msg)->dest = addr;
-       }
-
-       inline async command uint16_t IEEE154Packet.getSrcAddr(message_t* msg)
-       {
-               return getHeader(msg)->src;
-       }
-
-       inline async command void IEEE154Packet.setSrcAddr(message_t* msg, uint16_t addr)
-       {
-               getHeader(msg)->src = addr;
-       }
-
-#ifndef TFRAMES_ENABLED
-
-       inline async command uint8_t IEEE154Packet.get6LowPan(message_t* msg)
-       {
-               return getHeader(msg)->network;
-       }
-
-       inline async command void IEEE154Packet.set6LowPan(message_t* msg, uint8_t network)
-       {
-               getHeader(msg)->network = network;
-       }
-
-#endif
-
-       inline async command am_id_t IEEE154Packet.getType(message_t* msg)
-       {
-               return getHeader(msg)->type;
-       }
-
-       inline async command void IEEE154Packet.setType(message_t* msg, am_id_t type)
-       {
-               getHeader(msg)->type = type;
-       }
-
-       async command bool IEEE154Packet.requiresAckWait(message_t* msg)
-       {
-               return call IEEE154Packet.getAckRequired(msg)
-                       && call IEEE154Packet.isDataFrame(msg)
-                       && call IEEE154Packet.getDestAddr(msg) != 0xFFFF;
-       }
-
-       async command bool IEEE154Packet.requiresAckReply(message_t* msg)
-       {
-               return call IEEE154Packet.getAckRequired(msg)
-                       && call IEEE154Packet.isDataFrame(msg)
-                       && call IEEE154Packet.getDestAddr(msg) == call ActiveMessageAddress.amAddress();
-       }
-
-       inline async event void ActiveMessageAddress.changed()
-       {
-       }
-
-/*----------------- AMPacket -----------------*/
-
-       inline command am_addr_t AMPacket.address()
-       {
-               return call ActiveMessageAddress.amAddress();
-       }
-       inline command am_group_t AMPacket.localGroup()
-       {
-               // TODO: check if this is correct
-               return call ActiveMessageAddress.amGroup();
-       }
-
-       inline command am_addr_t AMPacket.destination(message_t* msg)
-       {
-               return call IEEE154Packet.getDestAddr(msg);
-       }
-       inline command am_addr_t AMPacket.source(message_t* msg)
-       {
-               return call IEEE154Packet.getSrcAddr(msg);
-       }
-
-       inline command void AMPacket.setDestination(message_t* msg, am_addr_t addr)
-       {
-               call IEEE154Packet.setDestAddr(msg, addr);
-       }
-
-       inline command void AMPacket.setSource(message_t* msg, am_addr_t addr)
-       {
-               call IEEE154Packet.setSrcAddr(msg, addr);
-       }
-
-       inline command bool AMPacket.isForMe(message_t* msg)
-       {
-               am_addr_t addr = call AMPacket.destination(msg);
-               return addr == call AMPacket.address() || addr == AM_BROADCAST_ADDR;
-       }
-
-       inline command am_id_t AMPacket.type(message_t* msg)
-       {
-               return call IEEE154Packet.getType(msg);
-       }
-
-       inline command void AMPacket.setType(message_t* msg, am_id_t type)
-       {
-               call IEEE154Packet.setType(msg, type);
-       }
-  
-       inline command am_group_t AMPacket.group(message_t* msg) 
-       {
-               return call IEEE154Packet.getDestPan(msg);
-       }
-
-       inline command void AMPacket.setGroup(message_t* msg, am_group_t grp)
-       {
-               call IEEE154Packet.setDestPan(msg, grp);
-       }
-}
diff --git a/tos/chips/rf230/LowPowerListeningLayerC.nc b/tos/chips/rf230/LowPowerListeningLayerC.nc
deleted file mode 100644 (file)
index b1efca2..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#warning "*** USING LOW POWER LISTENING LAYER"
-
-configuration LowPowerListeningLayerC
-{
-       provides
-       {
-               interface SplitControl;
-               interface Send;
-               interface Receive;
-
-               interface LowPowerListening;
-       }
-       uses
-       {
-               interface SplitControl as SubControl;
-               interface Send as SubSend;
-               interface Receive as SubReceive;
-
-               interface PacketField<uint16_t> as PacketSleepInterval;
-               interface IEEE154Packet;
-               interface PacketAcknowledgements;
-       }
-}
-
-implementation
-{
-       components LowPowerListeningLayerP, new TimerMilliC();
-
-       SplitControl = LowPowerListeningLayerP;
-       Send = LowPowerListeningLayerP;
-       Receive = LowPowerListeningLayerP;
-       LowPowerListening = LowPowerListeningLayerP;
-
-       SubControl = LowPowerListeningLayerP;
-       SubSend = LowPowerListeningLayerP;
-       SubReceive = LowPowerListeningLayerP;
-       PacketSleepInterval = LowPowerListeningLayerP;
-       IEEE154Packet = LowPowerListeningLayerP;
-       PacketAcknowledgements = LowPowerListeningLayerP;
-       
-       LowPowerListeningLayerP.Timer -> TimerMilliC;
-}
diff --git a/tos/chips/rf230/LowPowerListeningLayerP.nc b/tos/chips/rf230/LowPowerListeningLayerP.nc
deleted file mode 100644 (file)
index ef4bac5..0000000
+++ /dev/null
@@ -1,443 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <RadioAssert.h>
-
-module LowPowerListeningLayerP
-{
-       provides
-       {
-               interface SplitControl;
-               interface Send;
-               interface Receive;
-
-               interface LowPowerListening;
-       }
-
-       uses
-       {
-               interface SplitControl as SubControl;
-               interface Send as SubSend;
-               interface Receive as SubReceive;
-
-               interface PacketField<uint16_t> as PacketSleepInterval;
-               interface IEEE154Packet;
-               interface PacketAcknowledgements;
-               interface Timer<TMilli>;
-       }
-}
-
-implementation
-{
-       enum
-       {
-               // minimum wakeup time to catch a transmission in milliseconds
-               LISTEN_WAKEUP = 6U,     // use xxxL if LISTEN_WAKEUP * 10000 > 65535
-
-               // extra wakeup time after receiving a message in milliseconds
-               AFTER_RECEIVE = 10U,
-
-               // extra wakeup time after transmitting a message in milliseconds
-               AFTER_TRANSMIT = 10U,
-
-               MIN_SLEEP = 2,          // the minimum sleep interval in milliseconds
-               MAX_SLEEP = 30000,      // the maximum sleep interval in milliseconds
-               MIN_DUTY = 2,           // the minimum duty cycle
-       };
-
-       uint16_t sleepInterval;
-
-       message_t* txMsg;
-       uint8_t txLen;
-       error_t txError;
-
-/*----------------- state machine -----------------*/
-
-       enum
-       {
-               OFF = 0,                                        
-               OFF_SUBSTOP = 1,                        // must have consecutive indices
-               OFF_SUBSTOP_DONE = 2,           // must have consecutive indices
-               OFF_STOP_END = 3,                       // must have consecutive indices
-               OFF_START_END = 4,
-
-               LISTEN_SUBSTART = 5,            // must have consecutive indices
-               LISTEN_SUBSTART_DONE = 6,       // must have consecutive indices
-               LISTEN_TIMER = 7,                       // must have consecutive indices
-               LISTEN = 8,                                     // must have consecutive indices
-
-               SLEEP_SUBSTOP = 9,                      // must have consecutive indices
-               SLEEP_SUBSTOP_DONE = 10,        // must have consecutive indices
-               SLEEP_TIMER = 11,                       // must have consecutive indices
-               SLEEP = 12,                                     // must have consecutive indices
-
-               SEND_SUBSTART = 13,                     // must have consecutive indices
-               SEND_SUBSTART_DONE = 14,        // must have consecutive indices
-               SEND_TIMER = 15,                        // must have consecutive indices
-               SEND_SUBSEND= 16,
-               SEND_SUBSEND_DONE = 17,
-               SEND_SUBSEND_DONE_LAST = 18,
-               SEND_DONE = 19,
-       };
-
-       uint8_t state;
-
-       task void transition()
-       {
-               error_t error;
-               uint16_t transmitInterval;
-
-               if( state == LISTEN_SUBSTART || state == SEND_SUBSTART )
-               {
-                       error = call SubControl.start();
-                       ASSERT( error == SUCCESS || error == EBUSY );
-
-                       if( error == SUCCESS )
-                               ++state;
-                       else
-                               post transition();
-               }
-               else if( state == SLEEP_SUBSTOP || state == OFF_SUBSTOP )
-               {
-                       error = call SubControl.stop();
-                       ASSERT( error == SUCCESS || error == EBUSY );
-
-                       if( error == SUCCESS )
-                               ++state;
-                       else
-                               post transition();
-               }
-               else if( state == OFF_START_END )
-               {
-                       state = LISTEN_SUBSTART;
-                       post transition();
-
-                       signal SplitControl.startDone(SUCCESS);
-               }
-               else if( state == OFF_STOP_END )
-               {
-                       state = OFF;
-                       signal SplitControl.stopDone(SUCCESS);
-               }
-               else if( state == LISTEN_TIMER )
-               {
-                       state = LISTEN;
-                       if( sleepInterval > 0 )
-                               call Timer.startOneShot(LISTEN_WAKEUP);
-               }
-               else if( state == SLEEP_TIMER )
-               {
-                       if( sleepInterval > 0 )
-                       {
-                               state = SLEEP;
-                               call Timer.startOneShot(sleepInterval);
-                       }
-                       else
-                       {
-                               state = LISTEN_SUBSTART;
-                               post transition();
-                       }
-               }
-               else if( state == SEND_TIMER )
-               {
-                       transmitInterval = call LowPowerListening.getRxSleepInterval(txMsg);
-
-                       if( transmitInterval > 0 )
-                               call Timer.startOneShot(transmitInterval);
-
-                       state = SEND_SUBSEND;
-                       post transition();
-               }
-               else if( state == SEND_SUBSEND)
-               {
-                       txError = call SubSend.send(txMsg, txLen);
-
-                       if( txError == SUCCESS )
-                               state = SEND_SUBSEND_DONE;
-                       else
-                       {
-                               state = SEND_DONE;
-                               post transition();
-                       }
-               }
-               else if( state == SEND_DONE )
-               {
-                       state = LISTEN;
-                       if( sleepInterval > 0 )
-                               call Timer.startOneShot(AFTER_TRANSMIT);
-
-                       signal Send.sendDone(txMsg, txError);
-               }
-       }
-
-       command error_t SplitControl.start()
-       {
-               if( state == OFF_START_END )
-                       return EBUSY;
-               else if( state != OFF )
-                       return EALREADY;
-
-               state = OFF_START_END;
-               post transition();
-
-               return SUCCESS;
-       }
-
-       event void SubControl.startDone(error_t error)
-       {
-               ASSERT( error == SUCCESS || error == EBUSY );
-               ASSERT( state == LISTEN_SUBSTART_DONE || state == SEND_SUBSTART_DONE );
-
-               if( error == SUCCESS )
-                       ++state;
-               else
-                       --state;
-
-               post transition();
-       }
-
-       command error_t SplitControl.stop()
-       {
-               if( state == SLEEP || state == LISTEN )
-               {
-                       call Timer.stop();
-                       post transition();
-               }
-
-               if( state == LISTEN_TIMER || state == LISTEN || state == SLEEP_SUBSTOP )
-                       state = OFF_SUBSTOP;
-               else if( state == SLEEP_SUBSTOP_DONE )
-                       state = OFF_SUBSTOP_DONE;
-               else if( state == LISTEN_SUBSTART || state == SLEEP_TIMER || state == SLEEP )
-                       state = OFF_STOP_END;
-               else if( state == OFF )
-                       return EALREADY;
-               else
-                       return EBUSY;
-
-               return SUCCESS;
-       }
-
-       event void SubControl.stopDone(error_t error)
-       {
-               ASSERT( error == SUCCESS || error == EBUSY );
-               ASSERT( state == SLEEP_SUBSTOP_DONE || state == OFF_SUBSTOP_DONE );
-
-               if( error == SUCCESS )
-                       ++state;
-               else
-                       --state;
-
-               post transition();
-       }
-
-       event void Timer.fired()
-       {
-               ASSERT( state == LISTEN || state == SLEEP || state == SEND_SUBSEND || state == SEND_SUBSEND_DONE );
-
-               if( state == LISTEN )
-                       state = SLEEP_SUBSTOP;
-               else if( state == SLEEP )
-                       state = LISTEN_SUBSTART;
-               else if( state == SEND_SUBSEND_DONE )
-                       state = SEND_SUBSEND_DONE_LAST;
-               else if( state == SEND_SUBSEND)
-                       state = SEND_DONE;
-
-               post transition();
-       }
-
-       event message_t* SubReceive.receive(message_t* msg, void* payload, uint8_t len)
-       {
-               if( state == SLEEP_SUBSTOP )
-                       state = LISTEN;
-
-               if( state == LISTEN && sleepInterval > 0 )
-                       call Timer.startOneShot(AFTER_RECEIVE);
-
-               return signal Receive.receive(msg, payload, len);
-       }
-
-       command error_t Send.send(message_t* msg, uint8_t len)
-       {
-               if( state == LISTEN || state == SLEEP )
-               {
-                       call Timer.stop();
-                       post transition();
-               }
-
-               if( state == LISTEN_SUBSTART || state == SLEEP_TIMER || state == SLEEP )
-                       state = SEND_SUBSTART;
-               else if( state == LISTEN_SUBSTART_DONE )
-                       state = SEND_SUBSTART_DONE;
-               else if( state == LISTEN_TIMER || state == SLEEP_SUBSTOP || state == LISTEN )
-                       state = SEND_TIMER;
-               else
-                       return EBUSY;
-
-               txMsg = msg;
-               txLen = len;
-               txError = FAIL;
-
-               return SUCCESS;
-       }
-
-       command error_t Send.cancel(message_t* msg)
-       {
-               if( state == SEND_SUBSEND )
-               {
-                       call Timer.stop();
-                       state = SEND_DONE;
-                       txError = ECANCEL;
-                       post transition();
-
-                       return SUCCESS;
-               }
-               else if( state == SEND_SUBSEND_DONE )
-               {
-                       // we stop sending the message even if SubSend.cancel was not succesfull
-                       state = SEND_SUBSEND_DONE_LAST;
-
-                       return call SubSend.cancel(txMsg);
-               }
-               else
-                       return FAIL;
-       }
-
-       event void SubSend.sendDone(message_t* msg, error_t error)
-       {
-               ASSERT( state == SEND_SUBSEND_DONE || state == SEND_SUBSEND_DONE_LAST );
-               ASSERT( msg == txMsg );
-
-               txError = error;
-
-               // TODO: extend the PacketAcknowledgements interface with getAckRequired
-               if( error != SUCCESS
-                       || call LowPowerListening.getRxSleepInterval(msg) == 0
-                       || state == SEND_SUBSEND_DONE_LAST
-                       || (call IEEE154Packet.getAckRequired(msg) && call PacketAcknowledgements.wasAcked(msg)) )
-               {
-                       call Timer.stop();
-                       state = SEND_DONE;
-               }
-               else
-                       state = SEND_SUBSEND;
-
-               post transition();
-       }
-
-       command uint8_t Send.maxPayloadLength()
-       {
-               return call SubSend.maxPayloadLength();
-       }
-
-       command void* Send.getPayload(message_t* msg, uint8_t len)
-       {
-               return call SubSend.getPayload(msg, len);
-       }
-
-/*----------------- LowPowerListening -----------------*/
-
-       command uint16_t LowPowerListening.dutyCycleToSleepInterval(uint16_t dutyCycle)
-       {
-               if( dutyCycle >= 10000 )
-                       return 0;
-               else if( dutyCycle <= MIN_DUTY  )
-                       return MAX_SLEEP;
-
-               return ((10000U * LISTEN_WAKEUP) / dutyCycle) - LISTEN_WAKEUP;
-       }
-
-       command uint16_t LowPowerListening.sleepIntervalToDutyCycle(uint16_t interval)
-       {
-               if( interval < MIN_SLEEP )
-                       return 10000;
-               else if( interval >= MAX_SLEEP )
-                       return MIN_DUTY;
-
-               return (10000U * LISTEN_WAKEUP) / (LISTEN_WAKEUP + interval);
-       }
-
-       command void LowPowerListening.setLocalSleepInterval(uint16_t interval)
-    {
-               if( interval < MIN_SLEEP )
-                       interval = 0;
-               else if( interval > MAX_SLEEP )
-                       interval = MAX_SLEEP;
-
-               sleepInterval = interval;
-
-               if( (state == LISTEN && sleepInterval == 0) || state == SLEEP )
-               {
-                       call Timer.stop();
-                       --state;
-                       post transition();
-               }
-       }
-
-       command uint16_t LowPowerListening.getLocalSleepInterval()
-    {  
-               return sleepInterval;
-       }
-
-       command void LowPowerListening.setLocalDutyCycle(uint16_t dutyCycle)
-       {
-               call LowPowerListening.setLocalSleepInterval(
-                       call LowPowerListening.dutyCycleToSleepInterval(dutyCycle));
-       }
-
-       command uint16_t LowPowerListening.getLocalDutyCycle()
-       {
-               return call LowPowerListening.sleepIntervalToDutyCycle(sleepInterval);
-       }
-
-       command void LowPowerListening.setRxSleepInterval(message_t *msg, uint16_t interval)
-       {
-               if( interval < MIN_SLEEP )
-                       interval = 0;
-               else if( interval > MAX_SLEEP )
-                       interval = MAX_SLEEP;
-
-               call PacketSleepInterval.set(msg, interval);
-       }
-
-       command uint16_t LowPowerListening.getRxSleepInterval(message_t *msg)
-    {
-               if( ! call PacketSleepInterval.isSet(msg) )
-                       return sleepInterval;
-
-               return call PacketSleepInterval.get(msg);
-       }
-
-       command void LowPowerListening.setRxDutyCycle(message_t *msg, uint16_t dutyCycle)
-    {
-               call LowPowerListening.setRxSleepInterval(msg, 
-                       call LowPowerListening.dutyCycleToSleepInterval(dutyCycle));
-       }
-
-       command uint16_t LowPowerListening.getRxDutyCycle(message_t *msg)
-    {
-               return call LowPowerListening.sleepIntervalToDutyCycle(
-                       call LowPowerListening.getRxSleepInterval(msg));
-       }
-}
diff --git a/tos/chips/rf230/MessageBufferLayerC.nc b/tos/chips/rf230/MessageBufferLayerC.nc
deleted file mode 100644 (file)
index 89f0059..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration MessageBufferLayerC
-{
-       provides
-       {
-               interface SplitControl;
-               interface Send;
-               interface Receive;
-       }
-       uses
-       {
-               interface RadioState;
-               interface RadioSend;
-               interface RadioReceive;
-
-               interface Packet;
-       }
-}
-
-implementation
-{
-       components MessageBufferLayerP, MainC, TaskletC;
-
-       MainC.SoftwareInit -> MessageBufferLayerP;
-
-       SplitControl = MessageBufferLayerP;
-       Send = MessageBufferLayerP;
-       Receive = MessageBufferLayerP.Receive;
-
-       RadioState = MessageBufferLayerP;
-       MessageBufferLayerP.Tasklet -> TaskletC;
-       RadioSend = MessageBufferLayerP;
-       RadioReceive = MessageBufferLayerP;
-
-       Packet = MessageBufferLayerP;
-}
diff --git a/tos/chips/rf230/MessageBufferLayerP.nc b/tos/chips/rf230/MessageBufferLayerP.nc
deleted file mode 100644 (file)
index 738835b..0000000
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-#include <RadioAssert.h>
-
-module MessageBufferLayerP
-{
-       provides
-       {
-               interface SplitControl;
-               interface Init as SoftwareInit;
-
-               interface Send;
-               interface Receive;
-       }
-       uses
-       {
-               interface RadioState;
-               interface Tasklet;
-               interface RadioSend;
-               interface RadioReceive;
-
-               interface Packet;
-       }
-}
-
-implementation
-{
-/*----------------- State -----------------*/
-
-       norace uint8_t state;   // written only from tasks
-       enum
-       {
-               STATE_READY = 0,
-               STATE_TX_PENDING = 1,
-               STATE_TX_SEND = 2,
-               STATE_TX_DONE = 3,
-               STATE_TURN_ON = 4,
-               STATE_TURN_OFF = 5,
-       };
-
-       command error_t SplitControl.start()
-       {
-               error_t error;
-
-               call Tasklet.suspend();
-
-               if( state != STATE_READY )
-                       error = EBUSY;
-               else
-                       error = call RadioState.turnOn();
-
-               if( error == SUCCESS )
-                       state = STATE_TURN_ON;
-
-               call Tasklet.resume();
-
-               return error;
-       }
-
-       command error_t SplitControl.stop()
-       {
-               error_t error;
-
-               call Tasklet.suspend();
-
-               if( state != STATE_READY )
-                       error = EBUSY;
-               else
-                       error = call RadioState.turnOff();
-
-               if( error == SUCCESS )
-                       state = STATE_TURN_OFF;
-
-               call Tasklet.resume();
-
-               return error;
-       }
-
-       task void stateDoneTask()
-       {
-               uint8_t s;
-               
-               s = state;
-
-               // change the state before so we can be reentered from the event
-               if( s == STATE_TURN_ON || s == STATE_TURN_OFF )
-                       state = STATE_READY;
-
-               if( s == STATE_TURN_ON )
-                       signal SplitControl.startDone(SUCCESS);
-               else
-                       signal SplitControl.stopDone(SUCCESS);
-       }
-
-       tasklet_async event void RadioState.done()
-       {
-               post stateDoneTask();
-       }
-
-       default event void SplitControl.startDone(error_t error)
-       {
-       }
-
-       default event void SplitControl.stopDone(error_t error)
-       {
-       }
-
-/*----------------- Send -----------------*/
-
-       message_t* txMsg;
-       error_t txError;
-       uint8_t retries;
-
-       // Many EBUSY replies from RadioSend are normal if the channel is cognested
-       enum { MAX_RETRIES = 5 };
-
-       task void sendTask()
-       {
-               error_t error;
-
-               ASSERT( state == STATE_TX_PENDING || state == STATE_TX_SEND );
-
-               atomic error = txError;
-               if( (state == STATE_TX_SEND && error == SUCCESS) || ++retries > MAX_RETRIES )
-                       state = STATE_TX_DONE;
-               else
-               {
-                       call Tasklet.suspend();
-
-                       error = call RadioSend.send(txMsg);
-                       if( error == SUCCESS )
-                               state = STATE_TX_SEND;
-                       else if( retries == MAX_RETRIES )
-                               state = STATE_TX_DONE;
-                       else
-                               state = STATE_TX_PENDING;
-
-                       call Tasklet.resume();
-               }
-
-               if( state == STATE_TX_DONE )
-               {
-                       state = STATE_READY;
-                       signal Send.sendDone(txMsg, error);
-               }
-       }
-
-       tasklet_async event void RadioSend.sendDone(error_t error)
-       {
-               ASSERT( state == STATE_TX_SEND );
-
-               atomic txError = error;
-               post sendTask();
-       }
-
-       command error_t Send.send(message_t* msg, uint8_t len)
-       {
-               if( len > call Packet.maxPayloadLength() )
-                       return EINVAL;
-               else if( state != STATE_READY )
-                       return EBUSY;
-
-               call Packet.setPayloadLength(msg, len);
-
-               txMsg = msg;
-               state = STATE_TX_PENDING;
-               retries = 0;
-               post sendTask();
-
-               return SUCCESS;
-       }
-
-       tasklet_async event void RadioSend.ready()
-       {
-               if( state == STATE_TX_PENDING )
-                       post sendTask();
-       }
-
-       tasklet_async event void Tasklet.run()
-       {
-       }
-
-       command error_t Send.cancel(message_t* msg)
-       {
-               if( state == STATE_TX_PENDING )
-               {
-                       state = STATE_READY;
-
-                       // TODO: check if sendDone can be called before cancel returns
-                       signal Send.sendDone(msg, ECANCEL);
-
-                       return SUCCESS;
-               }
-               else
-                       return FAIL;
-       }
-
-       default event void Send.sendDone(message_t* msg, error_t error)
-       {
-       }
-
-       inline command uint8_t Send.maxPayloadLength()
-       {
-               return call Packet.maxPayloadLength();
-       }
-
-       inline command void* Send.getPayload(message_t* msg, uint8_t len)
-       {
-               return call Packet.getPayload(msg, len);
-       }
-
-/*----------------- Receive -----------------*/
-
-       enum
-       {
-               RECEIVE_QUEUE_SIZE = 3,
-       };
-
-       message_t receiveQueueData[RECEIVE_QUEUE_SIZE];
-       message_t* receiveQueue[RECEIVE_QUEUE_SIZE];
-
-       uint8_t receiveQueueHead;
-       uint8_t receiveQueueSize;
-
-       command error_t SoftwareInit.init()
-       {
-               uint8_t i;
-
-               for(i = 0; i < RECEIVE_QUEUE_SIZE; ++i)
-                       receiveQueue[i] = receiveQueueData + i;
-
-               return SUCCESS;
-       }
-
-       tasklet_async event bool RadioReceive.header(message_t* msg)
-       {
-               bool notFull;
-
-               // this prevents undeliverable messages to be acknowledged
-               atomic notFull = receiveQueueSize < RECEIVE_QUEUE_SIZE;
-
-               return notFull;
-       }
-
-       task void deliverTask()
-       {
-               // get rid of as many messages as possible without interveining tasks
-               for(;;)
-               {
-                       message_t* msg;
-
-                       atomic
-                       {
-                               if( receiveQueueSize == 0 )
-                                       return;
-
-                               msg = receiveQueue[receiveQueueHead];
-                       }
-
-                       msg = signal Receive.receive(msg, 
-                               call Packet.getPayload(msg, call Packet.maxPayloadLength()), 
-                               call Packet.payloadLength(msg));
-
-                       atomic
-                       {
-                               receiveQueue[receiveQueueHead] = msg;
-
-                               if( ++receiveQueueHead >= RECEIVE_QUEUE_SIZE )
-                                       receiveQueueHead = 0;
-
-                               --receiveQueueSize;
-                       }
-               }
-       }
-
-       tasklet_async event message_t* RadioReceive.receive(message_t* msg)
-       {
-               message_t *m;
-
-               atomic
-               {
-                       if( receiveQueueSize >= RECEIVE_QUEUE_SIZE )
-                               m = msg;
-                       else
-                       {
-                               uint8_t index = receiveQueueHead + receiveQueueSize;
-                               if( index >= RECEIVE_QUEUE_SIZE )
-                                       index -= RECEIVE_QUEUE_SIZE;
-
-                               m = receiveQueue[index];
-                               receiveQueue[index] = msg;
-
-                               ++receiveQueueSize;
-                               post deliverTask();
-                       }
-               }
-
-               return m;
-       }
-
-       default event message_t* Receive.receive(message_t* msg, void* payload, uint8_t len)
-       {
-               return msg;
-       }
-}
diff --git a/tos/chips/rf230/Neighborhood.h b/tos/chips/rf230/Neighborhood.h
deleted file mode 100644 (file)
index 40884e3..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#ifndef __NEIGHBORHOOD_H__
-#define __NEIGHBORHOOD_H__
-
-#ifndef NEIGHBORHOOD_SIZE
-#define NEIGHBORHOOD_SIZE      5
-#endif
-
-#endif//__NEIGHBORHOOD_H__
diff --git a/tos/chips/rf230/Neighborhood.nc b/tos/chips/rf230/Neighborhood.nc
deleted file mode 100644 (file)
index cc4b7db..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-/**
- * Every component maintains its own neighborhood data. The Neighboorhood
- * component maintains only the nodeids and ages of the neighbors, and
- * evicts old entries from the table when necessary.
- */
-interface Neighborhood
-{
-       /**
-        * Returns the index of the neighbor in the table. If the node was not 
-        * found in the table, then the value NEIGHBORHOOD is  returned, 
-        * otherwise an index in the range [0, NEIGHBORHOOD-1] is returned.
-        */
-       tasklet_async command uint8_t getIndex(am_addr_t id);
-
-       /**
-        * Returns the age of the given entry. The age is incremented by one
-        * every time a new node is inserted into the neighborhood table that
-        * is not already at the very end. If the age would get too large to
-        * fit into a byte, then it is periodically reset to a smaller value.
-        */
-       tasklet_async command uint8_t getAge(uint8_t index);
-
-       /**
-        * Returns the node address for the given entry.
-        */
-       tasklet_async command am_addr_t getNode(uint8_t index);
-
-       /**
-        * Adds a new node into the neighborhood table. If this node was already
-        * in the table, then it is just brought to the front (its age is reset
-        * to zero). If the node was not in the table, then the oldest is evicted
-        * and its entry is replaced with this node. The index of the entry
-        * is returned in the range [0, NEIGHBORHOOD-1]. 
-        */
-       tasklet_async command uint8_t insertNode(am_addr_t id);
-
-       /**
-        * This event is fired when the oldest entry is replaced with a new
-        * node. The same interface is used by many users, so all of them
-        * will receive this event and can clear the corresponding entry.
-        * After this event is fired, all flags for this entry are cleared
-        * (see the NeighborhoodFlag interface)
-        */
-       tasklet_async event void evicted(uint8_t index);
-}
diff --git a/tos/chips/rf230/NeighborhoodC.nc b/tos/chips/rf230/NeighborhoodC.nc
deleted file mode 100644 (file)
index e2ba9b5..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration NeighborhoodC
-{
-       provides interface Neighborhood;
-}
-
-implementation
-{
-       components NeighborhoodP, MainC;
-
-       Neighborhood = NeighborhoodP;
-       MainC.SoftwareInit -> NeighborhoodP;
-}
diff --git a/tos/chips/rf230/NeighborhoodFlag.nc b/tos/chips/rf230/NeighborhoodFlag.nc
deleted file mode 100644 (file)
index e1dda90..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-/**
- * This interface provides one bit storage for each neighbor in a very
- * fast and conveint way (without using shifts for example). 
- */
-interface NeighborhoodFlag
-{
-       /**
-        * Returns the value of the flag for the given index
-        */
-       tasklet_async command bool get(uint8_t index);
-       
-       /**
-        * Sets the flag for the given index
-        */
-       tasklet_async command void set(uint8_t index);
-
-       /**
-        * Clears the flag for the given index. The flag is automatically
-        * cleared after the Neighborhood.evicted event is fired.
-        */
-       tasklet_async command void clear(uint8_t index);
-
-       /**
-        * Clears the flag for all indices
-        */
-       tasklet_async command void clearAll();
-}
diff --git a/tos/chips/rf230/NeighborhoodFlagC.nc b/tos/chips/rf230/NeighborhoodFlagC.nc
deleted file mode 100644 (file)
index 2f064eb..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-generic configuration NeighborhoodFlagC()
-{
-       provides interface NeighborhoodFlag;
-}
-
-implementation
-{
-       components NeighborhoodP;
-
-       // TODO: make sure that no more than 8 flags are used at a time
-       NeighborhoodFlag = NeighborhoodP.NeighborhoodFlag[unique("NeighborhoodFlag")];
-}
diff --git a/tos/chips/rf230/NeighborhoodP.nc b/tos/chips/rf230/NeighborhoodP.nc
deleted file mode 100644 (file)
index fb84dc8..0000000
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Neighborhood.h>
-
-module NeighborhoodP
-{
-       provides
-       {
-               interface Init;
-               interface Neighborhood;
-               interface NeighborhoodFlag[uint8_t bit];
-       }
-}
-
-implementation
-{
-       tasklet_norace am_addr_t nodes[NEIGHBORHOOD_SIZE];
-       tasklet_norace uint8_t ages[NEIGHBORHOOD_SIZE];
-       tasklet_norace uint8_t flags[NEIGHBORHOOD_SIZE];
-       tasklet_norace uint8_t time;
-       tasklet_norace uint8_t last;
-
-       command error_t Init.init()
-       {
-               uint8_t i;
-
-               for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
-                       nodes[i] = AM_BROADCAST_ADDR;
-       
-               return SUCCESS;
-       }
-
-       inline tasklet_async command am_addr_t Neighborhood.getNode(uint8_t index)
-       {
-               return nodes[index];
-       }
-
-       inline tasklet_async command uint8_t Neighborhood.getAge(uint8_t index)
-       {
-               return time - ages[index];
-       }
-
-       tasklet_async uint8_t command Neighborhood.getIndex(am_addr_t node)
-       {
-               uint8_t i;
-
-               if( nodes[last] == node )
-                       return last;
-
-               for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
-               {
-                       if( nodes[i] == node )
-                       {
-                               last = i;
-                               break;
-                       }
-               }
-
-               return i;
-       }
-
-       tasklet_async uint8_t command Neighborhood.insertNode(am_addr_t node)
-       {
-               uint8_t i;
-               uint8_t maxAge;
-
-               if( nodes[last] == node )
-               {
-                       if( ages[last] == time )
-                               return last;
-
-                       ages[last] = ++time;
-                       maxAge = 0x80;
-               }
-               else
-               {
-                       uint8_t oldest = 0;
-                       maxAge = 0;
-
-                       for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
-                       {
-                               uint8_t age;
-
-                               if( nodes[i] == node )
-                               {
-                                       last = i;
-                                       if( ages[i] == time )
-                                               return i;
-
-                                       ages[i] = ++time;
-                                       maxAge = 0x80;
-                                       break;
-                               }
-
-                               age = time - ages[i];
-                               if( age > maxAge )
-                               {
-                                       maxAge = age;
-                                       oldest = i;
-                               }
-                       }
-
-                       if( i == NEIGHBORHOOD_SIZE )
-                       {
-                               signal Neighborhood.evicted(oldest);
-
-                               last = oldest;
-                               nodes[oldest] = node;
-                               ages[oldest] = ++time;
-                               flags[oldest] = 0;
-                       }
-               }
-
-               if( (time & 0x7F) == 0x7F && maxAge >= 0x7F )
-               {
-                       for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
-                       {
-                               if( (ages[i] | 0x7F) != time )
-                                       ages[i] = time & 0x80;
-                       }
-               }
-
-               return last;
-       }
-
-       inline tasklet_async command bool NeighborhoodFlag.get[uint8_t bit](uint8_t index)
-       {
-               return flags[index] & (1 << bit);
-       }
-
-       inline tasklet_async command void NeighborhoodFlag.set[uint8_t bit](uint8_t index)
-       {
-               flags[index] |= (1 << bit);
-       }
-
-       inline tasklet_async command void NeighborhoodFlag.clear[uint8_t bit](uint8_t index)
-       {
-               flags[index] &= ~(1 << bit);
-       }
-
-       tasklet_async command void NeighborhoodFlag.clearAll[uint8_t bit]()
-       {
-               uint8_t i;
-
-               bit = ~(1 << bit);
-
-               for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
-                       flags[i] &= bit;
-       }
-}
diff --git a/tos/chips/rf230/PacketField.nc b/tos/chips/rf230/PacketField.nc
deleted file mode 100644 (file)
index 3f90293..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-interface PacketField<value_type>
-{
-       /**
-        * Returns TRUE if the value is set for this message.
-        */
-       async command bool isSet(message_t* msg);
-
-       /**
-        * Returns the stored value of this field in the message. If the
-        * value is not set, then the returned value is undefined.
-        */
-       async command value_type get(message_t* msg);
-
-       /**
-        * Clears the isSet flag.
-        */
-       async command void clear(message_t* msg);
-
-       /**
-        * Sets the isSet false to TRUE and the time stamp value to the 
-        * specified value.
-        */
-       async command void set(message_t* msg, value_type value);
-}
diff --git a/tos/chips/rf230/RF230.h b/tos/chips/rf230/RF230.h
deleted file mode 100644 (file)
index 781a133..0000000
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#ifndef __RF230_H__
-#define __RF230_H__
-
-enum rf230_registers_enum
-{
-       RF230_TRX_STATUS = 0x01,
-       RF230_TRX_STATE = 0x02,
-       RF230_TRX_CTRL_0 = 0x03,
-       RF230_PHY_TX_PWR = 0x05,
-       RF230_PHY_RSSI = 0x06,
-       RF230_PHY_ED_LEVEL = 0x07,
-       RF230_PHY_CC_CCA = 0x08,
-       RF230_CCA_THRES = 0x09,
-       RF230_IRQ_MASK = 0x0E,
-       RF230_IRQ_STATUS = 0x0F,
-       RF230_VREG_CTRL = 0x10,
-       RF230_BATMON = 0x11,
-       RF230_XOSC_CTRL = 0x12,
-       RF230_PLL_CF = 0x1A,
-       RF230_PLL_DCU = 0x1B,
-       RF230_PART_NUM = 0x1C,
-       RF230_VERSION_NUM = 0x1D,
-       RF230_MAN_ID_0 = 0x1E,
-       RF230_MAN_ID_1 = 0x1F,
-       RF230_SHORT_ADDR_0 = 0x20,
-       RF230_SHORT_ADDR_1 = 0x21,
-       RF230_PAN_ID_0 = 0x22,
-       RF230_PAN_ID_1 = 0x23,
-       RF230_IEEE_ADDR_0 = 0x24,
-       RF230_IEEE_ADDR_1 = 0x25,
-       RF230_IEEE_ADDR_2 = 0x26,
-       RF230_IEEE_ADDR_3 = 0x27,
-       RF230_IEEE_ADDR_4 = 0x28,
-       RF230_IEEE_ADDR_5 = 0x29,
-       RF230_IEEE_ADDR_6 = 0x2A,
-       RF230_IEEE_ADDR_7 = 0x2B,
-       RF230_XAH_CTRL = 0x2C,
-       RF230_CSMA_SEED_0 = 0x2D,
-       RF230_CSMA_SEED_1 = 0x2E,
-};
-
-enum rf230_trx_register_enums
-{
-       RF230_CCA_DONE = 1 << 7,
-       RF230_CCA_STATUS = 1 << 6,
-       RF230_TRX_STATUS_MASK = 0x1F,
-       RF230_P_ON = 0,
-       RF230_BUSY_RX = 1,
-       RF230_BUSY_TX = 2,
-       RF230_RX_ON = 6,
-       RF230_TRX_OFF = 8,
-       RF230_PLL_ON = 9,
-       RF230_SLEEP = 15,
-       RF230_BUSY_RX_AACK = 16,
-       RF230_BUSR_TX_ARET = 17,
-       RF230_RX_AACK_ON = 22,
-       RF230_TX_ARET_ON = 25,
-       RF230_RX_ON_NOCLK = 28,
-       RF230_AACK_ON_NOCLK = 29,
-       RF230_BUSY_RX_AACK_NOCLK = 30,
-       RF230_STATE_TRANSITION_IN_PROGRESS = 31,
-       RF230_TRAC_STATUS_MASK = 0xE0,
-       RF230_TRAC_SUCCESS = 0,
-       RF230_TRAC_CHANNEL_ACCESS_FAILURE = 3 << 5,
-       RF230_TRAC_NO_ACK = 5 << 5,
-       RF230_TRX_CMD_MASK = 0x1F,
-       RF230_NOP = 0,
-       RF230_TX_START = 2,
-       RF230_FORCE_TRX_OFF = 3,
-};
-
-enum rf230_phy_register_enums
-{
-       RF230_TX_AUTO_CRC_ON = 1 << 7,
-       RF230_TX_PWR_MASK = 0x0F,
-       RF230_TX_PWR_DEFAULT = 0,
-       RF230_RSSI_MASK = 0x1F,
-       RF230_CCA_REQUEST = 1 << 7,
-       RF230_CCA_MODE_0 = 0 << 5,
-       RF230_CCA_MODE_1 = 1 << 5,
-       RF230_CCA_MODE_2 = 2 << 5,
-       RF230_CCA_MODE_3 = 3 << 5,
-       RF230_CHANNEL_DEFAULT = 11,
-       RF230_CHANNEL_MASK = 0x1F,
-       RF230_CCA_CS_THRES_SHIFT = 4,
-       RF230_CCA_ED_THRES_SHIFT = 0,
-};
-
-enum rf230_irq_register_enums
-{
-       RF230_IRQ_BAT_LOW = 1 << 7,
-       RF230_IRQ_TRX_UR = 1 << 6,
-       RF230_IRQ_TRX_END = 1 << 3,
-       RF230_IRQ_RX_START = 1 << 2,
-       RF230_IRQ_PLL_UNLOCK = 1 << 1,
-       RF230_IRQ_PLL_LOCK = 1 << 0,
-};
-
-enum rf230_control_register_enums
-{
-       RF230_AVREG_EXT = 1 << 7,
-       RF230_AVDD_OK = 1 << 6,
-       RF230_DVREG_EXT = 1 << 3,
-       RF230_DVDD_OK = 1 << 2,
-       RF230_BATMON_OK = 1 << 5,
-       RF230_BATMON_VHR = 1 << 4,
-       RF230_BATMON_VTH_MASK = 0x0F,
-       RF230_XTAL_MODE_OFF = 0 << 4,
-       RF230_XTAL_MODE_EXTERNAL = 4 << 4,
-       RF230_XTAL_MODE_INTERNAL = 15 << 4,
-};
-
-enum rf230_pll_register_enums
-{
-       RF230_PLL_CF_START = 1 << 7,
-       RF230_PLL_DCU_START = 1 << 7,
-};
-
-enum rf230_spi_command_enums
-{
-       RF230_CMD_REGISTER_READ = 0x80,
-       RF230_CMD_REGISTER_WRITE = 0xC0,
-       RF230_CMD_REGISTER_MASK = 0x3F,
-       RF230_CMD_FRAME_READ = 0x20,
-       RF230_CMD_FRAME_WRITE = 0x60,
-       RF230_CMD_SRAM_READ = 0x00,
-       RF230_CMD_SRAM_WRITE = 0x40,
-};
-
-#endif//__RF230_H__
diff --git a/tos/chips/rf230/RF230ActiveMessageC.nc b/tos/chips/rf230/RF230ActiveMessageC.nc
deleted file mode 100644 (file)
index 96a6fa7..0000000
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <HplRF230.h>
-
-configuration RF230ActiveMessageC
-{
-       provides 
-       {
-               interface SplitControl;
-
-               interface AMSend[am_id_t id];
-               interface Receive[am_id_t id];
-               interface Receive as Snoop[am_id_t id];
-
-               interface Packet;
-               interface AMPacket;
-               interface PacketAcknowledgements;
-               interface LowPowerListening;
-
-               interface PacketField<uint8_t> as PacketLinkQuality;
-               interface PacketField<uint8_t> as PacketTransmitPower;
-               interface PacketField<uint8_t> as PacketRSSI;
-
-               interface PacketTimeStamp<TRF230, uint32_t> as PacketTimeStampRadio;
-               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
-       }
-}
-
-implementation
-{
-       components RF230ActiveMessageP, RF230PacketC, IEEE154PacketC, RadioAlarmC;
-
-#ifdef RF230_DEBUG
-       components AssertC;
-#endif
-
-       RF230ActiveMessageP.IEEE154Packet -> IEEE154PacketC;
-       RF230ActiveMessageP.Packet -> RF230PacketC;
-       RF230ActiveMessageP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
-
-       Packet = RF230PacketC;
-       AMPacket = RF230PacketC;
-       PacketAcknowledgements = RF230PacketC;
-       PacketLinkQuality = RF230PacketC.PacketLinkQuality;
-       PacketTransmitPower = RF230PacketC.PacketTransmitPower;
-       PacketRSSI = RF230PacketC.PacketRSSI;
-       PacketTimeStampRadio = RF230PacketC;
-       PacketTimeStampMilli = RF230PacketC;
-       LowPowerListening = LowPowerListeningLayerC;
-
-       components ActiveMessageLayerC;
-#ifdef TFRAMES_ENABLED
-       components new DummyLayerC() as IEEE154NetworkLayerC;
-#else
-       components IEEE154NetworkLayerC;
-#endif
-#ifdef LOW_POWER_LISTENING
-       components LowPowerListeningLayerC;
-#else  
-       components new DummyLayerC() as LowPowerListeningLayerC;
-#endif
-       components MessageBufferLayerC;
-       components UniqueLayerC;
-       components TrafficMonitorLayerC;
-#ifdef RF230_SLOTTED_MAC
-       components SlottedCollisionLayerC as CollisionAvoidanceLayerC;
-#else
-       components RandomCollisionLayerC as CollisionAvoidanceLayerC;
-#endif
-       components SoftwareAckLayerC;
-       components new DummyLayerC() as CsmaLayerC;
-       components RF230LayerC;
-
-       SplitControl = LowPowerListeningLayerC;
-       AMSend = ActiveMessageLayerC;
-       Receive = ActiveMessageLayerC.Receive;
-       Snoop = ActiveMessageLayerC.Snoop;
-
-       ActiveMessageLayerC.Config -> RF230ActiveMessageP;
-       ActiveMessageLayerC.AMPacket -> IEEE154PacketC;
-       ActiveMessageLayerC.SubSend -> IEEE154NetworkLayerC;
-       ActiveMessageLayerC.SubReceive -> IEEE154NetworkLayerC;
-
-       IEEE154NetworkLayerC.SubSend -> UniqueLayerC;
-       IEEE154NetworkLayerC.SubReceive -> LowPowerListeningLayerC;
-
-       // the UniqueLayer is wired at two points
-       UniqueLayerC.Config -> RF230ActiveMessageP;
-       UniqueLayerC.SubSend -> LowPowerListeningLayerC;
-
-       LowPowerListeningLayerC.SubControl -> MessageBufferLayerC;
-       LowPowerListeningLayerC.SubSend -> MessageBufferLayerC;
-       LowPowerListeningLayerC.SubReceive -> MessageBufferLayerC;
-#ifdef LOW_POWER_LISTENING
-       LowPowerListeningLayerC.PacketSleepInterval -> RF230PacketC;
-       LowPowerListeningLayerC.IEEE154Packet -> IEEE154PacketC;
-       LowPowerListeningLayerC.PacketAcknowledgements -> RF230PacketC;
-#endif
-
-       MessageBufferLayerC.Packet -> RF230PacketC;
-       MessageBufferLayerC.RadioSend -> TrafficMonitorLayerC;
-       MessageBufferLayerC.RadioReceive -> UniqueLayerC;
-       MessageBufferLayerC.RadioState -> TrafficMonitorLayerC;
-
-       UniqueLayerC.SubReceive -> TrafficMonitorLayerC;
-
-       TrafficMonitorLayerC.Config -> RF230ActiveMessageP;
-       TrafficMonitorLayerC.SubSend -> CollisionAvoidanceLayerC;
-       TrafficMonitorLayerC.SubReceive -> CollisionAvoidanceLayerC;
-       TrafficMonitorLayerC.SubState -> RF230LayerC;
-
-       CollisionAvoidanceLayerC.Config -> RF230ActiveMessageP;
-       CollisionAvoidanceLayerC.SubSend -> SoftwareAckLayerC;
-       CollisionAvoidanceLayerC.SubReceive -> SoftwareAckLayerC;
-
-       SoftwareAckLayerC.Config -> RF230ActiveMessageP;
-       SoftwareAckLayerC.SubSend -> CsmaLayerC;
-       SoftwareAckLayerC.SubReceive -> RF230LayerC;
-
-       CsmaLayerC.Config -> RF230ActiveMessageP;
-       CsmaLayerC -> RF230LayerC.RadioSend;
-       CsmaLayerC -> RF230LayerC.RadioCCA;
-
-       RF230LayerC.RF230Config -> RF230ActiveMessageP;
-}
diff --git a/tos/chips/rf230/RF230ActiveMessageP.nc b/tos/chips/rf230/RF230ActiveMessageP.nc
deleted file mode 100644 (file)
index 0337bbd..0000000
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <RF230Packet.h>
-#include <HplRF230.h>
-#include <Tasklet.h>
-
-module RF230ActiveMessageP
-{
-       provides
-       {
-               interface RF230Config;
-               interface SoftwareAckConfig;
-               interface UniqueConfig;
-               interface CsmaConfig;
-               interface TrafficMonitorConfig;
-               interface RandomCollisionConfig;
-               interface SlottedCollisionConfig;
-               interface ActiveMessageConfig;
-               interface DummyConfig;
-       }
-
-       uses
-       {
-               interface IEEE154Packet;
-               interface Packet;
-               interface RadioAlarm;
-       }
-}
-
-implementation
-{
-/*----------------- RF230Config -----------------*/
-
-       async command uint8_t RF230Config.getLength(message_t* msg)
-       {
-               return call IEEE154Packet.getLength(msg);
-       }
-
-       async command void RF230Config.setLength(message_t* msg, uint8_t len)
-       {
-               call IEEE154Packet.setLength(msg, len);
-       }
-
-       async command uint8_t* RF230Config.getPayload(message_t* msg)
-       {
-               return ((uint8_t*)(call IEEE154Packet.getHeader(msg))) + 1;
-       }
-
-       inline rf230packet_metadata_t* getMeta(message_t* msg)
-       {
-               return (rf230packet_metadata_t*)(msg->metadata);
-       }
-
-       async command uint8_t RF230Config.getHeaderLength()
-       {
-               // we need the fcf, dsn, destpan and dest
-               return 7;
-       }
-
-       async command uint8_t RF230Config.getMaxLength()
-       {
-               // note, that the ieee154_footer_t is not stored, but we should include it here
-               return sizeof(rf230packet_header_t) - 1 + TOSH_DATA_LENGTH + sizeof(ieee154_footer_t);
-       }
-
-       async command uint8_t RF230Config.getDefaultChannel()
-       {
-               return RF230_DEF_CHANNEL;
-       }
-
-       async command bool RF230Config.requiresRssiCca(message_t* msg)
-       {
-               return call IEEE154Packet.isDataFrame(msg);
-       }
-
-/*----------------- SoftwareAckConfig -----------------*/
-
-       async command bool SoftwareAckConfig.requiresAckWait(message_t* msg)
-       {
-               return call IEEE154Packet.requiresAckWait(msg);
-       }
-
-       async command bool SoftwareAckConfig.isAckPacket(message_t* msg)
-       {
-               return call IEEE154Packet.isAckFrame(msg);
-       }
-
-       async command bool SoftwareAckConfig.verifyAckPacket(message_t* data, message_t* ack)
-       {
-               return call IEEE154Packet.verifyAckReply(data, ack);
-       }
-
-       async command bool SoftwareAckConfig.requiresAckReply(message_t* msg)
-       {
-               return call IEEE154Packet.requiresAckReply(msg);
-       }
-
-       async command void SoftwareAckConfig.createAckPacket(message_t* data, message_t* ack)
-       {
-               call IEEE154Packet.createAckReply(data, ack);
-       }
-
-       async command void SoftwareAckConfig.setAckReceived(message_t* msg, bool acked)
-       {
-               if( acked )
-                       getMeta(msg)->flags |= RF230PACKET_WAS_ACKED;
-               else
-                       getMeta(msg)->flags &= ~RF230PACKET_WAS_ACKED;
-       }
-
-       async command uint16_t SoftwareAckConfig.getAckTimeout()
-       {
-               return (uint16_t)(800 * RF230_ALARM_MICROSEC);
-       }
-
-       tasklet_async command void SoftwareAckConfig.reportChannelError()
-       {
-               signal TrafficMonitorConfig.channelError();
-       }
-
-/*----------------- UniqueConfig -----------------*/
-
-       async command uint8_t UniqueConfig.getSequenceNumber(message_t* msg)
-       {
-               return call IEEE154Packet.getDSN(msg);
-       }
-
-       async command void UniqueConfig.setSequenceNumber(message_t* msg, uint8_t dsn)
-       {
-               call IEEE154Packet.setDSN(msg, dsn);
-       }
-
-       async command am_addr_t UniqueConfig.getSender(message_t* msg)
-       {
-               return call IEEE154Packet.getSrcAddr(msg);
-       }
-
-       tasklet_async command void UniqueConfig.reportChannelError()
-       {
-               signal TrafficMonitorConfig.channelError();
-       }
-
-/*----------------- ActiveMessageConfig -----------------*/
-
-       command error_t ActiveMessageConfig.checkPacket(message_t* msg)
-       {
-               // the user forgot to call clear, we should return EINVAL
-               if( ! call IEEE154Packet.isDataFrame(msg) )
-                       call Packet.clear(msg);
-
-               return SUCCESS;
-       }
-
-/*----------------- CsmaConfig -----------------*/
-
-       async command bool CsmaConfig.requiresSoftwareCCA(message_t* msg)
-       {
-               return call IEEE154Packet.isDataFrame(msg);
-       }
-
-/*----------------- TrafficMonitorConfig -----------------*/
-
-       enum
-       {
-               TRAFFIC_UPDATE_PERIOD = 100,    // in milliseconds
-               TRAFFIC_MAX_BYTES = (uint16_t)(TRAFFIC_UPDATE_PERIOD * 1000UL / 32),    // 3125
-       };
-
-       async command uint16_t TrafficMonitorConfig.getUpdatePeriod()
-       {
-               return TRAFFIC_UPDATE_PERIOD;
-       }
-
-       async command uint16_t TrafficMonitorConfig.getChannelTime(message_t* msg)
-       {
-               /* We count in bytes, one byte is 32 microsecond. We are conservative here.
-                *
-                * pure airtime: preable (4 bytes), SFD (1 byte), length (1 byte), payload + CRC (len bytes)
-                * frame separation: 5-10 bytes
-                * ack required: 8-16 byte separation, 11 bytes airtime, 5-10 bytes separation
-                */
-
-               uint8_t len = call IEEE154Packet.getLength(msg);
-               return call IEEE154Packet.getAckRequired(msg) ? len + 6 + 16 + 11 + 10 : len + 6 + 10;
-       }
-
-       async command am_addr_t TrafficMonitorConfig.getSender(message_t* msg)
-       {
-               return call IEEE154Packet.getSrcAddr(msg);
-       }
-
-       tasklet_async command void TrafficMonitorConfig.timerTick()
-       {
-               signal SlottedCollisionConfig.timerTick();
-       }
-
-/*----------------- RandomCollisionConfig -----------------*/
-
-       /*
-        * We try to use the same values as in CC2420
-        *
-        * CC2420_MIN_BACKOFF = 10 jiffies = 320 microsec
-        * CC2420_BACKOFF_PERIOD = 10 jiffies
-        * initial backoff = 0x1F * CC2420_BACKOFF_PERIOD = 310 jiffies = 9920 microsec
-        * congestion backoff = 0x7 * CC2420_BACKOFF_PERIOD = 70 jiffies = 2240 microsec
-        */
-
-       async command uint16_t RandomCollisionConfig.getMinimumBackoff()
-       {
-               return (uint16_t)(320 * RF230_ALARM_MICROSEC);
-       }
-
-       async command uint16_t RandomCollisionConfig.getInitialBackoff(message_t* msg)
-       {
-               return (uint16_t)(9920 * RF230_ALARM_MICROSEC);
-       }
-
-       async command uint16_t RandomCollisionConfig.getCongestionBackoff(message_t* msg)
-       {
-               return (uint16_t)(2240 * RF230_ALARM_MICROSEC);
-       }
-
-       async command uint16_t RandomCollisionConfig.getTransmitBarrier(message_t* msg)
-       {
-               uint16_t time;
-
-               // TODO: maybe we should use the embedded timestamp of the message
-               time = call RadioAlarm.getNow();
-
-               // estimated response time (download the message, etc) is 5-8 bytes
-               if( call IEEE154Packet.requiresAckReply(msg) )
-                       time += (uint16_t)(32 * (-5 + 16 + 11 + 5) * RF230_ALARM_MICROSEC);
-               else
-                       time += (uint16_t)(32 * (-5 + 5) * RF230_ALARM_MICROSEC);
-
-               return time;
-       }
-
-       tasklet_async event void RadioAlarm.fired()     { }
-
-/*----------------- SlottedCollisionConfig -----------------*/
-
-       async command uint16_t SlottedCollisionConfig.getInitialDelay()
-       {
-               return 300;
-       }
-
-       async command uint8_t SlottedCollisionConfig.getScheduleExponent()
-       {
-               return 11;
-       }
-
-       async command uint16_t SlottedCollisionConfig.getTransmitTime(message_t* msg)
-       {
-               // TODO: check if the timestamp is correct
-               return getMeta(msg)->timestamp;
-       }
-
-       async command uint16_t SlottedCollisionConfig.getCollisionWindowStart(message_t* msg)
-       {
-               // the preamble (4 bytes), SFD (1 byte), plus two extra for safety
-               return getMeta(msg)->timestamp - (uint16_t)(7 * 32 * RF230_ALARM_MICROSEC);
-       }
-
-       async command uint16_t SlottedCollisionConfig.getCollisionWindowLength(message_t* msg)
-       {
-               return (uint16_t)(2 * 7 * 32 * RF230_ALARM_MICROSEC);
-       }
-
-       default tasklet_async event void SlottedCollisionConfig.timerTick() { }
-
-/*----------------- Dummy -----------------*/
-
-       async command void DummyConfig.nothing()
-       {
-       }
-}
diff --git a/tos/chips/rf230/RF230Config.nc b/tos/chips/rf230/RF230Config.nc
deleted file mode 100644 (file)
index 0bd2e40..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-/**
- * This interface needs to be implemented by the MAC to control the behaviour 
- * of the RF230LayerC component.
- */
-interface RF230Config
-{
-       /**
-        * Returns the length of the PHY payload (including the FCF field).
-        * This value must be in the range [3, 127].
-        */
-       async command uint8_t getLength(message_t* msg);
-
-       /**
-        * Sets the length of the PHY payload.
-        */
-       async command void setLength(message_t* msg, uint8_t len);
-
-       /**
-        * Returns a pointer to the start of the PHY payload that contains 
-        * getLength()-2 number of bytes. The FCF field (CRC-16) is not stored,
-        * but automatically appended / verified.
-        */
-       async command uint8_t* getPayload(message_t* msg);
-
-       /**
-        * Gets the number of bytes we should read before the RadioReceive.header
-        * event is fired. If the length of the packet is less than this amount, 
-        * then that event is fired earlier. The last touch event is not signaled 
-        * for packets whose length is less than or equal to this header length.
-        * The header length must be at least 1.
-        */
-       async command uint8_t getHeaderLength();
-
-       /**
-        * Returns the maximum PHY length that can be set via the setLength command
-        */
-       async command uint8_t getMaxLength();
-
-       /**
-        * This command is used at power up to set the default channel.
-        * The default CC2420 channel is 26.
-        */
-       async command uint8_t getDefaultChannel();
-
-       /**
-        * Returns TRUE if before sending this message we should make sure that
-        * the channel is clear via a very basic (and quick) RSSI check.
-        */
-       async command bool requiresRssiCca(message_t* msg);
-}
diff --git a/tos/chips/rf230/RF230LayerC.nc b/tos/chips/rf230/RF230LayerC.nc
deleted file mode 100644 (file)
index 5e842c0..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <HplRF230.h>
-
-configuration RF230LayerC
-{
-       provides
-       {
-               interface RadioState;
-               interface RadioSend;
-               interface RadioReceive;
-               interface RadioCCA;
-       }
-
-       uses interface RF230Config;
-}
-
-implementation
-{
-       components RF230LayerP, HplRF230C, BusyWaitMicroC, TaskletC, MainC, RadioAlarmC, RF230PacketC, LocalTimeMicroC as LocalTimeRadioC;
-
-       RadioState = RF230LayerP;
-       RadioSend = RF230LayerP;
-       RadioReceive = RF230LayerP;
-       RadioCCA = RF230LayerP;
-
-       RF230Config = RF230LayerP;
-
-       RF230LayerP.PacketLinkQuality -> RF230PacketC.PacketLinkQuality;
-       RF230LayerP.PacketTransmitPower -> RF230PacketC.PacketTransmitPower;
-       RF230LayerP.PacketRSSI -> RF230PacketC.PacketRSSI;
-       RF230LayerP.PacketTimeSyncOffset -> RF230PacketC.PacketTimeSyncOffset;
-       RF230LayerP.PacketTimeStamp -> RF230PacketC;
-       RF230LayerP.LocalTime -> LocalTimeRadioC;
-
-       RF230LayerP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
-       RadioAlarmC.Alarm -> HplRF230C.Alarm;
-
-       RF230LayerP.SELN -> HplRF230C.SELN;
-       RF230LayerP.SpiResource -> HplRF230C.SpiResource;
-       RF230LayerP.SpiByte -> HplRF230C;
-       RF230LayerP.HplRF230 -> HplRF230C;
-
-       RF230LayerP.SLP_TR -> HplRF230C.SLP_TR;
-       RF230LayerP.RSTN -> HplRF230C.RSTN;
-
-       RF230LayerP.IRQ -> HplRF230C.IRQ;
-       RF230LayerP.Tasklet -> TaskletC;
-       RF230LayerP.BusyWait -> BusyWaitMicroC;
-
-#ifdef RF230_DEBUG
-       components DiagMsgC;
-       RF230LayerP.DiagMsg -> DiagMsgC;
-#endif
-
-       MainC.SoftwareInit -> RF230LayerP.SoftwareInit;
-
-       components RealMainP;
-       RealMainP.PlatformInit -> RF230LayerP.PlatformInit;
-}
diff --git a/tos/chips/rf230/RF230LayerP.nc b/tos/chips/rf230/RF230LayerP.nc
deleted file mode 100644 (file)
index 4ba79fc..0000000
+++ /dev/null
@@ -1,814 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <RF230.h>
-#include <HplRF230.h>
-#include <Tasklet.h>
-#include <RadioAssert.h>
-#include <TimeSyncMessage.h>
-
-module RF230LayerP
-{
-       provides
-       {
-               interface Init as PlatformInit @exactlyonce();
-               interface Init as SoftwareInit @exactlyonce();
-
-               interface RadioState;
-               interface RadioSend;
-               interface RadioReceive;
-               interface RadioCCA;
-       }
-
-       uses
-       {
-               interface GeneralIO as SELN;
-               interface Resource as SpiResource;
-
-               interface SpiByte;
-               interface HplRF230;
-
-               interface GeneralIO as SLP_TR;
-               interface GeneralIO as RSTN;
-
-               interface GpioCapture as IRQ;
-
-               interface BusyWait<TMicro, uint16_t>;
-
-               interface PacketField<uint8_t> as PacketLinkQuality;
-               interface PacketField<uint8_t> as PacketTransmitPower;
-               interface PacketField<uint8_t> as PacketRSSI;
-               interface PacketField<uint8_t> as PacketTimeSyncOffset;
-
-               interface PacketTimeStamp<TRF230, uint32_t>;
-               interface LocalTime<TRF230>;
-
-               interface RF230Config;
-               interface Tasklet;
-               interface RadioAlarm;
-
-#ifdef RF230_DEBUG
-               interface DiagMsg;
-#endif
-       }
-}
-
-implementation
-{
-/*----------------- STATE -----------------*/
-
-       tasklet_norace uint8_t state;
-       enum
-       {
-               STATE_P_ON = 0,
-               STATE_SLEEP = 1,
-               STATE_SLEEP_2_TRX_OFF = 2,
-               STATE_TRX_OFF = 3,
-               STATE_TRX_OFF_2_RX_ON = 4,
-               STATE_RX_ON = 5,
-               STATE_BUSY_TX_2_RX_ON = 6,
-               STATE_PLL_ON_2_RX_ON = 7,
-       };
-
-       tasklet_norace uint8_t cmd;
-       enum
-       {
-               CMD_NONE = 0,                   // the state machine has stopped
-               CMD_TURNOFF = 1,                // goto SLEEP state
-               CMD_STANDBY = 2,                // goto TRX_OFF state
-               CMD_TURNON = 3,                 // goto RX_ON state
-               CMD_TRANSMIT = 4,               // currently transmitting a message
-               CMD_RECEIVE = 5,                // currently receiving a message
-               CMD_CCA = 6,                    // performing clear chanel assesment
-               CMD_CHANNEL = 7,                // changing the channel
-               CMD_SIGNAL_DONE = 8,    // signal the end of the state transition
-               CMD_DOWNLOAD = 9,               // download the received message
-       };
-
-       norace bool radioIrq;
-
-       tasklet_norace uint8_t txPower;
-       tasklet_norace uint8_t channel;
-
-       tasklet_norace message_t* rxMsg;
-       message_t rxMsgBuffer;
-
-       uint16_t capturedTime;  // the current time when the last interrupt has occured
-
-       tasklet_norace uint8_t rssiClear;
-       tasklet_norace uint8_t rssiBusy;
-
-/*----------------- REGISTER -----------------*/
-
-       inline void writeRegister(uint8_t reg, uint8_t value)
-       {
-               ASSERT( call SpiResource.isOwner() );
-               ASSERT( reg == (reg & RF230_CMD_REGISTER_MASK) );
-
-               call SELN.clr();
-               call HplRF230.spiSplitWrite(RF230_CMD_REGISTER_WRITE | reg);
-               call HplRF230.spiSplitReadWrite(value);
-               call HplRF230.spiSplitRead();
-               call SELN.set();
-       }
-
-       inline uint8_t readRegister(uint8_t reg)
-       {
-               ASSERT( call SpiResource.isOwner() );
-               ASSERT( reg == (reg & RF230_CMD_REGISTER_MASK) );
-
-               call SELN.clr();
-               call HplRF230.spiSplitWrite(RF230_CMD_REGISTER_READ | reg);
-               call HplRF230.spiSplitReadWrite(0);
-               reg = call HplRF230.spiSplitRead();
-               call SELN.set();
-
-               return reg;
-       }
-
-/*----------------- ALARM -----------------*/
-
-       enum
-       {
-               SLEEP_WAKEUP_TIME = (uint16_t)(880 * RF230_ALARM_SEC / 1000000UL),
-               CCA_REQUEST_TIME = (uint16_t)(140 * RF230_ALARM_SEC / 1000000UL),
-
-               TX_SFD_DELAY = (uint16_t)(176 * RF230_ALARM_SEC / 1000000UL),
-               RX_SFD_DELAY = (uint16_t)(8 * RF230_ALARM_SEC / 1000000UL),
-       };
-
-       tasklet_async event void RadioAlarm.fired()
-       {
-               if( state == STATE_SLEEP_2_TRX_OFF )
-                       state = STATE_TRX_OFF;
-               else if( cmd == CMD_CCA )
-               {
-                       uint8_t cca;
-
-                       ASSERT( state == STATE_RX_ON );
-
-                       cmd = CMD_NONE;
-                       cca = readRegister(RF230_TRX_STATUS);
-
-                       ASSERT( (cca & RF230_TRX_STATUS_MASK) == RF230_RX_ON );
-
-                       signal RadioCCA.done( (cca & RF230_CCA_DONE) ? ((cca & RF230_CCA_STATUS) ? SUCCESS : EBUSY) : FAIL );
-               }
-               else
-                       ASSERT(FALSE);
-
-               // make sure the rest of the command processing is called
-               call Tasklet.schedule();
-       }
-
-/*----------------- INIT -----------------*/
-
-       command error_t PlatformInit.init()
-       {
-               call SELN.makeOutput();
-               call SELN.set();
-               call SLP_TR.makeOutput();
-               call SLP_TR.clr();
-               call RSTN.makeOutput();
-               call RSTN.set();
-
-               rxMsg = &rxMsgBuffer;
-
-               // these are just good approximates
-               rssiClear = 0;
-               rssiBusy = 90;
-
-               return SUCCESS;
-       }
-
-       command error_t SoftwareInit.init()
-       {
-               // for powering up the radio
-               return call SpiResource.request();
-       }
-
-       void initRadio()
-       {
-               call BusyWait.wait(510);
-
-               call RSTN.clr();
-               call SLP_TR.clr();
-               call BusyWait.wait(6);
-               call RSTN.set();
-
-               writeRegister(RF230_TRX_CTRL_0, RF230_TRX_CTRL_0_VALUE);
-               writeRegister(RF230_TRX_STATE, RF230_TRX_OFF);
-
-               call BusyWait.wait(510);
-
-               writeRegister(RF230_IRQ_MASK, RF230_IRQ_TRX_UR | RF230_IRQ_PLL_LOCK | RF230_IRQ_TRX_END | RF230_IRQ_RX_START);
-               writeRegister(RF230_CCA_THRES, RF230_CCA_THRES_VALUE);
-               writeRegister(RF230_PHY_TX_PWR, RF230_TX_AUTO_CRC_ON | RF230_TX_PWR_DEFAULT);
-
-               txPower = RF230_TX_PWR_DEFAULT;
-               channel = call RF230Config.getDefaultChannel() & RF230_CHANNEL_MASK;
-               writeRegister(RF230_PHY_CC_CCA, RF230_CCA_MODE_VALUE | channel);
-
-               call SLP_TR.set();
-               state = STATE_SLEEP;
-       }
-
-/*----------------- SPI -----------------*/
-
-       event void SpiResource.granted()
-       {
-               call SELN.makeOutput();
-               call SELN.set();
-
-               if( state == STATE_P_ON )
-               {
-                       initRadio();
-                       call SpiResource.release();
-               }
-               else
-                       call Tasklet.schedule();
-       }
-
-       bool isSpiAcquired()
-       {
-               if( call SpiResource.isOwner() )
-                       return TRUE;
-
-               if( call SpiResource.immediateRequest() == SUCCESS )
-               {
-                       call SELN.makeOutput();
-                       call SELN.set();
-
-                       return TRUE;
-               }
-
-               call SpiResource.request();
-               return FALSE;
-       }
-
-/*----------------- CHANNEL -----------------*/
-
-       tasklet_async command error_t RadioState.setChannel(uint8_t c)
-       {
-               c &= RF230_CHANNEL_MASK;
-
-               if( cmd != CMD_NONE )
-                       return EBUSY;
-               else if( channel == c )
-                       return EALREADY;
-
-               channel = c;
-               cmd = CMD_CHANNEL;
-               call Tasklet.schedule();
-
-               return SUCCESS;
-       }
-
-       inline void changeChannel()
-       {
-               ASSERT( cmd == CMD_CHANNEL );
-               ASSERT( state == STATE_SLEEP || state == STATE_TRX_OFF || state == STATE_RX_ON );
-
-               if( isSpiAcquired() )
-               {
-                       writeRegister(RF230_PHY_CC_CCA, RF230_CCA_MODE_VALUE | channel);
-
-                       if( state == STATE_RX_ON )
-                               state = STATE_TRX_OFF_2_RX_ON;
-                       else
-                               cmd = CMD_SIGNAL_DONE;
-               }
-       }
-
-/*----------------- TURN ON/OFF -----------------*/
-
-       inline void changeState()
-       {
-               if( (cmd == CMD_STANDBY || cmd == CMD_TURNON)
-                       && state == STATE_SLEEP && call RadioAlarm.isFree() )
-               {
-                       call SLP_TR.clr();
-
-                       call RadioAlarm.wait(SLEEP_WAKEUP_TIME);
-                       state = STATE_SLEEP_2_TRX_OFF;
-               }
-               else if( cmd == CMD_TURNON && state == STATE_TRX_OFF && isSpiAcquired() )
-               {
-                       ASSERT( ! radioIrq );
-
-                       readRegister(RF230_IRQ_STATUS); // clear the interrupt register
-                       call IRQ.captureRisingEdge();
-
-                       writeRegister(RF230_TRX_STATE, RF230_RX_ON);
-                       state = STATE_TRX_OFF_2_RX_ON;
-               }
-               else if( (cmd == CMD_TURNOFF || cmd == CMD_STANDBY) 
-                       && state == STATE_RX_ON && isSpiAcquired() )
-               {
-                       writeRegister(RF230_TRX_STATE, RF230_FORCE_TRX_OFF);
-
-                       call IRQ.disable();
-                       radioIrq = FALSE;
-
-                       state = STATE_TRX_OFF;
-               }
-
-               if( cmd == CMD_TURNOFF && state == STATE_TRX_OFF )
-               {
-                       call SLP_TR.set();
-                       state = STATE_SLEEP;
-                       cmd = CMD_SIGNAL_DONE;
-               }
-               else if( cmd == CMD_STANDBY && state == STATE_TRX_OFF )
-                       cmd = CMD_SIGNAL_DONE;
-       }
-
-       tasklet_async command error_t RadioState.turnOff()
-       {
-               if( cmd != CMD_NONE )
-                       return EBUSY;
-               else if( state == STATE_SLEEP )
-                       return EALREADY;
-
-               cmd = CMD_TURNOFF;
-               call Tasklet.schedule();
-
-               return SUCCESS;
-       }
-       
-       tasklet_async command error_t RadioState.standby()
-       {
-               if( cmd != CMD_NONE || (state == STATE_SLEEP && ! call RadioAlarm.isFree()) )
-                       return EBUSY;
-               else if( state == STATE_TRX_OFF )
-                       return EALREADY;
-
-               cmd = CMD_STANDBY;
-               call Tasklet.schedule();
-
-               return SUCCESS;
-       }
-
-       tasklet_async command error_t RadioState.turnOn()
-       {
-               if( cmd != CMD_NONE || (state == STATE_SLEEP && ! call RadioAlarm.isFree()) )
-                       return EBUSY;
-               else if( state == STATE_RX_ON )
-                       return EALREADY;
-
-               cmd = CMD_TURNON;
-               call Tasklet.schedule();
-
-               return SUCCESS;
-       }
-
-       default tasklet_async event void RadioState.done() { }
-
-/*----------------- TRANSMIT -----------------*/
-
-       tasklet_async command error_t RadioSend.send(message_t* msg)
-       {
-               uint16_t time;
-               uint8_t length;
-               uint8_t* data;
-               uint8_t header;
-               uint32_t time32;
-               void* timesync;
-
-               if( cmd != CMD_NONE || state != STATE_RX_ON || ! isSpiAcquired() || radioIrq )
-                       return EBUSY;
-
-               length = (call PacketTransmitPower.isSet(msg) ?
-                       call PacketTransmitPower.get(msg) : RF230_DEF_RFPOWER) & RF230_TX_PWR_MASK;
-
-               if( length != txPower )
-               {
-                       txPower = length;
-                       writeRegister(RF230_PHY_TX_PWR, RF230_TX_AUTO_CRC_ON | txPower);
-               }
-
-               if( call RF230Config.requiresRssiCca(msg) 
-                               && (readRegister(RF230_PHY_RSSI) & RF230_RSSI_MASK) > ((rssiClear + rssiBusy) >> 3) )
-                       return EBUSY;
-
-               writeRegister(RF230_TRX_STATE, RF230_PLL_ON);
-
-               // do something useful, just to wait a little
-               time32 = call LocalTime.get();
-               timesync = call PacketTimeSyncOffset.isSet(msg) ? msg->data + call PacketTimeSyncOffset.get(msg) : 0;
-
-               // we have missed an incoming message in this short amount of time
-               if( (readRegister(RF230_TRX_STATUS) & RF230_TRX_STATUS_MASK) != RF230_PLL_ON )
-               {
-                       ASSERT( (readRegister(RF230_TRX_STATUS) & RF230_TRX_STATUS_MASK) == RF230_BUSY_RX );
-
-                       state = STATE_PLL_ON_2_RX_ON;
-                       return EBUSY;
-               }
-
-               atomic
-               {
-                       call SLP_TR.set();
-                       time = call RadioAlarm.getNow() + TX_SFD_DELAY;
-               }
-               call SLP_TR.clr();
-
-               ASSERT( ! radioIrq );
-
-               call SELN.clr();
-               call HplRF230.spiSplitWrite(RF230_CMD_FRAME_WRITE);
-
-               length = call RF230Config.getLength(msg);
-               data = call RF230Config.getPayload(msg);
-
-               // length | data[0] ... data[length-3] | automatically generated FCS
-               call HplRF230.spiSplitReadWrite(length);
-
-               // the FCS is atomatically generated (2 bytes)
-               length -= 2;
-
-               header = call RF230Config.getHeaderLength();
-               if( header > length )
-                       header = length;
-
-               length -= header;
-
-               // first upload the header to gain some time
-               do {
-                       call HplRF230.spiSplitReadWrite(*(data++));
-               }
-               while( --header != 0 );
-
-               time32 += (int16_t)(time) - (int16_t)(time32);
-
-               if( timesync != 0 )
-                       *(timesync_relative_t*)timesync = (*(timesync_absolute_t*)timesync) - time32;
-
-               do {
-                       call HplRF230.spiSplitReadWrite(*(data++));
-               }
-               while( --length != 0 );
-
-               // wait for the SPI transfer to finish
-               call HplRF230.spiSplitRead();
-               call SELN.set();
-
-               /*
-                * There is a very small window (~1 microsecond) when the RF230 went 
-                * into PLL_ON state but was somehow not properly initialized because 
-                * of an incoming message and could not go into BUSY_TX. I think the
-                * radio can even receive a message, and generate a TRX_UR interrupt
-                * because of concurrent access, but that message probably cannot be
-                * recovered.
-                *
-                * TODO: this needs to be verified, and make sure that the chip is 
-                * not locked up in this case.
-                */
-
-               // go back to RX_ON state when finished
-               writeRegister(RF230_TRX_STATE, RF230_RX_ON);
-
-#ifdef RF230_DEBUG_MESSAGES
-               if( call DiagMsg.record() )
-               {
-                       length = call RF230Config.getLength(msg);
-
-                       call DiagMsg.str("tx");
-                       call DiagMsg.uint16(time);
-                       call DiagMsg.uint8(length);
-                       call DiagMsg.hex8s(data, length - 2);
-                       call DiagMsg.send();
-               }
-#endif
-
-               if( timesync != 0 )
-                       *(timesync_absolute_t*)timesync = (*(timesync_relative_t*)timesync) + time32;
-
-               call PacketTimeStamp.set(msg, time32);
-
-               // wait for the TRX_END interrupt
-               state = STATE_BUSY_TX_2_RX_ON;
-               cmd = CMD_TRANSMIT;
-
-               return SUCCESS;
-       }
-
-       default tasklet_async event void RadioSend.sendDone(error_t error) { }
-       default tasklet_async event void RadioSend.ready() { }
-
-/*----------------- CCA -----------------*/
-
-       tasklet_async command error_t RadioCCA.request()
-       {
-               if( cmd != CMD_NONE || state != STATE_RX_ON || ! isSpiAcquired() || ! call RadioAlarm.isFree() )
-                       return EBUSY;
-
-               // see Errata B7 of the datasheet
-               // writeRegister(RF230_TRX_STATE, RF230_PLL_ON);
-               // writeRegister(RF230_TRX_STATE, RF230_RX_ON);
-
-               writeRegister(RF230_PHY_CC_CCA, RF230_CCA_REQUEST | RF230_CCA_MODE_VALUE | channel);
-               call RadioAlarm.wait(CCA_REQUEST_TIME);
-               cmd = CMD_CCA;
-               
-               return SUCCESS;
-       }
-
-       default tasklet_async event void RadioCCA.done(error_t error) { }
-
-/*----------------- RECEIVE -----------------*/
-
-       inline void downloadMessage()
-       {
-               uint8_t length;
-               uint16_t crc;
-
-               call SELN.clr();
-               call HplRF230.spiWrite(RF230_CMD_FRAME_READ);
-
-               // read the length byte
-               length = call HplRF230.spiWrite(0);
-
-               // if correct length
-               if( length >= 3 && length <= call RF230Config.getMaxLength() )
-               {
-                       uint8_t read;
-                       uint8_t* data;
-
-                       // initiate the reading
-                       call HplRF230.spiSplitWrite(0);
-
-                       call RF230Config.setLength(rxMsg, length);
-                       data = call RF230Config.getPayload(rxMsg);
-                       crc = 0;
-
-                       // we do not store the CRC field
-                       length -= 2;
-
-                       read = call RF230Config.getHeaderLength();
-                       if( length < read )
-                               read = length;
-
-                       length -= read;
-
-                       do {
-                               crc = call HplRF230.crcByte(crc, *(data++) = call HplRF230.spiSplitReadWrite(0));
-                       }
-                       while( --read != 0  );
-
-                       if( signal RadioReceive.header(rxMsg) )
-                       {
-                               while( length-- != 0 )
-                                       crc = call HplRF230.crcByte(crc, *(data++) = call HplRF230.spiSplitReadWrite(0));
-
-                               crc = call HplRF230.crcByte(crc, call HplRF230.spiSplitReadWrite(0));
-                               crc = call HplRF230.crcByte(crc, call HplRF230.spiSplitReadWrite(0));
-
-                               call PacketLinkQuality.set(rxMsg, call HplRF230.spiSplitRead());
-                       }
-                       else
-                               crc = 1;
-               }
-               else
-                       crc = 1;
-
-               call SELN.set();
-               state = STATE_RX_ON;
-
-#ifdef RF230_DEBUG_MESSAGES
-               if( call DiagMsg.record() )
-               {
-                       length = call RF230Config.getLength(rxMsg);
-
-                       call DiagMsg.str("rx");
-                       call DiagMsg.uint32(call PacketTimeStamp.isValid(rxMsg) ? call PacketTimeStamp.timestamp(rxMsg) : 0);
-                       call DiagMsg.uint16(call RadioAlarm.getNow());
-                       call DiagMsg.uint8(crc != 0);
-                       call DiagMsg.uint8(length);
-                       call DiagMsg.hex8s(call RF230Config.getPayload(rxMsg), length - 2);
-                       call DiagMsg.send();
-               }
-#endif
-               
-               cmd = CMD_NONE;
-
-               // signal only if it has passed the CRC check
-               if( crc == 0 )
-                       rxMsg = signal RadioReceive.receive(rxMsg);
-       }
-
-/*----------------- IRQ -----------------*/
-
-       async event void IRQ.captured(uint16_t time)
-       {
-               ASSERT( ! radioIrq );
-
-               atomic
-               {
-                       capturedTime = time;
-                       radioIrq = TRUE;
-               }
-
-               call Tasklet.schedule();
-       }
-
-       void serviceRadio()
-       {
-               if( isSpiAcquired() )
-               {
-                       uint16_t time;
-                       uint32_t time32;
-                       uint8_t irq;
-                       uint8_t temp;
-                       
-                       atomic time = capturedTime;
-                       radioIrq = FALSE;
-                       irq = readRegister(RF230_IRQ_STATUS);
-
-#ifdef RF230_DEBUG
-                       // TODO: handle this interrupt
-                       if( irq & RF230_IRQ_TRX_UR )
-                       {
-                               if( call DiagMsg.record() )
-                               {
-                                       call DiagMsg.str("assert ur");
-                                       call DiagMsg.uint16(call RadioAlarm.getNow());
-                                       call DiagMsg.hex8(readRegister(RF230_TRX_STATUS));
-                                       call DiagMsg.hex8(readRegister(RF230_TRX_STATE));
-                                       call DiagMsg.hex8(irq);
-                                       call DiagMsg.uint8(state);
-                                       call DiagMsg.uint8(cmd);
-                                       call DiagMsg.send();
-                               }
-                       }
-#endif
-
-                       if( irq & RF230_IRQ_PLL_LOCK )
-                       {
-                               if( cmd == CMD_TURNON || cmd == CMD_CHANNEL )
-                               {
-                                       ASSERT( state == STATE_TRX_OFF_2_RX_ON );
-
-                                       state = STATE_RX_ON;
-                                       cmd = CMD_SIGNAL_DONE;
-                               }
-                               else if( cmd == CMD_TRANSMIT )
-                               {
-                                       ASSERT( state == STATE_BUSY_TX_2_RX_ON );
-                               }
-                               else
-                                       ASSERT(FALSE);
-                       }
-
-                       if( irq & RF230_IRQ_RX_START )
-                       {
-                               if( cmd == CMD_CCA )
-                               {
-                                       signal RadioCCA.done(FAIL);
-                                       cmd = CMD_NONE;
-                               }
-
-                               if( cmd == CMD_NONE )
-                               {
-                                       ASSERT( state == STATE_RX_ON || state == STATE_PLL_ON_2_RX_ON );
-
-                                       // the most likely place for busy channel, with no TRX_END interrupt
-                                       if( irq == RF230_IRQ_RX_START )
-                                       {
-                                               temp = readRegister(RF230_PHY_RSSI) & RF230_RSSI_MASK;
-                                               rssiBusy += temp - (rssiBusy >> 2);
-#ifndef RF230_RSSI_ENERGY
-                                               call PacketRSSI.set(rxMsg, temp);
-                                       }
-                                       else
-                                       {
-                                               call PacketRSSI.clear(rxMsg);
-#endif
-                                       }
-
-                                       /*
-                                        * The timestamp corresponds to the first event which could not
-                                        * have been a PLL_LOCK because then cmd != CMD_NONE, so we must
-                                        * have received a message (and could also have received the 
-                                        * TRX_END interrupt in the mean time, but that is fine. Also,
-                                        * we could not be after a transmission, because then cmd = 
-                                        * CMD_TRANSMIT.
-                                        */
-                                       if( irq == RF230_IRQ_RX_START ) // just to be cautious
-                                       {
-                                               time32 = call LocalTime.get();
-                                               time32 += (int16_t)(time - RX_SFD_DELAY) - (int16_t)(time32);
-                                               call PacketTimeStamp.set(rxMsg, time32);
-                                       }
-                                       else
-                                               call PacketTimeStamp.clear(rxMsg);
-
-                                       cmd = CMD_RECEIVE;
-                               }
-                               else
-                                       ASSERT( cmd == CMD_TURNOFF );
-                       }
-
-                       if( irq & RF230_IRQ_TRX_END )
-                       {
-                               if( cmd == CMD_TRANSMIT )
-                               {
-                                       ASSERT( state == STATE_BUSY_TX_2_RX_ON );
-
-                                       state = STATE_RX_ON;
-                                       cmd = CMD_NONE;
-                                       signal RadioSend.sendDone(SUCCESS);
-
-                                       // TODO: we could have missed a received message
-                                       ASSERT( ! (irq & RF230_IRQ_RX_START) );
-                               }
-                               else if( cmd == CMD_RECEIVE )
-                               {
-                                       ASSERT( state == STATE_RX_ON || state == STATE_PLL_ON_2_RX_ON );
-#ifdef RF230_RSSI_ENERGY
-                                       if( irq == RF230_IRQ_TRX_END )
-                                               call PacketRSSI.set(rxMsg, readRegister(RF230_PHY_ED_LEVEL));
-                                       else
-                                               call PacketRSSI.clear(rxMsg);
-#endif
-                                       if( state == STATE_PLL_ON_2_RX_ON )
-                                       {
-                                               ASSERT( (readRegister(RF230_TRX_STATUS) & RF230_TRX_STATUS_MASK) == RF230_PLL_ON );
-
-                                               writeRegister(RF230_TRX_STATE, RF230_RX_ON);
-                                               state = STATE_RX_ON;
-                                       }
-                                       else
-                                       {
-                                               // the most likely place for clear channel (hope to avoid acks)
-                                               rssiClear += (readRegister(RF230_PHY_RSSI) & RF230_RSSI_MASK) - (rssiClear >> 2);
-                                       }
-
-                                       cmd = CMD_DOWNLOAD;
-                               }
-                               else
-                                       ASSERT(FALSE);
-                       }
-               }
-       }
-
-       default tasklet_async event bool RadioReceive.header(message_t* msg)
-       {
-               return TRUE;
-       }
-
-       default tasklet_async event message_t* RadioReceive.receive(message_t* msg)
-       {
-               return msg;
-       }
-
-/*----------------- TASKLET -----------------*/
-
-       tasklet_async event void Tasklet.run()
-       {
-               if( radioIrq )
-                       serviceRadio();
-
-               if( cmd != CMD_NONE )
-               {
-                       if( cmd == CMD_DOWNLOAD )
-                               downloadMessage();
-                       else if( CMD_TURNOFF <= cmd && cmd <= CMD_TURNON )
-                               changeState();
-                       else if( cmd == CMD_CHANNEL )
-                               changeChannel();
-                       
-                       if( cmd == CMD_SIGNAL_DONE )
-                       {
-                               cmd = CMD_NONE;
-                               signal RadioState.done();
-                       }
-               }
-
-               if( cmd == CMD_NONE && state == STATE_RX_ON && ! radioIrq )
-                       signal RadioSend.ready();
-
-               if( cmd == CMD_NONE )
-                       call SpiResource.release();
-       }
-}
diff --git a/tos/chips/rf230/RF230Packet.h b/tos/chips/rf230/RF230Packet.h
deleted file mode 100644 (file)
index f12e3e5..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#ifndef __RF230PACKET_H__
-#define __RF230PACKET_H__
-
-#include <IEEE154Packet.h>
-
-typedef ieee154_header_t rf230packet_header_t;
-
-typedef nx_struct rf230packet_footer_t
-{
-       // the time stamp is not recorded here, time stamped messaged cannot have max length
-} rf230packet_footer_t;
-
-typedef struct rf230packet_metadata_t
-{
-       uint8_t flags;
-       uint8_t lqi;
-       uint8_t power;                          // shared between TXPOWER and RSSI
-#ifdef LOW_POWER_LISTENING
-       uint16_t lpl_sleepint;
-#endif
-       uint32_t timestamp;
-} rf230packet_metadata_t;
-
-enum rf230packet_metadata_flags
-{
-       RF230PACKET_WAS_ACKED = 0x01,           // PacketAcknowledgements
-       RF230PACKET_TIMESTAMP = 0x02,           // PacketTimeStamp
-       RF230PACKET_TXPOWER = 0x04,             // PacketTransmitPower
-       RF230PACKET_RSSI = 0x08,                // PacketRSSI
-       RF230PACKET_TIMESYNC = 0x10,            // PacketTimeSync (update timesync_footer)
-       RF230PACKET_LPL_SLEEPINT = 0x20,        // LowPowerListening
-
-       RF230PACKET_CLEAR_METADATA = 0x00,
-};
-
-#endif//__RF230PACKET_H__
diff --git a/tos/chips/rf230/RF230PacketC.nc b/tos/chips/rf230/RF230PacketC.nc
deleted file mode 100644 (file)
index dc4321b..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <HplRF230.h>
-
-configuration RF230PacketC
-{
-       provides
-       {
-               interface Packet;
-               interface AMPacket;
-               interface PacketAcknowledgements;
-               interface PacketField<uint8_t> as PacketLinkQuality;
-               interface PacketField<uint8_t> as PacketTransmitPower;
-               interface PacketField<uint8_t> as PacketRSSI;
-               interface PacketField<uint16_t> as PacketSleepInterval;
-               interface PacketField<uint8_t> as PacketTimeSyncOffset;
-
-               interface PacketTimeStamp<TRF230, uint32_t> as PacketTimeStampRadio;
-               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
-       }
-}
-
-implementation
-{
-       components RF230PacketP, IEEE154PacketC, LocalTimeMicroC, LocalTimeMilliC;
-
-       RF230PacketP.IEEE154Packet -> IEEE154PacketC;
-       RF230PacketP.LocalTimeRadio -> LocalTimeMicroC;
-       RF230PacketP.LocalTimeMilli -> LocalTimeMilliC;
-
-       Packet = RF230PacketP;
-       AMPacket = IEEE154PacketC;
-
-       PacketAcknowledgements  = RF230PacketP;
-       PacketLinkQuality               = RF230PacketP.PacketLinkQuality;
-       PacketTransmitPower             = RF230PacketP.PacketTransmitPower;
-       PacketRSSI                              = RF230PacketP.PacketRSSI;
-       PacketSleepInterval             = RF230PacketP.PacketSleepInterval;
-       PacketTimeSyncOffset    = RF230PacketP.PacketTimeSyncOffset;
-
-       PacketTimeStampRadio    = RF230PacketP;
-       PacketTimeStampMilli    = RF230PacketP;
-}
diff --git a/tos/chips/rf230/RF230PacketP.nc b/tos/chips/rf230/RF230PacketP.nc
deleted file mode 100644 (file)
index 09b4977..0000000
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <RF230Packet.h>
-#include <TimeSyncMessage.h>
-
-module RF230PacketP
-{
-       provides
-       {
-               interface PacketAcknowledgements;
-               interface Packet;
-               interface PacketField<uint8_t> as PacketLinkQuality;
-               interface PacketField<uint8_t> as PacketTransmitPower;
-               interface PacketField<uint8_t> as PacketRSSI;
-               interface PacketField<uint16_t> as PacketSleepInterval;
-               interface PacketField<uint8_t> as PacketTimeSyncOffset;
-
-               interface PacketTimeStamp<TRF230, uint32_t> as PacketTimeStampRadio;
-               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
-       }
-
-       uses
-       {
-               interface IEEE154Packet;
-
-               interface LocalTime<TRF230> as LocalTimeRadio;
-               interface LocalTime<TMilli> as LocalTimeMilli;
-       }
-}
-
-implementation
-{
-       enum
-       {
-               PACKET_LENGTH_INCREASE = 
-                       sizeof(rf230packet_header_t) - 1        // the 8-bit length field is not counted
-                       + sizeof(ieee154_footer_t),             // the CRC is not stored in memory
-       };
-
-       inline rf230packet_metadata_t* getMeta(message_t* msg)
-       {
-               return (rf230packet_metadata_t*)(msg->metadata);
-       }
-
-/*----------------- Packet -----------------*/
-
-       command void Packet.clear(message_t* msg) 
-       {
-               call IEEE154Packet.createDataFrame(msg);
-
-               getMeta(msg)->flags = RF230PACKET_CLEAR_METADATA;
-       }
-
-       inline command void Packet.setPayloadLength(message_t* msg, uint8_t len) 
-       {
-               call IEEE154Packet.setLength(msg, len + PACKET_LENGTH_INCREASE);
-       }
-
-       inline command uint8_t Packet.payloadLength(message_t* msg) 
-       {
-               return call IEEE154Packet.getLength(msg) - PACKET_LENGTH_INCREASE;
-       }
-
-       inline command uint8_t Packet.maxPayloadLength()
-       {
-               return TOSH_DATA_LENGTH;
-       }
-
-       command void* Packet.getPayload(message_t* msg, uint8_t len)
-       {
-               if( len > TOSH_DATA_LENGTH )
-                       return NULL;
-
-               return msg->data;
-       }
-
-/*----------------- PacketAcknowledgements -----------------*/
-
-       async command error_t PacketAcknowledgements.requestAck(message_t* msg)
-       {
-               call IEEE154Packet.setAckRequired(msg, TRUE);
-
-               return SUCCESS;
-       }
-
-       async command error_t PacketAcknowledgements.noAck(message_t* msg)
-       {
-               call IEEE154Packet.setAckRequired(msg, FALSE);
-
-               return SUCCESS;
-       }
-
-       async command bool PacketAcknowledgements.wasAcked(message_t* msg)
-       {
-               return getMeta(msg)->flags & RF230PACKET_WAS_ACKED;
-       }
-
-/*----------------- PacketLinkQuality -----------------*/
-
-       async command bool PacketLinkQuality.isSet(message_t* msg)
-       {
-               return TRUE;
-       }
-
-       async command uint8_t PacketLinkQuality.get(message_t* msg)
-       {
-               return getMeta(msg)->lqi;
-       }
-
-       async command void PacketLinkQuality.clear(message_t* msg)
-       {
-       }
-
-       async command void PacketLinkQuality.set(message_t* msg, uint8_t value)
-       {
-               getMeta(msg)->lqi = value;
-       }
-
-/*----------------- PacketTimeStampRadio -----------------*/
-
-       async command bool PacketTimeStampRadio.isValid(message_t* msg)
-       {
-               return getMeta(msg)->flags & RF230PACKET_TIMESTAMP;
-       }
-
-       async command uint32_t PacketTimeStampRadio.timestamp(message_t* msg)
-       {
-               return getMeta(msg)->timestamp;
-       }
-
-       async command void PacketTimeStampRadio.clear(message_t* msg)
-       {
-               getMeta(msg)->flags &= ~RF230PACKET_TIMESTAMP;
-       }
-
-       async command void PacketTimeStampRadio.set(message_t* msg, uint32_t value)
-       {
-               getMeta(msg)->flags |= RF230PACKET_TIMESTAMP;
-               getMeta(msg)->timestamp = value;
-       }
-
-/*----------------- PacketTimeStampMilli -----------------*/
-
-       async command bool PacketTimeStampMilli.isValid(message_t* msg)
-       {
-               return call PacketTimeStampRadio.isValid(msg);
-       }
-
-       async command uint32_t PacketTimeStampMilli.timestamp(message_t* msg)
-       {
-               int32_t offset = call PacketTimeStampRadio.timestamp(msg) - call LocalTimeRadio.get();
-
-               // TODO: Make the shift constant configurable
-               return (offset >> 10) + call LocalTimeMilli.get();
-       }
-
-       async command void PacketTimeStampMilli.clear(message_t* msg)
-       {
-               call PacketTimeStampRadio.clear(msg);
-       }
-
-       async command void PacketTimeStampMilli.set(message_t* msg, uint32_t value)
-       {
-               // TODO: Make the shift constant configurable
-               int32_t offset = (value - call LocalTimeMilli.get()) << 10;
-
-               call PacketTimeStampRadio.set(msg, offset + call LocalTimeRadio.get());
-       }
-
-/*----------------- PacketTransmitPower -----------------*/
-
-       async command bool PacketTransmitPower.isSet(message_t* msg)
-       {
-               return getMeta(msg)->flags & RF230PACKET_TXPOWER;
-       }
-
-       async command uint8_t PacketTransmitPower.get(message_t* msg)
-       {
-               return getMeta(msg)->power;
-       }
-
-       async command void PacketTransmitPower.clear(message_t* msg)
-       {
-               getMeta(msg)->flags &= ~RF230PACKET_TXPOWER;
-       }
-
-       async command void PacketTransmitPower.set(message_t* msg, uint8_t value)
-       {
-               getMeta(msg)->flags &= ~RF230PACKET_RSSI;
-               getMeta(msg)->flags |= RF230PACKET_TXPOWER;
-               getMeta(msg)->power = value;
-       }
-
-/*----------------- PacketRSSI -----------------*/
-
-       async command bool PacketRSSI.isSet(message_t* msg)
-       {
-               return getMeta(msg)->flags & RF230PACKET_RSSI;
-       }
-
-       async command uint8_t PacketRSSI.get(message_t* msg)
-       {
-               return getMeta(msg)->power;
-       }
-
-       async command void PacketRSSI.clear(message_t* msg)
-       {
-               getMeta(msg)->flags &= ~RF230PACKET_RSSI;
-       }
-
-       async command void PacketRSSI.set(message_t* msg, uint8_t value)
-       {
-               getMeta(msg)->flags &= ~RF230PACKET_TXPOWER;
-               getMeta(msg)->flags |= RF230PACKET_RSSI;
-               getMeta(msg)->power = value;
-       }
-
-/*----------------- PacketTimeSyncOffset -----------------*/
-
-       async command bool PacketTimeSyncOffset.isSet(message_t* msg)
-       {
-               return getMeta(msg)->flags & RF230PACKET_TIMESYNC;
-       }
-
-       async command uint8_t PacketTimeSyncOffset.get(message_t* msg)
-       {
-               return call IEEE154Packet.getLength(msg) - PACKET_LENGTH_INCREASE - sizeof(timesync_absolute_t);
-       }
-
-       async command void PacketTimeSyncOffset.clear(message_t* msg)
-       {
-               getMeta(msg)->flags &= ~RF230PACKET_TIMESYNC;
-       }
-
-       async command void PacketTimeSyncOffset.set(message_t* msg, uint8_t value)
-       {
-               // the value is ignored, the offset always points to the timesync footer at the end of the payload
-               getMeta(msg)->flags |= RF230PACKET_TIMESYNC;
-       }
-
-/*----------------- PacketSleepInterval -----------------*/
-
-       async command bool PacketSleepInterval.isSet(message_t* msg)
-       {
-               return getMeta(msg)->flags & RF230PACKET_LPL_SLEEPINT;
-       }
-
-       async command uint16_t PacketSleepInterval.get(message_t* msg)
-       {
-#ifdef LOW_POWER_LISTENING
-               return getMeta(msg)->lpl_sleepint;
-#else
-               return 0;
-#endif
-       }
-
-       async command void PacketSleepInterval.clear(message_t* msg)
-       {
-               getMeta(msg)->flags &= ~RF230PACKET_LPL_SLEEPINT;
-       }
-
-       async command void PacketSleepInterval.set(message_t* msg, uint16_t value)
-       {
-               getMeta(msg)->flags |= RF230PACKET_LPL_SLEEPINT;
-
-#ifdef LOW_POWER_LISTENING
-               getMeta(msg)->lpl_sleepint = value;
-#endif
-       }
-}
diff --git a/tos/chips/rf230/RF230TimeSyncMessageC.nc b/tos/chips/rf230/RF230TimeSyncMessageC.nc
deleted file mode 100644 (file)
index 70b6440..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Timer.h>
-#include <AM.h>
-#include <HplRF230.h>
-
-configuration RF230TimeSyncMessageC
-{
-       provides
-       {
-               interface SplitControl;
-
-               interface Receive[uint8_t id];
-               interface Receive as Snoop[am_id_t id];
-               interface Packet;
-               interface AMPacket;
-
-               interface TimeSyncAMSend<TRF230, uint32_t> as TimeSyncAMSendRadio[am_id_t id];
-               interface TimeSyncPacket<TRF230, uint32_t> as TimeSyncPacketRadio;
-
-               interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[am_id_t id];
-               interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
-       }
-}
-
-implementation
-{
-       components RF230TimeSyncMessageP, RF230ActiveMessageC, LocalTimeMilliC, LocalTimeMicroC as LocalTimeRadioC, RF230PacketC;
-
-       TimeSyncAMSendRadio = RF230TimeSyncMessageP;
-       TimeSyncPacketRadio = RF230TimeSyncMessageP;
-
-       TimeSyncAMSendMilli = RF230TimeSyncMessageP;
-       TimeSyncPacketMilli = RF230TimeSyncMessageP;
-
-       Packet = RF230TimeSyncMessageP;
-       RF230TimeSyncMessageP.SubSend -> RF230ActiveMessageC.AMSend;
-       RF230TimeSyncMessageP.SubPacket -> RF230ActiveMessageC.Packet;
-
-       RF230TimeSyncMessageP.PacketTimeStampRadio -> RF230ActiveMessageC;
-       RF230TimeSyncMessageP.PacketTimeStampMilli -> RF230ActiveMessageC;
-       RF230TimeSyncMessageP.LocalTimeRadio -> LocalTimeRadioC;
-       RF230TimeSyncMessageP.LocalTimeMilli -> LocalTimeMilliC;
-
-       RF230TimeSyncMessageP.PacketTimeSyncOffset -> RF230PacketC.PacketTimeSyncOffset;
-
-       SplitControl = RF230ActiveMessageC;
-       Receive = RF230ActiveMessageC.Receive;
-       Snoop = RF230ActiveMessageC.Snoop;
-       AMPacket = RF230ActiveMessageC;
-}
diff --git a/tos/chips/rf230/RF230TimeSyncMessageP.nc b/tos/chips/rf230/RF230TimeSyncMessageP.nc
deleted file mode 100644 (file)
index 181d5c2..0000000
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <TimeSyncMessage.h>
-#include <HplRF230.h>
-
-module RF230TimeSyncMessageP
-{
-       provides
-       {
-               interface TimeSyncAMSend<TRF230, uint32_t> as TimeSyncAMSendRadio[uint8_t id];
-               interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[uint8_t id];
-               interface Packet;
-
-               interface TimeSyncPacket<TRF230, uint32_t> as TimeSyncPacketRadio;
-               interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
-       }
-
-       uses
-       {
-               interface AMSend as SubSend[uint8_t id];
-               interface Packet as SubPacket;
-
-               interface PacketTimeStamp<TRF230, uint32_t> as PacketTimeStampRadio;
-               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
-
-               interface LocalTime<TRF230> as LocalTimeRadio;
-               interface LocalTime<TMilli> as LocalTimeMilli;
-
-               interface PacketField<uint8_t> as PacketTimeSyncOffset;
-       }
-}
-
-implementation
-{
-       inline void* getFooter(message_t* msg)
-       {
-               // we use the payload length that we export (the smaller one)
-               return msg->data + call Packet.payloadLength(msg);
-       }
-
-/*----------------- Packet -----------------*/
-
-       command void Packet.clear(message_t* msg) 
-       {
-               call SubPacket.clear(msg);
-       }
-
-       command void Packet.setPayloadLength(message_t* msg, uint8_t len) 
-       {
-               call SubPacket.setPayloadLength(msg, len + sizeof(timesync_relative_t));
-       }
-
-       command uint8_t Packet.payloadLength(message_t* msg) 
-       {
-               return call SubPacket.payloadLength(msg) - sizeof(timesync_relative_t);
-       }
-
-       command uint8_t Packet.maxPayloadLength()
-       {
-               return call SubPacket.maxPayloadLength() - sizeof(timesync_relative_t);
-       }
-
-       command void* Packet.getPayload(message_t* msg, uint8_t len)
-       {
-               return call SubPacket.getPayload(msg, len + sizeof(timesync_relative_t));
-       }
-
-/*----------------- TimeSyncAMSendRadio -----------------*/
-
-       command error_t TimeSyncAMSendRadio.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len, uint32_t event_time)
-       {
-               *(timesync_absolute_t*)(msg->data + len) = event_time;
-
-               call PacketTimeSyncOffset.set(msg, len);
-
-               return call SubSend.send[id](addr, msg, len + sizeof(timesync_relative_t));
-       }
-
-       command error_t TimeSyncAMSendRadio.cancel[am_id_t id](message_t* msg)
-       {
-               return call SubSend.cancel[id](msg);
-       }
-
-       default event void TimeSyncAMSendRadio.sendDone[am_id_t id](message_t* msg, error_t error)
-       {
-       }
-
-       command uint8_t TimeSyncAMSendRadio.maxPayloadLength[am_id_t id]()
-       {
-               return call SubSend.maxPayloadLength[id]() - sizeof(timesync_relative_t);
-       }
-
-       command void* TimeSyncAMSendRadio.getPayload[am_id_t id](message_t* msg, uint8_t len)
-       {
-               return call SubSend.getPayload[id](msg, len + sizeof(timesync_relative_t));
-       }
-
-/*----------------- TimeSyncAMSendMilli -----------------*/
-
-       command error_t TimeSyncAMSendMilli.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len, uint32_t event_time)
-       {
-               // compute elapsed time in millisecond
-               event_time = ((int32_t)(event_time - call LocalTimeMilli.get()) << 10) + call LocalTimeRadio.get();
-
-               return call TimeSyncAMSendRadio.send[id](addr, msg, len, event_time);
-       }
-
-       command error_t TimeSyncAMSendMilli.cancel[am_id_t id](message_t* msg)
-       {
-               return call TimeSyncAMSendRadio.cancel[id](msg);
-       }
-
-       default event void TimeSyncAMSendMilli.sendDone[am_id_t id](message_t* msg, error_t error)
-       {
-       }
-
-       command uint8_t TimeSyncAMSendMilli.maxPayloadLength[am_id_t id]()
-       {
-               return call TimeSyncAMSendRadio.maxPayloadLength[id]();
-       }
-
-       command void* TimeSyncAMSendMilli.getPayload[am_id_t id](message_t* msg, uint8_t len)
-       {
-               return call TimeSyncAMSendRadio.getPayload[id](msg, len);
-       }
-
-       /*----------------- SubSend.sendDone -------------------*/
-
-       event void SubSend.sendDone[am_id_t id](message_t* msg, error_t error)
-       {
-               signal TimeSyncAMSendRadio.sendDone[id](msg, error);
-               signal TimeSyncAMSendMilli.sendDone[id](msg, error);
-       }
-
-       /*----------------- TimeSyncPacketRadio -----------------*/
-
-       command bool TimeSyncPacketRadio.isValid(message_t* msg)
-       {
-               timesync_relative_t* timesync = getFooter(msg);
-
-               return call PacketTimeStampRadio.isValid(msg) && *timesync != 0x80000000L;
-       }
-
-       command uint32_t TimeSyncPacketRadio.eventTime(message_t* msg)
-       {
-               timesync_relative_t* timesync = getFooter(msg);
-
-               return (*timesync) + call PacketTimeStampRadio.timestamp(msg);
-       }
-
-       /*----------------- TimeSyncPacketMilli -----------------*/
-
-       command bool TimeSyncPacketMilli.isValid(message_t* msg)
-       {
-               timesync_relative_t* timesync = getFooter(msg);
-
-               return call PacketTimeStampMilli.isValid(msg) && *timesync != 0x80000000L;
-       }
-
-       command uint32_t TimeSyncPacketMilli.eventTime(message_t* msg)
-       {
-               timesync_relative_t* timesync = getFooter(msg);
-
-               return ((int32_t)(*timesync) >> 10) + call PacketTimeStampMilli.timestamp(msg);
-       }
-}
diff --git a/tos/chips/rf230/RadioAlarm.nc b/tos/chips/rf230/RadioAlarm.nc
deleted file mode 100644 (file)
index d09c4f0..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-interface RadioAlarm
-{
-       /**
-        * Returns TRUE if the alarm is free and ready to be used. Once the alarm
-        * is free, it cannot become nonfree in the same tasklet block. Note,
-        * if the alarm is currently set (even if for ourselves) then it is not free.
-        */
-       tasklet_async command bool isFree();
-
-       /**
-        * Waits till the specified timeout period expires. The alarm must be free.
-        */
-       tasklet_async command void wait(uint16_t timeout);
-
-       /**
-        * Cancels the running alarm. The alarm must be pending.
-        */
-       tasklet_async command void cancel();
-
-       /**
-        * This event is fired when the specified timeout period expires.
-        */
-       tasklet_async event void fired();
-
-       /**
-        * Returns the current time as measured by the radio stack.
-        */
-       async command uint16_t getNow();
-}
diff --git a/tos/chips/rf230/RadioAlarmC.nc b/tos/chips/rf230/RadioAlarmC.nc
deleted file mode 100644 (file)
index a1b811d..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration RadioAlarmC
-{
-       provides
-       {
-               interface RadioAlarm[uint8_t id]; // use unique("RadioAlarm")
-       }
-
-       uses
-       {
-               interface Alarm<TRF230, uint16_t> @exactlyonce();
-       }
-}
-
-implementation
-{
-       components RadioAlarmP, TaskletC;
-
-       RadioAlarm = RadioAlarmP;
-       Alarm = RadioAlarmP;
-       RadioAlarmP.Tasklet -> TaskletC;
-}
diff --git a/tos/chips/rf230/RadioAlarmP.nc b/tos/chips/rf230/RadioAlarmP.nc
deleted file mode 100644 (file)
index d712c6e..0000000
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-#include <RadioAssert.h>
-
-module RadioAlarmP
-{
-       provides
-       {
-               interface RadioAlarm[uint8_t id];
-       }
-
-       uses
-       {
-               interface Alarm<TRF230, uint16_t>;
-               interface Tasklet;
-       }
-}
-
-implementation
-{
-       norace uint8_t state;
-       enum
-       {
-               STATE_READY = 0,
-               STATE_WAIT = 1,
-               STATE_FIRED = 2,
-       };
-
-       tasklet_norace uint8_t alarm;
-
-       async event void Alarm.fired()
-       {
-               atomic
-               {
-                       if( state == STATE_WAIT )
-                               state = STATE_FIRED;
-               }
-
-               call Tasklet.schedule();
-       }
-
-       inline async command uint16_t RadioAlarm.getNow[uint8_t id]()
-       {
-               return call Alarm.getNow();
-       }
-
-       tasklet_async event void Tasklet.run()
-       {
-               if( state == STATE_FIRED )
-               {
-                       state = STATE_READY;
-                       signal RadioAlarm.fired[alarm]();
-               }
-       }
-
-       default tasklet_async event void RadioAlarm.fired[uint8_t id]()
-       {
-       }
-
-       inline tasklet_async command bool RadioAlarm.isFree[uint8_t id]()
-       {
-               return state == STATE_READY;
-       }
-
-       tasklet_async command void RadioAlarm.wait[uint8_t id](uint16_t timeout)
-       {
-               ASSERT( state == STATE_READY );
-
-               alarm = id;
-               state = STATE_WAIT;
-               call Alarm.start(timeout);
-       }
-
-       tasklet_async command void RadioAlarm.cancel[uint8_t id]()
-       {
-               ASSERT( alarm == id );
-               ASSERT( state != STATE_READY );
-
-               call Alarm.stop();
-               state = STATE_READY;
-       }
-}
diff --git a/tos/chips/rf230/RadioAssert.h b/tos/chips/rf230/RadioAssert.h
deleted file mode 100644 (file)
index 19f1726..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#ifndef __RADIOASSERT_H__
-#define __RADIOASSERT_H__
-
-#ifdef RF230_DEBUG
-
-       void assert(bool condition, const char* file, uint16_t line);
-       #define ASSERT(COND) assert(COND, __FILE__, __LINE__)
-
-#else
-
-       #define ASSERT(COND) for(;0;)
-
-#endif
-
-#endif//__RADIOASSERT_H__
diff --git a/tos/chips/rf230/RadioCCA.nc b/tos/chips/rf230/RadioCCA.nc
deleted file mode 100644 (file)
index 78e1694..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-interface RadioCCA
-{
-       /**
-        * Starts the clear channel assesment procedure. Returns EBUSY if the radio
-        * is currently servicing a clear channel assesment, and SUCCESS otherwise.
-        * The check will be performed only in the RX_READY state.
-        */
-       tasklet_async command error_t request();
-
-       /**
-        * Signals the completion of the clear channel assesment send command.
-        * SUCCESS means the channel is clear, EBUSY means the channel is not
-        * clear, and FAIL means that the clear channel assesment could not
-        * be finished or the operation was cancelled.
-        */
-       tasklet_async event void done(error_t error);
-}
diff --git a/tos/chips/rf230/RadioReceive.nc b/tos/chips/rf230/RadioReceive.nc
deleted file mode 100644 (file)
index 0e8330f..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-interface RadioReceive
-{
-       /**
-        * This event is fired when the header is received/downloaded and the 
-        * higher layers are consulted whether it needs to be downloaded and 
-        * further processed. Return FALSE if the message should be discarded.
-        * In particular, the message buffer layer returns FALSE if there is
-        * no space for a new message, so this message will not get acknowledged.
-        */
-       tasklet_async event bool header(message_t* msg);
-
-       /**
-        * Signals the reception of a message, but only for those messages for
-        * which SUCCESS was returned in the header event. The usual owner rules 
-        * apply to the message pointers.
-        */
-       tasklet_async event message_t* receive(message_t* msg);
-}
diff --git a/tos/chips/rf230/RadioSend.nc b/tos/chips/rf230/RadioSend.nc
deleted file mode 100644 (file)
index 5943794..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-interface RadioSend
-{
-       /**
-        * Starts the transmission of the given message. This command must not
-        * be called while another send is in progress (so one must wait for the
-        * sendDone event). Returns EBUSY if a reception is in progress or for
-        * some other reason the request cannot be temporarily satisfied (e.g.
-        * the SPI bus access could not be acquired). In this case the send 
-        * command could be retried from a tasklet. Returns SUCCESS if the 
-        * transmission could be started. In this case sendDone will be fired.
-        */
-       tasklet_async command error_t send(message_t* msg);
-       
-       /**
-        * Signals the completion of the send command, exactly once for each 
-        * successfull send command. If the returned error code is SUCCESS, then 
-        * the message was sent (may not have been acknowledged), otherwise 
-        * the message was not transmitted over the air.
-        */
-       tasklet_async event void sendDone(error_t error);
-
-       /**
-        * This event is fired when the component is most likely able to accept 
-        * a send request. If the send command has returned with a failure, then
-        * this event will be called at least once in the near future.
-        */
-       tasklet_async event void ready();
-}
diff --git a/tos/chips/rf230/RadioState.nc b/tos/chips/rf230/RadioState.nc
deleted file mode 100644 (file)
index 7254383..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-interface RadioState
-{
-       /**
-        * Moves to radio into sleep state with the lowest power consumption but 
-        * highest wakeup time. The radio cannot send or receive in this state 
-        * and releases all access to shared resources (e.g. SPI bus). 
-        */
-       tasklet_async command error_t turnOff();
-
-       /**
-        * The same as the turnOff command, except it is not as deep sleep, and
-        * it is quicker to recover from this state.
-        */
-       tasklet_async command error_t standby();
-
-       /**
-        * Goes into receive state. The radio continuously receive messages 
-        * and able to transmit.
-        */
-       tasklet_async command error_t turnOn();
-
-       /**
-        * Sets the current channel. Returns EBUSY if the stack is unable
-        * to change the channel this time (some other operation is in progress)
-        * SUCCESS otherwise.
-        */
-       tasklet_async command error_t setChannel(uint8_t channel);
-
-       /**
-        * This event is signaled exactly once for each sucessfully posted state 
-        * transition and setChannel command when it is completed.
-        */
-       tasklet_async event void done();
-}
diff --git a/tos/chips/rf230/RandomCollisionConfig.nc b/tos/chips/rf230/RandomCollisionConfig.nc
deleted file mode 100644 (file)
index b12cc69..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-interface RandomCollisionConfig
-{
-       /**
-        * Returns the initial amount of maximum backoff for this message.
-        */
-       async command uint16_t getInitialBackoff(message_t* msg);
-
-       /**
-        * Returns the amount of maximum backoff when there is congestion
-        * (the channel was busy for the first try)
-        */
-       async command uint16_t getCongestionBackoff(message_t* msg);
-
-       /**
-        * Returns the minimum ticks before the message could be sent.
-        */
-       async command uint16_t getMinimumBackoff();
-
-       /**
-        * The provided message was just received, and this command should return 
-        * the time till no transmission should be initiated.
-        */
-       async command uint16_t getTransmitBarrier(message_t* msg);
-}
diff --git a/tos/chips/rf230/RandomCollisionLayerC.nc b/tos/chips/rf230/RandomCollisionLayerC.nc
deleted file mode 100644 (file)
index ba7ad05..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration RandomCollisionLayerC
-{
-       provides
-       {
-               interface RadioSend;
-               interface RadioReceive;
-       }
-       uses
-       {
-               interface RadioSend as SubSend;
-               interface RadioReceive as SubReceive;
-               interface RandomCollisionConfig as Config;
-       }
-}
-
-implementation
-{
-       components RandomCollisionLayerP, RadioAlarmC, RandomC;
-
-       RadioSend = RandomCollisionLayerP;
-       SubSend = RandomCollisionLayerP;
-       Config = RandomCollisionLayerP;
-       RadioReceive = RandomCollisionLayerP;
-       SubReceive = RandomCollisionLayerP;
-
-       RandomCollisionLayerP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
-       RandomCollisionLayerP.Random -> RandomC;
-}
diff --git a/tos/chips/rf230/RandomCollisionLayerP.nc b/tos/chips/rf230/RandomCollisionLayerP.nc
deleted file mode 100644 (file)
index c53d1b9..0000000
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-#include <RadioAssert.h>
-
-module RandomCollisionLayerP
-{
-       provides
-       {
-               interface RadioSend;
-               interface RadioReceive;
-       }
-       uses
-       {
-               interface RadioSend as SubSend;
-               interface RadioReceive as SubReceive;
-               interface RadioAlarm;
-               interface Random;
-               interface RandomCollisionConfig as Config;
-       }
-}
-
-implementation
-{
-       tasklet_norace uint8_t state;
-       enum
-       {
-               STATE_READY = 0,
-               STATE_TX_PENDING_FIRST = 1,
-               STATE_TX_PENDING_SECOND = 2,
-               STATE_TX_SENDING = 3,
-
-               STATE_BARRIER = 0x80,
-       };
-
-       tasklet_norace message_t *txMsg;
-       tasklet_norace uint16_t txBarrier;
-
-       tasklet_async event void SubSend.ready()
-       {
-               if( state == STATE_READY && call RadioAlarm.isFree() )
-                       signal RadioSend.ready();
-       }
-
-       uint16_t nextRandom;
-       task void calcNextRandom()
-       {
-               uint16_t a = call Random.rand16();
-               atomic nextRandom = a;
-       }
-
-       uint16_t getBackoff(uint16_t maxBackoff)
-       {
-               uint16_t a;
-
-               atomic
-               {
-                       a = nextRandom;
-                       nextRandom += 273;
-               }
-               post calcNextRandom();
-
-               return (a % maxBackoff) + call Config.getMinimumBackoff();
-       }
-
-       tasklet_async command error_t RadioSend.send(message_t* msg)
-       {
-               if( state != STATE_READY || ! call RadioAlarm.isFree() )
-                       return EBUSY;
-
-               txMsg = msg;
-               state = STATE_TX_PENDING_FIRST;
-               call RadioAlarm.wait(getBackoff(call Config.getInitialBackoff(msg)));
-
-               return SUCCESS;
-       }
-
-       tasklet_async event void RadioAlarm.fired()
-       {
-               error_t error;
-               int16_t delay;
-
-               ASSERT( state != STATE_READY );
-
-               delay = (int16_t)txBarrier - call RadioAlarm.getNow();
-
-               if( state == STATE_BARRIER )
-               {
-                       state = STATE_READY;
-
-                       signal RadioSend.ready();
-                       return;
-               }
-               else if( (state & STATE_BARRIER) && delay > 0 )
-                       error = EBUSY;
-               else
-                       error = call SubSend.send(txMsg);
-
-               if( error != SUCCESS )
-               {
-                       if( (state & ~STATE_BARRIER) == STATE_TX_PENDING_FIRST )
-                       {
-                               state = (state & STATE_BARRIER) | STATE_TX_PENDING_SECOND;
-                               call RadioAlarm.wait(getBackoff(call Config.getCongestionBackoff(txMsg)));
-                       }
-                       else
-                       {
-                               if( (state & STATE_BARRIER) && delay > 0 )
-                               {
-                                       state = STATE_BARRIER;
-                                       call RadioAlarm.wait(delay);
-                               }
-                               else
-                                       state = STATE_READY;
-
-                               signal RadioSend.sendDone(error);
-                       }
-               }
-               else
-                       state = STATE_TX_SENDING;
-       }
-
-       tasklet_async event void SubSend.sendDone(error_t error)
-       {
-               ASSERT( state == STATE_TX_SENDING );
-
-               state = STATE_READY;
-               signal RadioSend.sendDone(error);
-       }
-
-       tasklet_async event bool SubReceive.header(message_t* msg)
-       {
-               return signal RadioReceive.header(msg);
-       }
-
-       tasklet_async event message_t* SubReceive.receive(message_t* msg)
-       {
-               int16_t delay;
-
-               txBarrier = call Config.getTransmitBarrier(msg);
-               delay = txBarrier - call RadioAlarm.getNow();
-
-               if( delay > 0 )
-               {
-                       if( state == STATE_READY )
-                       {
-                               call RadioAlarm.wait(delay);
-                               state = STATE_BARRIER;
-                       }
-                       else
-                               state |= STATE_BARRIER;
-               }
-
-               return signal RadioReceive.receive(msg);
-       }
-}
diff --git a/tos/chips/rf230/SlottedCollisionConfig.nc b/tos/chips/rf230/SlottedCollisionConfig.nc
deleted file mode 100644 (file)
index 4b6b993..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-interface SlottedCollisionConfig
-{
-       /**
-        * This command should return the approximate transmit delay between
-        * setting an alarm, waiting for the fire event, calling send and
-        * obtaining the timestamp for the transmitted message.
-        */
-       async command uint16_t getInitialDelay();
-
-       /**
-        * Must return a binary exponent so that the collision avoidance layer
-        * can assign slots in the range of [0, 1 << exponent) of size collision
-        * window.
-        */
-       async command uint8_t getScheduleExponent();
-
-       /**
-        * This command must return the time when the message was transmitted.
-        */
-       async command uint16_t getTransmitTime(message_t* msg);
-
-       /**
-        * Returns the start of the collision window for this received message,
-        * so transmit times in this range would be considered possible collisions.
-        */
-       async command uint16_t getCollisionWindowStart(message_t* msg);
-
-       /**
-        * Returns the size of the collision window for this received message.
-        */
-       async command uint16_t getCollisionWindowLength(message_t* msg);
-
-       /**
-        * This event should be called periodically to indicate the passing of
-        * time (maybe we should use a timer)
-        */
-       tasklet_async event void timerTick();
-}
diff --git a/tos/chips/rf230/SlottedCollisionLayerC.nc b/tos/chips/rf230/SlottedCollisionLayerC.nc
deleted file mode 100644 (file)
index 0028846..0000000
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration SlottedCollisionLayerC
-{
-       provides
-       {
-               interface RadioSend;
-               interface RadioReceive;
-       }
-       uses
-       {
-               interface RadioSend as SubSend;
-               interface RadioReceive as SubReceive;
-               interface SlottedCollisionConfig as Config;
-       }
-}
-
-implementation
-{
-       components SlottedCollisionLayerP, MainC, RadioAlarmC, RandomC;
-
-       RadioSend = SlottedCollisionLayerP;
-       RadioReceive = SlottedCollisionLayerP;
-       SubSend = SlottedCollisionLayerP;
-       SubReceive = SlottedCollisionLayerP;
-       Config = SlottedCollisionLayerP;
-       
-       SlottedCollisionLayerP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
-       SlottedCollisionLayerP.Random -> RandomC;
-       MainC.SoftwareInit -> SlottedCollisionLayerP;
-
-#ifdef RF230_DEBUG
-       components DiagMsgC;
-       SlottedCollisionLayerP.DiagMsg -> DiagMsgC;
-#endif
-}
diff --git a/tos/chips/rf230/SlottedCollisionLayerP.nc b/tos/chips/rf230/SlottedCollisionLayerP.nc
deleted file mode 100644 (file)
index f9108ee..0000000
+++ /dev/null
@@ -1,275 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-#include <RadioAssert.h>
-
-module SlottedCollisionLayerP
-{
-       provides
-       {
-               interface RadioSend;
-               interface RadioReceive;
-               interface Init;
-       }
-       uses
-       {
-               interface RadioSend as SubSend;
-               interface RadioReceive as SubReceive;
-               interface RadioAlarm;
-               interface Random;
-               interface SlottedCollisionConfig as Config;
-#ifdef RF230_DEBUG
-               interface DiagMsg;
-#endif
-       }
-}
-
-implementation
-{
-/* ----- random ----- */
-
-       uint16_t nextRandom;
-
-       task void calcNextRandom()
-       {
-               uint16_t a = call Random.rand16();
-               atomic nextRandom = a;
-       }
-
-       uint16_t getNextRandom()
-       {
-               uint16_t a;
-
-               atomic
-               {
-                       a = nextRandom;
-                       nextRandom += 273;
-               }
-               post calcNextRandom();
-
-               return a;
-       }
-
-/* ----- schedule selection ----- */
-
-       tasklet_async event bool SubReceive.header(message_t* msg)
-       {
-               return signal RadioReceive.header(msg);
-       }
-
-       // WARNING!!! Do not change these values, the error values can overflow
-       enum
-       {
-               ERROR_DECAY = 3,
-               ERROR_SWITCH = 30,              // should be a multiple of (1 << decay)
-               ERROR_COLLISION = 20,   // must be less than (255 - switch) >> decay
-               ERROR_BUSY = 1,                 // must be less than collision
-               ERROR_INITIAL = 80,             // must be less than giveup
-               ERROR_GIVEUP = 120,             // must be less than collision * (1 << decay)
-               ERROR_REPRESS = 40,             // must be more than switch
-               ERROR_MAX = 255,
-       };
-
-       /**
-        * Returns TRUE if time is between start and start + window 
-        * modulo the schedule size of (1 << exponent)
-        */
-       inline bool isBetween(uint8_t exponent, uint16_t time, uint16_t start, uint16_t length)
-       {
-               return (uint16_t)((time - start) & ((1 << exponent) - 1)) < length;
-       }
-
-       tasklet_norace uint16_t schedule1;
-       tasklet_norace uint16_t schedule2;
-
-       tasklet_norace uint8_t error1;
-       tasklet_norace uint8_t error2;
-
-       tasklet_async event message_t* SubReceive.receive(message_t* msg)
-       {
-               uint8_t exponent = call Config.getScheduleExponent();
-               uint16_t start = call Config.getCollisionWindowStart(msg);
-               uint16_t length = call Config.getCollisionWindowLength(msg);
-
-               error1 -= error1 >> ERROR_DECAY;
-               if( isBetween(exponent, schedule1, start, length) )
-                       error1 += ERROR_COLLISION; 
-
-               error2 -= error2 >> ERROR_DECAY;
-               if( isBetween(exponent, schedule2, start, length) )
-                       error2 += ERROR_COLLISION;
-
-               if( error2 + ERROR_SWITCH <= error1 )
-               {
-                       error1 = error2;
-                       schedule1 = schedule2;
-                       error2 = ERROR_GIVEUP;
-               }
-
-               if( error2 >= ERROR_GIVEUP )
-               {
-                       error2 = ERROR_INITIAL;
-                       schedule2 = getNextRandom();
-               }
-
-               return signal RadioReceive.receive(msg);
-       }
-
-       void printStats();
-
-       tasklet_async event void Config.timerTick()
-       {
-               if( error1 >= (1 << ERROR_DECAY) )
-                       error1 -= error1 >> ERROR_DECAY;
-               else if( error1 > 0 )
-                       --error1;
-
-               if( error2 >= (1 << ERROR_DECAY) )
-                       error2 -= error2 >> ERROR_DECAY;
-               else if( error2 > 0 )
-                       --error2;
-
-               printStats();
-       }
-
-/* ------ transmit ------ */
-
-       tasklet_norace uint8_t state;
-       enum
-       {
-               STATE_READY = 0,
-               STATE_PENDING = 1,
-               STATE_SENDING = 2,
-       };
-
-       enum { DELAY_DECAY = 2 };
-
-       tasklet_norace message_t *txMsg;
-       tasklet_norace uint16_t txDelay;        // the averaged delay between schedule and timestamp
-       tasklet_norace uint16_t txTime;         // the schedule time of transmission
-
-       tasklet_async event void SubSend.ready()
-       {
-               if( state == STATE_READY && call RadioAlarm.isFree() )
-                       signal RadioSend.ready();
-       }
-
-       tasklet_async command error_t RadioSend.send(message_t* msg)
-       {
-               uint16_t backoff;
-               uint16_t time;
-
-               // TODO: we could supress transmission while error is large
-               if( state != STATE_READY || ! call RadioAlarm.isFree() || error1 >= ERROR_REPRESS )
-                       return EBUSY;
-
-               txMsg = msg;
-               state = STATE_PENDING;
-
-               time = call RadioAlarm.getNow();
-               backoff = 1 + ((schedule1 - time - (txDelay >> DELAY_DECAY))
-                       & ((1 << call Config.getScheduleExponent()) - 1));
-
-               backoff += getNextRandom() & (3 << call Config.getScheduleExponent());
-
-               call RadioAlarm.wait(backoff);
-               txTime = time + backoff;
-
-               return SUCCESS;
-       }
-
-       tasklet_async event void RadioAlarm.fired()
-       {
-               error_t error;
-
-               ASSERT( state == STATE_PENDING );
-
-               error = call SubSend.send(txMsg);
-               if( error == SUCCESS )
-                       state = STATE_SENDING;
-               else
-               {
-                       if( error2 + ERROR_SWITCH <= error1 )
-                       {
-                               error1 = error2;
-                               schedule1 = schedule2;
-                               error2 = ERROR_INITIAL;
-                               schedule2 = getNextRandom();
-                       }
-                       else if( error1 < ERROR_MAX - ERROR_BUSY )
-                               error1 = error1 + ERROR_BUSY;
-
-                       state = STATE_READY;
-                       signal RadioSend.sendDone(error);
-               }
-       }
-
-       tasklet_async event void SubSend.sendDone(error_t error)
-       {
-               ASSERT( state == STATE_SENDING );
-
-               if( error == SUCCESS )
-               {
-                       txDelay += (call Config.getTransmitTime(txMsg) - txTime) - (txDelay >> DELAY_DECAY);
-
-                       ASSERT( (txDelay >> DELAY_DECAY) < (1 << call Config.getScheduleExponent()) );
-               }
-
-               state = STATE_READY;
-               signal RadioSend.sendDone(error);
-       }
-
-/* ------ init  ------ */
-
-       command error_t Init.init()
-       {
-               // do not use Random here because it might not be initialized
-               schedule1 = (uint16_t)(TOS_NODE_ID * 1973);
-               schedule2 = schedule1 + 0117;
-               txDelay = call Config.getInitialDelay() << DELAY_DECAY;
-
-               return SUCCESS;
-       }
-
-#ifdef RF230_DEBUG
-       tasklet_norace uint8_t count;
-       void printStats()
-       {
-               if( ++count > 10 && call DiagMsg.record() )
-               {
-                       count = 0;
-
-                       call DiagMsg.str("slotted");
-                       call DiagMsg.uint16(txDelay >> DELAY_DECAY);
-                       call DiagMsg.uint16(schedule1);
-                       call DiagMsg.uint8(error1);
-                       call DiagMsg.uint16(schedule2);
-                       call DiagMsg.uint8(error2);
-                       call DiagMsg.send();
-               }
-       }
-#else
-       void printStats() { }
-#endif
-}
diff --git a/tos/chips/rf230/SoftwareAckConfig.nc b/tos/chips/rf230/SoftwareAckConfig.nc
deleted file mode 100644 (file)
index b3c87c7..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-interface SoftwareAckConfig
-{
-       /**
-        * Returns the acknowledgement timeout (in the radio clock units),
-        * in which a sent packet must be acknowledged.
-        */
-       async command uint16_t getAckTimeout();
-
-       /**
-        * Returns TRUE if the layer should wait for a software acknowledgement
-        * to be received after this packet was transmitted.
-        */
-       async command bool requiresAckWait(message_t* msg);
-
-       /**
-        * Sets for the transmitted message whether it was acknowledged or not.
-        */
-       async command void setAckReceived(message_t* msg, bool acked);
-
-       /**
-        * Returns TRUE if the received packet is an acknowledgement packet.
-        * The AckedSend layer will filter out all received acknowledgement
-        * packets and uses  only the matching one for the acknowledgement.
-        */
-       async command bool isAckPacket(message_t* msg);
-
-       /**
-        * Returns TRUE if the acknowledgement packet corresponds to the
-        * data packet. The acknowledgement packect was already verified 
-        * to be a valid acknowledgement packet via the isAckPacket command.
-        */
-       async command bool verifyAckPacket(message_t* data, message_t* ack);
-
-       /**
-        * Returns TRUE if the received packet needs software acknowledgements
-        * to be sent back to the sender.
-        */
-       async command bool requiresAckReply(message_t* msg);
-
-       /**
-        * Creates an acknowledgement packet for the given data packet.
-        */
-       async command void createAckPacket(message_t* data, message_t* ack);
-
-       /**
-        * This command is called when a sent packet did not receive an
-        * acknowledgement.
-        */
-       tasklet_async command void reportChannelError();
-}
diff --git a/tos/chips/rf230/SoftwareAckLayerC.nc b/tos/chips/rf230/SoftwareAckLayerC.nc
deleted file mode 100644 (file)
index 97703e1..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration SoftwareAckLayerC
-{
-       provides
-       {
-               interface RadioSend;
-               interface RadioReceive;
-       }
-       uses
-       {
-               interface RadioSend as SubSend;
-               interface RadioReceive as SubReceive;
-
-               interface SoftwareAckConfig as Config;
-       }
-}
-
-implementation
-{
-       components SoftwareAckLayerP, RadioAlarmC;
-
-       RadioSend = SoftwareAckLayerP;
-       RadioReceive = SoftwareAckLayerP;
-       SubSend = SoftwareAckLayerP;
-       SubReceive = SoftwareAckLayerP;
-       Config = SoftwareAckLayerP;
-
-       SoftwareAckLayerP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
-}
diff --git a/tos/chips/rf230/SoftwareAckLayerP.nc b/tos/chips/rf230/SoftwareAckLayerP.nc
deleted file mode 100644 (file)
index 02ca70d..0000000
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-#include <RadioAssert.h>
-
-module SoftwareAckLayerP
-{
-       provides
-       {
-               interface RadioSend;
-               interface RadioReceive;
-       }
-       uses
-       {
-               interface RadioSend as SubSend;
-               interface RadioReceive as SubReceive;
-               interface RadioAlarm;
-
-               interface SoftwareAckConfig;
-       }
-}
-
-implementation
-{
-       tasklet_norace uint8_t state;
-       enum
-       {
-               STATE_READY = 0,
-               STATE_DATA_SEND = 1,
-               STATE_ACK_WAIT = 2,
-               STATE_ACK_SEND = 3,
-       };
-
-       tasklet_norace message_t *txMsg;
-       tasklet_norace message_t ackMsg;
-
-       tasklet_async event void SubSend.ready()
-       {
-               if( state == STATE_READY )
-                       signal RadioSend.ready();
-       }
-
-       tasklet_async command error_t RadioSend.send(message_t* msg)
-       {
-               error_t error;
-
-               if( state == STATE_READY )
-               {
-                       if( (error = call SubSend.send(msg)) == SUCCESS )
-                       {
-                               call SoftwareAckConfig.setAckReceived(msg, FALSE);
-                               state = STATE_DATA_SEND;
-                               txMsg = msg;
-                       }
-               }
-               else
-                       error = EBUSY;
-
-               return error;
-       }
-
-       tasklet_async event void SubSend.sendDone(error_t error)
-       {
-               if( state == STATE_ACK_SEND )
-               {
-                       // TODO: what if error != SUCCESS
-                       ASSERT( error == SUCCESS );
-
-                       state = STATE_READY;
-               }
-               else
-               {
-                       ASSERT( state == STATE_DATA_SEND );
-                       ASSERT( call RadioAlarm.isFree() );
-
-                       if( error == SUCCESS && call SoftwareAckConfig.requiresAckWait(txMsg) && call RadioAlarm.isFree() )
-                       {
-                               call RadioAlarm.wait(call SoftwareAckConfig.getAckTimeout());
-                               state = STATE_ACK_WAIT;
-                       }
-                       else
-                       {
-                               state = STATE_READY;
-                               signal RadioSend.sendDone(error);
-                       }
-               }
-       }
-
-       tasklet_async event void RadioAlarm.fired()
-       {
-               ASSERT( state == STATE_ACK_WAIT );
-
-               call SoftwareAckConfig.reportChannelError();
-
-               state = STATE_READY;
-               signal RadioSend.sendDone(SUCCESS);     // we have sent it, but not acked
-       }
-
-       tasklet_async event bool SubReceive.header(message_t* msg)
-       {
-               if( call SoftwareAckConfig.isAckPacket(msg) )
-                       return state == STATE_ACK_WAIT && call SoftwareAckConfig.verifyAckPacket(txMsg, msg);
-               else
-                       return signal RadioReceive.header(msg);
-       }
-
-       tasklet_async event message_t* SubReceive.receive(message_t* msg)
-       {
-               bool ack = call SoftwareAckConfig.isAckPacket(msg);
-
-               ASSERT( state == STATE_ACK_WAIT || state == STATE_READY );
-
-               if( state == STATE_ACK_WAIT )
-               {
-                       ASSERT( !ack || call SoftwareAckConfig.verifyAckPacket(txMsg, msg) );
-
-                       call RadioAlarm.cancel();
-                       call SoftwareAckConfig.setAckReceived(txMsg, ack);
-
-                       state = STATE_READY;
-                       signal RadioSend.sendDone(SUCCESS);
-               }
-
-               if( ack )
-                       return msg;
-
-               if( call SoftwareAckConfig.requiresAckReply(msg) )
-               {
-                       call SoftwareAckConfig.createAckPacket(msg, &ackMsg);
-
-                       // TODO: what to do if we are busy and cannot send an ack
-                       if( call SubSend.send(&ackMsg) == SUCCESS )
-                               state = STATE_ACK_SEND;
-                       else
-                               ASSERT(FALSE);
-               }
-
-               return signal RadioReceive.receive(msg);
-       }
-}
diff --git a/tos/chips/rf230/Tasklet.h b/tos/chips/rf230/Tasklet.h
deleted file mode 100644 (file)
index 38f185f..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#ifndef __TASKLET_H__
-#define __TASKLET_H__
-
-#ifdef TASKLET_IS_TASK
-
-       #define tasklet_async
-       #define tasklet_norace
-
-#else
-
-       #define tasklet_async   async   
-       #define tasklet_norace  norace
-
-#endif
-
-#endif//__RF230_H__
diff --git a/tos/chips/rf230/Tasklet.nc b/tos/chips/rf230/Tasklet.nc
deleted file mode 100644 (file)
index 527400a..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-/**
- * This interface is useful in building state machines when the state 
- * transitions should be executed atomically but with interrupts enabled. 
- * All state transitions should take place in the run event handler or
- * in blocks protected by the suspend and resume commands.
- */
-interface Tasklet
-{
-       /**
-        * This method is executed atomically. 
-        */
-       tasklet_async event void run();
-
-       /**
-        * Makes sure that the run event is called at least once more. If the 
-        * run event is currently not executing, then it  is called immediately 
-        * and this command returns only after the completion of the run event. 
-        * If the run event is currently executed, then this method returns at 
-        * once, and makes sure that the run event is called once more when 
-        * it is finished. If this method is called from a task, then by the 
-        * above rules, the run event will be called from a task as well.
-        */
-       async command void schedule();
-
-       /**
-        * Enters a critical section of the code and meakes sure that the
-        * run event is not called while in this section. No long running
-        * computation should be called from the critical session, and
-        * in particular no user event should be fired. This call is only
-        * possible from task context, otherwise we cannot guarantee that
-        * the run event is not currently running. The suspend calls
-        * can be nested. It is very important that the same number of
-        * resume commands must be called in all control paths, e.g. be very
-        * careful with the return and break commands.
-        */
-       command void suspend();
-
-       /**
-        * Leaves the critical section. This call is conly possible from 
-        * task context. If there were scheduled executions of the run
-        * event, then those will be called before this command returns.
-        */
-       command void resume();
-}
diff --git a/tos/chips/rf230/TaskletC.nc b/tos/chips/rf230/TaskletC.nc
deleted file mode 100644 (file)
index 360f54f..0000000
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-#include <RadioAssert.h>
-
-module TaskletC
-{
-       provides interface Tasklet;
-}
-
-implementation
-{
-#ifdef TASKLET_IS_TASK
-
-       task void tasklet()
-       {
-               signal Tasklet.run();
-       }
-
-       inline async command void Tasklet.schedule()
-       {
-               post tasklet();
-       }
-
-       inline command void Tasklet.suspend()
-       {
-       }
-
-       inline command void Tasklet.resume()
-       {
-       }
-
-#else
-       
-       /**
-        * The lower 7 bits contain the number of suspends plus one if the run 
-        * event is currently beeing executed. The highest bit is set if the run 
-        * event needs to be called again when the suspend count goes down to zero.
-        */
-       uint8_t state;
-
-       void doit()
-       {
-               for(;;)
-               {
-                       signal Tasklet.run();
-
-                       atomic
-                       {
-                               if( state == 1 )
-                               {
-                                       state = 0;
-                                       return;
-                               }
-
-                               ASSERT( state == 0x81 );
-                               state = 1;
-                       }
-               }
-       }
-
-       inline command void Tasklet.suspend()
-       {
-               atomic ++state;
-       }
-
-       command void Tasklet.resume()
-       {
-               atomic
-               {
-                       if( --state != 0x80 )
-                               return;
-
-                       state = 1;
-               }
-
-               doit();
-       }
-
-       async command void Tasklet.schedule()
-       {
-               atomic
-               {
-                       if( state != 0 )
-                       {
-                               state |= 0x80;
-                               return;
-                       }
-
-                       state = 1;
-               }
-
-               doit();
-       }
-
-#endif
-}
diff --git a/tos/chips/rf230/TimeSyncMessage.h b/tos/chips/rf230/TimeSyncMessage.h
deleted file mode 100644 (file)
index 38fba02..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#ifndef __TIMESYNCMESSAGE_H__
-#define __TIMESYNCMESSAGE_H__
-
-// this value is sent in the air
-typedef nx_int32_t timesync_relative_t;
-
-// this value is stored in memory
-typedef uint32_t timesync_absolute_t;
-
-#endif//__TIMESYNCMESSAGE_H__
diff --git a/tos/chips/rf230/TrafficMonitorConfig.nc b/tos/chips/rf230/TrafficMonitorConfig.nc
deleted file mode 100644 (file)
index 0b7bc64..0000000
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-interface TrafficMonitorConfig
-{
-       /**
-        * Returns the frequency (in milliseconds) when the traffic averages
-        * should be updated. 
-        */
-       async command uint16_t getUpdatePeriod();
-
-       /**
-        * Returns the amount of time this message has occupied the channel.
-        */
-       async command uint16_t getChannelTime(message_t* msg);
-
-       /**
-        * Returns the sender address of the message so we can calculate the
-        * average number of neighbors that send messages per update period.
-        */
-       async command am_addr_t getSender(message_t* msg);
-
-       /**
-        * This event should be fired if we notice some anomalies in the operation
-        * of the channel, such as not receiving acknowledgements, missing
-        * sequence numbers or packets with corrupted CRC.
-        */
-       tasklet_async event void channelError();
-
-       /**
-        * Returns the averaged (exponential decay) transmit channel time 
-        * during one update period.
-        */
-       tasklet_async event uint16_t getTransmitAverage();
-
-       /**
-        * Returns the averaged (exponential decay) receive channel time 
-        * during one update period.
-        */
-       tasklet_async event uint16_t getReceiveAverage();
-
-       /**
-        * Returns the averaged (exponential decay) number of neighbors 
-        * whose messages this component receives during one update period.
-        */
-       tasklet_async event uint8_t getNeighborAverage();
-
-       /**
-        * Returns the averaged error events during one update period.
-        */
-       tasklet_async event uint8_t getErrorAverage();
-
-       /**
-        * This command is periodically called when the timer is fired and
-        * the averages are updated
-        */
-       tasklet_async command void timerTick();
-}
diff --git a/tos/chips/rf230/TrafficMonitorLayerC.nc b/tos/chips/rf230/TrafficMonitorLayerC.nc
deleted file mode 100644 (file)
index b144c8a..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration TrafficMonitorLayerC
-{
-       provides
-       {
-               interface RadioSend;
-               interface RadioReceive;
-               interface RadioState;
-       }
-       uses
-       {
-               interface RadioSend as SubSend;
-               interface RadioReceive as SubReceive;
-               interface RadioState as SubState;
-
-               interface TrafficMonitorConfig as Config;
-       }
-}
-
-implementation
-{
-       components TrafficMonitorLayerP, new TimerMilliC() as UpdateTimerC; 
-       components NeighborhoodC, new NeighborhoodFlagC(), TaskletC;
-
-       RadioSend = TrafficMonitorLayerP;
-       RadioReceive = TrafficMonitorLayerP;
-       RadioState = TrafficMonitorLayerP;
-       SubSend = TrafficMonitorLayerP;
-       SubReceive = TrafficMonitorLayerP;
-       SubState = TrafficMonitorLayerP;
-       Config = TrafficMonitorLayerP;
-
-       TrafficMonitorLayerP.Timer -> UpdateTimerC;
-       TrafficMonitorLayerP.Neighborhood -> NeighborhoodC;
-       TrafficMonitorLayerP.NeighborhoodFlag -> NeighborhoodFlagC;
-       TrafficMonitorLayerP.Tasklet -> TaskletC;
-
-#ifdef RF230_DEBUG
-       components DiagMsgC;
-       TrafficMonitorLayerP.DiagMsg -> DiagMsgC;
-#endif
-}
diff --git a/tos/chips/rf230/TrafficMonitorLayerP.nc b/tos/chips/rf230/TrafficMonitorLayerP.nc
deleted file mode 100644 (file)
index 75328ac..0000000
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, reportS, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-/*
- * You have to make sure that the maximum channel time in one report
- * period times (1 << TRAFFIC_MONITOR_DECAY) is less than 65535.
- */
-#ifndef TRAFFIC_MONITOR_DECAY
-#define TRAFFIC_MONITOR_DECAY  3
-#endif
-
-module TrafficMonitorLayerP
-{
-       provides
-       {
-               interface RadioSend;
-               interface RadioReceive;
-               interface RadioState;
-       }
-
-       uses
-       {
-               interface TrafficMonitorConfig;
-               interface RadioSend as SubSend;
-               interface RadioReceive as SubReceive;
-               interface RadioState as SubState;
-               interface Timer<TMilli> as Timer;
-               interface Neighborhood;
-               interface NeighborhoodFlag;
-               interface Tasklet;
-#ifdef RF230_DEBUG
-               interface DiagMsg;
-#endif
-       }
-}
-
-implementation
-{
-       tasklet_norace message_t *txMsg;
-       tasklet_norace uint8_t neighborCount;
-
-       tasklet_norace uint16_t txAverage;
-       tasklet_norace uint16_t rxAverage;
-       tasklet_norace uint8_t neighborAverage;
-       tasklet_norace uint8_t errorAverage;
-
-       enum
-       {
-               // the maximum average value
-               TRAFFIC_MONITOR_UINT8_MAX = 1 << (7-TRAFFIC_MONITOR_DECAY),
-
-               // the unsignificant bits of the averaged values
-               TRAFFIC_MONITOR_MASK = (1 << TRAFFIC_MONITOR_DECAY) - 1,
-
-               // to get the ceiling integer value
-               TRAFFIC_MONITOR_ROUND_UP = (1 << TRAFFIC_MONITOR_DECAY) - 1,
-       };
-
-       tasklet_async event void SubSend.ready()
-       {
-               signal RadioSend.ready();
-       }
-
-       tasklet_async command error_t RadioSend.send(message_t* msg)
-       {
-               txMsg = msg;
-               return call SubSend.send(msg);
-       }
-
-       tasklet_async event void SubSend.sendDone(error_t error)
-       {
-               if( error == SUCCESS )
-                       txAverage += call TrafficMonitorConfig.getChannelTime(txMsg);
-
-               signal RadioSend.sendDone(error);
-       }
-
-       tasklet_async event bool SubReceive.header(message_t* msg)
-       {
-               return signal RadioReceive.header(msg);
-       }
-
-       tasklet_async event message_t* SubReceive.receive(message_t* msg)
-       {
-               uint8_t index;
-
-               rxAverage += call TrafficMonitorConfig.getChannelTime(msg);
-
-               index = call Neighborhood.insertNode(call TrafficMonitorConfig.getSender(msg));
-               if( ! call NeighborhoodFlag.get(index) )
-               {
-                       if( neighborCount < TRAFFIC_MONITOR_UINT8_MAX )
-                       {
-                               ++neighborCount;
-                               call NeighborhoodFlag.set(index);
-                       }
-               }
-
-               return signal RadioReceive.receive(msg);
-       }
-
-       tasklet_async event void TrafficMonitorConfig.channelError()
-       {
-               if( errorAverage < 255 )
-                       ++errorAverage;
-       }
-
-       uint8_t debugCounter;
-
-       event void Timer.fired()
-       {
-               uint8_t fraction;
-
-               call Tasklet.suspend();
-
-               txAverage -= (txAverage >> TRAFFIC_MONITOR_DECAY);
-               rxAverage -= (rxAverage >> TRAFFIC_MONITOR_DECAY);
-               errorAverage -= (errorAverage >> TRAFFIC_MONITOR_DECAY);
-
-               // we could get stuck in the [1,7] range with no neighbors, so be more precise
-               fraction = neighborAverage >> TRAFFIC_MONITOR_DECAY;
-               if( fraction == neighborCount && (neighborAverage & TRAFFIC_MONITOR_MASK) != 0 )
-                       --neighborAverage;
-               else
-                       neighborAverage += neighborCount - fraction;
-
-               call NeighborhoodFlag.clearAll();
-               neighborCount = 0;
-
-               call TrafficMonitorConfig.timerTick();
-
-               call Tasklet.resume();
-
-#ifdef RF230_DEBUG
-               if( ++debugCounter >= 10 && call DiagMsg.record() )
-               {
-                       debugCounter = 0;
-
-                       call DiagMsg.str("traffic");
-                       call DiagMsg.uint16(signal TrafficMonitorConfig.getTransmitAverage());
-                       call DiagMsg.uint16(signal TrafficMonitorConfig.getReceiveAverage());
-                       call DiagMsg.uint8(signal TrafficMonitorConfig.getNeighborAverage());
-                       call DiagMsg.uint8(signal TrafficMonitorConfig.getErrorAverage());
-                       call DiagMsg.send();
-               }
-#endif
-       }
-
-       tasklet_async event void Tasklet.run()
-       {
-       }
-
-       tasklet_async event uint16_t TrafficMonitorConfig.getTransmitAverage()
-       {
-               return txAverage >> TRAFFIC_MONITOR_DECAY;
-       }
-
-       tasklet_async event uint16_t TrafficMonitorConfig.getReceiveAverage()
-       {
-               return rxAverage >> TRAFFIC_MONITOR_DECAY;
-       }
-
-       tasklet_async event uint8_t TrafficMonitorConfig.getNeighborAverage()
-       {
-               return (neighborAverage + TRAFFIC_MONITOR_ROUND_UP) >> TRAFFIC_MONITOR_DECAY;
-       }
-
-       tasklet_async event uint8_t TrafficMonitorConfig.getErrorAverage()
-       {
-               return errorAverage >> TRAFFIC_MONITOR_DECAY;
-       }
-
-       tasklet_async event void Neighborhood.evicted(uint8_t index) { }
-
-       enum
-       {
-               RADIO_CMD_NONE = 0,
-               RADIO_CMD_TURNON = 1,
-               RADIO_CMD_TURNOFF = 2,
-       };
-       tasklet_norace uint8_t radioCmd;
-
-       tasklet_async command error_t RadioState.turnOff()
-       {
-               radioCmd = RADIO_CMD_TURNOFF;
-               return call SubState.turnOff();
-       }
-
-       tasklet_async command error_t RadioState.standby()
-       {
-               radioCmd = RADIO_CMD_TURNOFF;
-               return call SubState.standby();
-       }
-
-       tasklet_async command error_t RadioState.turnOn()
-       {
-               radioCmd = RADIO_CMD_TURNON;
-               return call SubState.turnOn();
-       }
-
-       tasklet_async command error_t RadioState.setChannel(uint8_t channel)
-       {
-               radioCmd = RADIO_CMD_NONE;
-               return call SubState.setChannel(channel);
-       }
-
-       task void startStopTimer()
-       {
-               if( radioCmd == RADIO_CMD_TURNON )
-                       call Timer.startPeriodic(call TrafficMonitorConfig.getUpdatePeriod());
-               else if( radioCmd == RADIO_CMD_TURNOFF )
-                       call Timer.stop();
-       }
-
-       tasklet_async event void SubState.done()
-       {
-               post startStopTimer();
-               signal RadioState.done();
-       }
-}
diff --git a/tos/chips/rf230/UniqueConfig.nc b/tos/chips/rf230/UniqueConfig.nc
deleted file mode 100644 (file)
index 5f14c52..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-
-interface UniqueConfig
-{
-       /**
-        * Returns the sequence number of the packet.
-        */
-       async command uint8_t getSequenceNumber(message_t* msg);
-
-       /**
-        * Returns the sender of the packet. 
-        */
-       async command am_addr_t getSender(message_t* msg);
-
-       /**
-        * Sets the sequence number of the packet.
-        */
-       async command void setSequenceNumber(message_t*msg, uint8_t number);
-
-       /**
-        * This command is called when the unqiue layer detects a missing (jump 
-        * in the data sequence number) or a duplicate packet.
-        */
-       tasklet_async command void reportChannelError();
-}
diff --git a/tos/chips/rf230/UniqueLayerC.nc b/tos/chips/rf230/UniqueLayerC.nc
deleted file mode 100644 (file)
index 5d2e5f2..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-configuration UniqueLayerC
-{
-       provides
-       {
-               // NOTE, this is a combined layer, should be hooked up at two places
-               interface Send;
-               interface RadioReceive;
-       }
-       uses
-       {
-               interface Send as SubSend;
-               interface RadioReceive as SubReceive;
-
-               interface UniqueConfig as Config;
-       }
-}
-
-implementation
-{
-       components UniqueLayerP, MainC, NeighborhoodC, new NeighborhoodFlagC();
-
-       MainC.SoftwareInit -> UniqueLayerP;
-       UniqueLayerP.Neighborhood -> NeighborhoodC;
-       UniqueLayerP.NeighborhoodFlag -> NeighborhoodFlagC;
-
-       Send = UniqueLayerP;
-       SubSend = UniqueLayerP;
-
-       RadioReceive = UniqueLayerP;
-       SubReceive = UniqueLayerP;
-       Config = UniqueLayerP;
-}
diff --git a/tos/chips/rf230/UniqueLayerP.nc b/tos/chips/rf230/UniqueLayerP.nc
deleted file mode 100644 (file)
index d341942..0000000
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <Tasklet.h>
-#include <Neighborhood.h>
-
-module UniqueLayerP
-{
-       provides
-       {
-               interface Send;
-               interface RadioReceive;
-
-               interface Init;
-       }
-
-       uses
-       {
-               interface Send as SubSend;
-               interface RadioReceive as SubReceive;
-
-               interface UniqueConfig;
-               interface Neighborhood;
-               interface NeighborhoodFlag;
-       }
-}
-
-implementation
-{
-       uint8_t sequenceNumber;
-
-       command error_t Init.init()
-       {
-               sequenceNumber = TOS_NODE_ID << 4;
-               return SUCCESS;
-       }
-
-       command error_t Send.send(message_t* msg, uint8_t len)
-       {
-               call UniqueConfig.setSequenceNumber(msg, ++sequenceNumber);
-               return call SubSend.send(msg, len);
-       }
-
-       command error_t Send.cancel(message_t* msg)
-       {
-               return call SubSend.cancel(msg);
-       }
-
-       event void SubSend.sendDone(message_t* msg, error_t error)
-       {
-               signal Send.sendDone(msg, error);
-       }
-
-       command uint8_t Send.maxPayloadLength()
-       {
-               return call SubSend.maxPayloadLength();
-       }
-
-       command void* Send.getPayload(message_t* msg, uint8_t len)
-       {
-               return call SubSend.getPayload(msg, len);
-       }
-
-       tasklet_async event bool SubReceive.header(message_t* msg)
-       {
-               // we could scan here, but better be lazy
-               return signal RadioReceive.header(msg);
-       }
-
-       tasklet_norace uint8_t receivedNumbers[NEIGHBORHOOD_SIZE];
-
-       tasklet_async event message_t* SubReceive.receive(message_t* msg)
-       {
-               uint8_t index = call Neighborhood.insertNode(call UniqueConfig.getSender(msg));
-               uint8_t dsn = call UniqueConfig.getSequenceNumber(msg);
-
-               if( call NeighborhoodFlag.get(index) )
-               {
-                       uint8_t diff = dsn - receivedNumbers[index];
-
-                       if( diff == 0 )
-                       {
-                               call UniqueConfig.reportChannelError();
-                               return msg;
-                       }
-               }
-               else
-                       call NeighborhoodFlag.set(index);
-
-               receivedNumbers[index] = dsn;
-
-               return signal RadioReceive.receive(msg);
-       }
-
-       tasklet_async event void Neighborhood.evicted(uint8_t index) { }
-}
diff --git a/tos/chips/rf2xx/README b/tos/chips/rf2xx/README
new file mode 100644 (file)
index 0000000..35b6707
--- /dev/null
@@ -0,0 +1,76 @@
+
+The radio driver interfaces have a set of generic configuration options. 
+Some of these are set in the platforms/xxx/chips/rf230/RadioConfig.h header 
+file, see the IRIS platform for example, others can be set in your 
+Makefile.
+
+TFRAMES_ENABLED:
+
+If enabled, then tinyos frames are enabled, so 6lowpan will not work. See 
+TEP125 for the details.
+
+LOW_POWER_LISTENING:
+
+If enabled, then the radio will duty cycle the radio (turn it off and on). 
+See TEP105 for the details.
+
+SLOTTED_MAC:
+
+There are two CA (collision avoidance) algorithms: one is the simple random 
+backoff  just like the one used in the CC2420 driver. The other one is a 
+slotted time sync based version where each node makes a guarantee that only 
+at a given time within a time slot (e.g. 1 ms) they will ever start to 
+transmit. This value is monitored by nearby motes (no payload overhead) and 
+they preemptively avoid these time instances. This greatly reduces the 
+chance that two motes will start to transmit within 50-100 microsecs to 
+each other, so the CCA (clear channel assessment) will become much more 
+efficient. This slotted behavior can enabled by defining SLOTTED_MAC.
+
+RADIO_DEBUG:
+
+If enabled, then every component in the radio stack will make sure that 
+everything goes as intended via asserts. For example, we check that certain 
+calls are not made in certain states, the radio hardware responds according 
+to the datasheet, etc. Use the ASSERT macro defined in the RadioAssert.h
+and make sure that the AssertC from lib/diagmsg is included in your 
+application. All assert violations are reported over the serial interface. 
+You can use the net.tinyos.util.DiagMsg java application to display 
+diagnostic messages.
+
+RADIO_DEBUG_MESSAGES:
+
+If enabled, then the radio driver will print out all received and 
+transmitted messages via the DiagMsg interface. This feature is used in the 
+RF230Sniffer appliaction.
+
+TRAFFIC_MONITOR:
+
+If enabled, the TrafficMonitorLayer is included in the stack which keeps
+track of the average number of bytes sent, bytes received, the number of 
+transmission errors, and the number of neighboors. If RADIO_DEBUG is enabled
+then this information is also printed.
+
+typedef TRadio:
+
+The radio stack uses a single hardware alarm/counter. The resolution of 
+this counter is platform specific and should be set just like the T32khz or 
+TMilli time resolution types. All time stamps and time related information 
+are recorded in this resolution within the driver.
+
+RADIO_ALARM_MICROSEC:
+
+This should be set to the number of radio alarm ticks per one microsecond. 
+
+RADIO_ALARM_MILLI_EXP:
+
+The base two logarithm of the number of radio alarm ticks per one 
+millisecond.
+
+SOFTWAREACK_TIMEOUT:
+
+The number of microseconds the driver should wait for a software 
+acknowledgement on the sender side. If your SPI bus is slow, then it will 
+take more time to download and upload the message from/to the radio chip, 
+so you need to increase this wait period. For example, for IRIS->IRIS 
+communication 800 microsec is enough, but for IRIS->TELOS we need 1600 
+because the TELOS in software ack mode is slow to reply with an ack packet.
diff --git a/tos/chips/rf2xx/layers/ActiveMessageConfig.nc b/tos/chips/rf2xx/layers/ActiveMessageConfig.nc
new file mode 100755 (executable)
index 0000000..d5ba7b8
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <ActiveMessageLayer.h>
+
+interface ActiveMessageConfig
+{
+       /** Same as AMPacket.destination */
+       command am_addr_t destination(message_t* msg);
+
+       /** Same as AMPacket.setDestination */
+       command void setDestination(message_t* msg, am_addr_t addr);
+
+       /** Same as AMPacket.source */
+       command am_addr_t source(message_t* msg);
+
+       /** Same as AMPacket.setSource */
+       command void setSource(message_t* msg, am_addr_t addr);
+
+       /** Same as AMPacket.group */
+       command am_group_t group(message_t* msg);
+
+       /** Same as AMPacket.setGroup */
+       command void setGroup(message_t* msg, am_group_t grp);
+
+       /**
+        * Check if the packet is properly formatted, and if the user 
+        * forgot to call Packet.clear then format it properly.
+        * Return SUCCESS if the frame is now properly set up, 
+        * or FAIL of the send operation should be aborted.
+        */
+       command error_t checkFrame(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/layers/ActiveMessageLayer.h b/tos/chips/rf2xx/layers/ActiveMessageLayer.h
new file mode 100644 (file)
index 0000000..61a3cc1
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __ACTIVEMESSAGELAYER_H__
+#define __ACTIVEMESSAGELAYER_H__
+
+#include "AM.h"
+
+typedef nx_struct activemessage_header_t
+{
+       nx_am_id_t type;
+} activemessage_header_t;
+
+#endif//__ACTIVEMESSAGELAYER_H__
diff --git a/tos/chips/rf2xx/layers/ActiveMessageLayerC.nc b/tos/chips/rf2xx/layers/ActiveMessageLayerC.nc
new file mode 100755 (executable)
index 0000000..8ca6dce
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration ActiveMessageLayerC
+{
+       provides
+       {
+               interface AMPacket;
+               interface Packet;
+               interface AMSend[am_id_t id];
+               interface Receive[am_id_t id];
+               interface Receive as Snoop[am_id_t id]; 
+               interface SendNotifier[am_id_t id];
+       }
+
+       uses
+       {
+               interface RadioPacket as SubPacket;
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
+               interface ActiveMessageConfig as Config;
+       }
+}
+
+implementation
+{
+       components ActiveMessageLayerP, ActiveMessageAddressC;
+       ActiveMessageLayerP.ActiveMessageAddress -> ActiveMessageAddressC;
+
+       AMPacket = ActiveMessageLayerP;
+       Packet = ActiveMessageLayerP;
+       AMSend = ActiveMessageLayerP;
+       Receive = ActiveMessageLayerP.Receive;
+       Snoop = ActiveMessageLayerP.Snoop;
+       SendNotifier = ActiveMessageLayerP;
+       
+       SubPacket = ActiveMessageLayerP;
+       SubSend = ActiveMessageLayerP;
+       SubReceive = ActiveMessageLayerP;
+       Config = ActiveMessageLayerP;
+}
diff --git a/tos/chips/rf2xx/layers/ActiveMessageLayerP.nc b/tos/chips/rf2xx/layers/ActiveMessageLayerP.nc
new file mode 100644 (file)
index 0000000..1f75d36
--- /dev/null
@@ -0,0 +1,258 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <ActiveMessageLayer.h>
+
+module ActiveMessageLayerP
+{
+       provides
+       {
+               interface RadioPacket;
+               interface AMPacket;
+               interface Packet;
+               interface AMSend[am_id_t id];
+               interface Receive[am_id_t id];
+               interface Receive as Snoop[am_id_t id]; 
+               interface SendNotifier[am_id_t id];
+       }
+
+       uses
+       {
+               interface RadioPacket as SubPacket;
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
+               interface ActiveMessageConfig as Config;
+               interface ActiveMessageAddress;
+       }
+}
+
+implementation
+{
+       activemessage_header_t* getHeader(message_t* msg)
+       {
+               return ((void*)msg) + call SubPacket.headerLength(msg);
+       }
+
+       void* getPayload(message_t* msg)
+       {
+               return ((void*)msg) + call RadioPacket.headerLength(msg);
+       }
+
+/*----------------- Send -----------------*/
+
+       command error_t AMSend.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len)
+       {
+               if( len > call Packet.maxPayloadLength() )
+                       return EINVAL;
+
+               if( call Config.checkFrame(msg) != SUCCESS )
+                       return FAIL;
+
+               call Packet.setPayloadLength(msg, len);
+               call AMPacket.setSource(msg, call AMPacket.address());
+               call AMPacket.setGroup(msg, call AMPacket.localGroup());
+               call AMPacket.setType(msg, id);
+               call AMPacket.setDestination(msg, addr);
+
+               signal SendNotifier.aboutToSend[id](addr, msg);
+
+               return call SubSend.send(msg);
+       }
+
+       inline event void SubSend.sendDone(message_t* msg, error_t error)
+       {
+               signal AMSend.sendDone[call AMPacket.type(msg)](msg, error);
+       }
+
+       inline command error_t AMSend.cancel[am_id_t id](message_t* msg)
+       {
+               return call SubSend.cancel(msg);
+       }
+
+       default event void AMSend.sendDone[am_id_t id](message_t* msg, error_t error)
+       {
+       }
+
+       inline command uint8_t AMSend.maxPayloadLength[am_id_t id]()
+       {
+               return call Packet.maxPayloadLength();
+       }
+
+       inline command void* AMSend.getPayload[am_id_t id](message_t* msg, uint8_t len)
+       {
+               return call Packet.getPayload(msg, len);
+       }
+
+       default event void SendNotifier.aboutToSend[am_id_t id](am_addr_t addr, message_t* msg)
+       {
+       }
+
+/*----------------- Receive -----------------*/
+
+       event message_t* SubReceive.receive(message_t* msg)
+       {
+               am_id_t id = call AMPacket.type(msg);
+               void* payload = getPayload(msg);
+               uint8_t len = call Packet.payloadLength(msg);
+
+               msg = call AMPacket.isForMe(msg) 
+                       ? signal Receive.receive[id](msg, payload, len)
+                       : signal Snoop.receive[id](msg, payload, len);
+
+               return msg;
+       }
+
+       default event message_t* Receive.receive[am_id_t id](message_t* msg, void* payload, uint8_t len)
+       {
+               return msg;
+       }
+
+       default event message_t* Snoop.receive[am_id_t id](message_t* msg, void* payload, uint8_t len)
+       {
+               return msg;
+       }
+
+/*----------------- AMPacket -----------------*/
+
+       inline command am_addr_t AMPacket.address()
+       {
+               return call ActiveMessageAddress.amAddress();
+       }
+       inline command am_group_t AMPacket.localGroup()
+       {
+               return call ActiveMessageAddress.amGroup();
+       }
+
+       inline command bool AMPacket.isForMe(message_t* msg)
+       {
+               am_addr_t addr = call AMPacket.destination(msg);
+               return addr == call AMPacket.address() || addr == AM_BROADCAST_ADDR;
+       }
+
+       inline command am_addr_t AMPacket.destination(message_t* msg)
+       {
+               return call Config.destination(msg);
+       }
+       inline command void AMPacket.setDestination(message_t* msg, am_addr_t addr)
+       {
+               call Config.setDestination(msg, addr);
+       }
+
+       inline command am_addr_t AMPacket.source(message_t* msg)
+       {
+               return call Config.source(msg);
+       }
+
+       inline command void AMPacket.setSource(message_t* msg, am_addr_t addr)
+       {
+               call Config.setSource(msg, addr);
+       }
+
+       inline command am_id_t AMPacket.type(message_t* msg)
+       {
+               return getHeader(msg)->type;
+       }
+
+       inline command void AMPacket.setType(message_t* msg, am_id_t type)
+       {
+               getHeader(msg)->type = type;
+       }
+  
+       inline command am_group_t AMPacket.group(message_t* msg) 
+       {
+               return call Config.group(msg);
+       }
+
+       inline command void AMPacket.setGroup(message_t* msg, am_group_t grp)
+       {
+               call Config.setGroup(msg, grp);
+       }
+
+       inline async event void ActiveMessageAddress.changed()
+       {
+       }
+
+/*----------------- RadioPacket -----------------*/
+
+       async command uint8_t RadioPacket.headerLength(message_t* msg)
+       {
+               return call SubPacket.headerLength(msg) + sizeof(activemessage_header_t);
+       }
+
+       async command uint8_t RadioPacket.payloadLength(message_t* msg)
+       {
+               return call SubPacket.payloadLength(msg) - sizeof(activemessage_header_t);
+       }
+
+       async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               call SubPacket.setPayloadLength(msg, length + sizeof(activemessage_header_t));
+       }
+
+       async command uint8_t RadioPacket.maxPayloadLength()
+       {
+               return call SubPacket.maxPayloadLength() - sizeof(activemessage_header_t);
+       }
+
+       async command uint8_t RadioPacket.metadataLength(message_t* msg)
+       {
+               return call SubPacket.metadataLength(msg);
+       }
+
+       async command void RadioPacket.clear(message_t* msg)
+       {
+               call SubPacket.clear(msg);
+       }
+
+/*----------------- Packet -----------------*/
+
+       command void Packet.clear(message_t* msg)
+       {
+               call RadioPacket.clear(msg);
+       }
+
+       command uint8_t Packet.payloadLength(message_t* msg)
+       {
+               return call RadioPacket.payloadLength(msg);
+       }
+
+       command void Packet.setPayloadLength(message_t* msg, uint8_t len)
+       {
+               call RadioPacket.setPayloadLength(msg, len);
+       }
+
+       command uint8_t Packet.maxPayloadLength()
+       {
+               return call RadioPacket.maxPayloadLength();
+       }
+
+       command void* Packet.getPayload(message_t* msg, uint8_t len)
+       {
+               if( len > call RadioPacket.maxPayloadLength() )
+                       return NULL;
+
+               return ((void*)msg) + call RadioPacket.headerLength(msg);
+       }
+}
diff --git a/tos/chips/rf2xx/layers/AutoResourceAcquireLayerC.nc b/tos/chips/rf2xx/layers/AutoResourceAcquireLayerC.nc
new file mode 100644 (file)
index 0000000..7d3c846
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+generic module AutoResourceAcquireLayerC()
+{
+       provides
+       {
+               interface BareSend;
+       }
+
+       uses
+       {
+               interface BareSend as SubSend;
+               interface Resource;
+       }
+}
+
+implementation
+{
+       message_t *pending;
+
+       command error_t BareSend.send(message_t* msg)
+       {
+               if( call Resource.immediateRequest() == SUCCESS )
+               {
+                       error_t result = call SubSend.send(msg);
+                       if( result != SUCCESS )
+                               call Resource.release();
+
+                       return result;
+               }
+
+               pending = msg;
+               return call Resource.request();
+       }
+
+       event void Resource.granted()
+       {
+               error_t result = call SubSend.send(pending);
+               if( result != SUCCESS )
+               {
+                       call Resource.release();
+                       signal BareSend.sendDone(pending, result);
+               }
+       }
+
+       event void SubSend.sendDone(message_t* msg, error_t result)
+       {
+               call Resource.release();
+               signal BareSend.sendDone(msg, result);
+       }
+
+       command error_t BareSend.cancel(message_t* msg)
+       {
+               return call SubSend.cancel(msg);
+       }
+}
diff --git a/tos/chips/rf2xx/layers/CsmaConfig.nc b/tos/chips/rf2xx/layers/CsmaConfig.nc
new file mode 100755 (executable)
index 0000000..9d45376
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface CsmaConfig
+{
+       /**
+        * This command is called when the message is transmitted to
+        * check if it needs software clear channel assesment.
+        */
+       async command bool requiresSoftwareCCA(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/layers/CsmaLayerC.nc b/tos/chips/rf2xx/layers/CsmaLayerC.nc
new file mode 100755 (executable)
index 0000000..e0ddc26
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration CsmaLayerC
+{
+       provides
+       {
+               interface RadioSend;
+       }
+       uses
+       {
+               interface RadioSend as SubSend;
+               interface RadioCCA as SubCCA;
+
+               interface CsmaConfig as Config;
+       }
+}
+
+implementation
+{
+       components CsmaLayerP;
+
+       RadioSend = CsmaLayerP;
+       SubSend = CsmaLayerP;
+       SubCCA = CsmaLayerP;
+       Config = CsmaLayerP;
+}
diff --git a/tos/chips/rf2xx/layers/CsmaLayerP.nc b/tos/chips/rf2xx/layers/CsmaLayerP.nc
new file mode 100755 (executable)
index 0000000..5bd1aa4
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+#include <RadioAssert.h>
+
+module CsmaLayerP
+{
+       provides
+       {
+               interface RadioSend;
+       }
+
+       uses
+       {
+               interface CsmaConfig as Config;
+
+               interface RadioSend as SubSend;
+               interface RadioCCA as SubCCA;
+       }
+}
+
+implementation
+{
+       tasklet_norace message_t *txMsg;
+
+       tasklet_norace uint8_t state;
+       enum
+       {
+               STATE_READY = 0,
+               STATE_CCA_WAIT = 1,
+               STATE_SEND = 2,
+       };
+
+       tasklet_async event void SubSend.ready()
+       {
+               if( state == STATE_READY )
+                       signal RadioSend.ready();
+       }
+
+       tasklet_async command error_t RadioSend.send(message_t* msg)
+       {
+               error_t error;
+
+               if( state == STATE_READY )
+               {
+                       if( call Config.requiresSoftwareCCA(msg) )
+                       {
+                               txMsg = msg;
+
+                               if( (error = call SubCCA.request()) == SUCCESS )
+                                       state = STATE_CCA_WAIT;
+                       }
+                       else if( (error = call SubSend.send(msg)) == SUCCESS )
+                               state = STATE_SEND;
+               }
+               else
+                       error = EBUSY;
+
+               return error;
+       }
+
+       tasklet_async event void SubCCA.done(error_t error)
+       {
+               ASSERT( state == STATE_CCA_WAIT );
+
+               if( error == SUCCESS && (error = call SubSend.send(txMsg)) == SUCCESS )
+                       state = STATE_SEND;
+               else
+               {
+                       state = STATE_READY;
+                       signal RadioSend.sendDone(EBUSY);
+               }
+       }
+
+       tasklet_async event void SubSend.sendDone(error_t error)
+       {
+               ASSERT( state == STATE_SEND );
+
+               state = STATE_READY;
+               signal RadioSend.sendDone(error);
+       }
+}
diff --git a/tos/chips/rf2xx/layers/DummyConfig.nc b/tos/chips/rf2xx/layers/DummyConfig.nc
new file mode 100755 (executable)
index 0000000..c76631e
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface DummyConfig
+{
+       /**
+        * We need to put something here, but this is not going to get called
+        */
+       async command void nothing();
+}
diff --git a/tos/chips/rf2xx/layers/DummyLayerC.nc b/tos/chips/rf2xx/layers/DummyLayerC.nc
new file mode 100644 (file)
index 0000000..1c71a9a
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+generic configuration DummyLayerC()
+{
+       provides
+       {
+               interface SplitControl;
+               interface BareSend as Send;
+               interface BareReceive as Receive;
+
+               interface RadioState;
+               interface RadioSend;
+               interface RadioReceive;
+               interface RadioCCA;
+               interface RadioPacket;
+
+               interface DummyConfig as UnconnectedConfig;
+       }
+
+       uses 
+       {
+               interface SplitControl as SubControl;
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
+
+               interface RadioState as SubState;
+               interface RadioSend as SubRadioSend;
+               interface RadioReceive as SubRadioReceive;
+               interface RadioCCA as SubRadioCCA;
+               interface RadioPacket as SubPacket;
+
+               interface DummyConfig as Config;
+       }
+}
+
+implementation
+{
+       RadioState = SubState;
+       RadioSend = SubRadioSend;
+       RadioReceive = SubRadioReceive;
+       RadioCCA = SubRadioCCA;
+       RadioPacket = SubPacket;
+
+       SplitControl = SubControl;
+       Send = SubSend;
+       Receive = SubReceive;
+
+       Config = UnconnectedConfig;
+}
diff --git a/tos/chips/rf2xx/layers/Ieee154MessageLayerC.nc b/tos/chips/rf2xx/layers/Ieee154MessageLayerC.nc
new file mode 100644 (file)
index 0000000..d7e6311
--- /dev/null
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2007-2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+module Ieee154MessageLayerC
+{
+       provides 
+       {
+               interface Packet;
+               interface Ieee154Send;
+               interface Receive as Ieee154Receive;
+               interface SendNotifier;
+       }
+
+       uses
+       {
+               interface Ieee154PacketLayer;
+               interface Ieee154Packet;
+               interface RadioPacket;
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
+       }
+}
+
+implementation
+{
+       void* getPayload(message_t* msg)
+       {
+               return ((void*)msg) + call RadioPacket.headerLength(msg);
+       }
+
+/*----------------- Packet -----------------*/
+
+       command void Packet.clear(message_t* msg)
+       {
+               call RadioPacket.clear(msg);
+       }
+
+       command uint8_t Packet.payloadLength(message_t* msg)
+       {
+               return call RadioPacket.payloadLength(msg);
+       }
+
+       command void Packet.setPayloadLength(message_t* msg, uint8_t len)
+       {
+               call RadioPacket.setPayloadLength(msg, len);
+       }
+
+       command uint8_t Packet.maxPayloadLength()
+       {
+               return call RadioPacket.maxPayloadLength();
+       }
+
+       command void* Packet.getPayload(message_t* msg, uint8_t len)
+       {
+               if( len > call RadioPacket.maxPayloadLength() )
+                       return NULL;
+
+               return getPayload(msg);
+       }
+
+/*----------------- Ieee154Send -----------------*/
+
+       command void * Ieee154Send.getPayload(message_t* msg, uint8_t len)
+       {
+               return call Packet.getPayload(msg, len);
+       }
+
+       command uint8_t Ieee154Send.maxPayloadLength()
+       {
+               return call Packet.maxPayloadLength();
+       }
+
+       command error_t Ieee154Send.cancel(message_t* msg)
+       {
+               return call SubSend.cancel(msg);
+       }
+
+       command error_t Ieee154Send.send(ieee154_saddr_t addr, message_t* msg, uint8_t len)
+       {
+               if( len > call Packet.maxPayloadLength() )
+                       return EINVAL;
+
+               // user forgot to call Packet.clear(), maybe we should return EFAIL
+               if( ! call Ieee154PacketLayer.isDataFrame(msg) )
+                       call Ieee154PacketLayer.createDataFrame(msg);
+
+               call Packet.setPayloadLength(msg, len);
+               call Ieee154Packet.setSource(msg, call Ieee154Packet.address());
+               call Ieee154Packet.setDestination(msg, addr);
+               call Ieee154Packet.setPan(msg, call Ieee154Packet.localPan());
+               
+               signal SendNotifier.aboutToSend(addr, msg);
+       
+               return call SubSend.send(msg);
+       }
+
+       event void SubSend.sendDone(message_t* msg, error_t error)
+       {
+               signal Ieee154Send.sendDone(msg, error);
+       }
+
+       default event void Ieee154Send.sendDone(message_t* msg, error_t error)
+       {
+       }
+
+       default event void SendNotifier.aboutToSend(am_addr_t addr, message_t* msg)
+       {
+       }
+
+/*----------------- Receive -----------------*/
+
+       event message_t* SubReceive.receive(message_t* msg)
+       {
+               if( call Ieee154Packet.isForMe(msg) )
+                       return signal Ieee154Receive.receive(msg,
+                               getPayload(msg), call Packet.payloadLength(msg));
+               else
+                       return msg;
+       }
+
+       default event message_t* Ieee154Receive.receive(message_t* msg, void* payload, uint8_t len)
+       {
+               return msg;
+       }
+}
diff --git a/tos/chips/rf2xx/layers/Ieee154PacketLayer.h b/tos/chips/rf2xx/layers/Ieee154PacketLayer.h
new file mode 100644 (file)
index 0000000..b7b14a6
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __IEEE154PACKETLAYER_H__
+#define __IEEE154PACKETLAYER_H__
+
+typedef nx_struct ieee154_header_t
+{
+       nxle_uint16_t fcf;
+       nxle_uint8_t dsn;
+       nxle_uint16_t destpan;
+       nxle_uint16_t dest;
+       nxle_uint16_t src;
+} ieee154_header_t;
+
+enum ieee154_fcf_enums {
+       IEEE154_FCF_FRAME_TYPE = 0,
+       IEEE154_FCF_SECURITY_ENABLED = 3,
+       IEEE154_FCF_FRAME_PENDING = 4,
+       IEEE154_FCF_ACK_REQ = 5,
+       IEEE154_FCF_INTRAPAN = 6,
+       IEEE154_FCF_DEST_ADDR_MODE = 10,
+       IEEE154_FCF_SRC_ADDR_MODE = 14,
+};
+
+enum ieee154_fcf_type_enums {
+       IEEE154_TYPE_BEACON = 0,
+       IEEE154_TYPE_DATA = 1,
+       IEEE154_TYPE_ACK = 2,
+       IEEE154_TYPE_MAC_CMD = 3,
+       IEEE154_TYPE_MASK = 7,
+};
+
+enum iee154_fcf_addr_mode_enums {
+       IEEE154_ADDR_NONE = 0,
+       IEEE154_ADDR_SHORT = 2,
+       IEEE154_ADDR_EXT = 3,
+       IEEE154_ADDR_MASK = 3,
+};
+
+#endif//__IEEE154PACKETLAYER_H__
diff --git a/tos/chips/rf2xx/layers/Ieee154PacketLayer.nc b/tos/chips/rf2xx/layers/Ieee154PacketLayer.nc
new file mode 100644 (file)
index 0000000..140cb1b
--- /dev/null
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Ieee154PacketLayer.h>
+#include <message.h>
+
+/**
+ * This interface encapsulates IEEE 802.15.4 intrapan data frames with 
+ * 16-bit destination pan, source and destination addresses. It also 
+ * supports 6LowPan interoperability mode, and acknowledgement frames.
+ * Note, that this interface does not support the CRC-16 value, which
+ * should be verified before the data can be trusted.
+ */
+interface Ieee154PacketLayer
+{
+       /**
+        * Returns the frame control field. This method should not be used, 
+        * isDataFrame and isAckFrame should be used instead.
+        */
+       async command uint16_t getFCF(message_t* msg);
+
+       /**
+        * Sets the frame control field. This method should not be used, 
+        * createDataFrame and createAckFrame should be used instead.
+        */
+       async command void setFCF(message_t* msg, uint16_t fcf);
+
+       /**
+        * Returns TRUE if the message is a data frame supported by 
+        * this interface (based on the value of the FCF).
+        */
+       async command bool isDataFrame(message_t* msg);
+
+       /**
+        * Sets the FCF to create a data frame supported by this interface.
+        * You may call setAckRequired and setFramePending commands after this.
+        */
+       async command void createDataFrame(message_t* msg);
+
+       /**
+        * Returns TRUE if the message is an acknowledgement frame supported
+        * by this interface (based on the value of the FCF).
+        */
+       async command bool isAckFrame(message_t* msg);
+
+       /**
+        * Sets the FCF to create an acknowledgement frame supported by
+        * this interface. You may call setFramePending after this.
+        */
+       async command void createAckFrame(message_t* msg);
+
+       /**
+        * Creates an acknowledgement packet for the given data packet.
+        * This also sets the DSN value. The data message must be a 
+        * data frame, the ack message will be overwritten.
+        */
+       async command void createAckReply(message_t* data, message_t* ack);
+
+       /**
+        * Returns TRUE if the acknowledgement packet corresponds to the
+        * data packet. The data message must be a data packet.
+        */
+       async command bool verifyAckReply(message_t* data, message_t* ack);
+
+       /**
+        * Returns TRUE if the ACK required field is set in the FCF.
+        */
+       async command bool getAckRequired(message_t* msg);
+
+       /**
+        * Sets the ACK required field in the FCF, should never be set
+        * for acknowledgement frames.
+        */
+       async command void setAckRequired(message_t* msg, bool ack);
+
+       /**
+        * Returns TRUE if the frame pending field is set in the FCF.
+        */
+       async command bool getFramePending(message_t* msg);
+
+       /**
+        * Sets the frame pending field in the FCF.
+        */
+       async command void setFramePending(message_t* msg, bool pending);
+
+       /**
+        * Returns the data sequence number
+        */
+       async command uint8_t getDSN(message_t* msg);
+
+       /**
+        * Sets the data sequence number
+        */
+       async command void setDSN(message_t* msg, uint8_t dsn);
+
+       /**
+        * returns the destination PAN id, values <= 255 are tinyos groups,
+        * valid only for data frames
+        */
+       async command uint16_t getDestPan(message_t* msg);
+
+       /**
+        * Sets the destination PAN id, valid only for data frames
+        */
+       async command void setDestPan(message_t* msg, uint16_t pan);
+
+       /**
+        * Returns the destination address, valid only for data frames
+        */
+       async command uint16_t getDestAddr(message_t* msg);
+
+       /**
+        * Sets the destination address, valid only for data frames
+        */
+       async command void setDestAddr(message_t* msg, uint16_t addr);
+
+       /**
+        * Returns the source address, valid only for data frames
+        */
+       async command uint16_t getSrcAddr(message_t* msg);
+
+       /**
+        * Sets the source address, valid only for data frames
+        */
+       async command void setSrcAddr(message_t* msg, uint16_t addr);
+
+       /**
+        * Returns TRUE if the packet is a data packet, the ACK_REQ field
+        * is set and the destination address is not the broadcast address.
+        */
+       async command bool requiresAckWait(message_t* msg);
+
+       /**
+        * Returns TRUE if the packet is a data packet, the ACK_REQ field
+        * is set and the destionation address is this node.
+        */
+       async command bool requiresAckReply(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/layers/Ieee154PacketLayerC.nc b/tos/chips/rf2xx/layers/Ieee154PacketLayerC.nc
new file mode 100644 (file)
index 0000000..acf89c8
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration Ieee154PacketLayerC
+{
+       provides
+       {
+               interface Ieee154PacketLayer;
+               interface Ieee154Packet;
+               interface RadioPacket;
+       }
+
+       uses
+       {
+               interface RadioPacket as SubPacket;
+       }
+}
+
+implementation
+{
+       components Ieee154PacketLayerP, ActiveMessageAddressC;
+       Ieee154PacketLayerP.ActiveMessageAddress -> ActiveMessageAddressC;
+
+       Ieee154PacketLayer = Ieee154PacketLayerP;
+       Ieee154Packet = Ieee154PacketLayerP;
+       RadioPacket = Ieee154PacketLayerP;
+       SubPacket = Ieee154PacketLayerP;
+}
diff --git a/tos/chips/rf2xx/layers/Ieee154PacketLayerP.nc b/tos/chips/rf2xx/layers/Ieee154PacketLayerP.nc
new file mode 100644 (file)
index 0000000..29f4647
--- /dev/null
@@ -0,0 +1,285 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Ieee154PacketLayer.h>
+
+module Ieee154PacketLayerP
+{
+       provides 
+       {
+               interface Ieee154PacketLayer;
+               interface Ieee154Packet;
+               interface RadioPacket;
+       }
+
+       uses
+       {
+               interface ActiveMessageAddress;
+               interface RadioPacket as SubPacket;
+       }
+}
+
+implementation
+{
+/*----------------- Ieee154Packet -----------------*/
+
+       enum
+       {
+               IEEE154_DATA_FRAME_MASK = (IEEE154_TYPE_MASK << IEEE154_FCF_FRAME_TYPE) 
+                       | (1 << IEEE154_FCF_INTRAPAN) 
+                       | (IEEE154_ADDR_MASK << IEEE154_FCF_DEST_ADDR_MODE) 
+                       | (IEEE154_ADDR_MASK << IEEE154_FCF_SRC_ADDR_MODE),
+
+               IEEE154_DATA_FRAME_VALUE = (IEEE154_TYPE_DATA << IEEE154_FCF_FRAME_TYPE) 
+                       | (1 << IEEE154_FCF_INTRAPAN) 
+                       | (IEEE154_ADDR_SHORT << IEEE154_FCF_DEST_ADDR_MODE) 
+                       | (IEEE154_ADDR_SHORT << IEEE154_FCF_SRC_ADDR_MODE),
+
+               IEEE154_ACK_FRAME_LENGTH = 3,   // includes the FCF, DSN
+               IEEE154_ACK_FRAME_MASK = (IEEE154_TYPE_MASK << IEEE154_FCF_FRAME_TYPE), 
+               IEEE154_ACK_FRAME_VALUE = (IEEE154_TYPE_ACK << IEEE154_FCF_FRAME_TYPE),
+       };
+
+       ieee154_header_t* getHeader(message_t* msg)
+       {
+               return ((void*)msg) + call SubPacket.headerLength(msg);
+       }
+
+       void* getPayload(message_t* msg)
+       {
+               return ((void*)msg) + call RadioPacket.headerLength(msg);
+       }
+
+       async command uint16_t Ieee154PacketLayer.getFCF(message_t* msg)
+       {
+               return getHeader(msg)->fcf;
+       }
+
+       async command void Ieee154PacketLayer.setFCF(message_t* msg, uint16_t fcf)
+       {
+               getHeader(msg)->fcf = fcf;
+       }
+
+       async command bool Ieee154PacketLayer.isDataFrame(message_t* msg)
+       {
+               return (getHeader(msg)->fcf & IEEE154_DATA_FRAME_MASK) == IEEE154_DATA_FRAME_VALUE;
+       }
+
+       async command void Ieee154PacketLayer.createDataFrame(message_t* msg)
+       {
+               getHeader(msg)->fcf = IEEE154_DATA_FRAME_VALUE;
+       }
+
+       async command bool Ieee154PacketLayer.isAckFrame(message_t* msg)
+       {
+               return (getHeader(msg)->fcf & IEEE154_ACK_FRAME_MASK) == IEEE154_ACK_FRAME_VALUE;
+       }
+
+       async command void Ieee154PacketLayer.createAckFrame(message_t* msg)
+       {
+               call SubPacket.setPayloadLength(msg, IEEE154_ACK_FRAME_LENGTH);
+               getHeader(msg)->fcf = IEEE154_ACK_FRAME_VALUE;
+       }
+
+       async command void Ieee154PacketLayer.createAckReply(message_t* data, message_t* ack)
+       {
+               ieee154_header_t* header = getHeader(ack);
+               call SubPacket.setPayloadLength(ack, IEEE154_ACK_FRAME_LENGTH);
+
+               header->fcf = IEEE154_ACK_FRAME_VALUE;
+               header->dsn = getHeader(data)->dsn;
+       }
+
+       async command bool Ieee154PacketLayer.verifyAckReply(message_t* data, message_t* ack)
+       {
+               ieee154_header_t* header = getHeader(ack);
+
+               return header->dsn == getHeader(data)->dsn
+                       && (header->fcf & IEEE154_ACK_FRAME_MASK) == IEEE154_ACK_FRAME_VALUE;
+       }
+
+       async command bool Ieee154PacketLayer.getAckRequired(message_t* msg)
+       {
+               return getHeader(msg)->fcf & (1 << IEEE154_FCF_ACK_REQ);
+       }
+
+       async command void Ieee154PacketLayer.setAckRequired(message_t* msg, bool ack)
+       {
+               if( ack )
+                       getHeader(msg)->fcf |= (1 << IEEE154_FCF_ACK_REQ);
+               else
+                       getHeader(msg)->fcf &= ~(uint16_t)(1 << IEEE154_FCF_ACK_REQ);
+       }
+
+       async command bool Ieee154PacketLayer.getFramePending(message_t* msg)
+       {
+               return getHeader(msg)->fcf & (1 << IEEE154_FCF_FRAME_PENDING);
+       }
+
+       async command void Ieee154PacketLayer.setFramePending(message_t* msg, bool pending)
+       {
+               if( pending )
+                       getHeader(msg)->fcf |= (1 << IEEE154_FCF_FRAME_PENDING);
+               else
+                       getHeader(msg)->fcf &= ~(uint16_t)(1 << IEEE154_FCF_FRAME_PENDING);
+       }
+
+       async command uint8_t Ieee154PacketLayer.getDSN(message_t* msg)
+       {
+               return getHeader(msg)->dsn;
+       }
+
+       async command void Ieee154PacketLayer.setDSN(message_t* msg, uint8_t dsn)
+       {
+               getHeader(msg)->dsn = dsn;
+       }
+
+       async command uint16_t Ieee154PacketLayer.getDestPan(message_t* msg)
+       {
+               return getHeader(msg)->destpan;
+       }
+
+       async command void Ieee154PacketLayer.setDestPan(message_t* msg, uint16_t pan)
+       {
+               getHeader(msg)->destpan = pan;
+       }
+
+       async command uint16_t Ieee154PacketLayer.getDestAddr(message_t* msg)
+       {
+               return getHeader(msg)->dest;
+       }
+
+       async command void Ieee154PacketLayer.setDestAddr(message_t* msg, uint16_t addr)
+       {
+               getHeader(msg)->dest = addr;
+       }
+
+       async command uint16_t Ieee154PacketLayer.getSrcAddr(message_t* msg)
+       {
+               return getHeader(msg)->src;
+       }
+
+       async command void Ieee154PacketLayer.setSrcAddr(message_t* msg, uint16_t addr)
+       {       
+               getHeader(msg)->src = addr;
+       }
+
+       async command bool Ieee154PacketLayer.requiresAckWait(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getAckRequired(msg)
+                       && call Ieee154PacketLayer.isDataFrame(msg)
+                       && call Ieee154PacketLayer.getDestAddr(msg) != 0xFFFF;
+       }
+
+       async command bool Ieee154PacketLayer.requiresAckReply(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getAckRequired(msg)
+                       && call Ieee154PacketLayer.isDataFrame(msg)
+                       && call Ieee154PacketLayer.getDestAddr(msg) == call ActiveMessageAddress.amAddress();
+       }
+
+       async event void ActiveMessageAddress.changed()
+       {
+       }
+
+/*----------------- Ieee154Packet -----------------*/
+
+       command ieee154_saddr_t Ieee154Packet.address()
+       {
+               return call ActiveMessageAddress.amAddress();
+       }
+
+       command ieee154_saddr_t Ieee154Packet.destination(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDestAddr(msg);
+       }
+       command ieee154_saddr_t Ieee154Packet.source(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getSrcAddr(msg);
+       }
+
+       command void Ieee154Packet.setDestination(message_t* msg, ieee154_saddr_t addr)
+       {
+               call Ieee154PacketLayer.setDestAddr(msg, addr);
+       }
+
+       command void Ieee154Packet.setSource(message_t* msg, ieee154_saddr_t addr)
+       {
+               call Ieee154PacketLayer.setSrcAddr(msg, addr);
+       }
+
+       command bool Ieee154Packet.isForMe(message_t* msg)
+       {
+               ieee154_saddr_t addr = call Ieee154Packet.destination(msg);
+               return addr == call Ieee154Packet.address() || addr == IEEE154_BROADCAST_ADDR;
+       }
+
+       command ieee154_panid_t Ieee154Packet.pan(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDestPan(msg);
+       }
+
+       command void Ieee154Packet.setPan(message_t* msg, ieee154_panid_t grp)
+       {
+               call Ieee154PacketLayer.setDestPan(msg, grp);
+       }
+
+       command ieee154_panid_t Ieee154Packet.localPan()
+       {
+               return call ActiveMessageAddress.amGroup();
+       }
+
+/*----------------- RadioPacket -----------------*/
+
+       async command uint8_t RadioPacket.headerLength(message_t* msg)
+       {
+               return call SubPacket.headerLength(msg) + sizeof(ieee154_header_t);
+       }
+
+       async command uint8_t RadioPacket.payloadLength(message_t* msg)
+       {
+               return call SubPacket.payloadLength(msg) - sizeof(ieee154_header_t);
+       }
+
+       async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               call SubPacket.setPayloadLength(msg, length + sizeof(ieee154_header_t));
+       }
+
+       async command uint8_t RadioPacket.maxPayloadLength()
+       {
+               return call SubPacket.maxPayloadLength() - sizeof(ieee154_header_t);
+       }
+
+       async command uint8_t RadioPacket.metadataLength(message_t* msg)
+       {
+               return call SubPacket.metadataLength(msg);
+       }
+
+       async command void RadioPacket.clear(message_t* msg)
+       {
+               call Ieee154PacketLayer.createDataFrame(msg);
+               call SubPacket.clear(msg);
+       }
+}
diff --git a/tos/chips/rf2xx/layers/LowPowerListeningConfig.nc b/tos/chips/rf2xx/layers/LowPowerListeningConfig.nc
new file mode 100644 (file)
index 0000000..57c99d8
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface LowPowerListeningConfig
+{
+       /**
+        * Returns TRUE if an acknowledgement should be requested
+        * for the message automatically by the LPL code (this should 
+        * normally happen for all non-broadcast messages).
+        */
+       command bool needsAutoAckRequest(message_t* msg);
+
+       /**
+        * Returns TRUE if an acknowledgement has been requested for 
+        * this message via the PacketAcknowledgements interface.
+        */
+       command bool ackRequested(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/layers/LowPowerListeningDummyC.nc b/tos/chips/rf2xx/layers/LowPowerListeningDummyC.nc
new file mode 100644 (file)
index 0000000..163dc8a
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration LowPowerListeningDummyC
+{
+       provides
+       {
+               interface SplitControl;
+               interface BareSend as Send;
+               interface BareReceive as Receive;
+               interface RadioPacket;
+
+               interface LowPowerListening;
+       }
+       uses
+       {
+               interface SplitControl as SubControl;
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
+               interface RadioPacket as SubPacket;
+       }
+}
+
+implementation
+{
+       SplitControl = SubControl;
+       Send = SubSend;
+       Receive = SubReceive;
+       RadioPacket = SubPacket;
+
+       components LowPowerListeningDummyP;
+       LowPowerListening = LowPowerListeningDummyP;
+}
diff --git a/tos/chips/rf2xx/layers/LowPowerListeningDummyP.nc b/tos/chips/rf2xx/layers/LowPowerListeningDummyP.nc
new file mode 100644 (file)
index 0000000..a0294c2
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+module LowPowerListeningDummyP
+{
+       provides interface LowPowerListening;
+}
+
+implementation
+{
+       command void LowPowerListening.setLocalWakeupInterval(uint16_t intervalMs) { }
+
+       command uint16_t LowPowerListening.getLocalWakeupInterval() { return 0; }
+  
+       command void LowPowerListening.setRemoteWakeupInterval(message_t *msg, uint16_t intervalMs) { }
+  
+       command uint16_t LowPowerListening.getRemoteWakeupInterval(message_t *msg) { return 0; }
+}
diff --git a/tos/chips/rf2xx/layers/LowPowerListeningLayer.h b/tos/chips/rf2xx/layers/LowPowerListeningLayer.h
new file mode 100644 (file)
index 0000000..51ee4dd
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __LOWPOWERLISTENINGLAYER_H__
+#define __LOWPOWERLISTENINGLAYER_H__
+
+typedef struct lpl_metadata_t
+{
+       uint16_t sleepint;
+} lpl_metadata_t;
+
+#endif//__LOWPOWERLISTENINGLAYER_H__
diff --git a/tos/chips/rf2xx/layers/LowPowerListeningLayerC.nc b/tos/chips/rf2xx/layers/LowPowerListeningLayerC.nc
new file mode 100644 (file)
index 0000000..75d0715
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration LowPowerListeningLayerC
+{
+       provides
+       {
+               interface SplitControl;
+               interface BareSend as Send;
+               interface BareReceive as Receive;
+               interface RadioPacket;
+
+               interface LowPowerListening;
+       }
+       uses
+       {
+               interface SplitControl as SubControl;
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
+               interface RadioPacket as SubPacket;
+
+               interface LowPowerListeningConfig as Config;
+               interface PacketAcknowledgements;
+       }
+}
+
+implementation
+{
+       components LowPowerListeningLayerP, new TimerMilliC();
+       components SystemLowPowerListeningC;
+
+       SplitControl = LowPowerListeningLayerP;
+       Send = LowPowerListeningLayerP;
+       Receive = LowPowerListeningLayerP;
+       RadioPacket = LowPowerListeningLayerP;
+       LowPowerListening = LowPowerListeningLayerP;
+
+       SubControl = LowPowerListeningLayerP;
+       SubSend = LowPowerListeningLayerP;
+       SubReceive = LowPowerListeningLayerP;
+       SubPacket = LowPowerListeningLayerP;
+       Config = LowPowerListeningLayerP;
+       PacketAcknowledgements = LowPowerListeningLayerP;
+       
+       LowPowerListeningLayerP.Timer -> TimerMilliC;
+       LowPowerListeningLayerP.SystemLowPowerListening -> SystemLowPowerListeningC;
+}
diff --git a/tos/chips/rf2xx/layers/LowPowerListeningLayerP.nc b/tos/chips/rf2xx/layers/LowPowerListeningLayerP.nc
new file mode 100644 (file)
index 0000000..7efab6d
--- /dev/null
@@ -0,0 +1,418 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioAssert.h>
+#include <LowPowerListeningLayer.h>
+#include <Lpl.h>
+
+module LowPowerListeningLayerP
+{
+       provides
+       {
+               interface SplitControl;
+               interface BareSend as Send;
+               interface BareReceive as Receive;
+               interface RadioPacket;
+
+               interface LowPowerListening;
+       }
+
+       uses
+       {
+               interface SplitControl as SubControl;
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
+               interface RadioPacket as SubPacket;
+
+               interface PacketAcknowledgements;
+               interface LowPowerListeningConfig as Config;
+               interface Timer<TMilli>;
+               interface SystemLowPowerListening;
+       }
+}
+
+implementation
+{
+       enum
+       {
+               // minimum wakeup time to catch a transmission in milliseconds
+               LISTEN_WAKEUP = 6U,     // use xxxL if LISTEN_WAKEUP * 10000 > 65535
+
+               MIN_SLEEP = 2,          // the minimum sleep interval in milliseconds
+       };
+
+       uint16_t sleepInterval = LPL_DEF_LOCAL_WAKEUP;
+
+       message_t* txMsg;
+       error_t txError;
+
+/*----------------- state machine -----------------*/
+
+       enum
+       {
+               OFF = 0,                                        
+               OFF_SUBSTOP = 1,                        // must have consecutive indices
+               OFF_SUBSTOP_DONE = 2,                   // must have consecutive indices
+               OFF_STOP_END = 3,                       // must have consecutive indices
+               OFF_START_END = 4,
+
+               LISTEN_SUBSTART = 5,                    // must have consecutive indices
+               LISTEN_SUBSTART_DONE = 6,               // must have consecutive indices
+               LISTEN_TIMER = 7,                       // must have consecutive indices
+               LISTEN = 8,                             // must have consecutive indices
+
+               SLEEP_SUBSTOP = 9,                      // must have consecutive indices
+               SLEEP_SUBSTOP_DONE = 10,                // must have consecutive indices
+               SLEEP_TIMER = 11,                       // must have consecutive indices
+               SLEEP = 12,                             // must have consecutive indices
+
+               SEND_SUBSTART = 13,                     // must have consecutive indices
+               SEND_SUBSTART_DONE = 14,                // must have consecutive indices
+               SEND_TIMER = 15,                        // must have consecutive indices
+               SEND_SUBSEND= 16,
+               SEND_SUBSEND_DONE = 17,
+               SEND_SUBSEND_DONE_LAST = 18,
+               SEND_DONE = 19,
+       };
+
+       uint8_t state;
+
+       task void transition()
+       {
+               error_t error;
+               uint16_t transmitInterval;
+
+               if( state == LISTEN_SUBSTART || state == SEND_SUBSTART )
+               {
+                       error = call SubControl.start();
+                       ASSERT( error == SUCCESS || error == EBUSY );
+
+                       if( error == SUCCESS )
+                               ++state;
+                       else
+                               post transition();
+               }
+               else if( state == SLEEP_SUBSTOP || state == OFF_SUBSTOP )
+               {
+                       error = call SubControl.stop();
+                       ASSERT( error == SUCCESS || error == EBUSY );
+
+                       if( error == SUCCESS )
+                               ++state;
+                       else
+                               post transition();
+               }
+               else if( state == OFF_START_END )
+               {
+                       state = LISTEN_SUBSTART;
+                       post transition();
+
+                       signal SplitControl.startDone(SUCCESS);
+               }
+               else if( state == OFF_STOP_END )
+               {
+                       state = OFF;
+                       signal SplitControl.stopDone(SUCCESS);
+               }
+               else if( state == LISTEN_TIMER )
+               {
+                       state = LISTEN;
+                       if( sleepInterval > 0 )
+                               call Timer.startOneShot(LISTEN_WAKEUP);
+               }
+               else if( state == SLEEP_TIMER )
+               {
+                       if( sleepInterval > 0 )
+                       {
+                               state = SLEEP;
+                               call Timer.startOneShot(sleepInterval);
+                       }
+                       else
+                       {
+                               state = LISTEN_SUBSTART;
+                               post transition();
+                       }
+               }
+               else if( state == SEND_TIMER )
+               {
+                       transmitInterval = call LowPowerListening.getRemoteWakeupInterval(txMsg);
+
+                       if( transmitInterval > 0 )
+                               call Timer.startOneShot(transmitInterval);
+
+                       state = SEND_SUBSEND;
+                       post transition();
+               }
+               else if( state == SEND_SUBSEND)
+               {
+                       txError = call SubSend.send(txMsg);
+
+                       if( txError == SUCCESS )
+                               state = SEND_SUBSEND_DONE;
+                       else
+                       {
+                               state = SEND_DONE;
+                               post transition();
+                       }
+               }
+               else if( state == SEND_DONE )
+               {
+                       state = LISTEN;
+                       if( sleepInterval > 0 )
+                               call Timer.startOneShot(call SystemLowPowerListening.getDelayAfterReceive());
+
+                       signal Send.sendDone(txMsg, txError);
+               }
+       }
+
+       command error_t SplitControl.start()
+       {
+               if( state == OFF_START_END )
+                       return EBUSY;
+               else if( state != OFF )
+                       return EALREADY;
+
+               state = OFF_START_END;
+               post transition();
+
+               return SUCCESS;
+       }
+
+       event void SubControl.startDone(error_t error)
+       {
+               ASSERT( error == SUCCESS || error == EBUSY );
+               ASSERT( state == LISTEN_SUBSTART_DONE || state == SEND_SUBSTART_DONE );
+
+               if( error == SUCCESS )
+                       ++state;
+               else
+                       --state;
+
+               post transition();
+       }
+
+       command error_t SplitControl.stop()
+       {
+               if( state == SLEEP || state == LISTEN )
+               {
+                       call Timer.stop();
+                       post transition();
+               }
+
+               if( state == LISTEN_TIMER || state == LISTEN || state == SLEEP_SUBSTOP )
+                       state = OFF_SUBSTOP;
+               else if( state == SLEEP_SUBSTOP_DONE )
+                       state = OFF_SUBSTOP_DONE;
+               else if( state == LISTEN_SUBSTART || state == SLEEP_TIMER || state == SLEEP )
+                       state = OFF_STOP_END;
+               else if( state == OFF )
+                       return EALREADY;
+               else
+                       return EBUSY;
+
+               return SUCCESS;
+       }
+
+       event void SubControl.stopDone(error_t error)
+       {
+               ASSERT( error == SUCCESS || error == EBUSY );
+               ASSERT( state == SLEEP_SUBSTOP_DONE || state == OFF_SUBSTOP_DONE );
+
+               if( error == SUCCESS )
+                       ++state;
+               else
+                       --state;
+
+               post transition();
+       }
+
+       event void Timer.fired()
+       {
+               ASSERT( state == LISTEN || state == SLEEP || state == SEND_SUBSEND || state == SEND_SUBSEND_DONE );
+
+               if( state == LISTEN )
+                       state = SLEEP_SUBSTOP;
+               else if( state == SLEEP )
+                       state = LISTEN_SUBSTART;
+               else if( state == SEND_SUBSEND_DONE )
+                       state = SEND_SUBSEND_DONE_LAST;
+               else if( state == SEND_SUBSEND)
+                       state = SEND_DONE;
+
+               post transition();
+       }
+
+       event message_t* SubReceive.receive(message_t* msg)
+       {
+               if( state == SLEEP_SUBSTOP )
+                       state = LISTEN;
+
+               if( state == LISTEN && sleepInterval > 0 )
+                       call Timer.startOneShot(call SystemLowPowerListening.getDelayAfterReceive());
+
+               return signal Receive.receive(msg);
+       }
+
+       command error_t Send.send(message_t* msg)
+       {
+               if( state == LISTEN || state == SLEEP )
+               {
+                       call Timer.stop();
+                       post transition();
+               }
+
+               if( state == LISTEN_SUBSTART || state == SLEEP_TIMER || state == SLEEP )
+                       state = SEND_SUBSTART;
+               else if( state == LISTEN_SUBSTART_DONE )
+                       state = SEND_SUBSTART_DONE;
+               else if( state == LISTEN_TIMER || state == SLEEP_SUBSTOP || state == LISTEN )
+                       state = SEND_TIMER;
+               else
+                       return EBUSY;
+
+               if( call Config.needsAutoAckRequest(msg) )
+                       call PacketAcknowledgements.requestAck(msg);
+
+               txMsg = msg;
+               txError = FAIL;
+
+               return SUCCESS;
+       }
+
+       command error_t Send.cancel(message_t* msg)
+       {
+               if( state == SEND_SUBSEND )
+               {
+                       call Timer.stop();
+                       state = SEND_DONE;
+                       txError = ECANCEL;
+                       post transition();
+
+                       return SUCCESS;
+               }
+               else if( state == SEND_SUBSEND_DONE )
+               {
+                       // we stop sending the message even if SubSend.cancel was not succesfull
+                       state = SEND_SUBSEND_DONE_LAST;
+
+                       return call SubSend.cancel(txMsg);
+               }
+               else
+                       return FAIL;
+       }
+
+       event void SubSend.sendDone(message_t* msg, error_t error)
+       {
+               ASSERT( state == SEND_SUBSEND_DONE || state == SEND_SUBSEND_DONE_LAST );
+               ASSERT( msg == txMsg );
+
+               txError = error;
+
+               // TODO: extend the PacketAcknowledgements interface with getAckRequired
+               if( error != SUCCESS
+                       || call LowPowerListening.getRemoteWakeupInterval(msg) == 0
+                       || state == SEND_SUBSEND_DONE_LAST
+                       || (call Config.ackRequested(msg) && call PacketAcknowledgements.wasAcked(msg)) )
+               {
+                       call Timer.stop();
+                       state = SEND_DONE;
+               }
+               else
+                       state = SEND_SUBSEND;
+
+               post transition();
+       }
+
+/*----------------- LowPowerListening -----------------*/
+
+       lpl_metadata_t* getMeta(message_t* msg)
+       {
+               return ((void*)msg) + sizeof(message_t) - call RadioPacket.metadataLength(msg);
+       }
+
+       command void LowPowerListening.setLocalWakeupInterval(uint16_t interval)
+       {
+               if( interval < MIN_SLEEP )
+                       interval = 0;
+
+               sleepInterval = interval;
+
+               if( (state == LISTEN && sleepInterval == 0) || state == SLEEP )
+               {
+                       call Timer.stop();
+                       --state;
+                       post transition();
+               }
+       }
+
+       command uint16_t LowPowerListening.getLocalWakeupInterval()
+       {       
+               return sleepInterval;
+       }
+
+       command void LowPowerListening.setRemoteWakeupInterval(message_t *msg, uint16_t interval)
+       {
+               if( interval < MIN_SLEEP )
+                       interval = 0;
+
+               getMeta(msg)->sleepint = interval;
+       }
+
+       command uint16_t LowPowerListening.getRemoteWakeupInterval(message_t *msg)
+       {
+               return getMeta(msg)->sleepint;
+       }
+
+/*----------------- RadioPacket -----------------*/
+       
+       async command uint8_t RadioPacket.headerLength(message_t* msg)
+       {
+               return call SubPacket.headerLength(msg);
+       }
+
+       async command uint8_t RadioPacket.payloadLength(message_t* msg)
+       {
+               return call SubPacket.payloadLength(msg);
+       }
+
+       async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               call SubPacket.setPayloadLength(msg, length);
+       }
+
+       async command uint8_t RadioPacket.maxPayloadLength()
+       {
+               return call SubPacket.maxPayloadLength();
+       }
+
+       async command uint8_t RadioPacket.metadataLength(message_t* msg)
+       {
+               return call SubPacket.metadataLength(msg) + sizeof(lpl_metadata_t);
+       }
+
+       async command void RadioPacket.clear(message_t* msg)
+       {
+               getMeta(msg)->sleepint = 0;
+               call SubPacket.clear(msg);
+       }
+}
diff --git a/tos/chips/rf2xx/layers/MessageBufferLayerC.nc b/tos/chips/rf2xx/layers/MessageBufferLayerC.nc
new file mode 100644 (file)
index 0000000..5ef7644
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration MessageBufferLayerC
+{
+       provides
+       {
+               interface SplitControl;
+               interface BareSend as Send;
+               interface BareReceive as Receive;
+               interface RadioChannel;
+       }
+       uses
+       {
+               interface RadioState;
+               interface RadioSend;
+               interface RadioReceive;
+       }
+}
+
+implementation
+{
+       components MessageBufferLayerP, MainC, TaskletC;
+
+       MainC.SoftwareInit -> MessageBufferLayerP;
+
+       SplitControl = MessageBufferLayerP;
+       Send = MessageBufferLayerP;
+       Receive = MessageBufferLayerP;
+       RadioChannel = MessageBufferLayerP;
+
+       RadioState = MessageBufferLayerP;
+       MessageBufferLayerP.Tasklet -> TaskletC;
+       RadioSend = MessageBufferLayerP;
+       RadioReceive = MessageBufferLayerP;
+}
diff --git a/tos/chips/rf2xx/layers/MessageBufferLayerP.nc b/tos/chips/rf2xx/layers/MessageBufferLayerP.nc
new file mode 100644 (file)
index 0000000..224d2e2
--- /dev/null
@@ -0,0 +1,334 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+#include <RadioAssert.h>
+
+module MessageBufferLayerP
+{
+       provides
+       {
+               interface SplitControl;
+               interface Init as SoftwareInit;
+
+               interface BareSend as Send;
+               interface BareReceive as Receive;
+               interface RadioChannel;
+       }
+       uses
+       {
+               interface RadioState;
+               interface Tasklet;
+               interface RadioSend;
+               interface RadioReceive;
+       }
+}
+
+implementation
+{
+/*----------------- State -----------------*/
+
+       norace uint8_t state;   // written only from tasks
+       enum
+       {
+               STATE_READY = 0,
+               STATE_TX_PENDING = 1,
+               STATE_TX_SEND = 2,
+               STATE_TX_DONE = 3,
+               STATE_TURN_ON = 4,
+               STATE_TURN_OFF = 5,
+               STATE_CHANNEL = 6,
+       };
+
+       command error_t SplitControl.start()
+       {
+               error_t error;
+
+               call Tasklet.suspend();
+
+               if( state != STATE_READY )
+                       error = EBUSY;
+               else
+                       error = call RadioState.turnOn();
+
+               if( error == SUCCESS )
+                       state = STATE_TURN_ON;
+
+               call Tasklet.resume();
+
+               return error;
+       }
+
+       command error_t SplitControl.stop()
+       {
+               error_t error;
+
+               call Tasklet.suspend();
+
+               if( state != STATE_READY )
+                       error = EBUSY;
+               else
+                       error = call RadioState.turnOff();
+
+               if( error == SUCCESS )
+                       state = STATE_TURN_OFF;
+
+               call Tasklet.resume();
+
+               return error;
+       }
+
+       command error_t RadioChannel.setChannel(uint8_t channel)
+       {
+               error_t error;
+
+               call Tasklet.suspend();
+
+               if( state != STATE_READY )
+                       error = EBUSY;
+               else
+                       error = call RadioState.setChannel(channel);
+
+               if( error == SUCCESS )
+                       state = STATE_CHANNEL;
+
+               call Tasklet.resume();
+
+               return error;
+       }
+
+       command uint8_t RadioChannel.getChannel()
+       {
+               return call RadioState.getChannel();
+       }
+
+       task void stateDoneTask()
+       {
+               uint8_t s;
+               
+               s = state;
+
+               // change the state before so we can be reentered from the event
+               state = STATE_READY;
+
+               if( s == STATE_TURN_ON )
+                       signal SplitControl.startDone(SUCCESS);
+               else if( s == STATE_TURN_OFF )
+                       signal SplitControl.stopDone(SUCCESS);
+               else if( s == STATE_CHANNEL )
+                       signal RadioChannel.setChannelDone();
+               else    // not our event, ignore it
+                       state = s;
+       }
+
+       tasklet_async event void RadioState.done()
+       {
+               post stateDoneTask();
+       }
+
+       default event void SplitControl.startDone(error_t error)
+       {
+       }
+
+       default event void SplitControl.stopDone(error_t error)
+       {
+       }
+
+       default event void RadioChannel.setChannelDone()
+       {
+       }
+
+/*----------------- Send -----------------*/
+
+       message_t* txMsg;
+       error_t txError;
+       uint8_t retries;
+
+       // Many EBUSY replies from RadioSend are normal if the channel is cognested
+       enum { MAX_RETRIES = 5 };
+
+       task void sendTask()
+       {
+               error_t error;
+
+               ASSERT( state == STATE_TX_PENDING || state == STATE_TX_SEND );
+
+               atomic error = txError;
+               if( (state == STATE_TX_SEND && error == SUCCESS) || ++retries > MAX_RETRIES )
+                       state = STATE_TX_DONE;
+               else
+               {
+                       call Tasklet.suspend();
+
+                       error = call RadioSend.send(txMsg);
+                       if( error == SUCCESS )
+                               state = STATE_TX_SEND;
+                       else if( retries == MAX_RETRIES )
+                               state = STATE_TX_DONE;
+                       else
+                               state = STATE_TX_PENDING;
+
+                       call Tasklet.resume();
+               }
+
+               if( state == STATE_TX_DONE )
+               {
+                       state = STATE_READY;
+                       signal Send.sendDone(txMsg, error);
+               }
+       }
+
+       tasklet_async event void RadioSend.sendDone(error_t error)
+       {
+               ASSERT( state == STATE_TX_SEND );
+
+               atomic txError = error;
+               post sendTask();
+       }
+
+       command error_t Send.send(message_t* msg)
+       {
+               if( state != STATE_READY )
+                       return EBUSY;
+
+               txMsg = msg;
+               state = STATE_TX_PENDING;
+               retries = 0;
+               post sendTask();
+
+               return SUCCESS;
+       }
+
+       tasklet_async event void RadioSend.ready()
+       {
+               if( state == STATE_TX_PENDING )
+                       post sendTask();
+       }
+
+       tasklet_async event void Tasklet.run()
+       {
+       }
+
+       command error_t Send.cancel(message_t* msg)
+       {
+               if( state == STATE_TX_PENDING )
+               {
+                       state = STATE_READY;
+
+                       // TODO: check if sendDone can be called before cancel returns
+                       signal Send.sendDone(msg, ECANCEL);
+
+                       return SUCCESS;
+               }
+               else
+                       return FAIL;
+       }
+
+/*----------------- Receive -----------------*/
+
+       enum
+       {
+               RECEIVE_QUEUE_SIZE = 3,
+       };
+
+       message_t receiveQueueData[RECEIVE_QUEUE_SIZE];
+       message_t* receiveQueue[RECEIVE_QUEUE_SIZE];
+
+       uint8_t receiveQueueHead;
+       uint8_t receiveQueueSize;
+
+       command error_t SoftwareInit.init()
+       {
+               uint8_t i;
+
+               for(i = 0; i < RECEIVE_QUEUE_SIZE; ++i)
+                       receiveQueue[i] = receiveQueueData + i;
+
+               return SUCCESS;
+       }
+
+       tasklet_async event bool RadioReceive.header(message_t* msg)
+       {
+               bool notFull;
+
+               // this prevents undeliverable messages to be acknowledged
+               atomic notFull = receiveQueueSize < RECEIVE_QUEUE_SIZE;
+
+               return notFull;
+       }
+
+       task void deliverTask()
+       {
+               // get rid of as many messages as possible without interveining tasks
+               for(;;)
+               {
+                       message_t* msg;
+
+                       atomic
+                       {
+                               if( receiveQueueSize == 0 )
+                                       return;
+
+                               msg = receiveQueue[receiveQueueHead];
+                       }
+
+                       msg = signal Receive.receive(msg);
+
+                       atomic
+                       {
+                               receiveQueue[receiveQueueHead] = msg;
+
+                               if( ++receiveQueueHead >= RECEIVE_QUEUE_SIZE )
+                                       receiveQueueHead = 0;
+
+                               --receiveQueueSize;
+                       }
+               }
+       }
+
+       tasklet_async event message_t* RadioReceive.receive(message_t* msg)
+       {
+               message_t *m;
+
+               atomic
+               {
+                       if( receiveQueueSize >= RECEIVE_QUEUE_SIZE )
+                               m = msg;
+                       else
+                       {
+                               uint8_t index = receiveQueueHead + receiveQueueSize;
+                               if( index >= RECEIVE_QUEUE_SIZE )
+                                       index -= RECEIVE_QUEUE_SIZE;
+
+                               m = receiveQueue[index];
+                               receiveQueue[index] = msg;
+
+                               ++receiveQueueSize;
+                               post deliverTask();
+                       }
+               }
+
+               return m;
+       }
+
+}
diff --git a/tos/chips/rf2xx/layers/MetadataFlagsLayer.h b/tos/chips/rf2xx/layers/MetadataFlagsLayer.h
new file mode 100644 (file)
index 0000000..5694d07
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __METADATAFLAGSLAYER_H__
+#define __METADATAFLAGSLAYER_H__
+
+typedef struct flags_metadata_t
+{
+       // TODO: make sure that we have no more than 8 flags
+       uint8_t flags;
+} flags_metadata_t;
+
+#endif//__METADATAFLAGSLAYER_H__
diff --git a/tos/chips/rf2xx/layers/MetadataFlagsLayerC.nc b/tos/chips/rf2xx/layers/MetadataFlagsLayerC.nc
new file mode 100644 (file)
index 0000000..39b0bee
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <MetadataFlagsLayer.h>
+#include <RadioAssert.h>
+
+module MetadataFlagsLayerC
+{
+       provides 
+       {
+               interface PacketFlag[uint8_t bit];
+               interface RadioPacket;
+       }
+
+       uses
+       {
+               interface RadioPacket as SubPacket;
+       }
+}
+
+implementation
+{
+       flags_metadata_t* getMeta(message_t* msg)
+       {
+               return ((void*)msg) + sizeof(message_t) - call RadioPacket.metadataLength(msg);
+       }
+
+/*----------------- RadioPacket -----------------*/
+
+       async command bool PacketFlag.get[uint8_t bit](message_t* msg)
+       {
+               return getMeta(msg)->flags & (1<<bit);
+       }
+
+       async command void PacketFlag.set[uint8_t bit](message_t* msg)
+       {
+               ASSERT( bit  < 8 );
+
+               getMeta(msg)->flags |= (1<<bit);
+       }
+
+       async command void PacketFlag.clear[uint8_t bit](message_t* msg)
+       {
+               ASSERT( bit  < 8 );
+
+               getMeta(msg)->flags &= ~(1<<bit);
+       }
+
+       async command void PacketFlag.setValue[uint8_t bit](message_t* msg, bool value)
+       {
+               if( value )
+                       call PacketFlag.set[bit](msg);
+               else
+                       call PacketFlag.clear[bit](msg);
+       }
+
+/*----------------- RadioPacket -----------------*/
+       
+       async command uint8_t RadioPacket.headerLength(message_t* msg)
+       {
+               return call SubPacket.headerLength(msg);
+       }
+
+       async command uint8_t RadioPacket.payloadLength(message_t* msg)
+       {
+               return call SubPacket.payloadLength(msg);
+       }
+
+       async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               call SubPacket.setPayloadLength(msg, length);
+       }
+
+       async command uint8_t RadioPacket.maxPayloadLength()
+       {
+               return call SubPacket.maxPayloadLength();
+       }
+
+       async command uint8_t RadioPacket.metadataLength(message_t* msg)
+       {
+               return call SubPacket.metadataLength(msg) + sizeof(flags_metadata_t);
+       }
+
+       async command void RadioPacket.clear(message_t* msg)
+       {
+               getMeta(msg)->flags = 0;
+               call SubPacket.clear(msg);
+       }
+}
diff --git a/tos/chips/rf2xx/layers/PacketLinkLayer.h b/tos/chips/rf2xx/layers/PacketLinkLayer.h
new file mode 100644 (file)
index 0000000..df518ce
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __PACKETLINKLAYER_H__
+#define __PACKETLINKLAYER_H__
+
+typedef struct link_metadata_t
+{
+       uint16_t maxRetries;
+       uint16_t retryDelay;
+} link_metadata_t;
+
+#endif//__PACKETLINKLAYER_H__
diff --git a/tos/chips/rf2xx/layers/PacketLinkLayerC.nc b/tos/chips/rf2xx/layers/PacketLinkLayerC.nc
new file mode 100644 (file)
index 0000000..efd5a0c
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * Copyright (c) 2005-2006 Rincon Research Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Rincon Research Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * RINCON RESEARCH OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Reliable Packet Link Functionality
+ * @author David Moss
+ * @author Jon Wyant
+ * @author Miklos Maroti
+ */
+
+#include <PacketLinkLayer.h>
+
+configuration PacketLinkLayerC {
+  provides {
+    interface BareSend as Send;
+    interface PacketLink;
+    interface RadioPacket;
+  }
+  
+  uses {
+    interface BareSend as SubSend;
+    interface RadioPacket as SubPacket;
+    interface PacketAcknowledgements;
+  }
+}
+
+implementation {
+  components PacketLinkLayerP, new TimerMilliC() as DelayTimerC;
+  
+  PacketLink = PacketLinkLayerP;
+  Send = PacketLinkLayerP;
+  SubSend = PacketLinkLayerP;
+  PacketAcknowledgements = PacketLinkLayerP;
+  RadioPacket = PacketLinkLayerP;
+  SubPacket = PacketLinkLayerP;
+
+  PacketLinkLayerP.DelayTimer -> DelayTimerC;
+}
diff --git a/tos/chips/rf2xx/layers/PacketLinkLayerP.nc b/tos/chips/rf2xx/layers/PacketLinkLayerP.nc
new file mode 100644 (file)
index 0000000..b8f284e
--- /dev/null
@@ -0,0 +1,255 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*
+ * Copyright (c) 2005-2006 Rincon Research Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Rincon Research Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * RINCON RESEARCH OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Reliable Packet Link Functionality
+ * @author David Moss
+ * @author Jon Wyant
+ * @author Miklos Maroti
+ */
+
+#include <PacketLinkLayer.h>
+
+module PacketLinkLayerP {
+  provides {
+    interface BareSend as Send;
+    interface PacketLink;
+    interface RadioPacket;
+  }
+
+  uses {
+    interface BareSend as SubSend;
+    interface PacketAcknowledgements;
+    interface Timer<TMilli> as DelayTimer;
+    interface RadioPacket as SubPacket;
+  }
+}
+
+implementation {
+
+  /** The message currently being sent */
+  message_t *currentSendMsg;
+
+  /** The length of the current send message */
+  uint16_t totalRetries;
+
+  /***************** Prototypes ***************/
+
+  task void send();
+  void signalDone(error_t error);
+
+
+  /***************** PacketLink Commands ***************/
+
+  link_metadata_t* getMeta(message_t* msg) {
+    return ((void*)msg) + sizeof(message_t) - call RadioPacket.metadataLength(msg);
+  }
+
+  /**
+   * Set the maximum number of times attempt message delivery
+   * Default is 0
+   * @param msg
+   * @param maxRetries the maximum number of attempts to deliver
+   *     the message
+   */
+  command void PacketLink.setRetries(message_t *msg, uint16_t maxRetries) {
+    getMeta(msg)->maxRetries = maxRetries;
+  }
+
+  /**
+   * Set a delay between each retry attempt
+   * @param msg
+   * @param retryDelay the delay betweeen retry attempts, in milliseconds
+   */
+  command void PacketLink.setRetryDelay(message_t *msg, uint16_t retryDelay) {
+    getMeta(msg)->retryDelay = retryDelay;
+  }
+
+  /**
+   * @return the maximum number of retry attempts for this message
+   */
+  command uint16_t PacketLink.getRetries(message_t *msg) {
+    return getMeta(msg)->maxRetries;
+  }
+
+  /**
+   * @return the delay between retry attempts in ms for this message
+   */
+  command uint16_t PacketLink.getRetryDelay(message_t *msg) {
+    return getMeta(msg)->retryDelay;
+  }
+
+  /**
+   * @return TRUE if the message was delivered.
+   */
+  command bool PacketLink.wasDelivered(message_t *msg) {
+    return call PacketAcknowledgements.wasAcked(msg);
+  }
+
+  /***************** Send Commands ***************/
+  /**
+   * Each call to this send command gives the message a single
+   * DSN that does not change for every copy of the message
+   * sent out.  For messages that are not acknowledged, such as
+   * a broadcast address message, the receiving end does not
+   * signal receive() more than once for that message.
+   */
+  command error_t Send.send(message_t *msg) {
+    error_t error = EBUSY;
+    if(currentSendMsg == NULL) {
+
+      if(call PacketLink.getRetries(msg) > 0) {
+        call PacketAcknowledgements.requestAck(msg);
+      }
+
+      if((error = call SubSend.send(msg)) == SUCCESS) {
+        currentSendMsg = msg;
+        totalRetries = 0;
+      }
+    }
+    return error;
+  }
+
+  command error_t Send.cancel(message_t *msg) {
+    if(currentSendMsg == msg) {
+      currentSendMsg = NULL;
+      return call SubSend.cancel(msg);
+    }
+
+    return FAIL;
+  }
+
+  /***************** SubSend Events ***************/
+  event void SubSend.sendDone(message_t* msg, error_t error) {
+    totalRetries++;
+
+    if(call PacketAcknowledgements.wasAcked(msg)) {
+      signalDone(SUCCESS);
+      return;
+
+    } else if(totalRetries < call PacketLink.getRetries(currentSendMsg)) {
+
+      if(call PacketLink.getRetryDelay(currentSendMsg) > 0) {
+        // Resend after some delay
+        call DelayTimer.startOneShot(call PacketLink.getRetryDelay(currentSendMsg));
+      } else {
+        // Resend immediately
+        post send();
+      }
+
+      return;
+    }
+
+    signalDone(error);
+  }
+
+  /***************** Timer Events ****************/
+  /**
+   * When this timer is running, that means we're sending repeating messages
+   * to a node that is receive check duty cycling.
+   */
+  event void DelayTimer.fired() {
+    if(currentSendMsg != NULL) {
+      post send();
+    }
+  }
+
+  /***************** Tasks ***************/
+  task void send() {
+    if(call PacketLink.getRetries(currentSendMsg) > 0) {
+      call PacketAcknowledgements.requestAck(currentSendMsg);
+    }
+
+    if(call SubSend.send(currentSendMsg) != SUCCESS) {
+      post send();
+    }
+  }
+
+  /***************** Functions ***************/
+  void signalDone(error_t error) {
+    message_t* msg = currentSendMsg;
+    currentSendMsg = NULL;
+
+    // AT: A bit of a hack to be able to keep track of the number of retries
+    // printfUART("Signaling done with total retries at 0x%x\n", totalRetries);
+
+    call DelayTimer.stop();
+    call PacketLink.setRetries(msg, totalRetries);
+    signal Send.sendDone(msg, error);
+  }
+
+  /***************** Functions ***************/
+  async command uint8_t RadioPacket.headerLength(message_t* msg) {
+    return call SubPacket.headerLength(msg);
+  }
+
+  async command uint8_t RadioPacket.payloadLength(message_t* msg) {
+    return call SubPacket.payloadLength(msg);
+  }
+
+  async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length) {
+    call SubPacket.setPayloadLength(msg, length);
+  }
+
+  async command uint8_t RadioPacket.maxPayloadLength() {
+    return call SubPacket.maxPayloadLength();
+  }
+
+  async command uint8_t RadioPacket.metadataLength(message_t* msg) {
+    return call SubPacket.metadataLength(msg) + sizeof(link_metadata_t);
+  }
+
+  async command void RadioPacket.clear(message_t* msg) {
+    getMeta(msg)->maxRetries = 0;
+    call SubPacket.clear(msg);
+  }
+}
diff --git a/tos/chips/rf2xx/layers/RandomCollisionConfig.nc b/tos/chips/rf2xx/layers/RandomCollisionConfig.nc
new file mode 100755 (executable)
index 0000000..b12cc69
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface RandomCollisionConfig
+{
+       /**
+        * Returns the initial amount of maximum backoff for this message.
+        */
+       async command uint16_t getInitialBackoff(message_t* msg);
+
+       /**
+        * Returns the amount of maximum backoff when there is congestion
+        * (the channel was busy for the first try)
+        */
+       async command uint16_t getCongestionBackoff(message_t* msg);
+
+       /**
+        * Returns the minimum ticks before the message could be sent.
+        */
+       async command uint16_t getMinimumBackoff();
+
+       /**
+        * The provided message was just received, and this command should return 
+        * the time till no transmission should be initiated.
+        */
+       async command uint16_t getTransmitBarrier(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/layers/RandomCollisionLayerC.nc b/tos/chips/rf2xx/layers/RandomCollisionLayerC.nc
new file mode 100755 (executable)
index 0000000..ba7ad05
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration RandomCollisionLayerC
+{
+       provides
+       {
+               interface RadioSend;
+               interface RadioReceive;
+       }
+       uses
+       {
+               interface RadioSend as SubSend;
+               interface RadioReceive as SubReceive;
+               interface RandomCollisionConfig as Config;
+       }
+}
+
+implementation
+{
+       components RandomCollisionLayerP, RadioAlarmC, RandomC;
+
+       RadioSend = RandomCollisionLayerP;
+       SubSend = RandomCollisionLayerP;
+       Config = RandomCollisionLayerP;
+       RadioReceive = RandomCollisionLayerP;
+       SubReceive = RandomCollisionLayerP;
+
+       RandomCollisionLayerP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
+       RandomCollisionLayerP.Random -> RandomC;
+}
diff --git a/tos/chips/rf2xx/layers/RandomCollisionLayerP.nc b/tos/chips/rf2xx/layers/RandomCollisionLayerP.nc
new file mode 100755 (executable)
index 0000000..c53d1b9
--- /dev/null
@@ -0,0 +1,177 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+#include <RadioAssert.h>
+
+module RandomCollisionLayerP
+{
+       provides
+       {
+               interface RadioSend;
+               interface RadioReceive;
+       }
+       uses
+       {
+               interface RadioSend as SubSend;
+               interface RadioReceive as SubReceive;
+               interface RadioAlarm;
+               interface Random;
+               interface RandomCollisionConfig as Config;
+       }
+}
+
+implementation
+{
+       tasklet_norace uint8_t state;
+       enum
+       {
+               STATE_READY = 0,
+               STATE_TX_PENDING_FIRST = 1,
+               STATE_TX_PENDING_SECOND = 2,
+               STATE_TX_SENDING = 3,
+
+               STATE_BARRIER = 0x80,
+       };
+
+       tasklet_norace message_t *txMsg;
+       tasklet_norace uint16_t txBarrier;
+
+       tasklet_async event void SubSend.ready()
+       {
+               if( state == STATE_READY && call RadioAlarm.isFree() )
+                       signal RadioSend.ready();
+       }
+
+       uint16_t nextRandom;
+       task void calcNextRandom()
+       {
+               uint16_t a = call Random.rand16();
+               atomic nextRandom = a;
+       }
+
+       uint16_t getBackoff(uint16_t maxBackoff)
+       {
+               uint16_t a;
+
+               atomic
+               {
+                       a = nextRandom;
+                       nextRandom += 273;
+               }
+               post calcNextRandom();
+
+               return (a % maxBackoff) + call Config.getMinimumBackoff();
+       }
+
+       tasklet_async command error_t RadioSend.send(message_t* msg)
+       {
+               if( state != STATE_READY || ! call RadioAlarm.isFree() )
+                       return EBUSY;
+
+               txMsg = msg;
+               state = STATE_TX_PENDING_FIRST;
+               call RadioAlarm.wait(getBackoff(call Config.getInitialBackoff(msg)));
+
+               return SUCCESS;
+       }
+
+       tasklet_async event void RadioAlarm.fired()
+       {
+               error_t error;
+               int16_t delay;
+
+               ASSERT( state != STATE_READY );
+
+               delay = (int16_t)txBarrier - call RadioAlarm.getNow();
+
+               if( state == STATE_BARRIER )
+               {
+                       state = STATE_READY;
+
+                       signal RadioSend.ready();
+                       return;
+               }
+               else if( (state & STATE_BARRIER) && delay > 0 )
+                       error = EBUSY;
+               else
+                       error = call SubSend.send(txMsg);
+
+               if( error != SUCCESS )
+               {
+                       if( (state & ~STATE_BARRIER) == STATE_TX_PENDING_FIRST )
+                       {
+                               state = (state & STATE_BARRIER) | STATE_TX_PENDING_SECOND;
+                               call RadioAlarm.wait(getBackoff(call Config.getCongestionBackoff(txMsg)));
+                       }
+                       else
+                       {
+                               if( (state & STATE_BARRIER) && delay > 0 )
+                               {
+                                       state = STATE_BARRIER;
+                                       call RadioAlarm.wait(delay);
+                               }
+                               else
+                                       state = STATE_READY;
+
+                               signal RadioSend.sendDone(error);
+                       }
+               }
+               else
+                       state = STATE_TX_SENDING;
+       }
+
+       tasklet_async event void SubSend.sendDone(error_t error)
+       {
+               ASSERT( state == STATE_TX_SENDING );
+
+               state = STATE_READY;
+               signal RadioSend.sendDone(error);
+       }
+
+       tasklet_async event bool SubReceive.header(message_t* msg)
+       {
+               return signal RadioReceive.header(msg);
+       }
+
+       tasklet_async event message_t* SubReceive.receive(message_t* msg)
+       {
+               int16_t delay;
+
+               txBarrier = call Config.getTransmitBarrier(msg);
+               delay = txBarrier - call RadioAlarm.getNow();
+
+               if( delay > 0 )
+               {
+                       if( state == STATE_READY )
+                       {
+                               call RadioAlarm.wait(delay);
+                               state = STATE_BARRIER;
+                       }
+                       else
+                               state |= STATE_BARRIER;
+               }
+
+               return signal RadioReceive.receive(msg);
+       }
+}
diff --git a/tos/chips/rf2xx/layers/SlottedCollisionConfig.nc b/tos/chips/rf2xx/layers/SlottedCollisionConfig.nc
new file mode 100755 (executable)
index 0000000..5b3bec6
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface SlottedCollisionConfig
+{
+       /**
+        * This command should return the approximate transmit delay between
+        * setting an alarm, waiting for the fire event, calling send and
+        * obtaining the timestamp for the transmitted message.
+        */
+       async command uint16_t getInitialDelay();
+
+       /**
+        * Must return a binary exponent so that the collision avoidance layer
+        * can assign slots in the range of [0, 1 << exponent) of size collision
+        * window.
+        */
+       async command uint8_t getScheduleExponent();
+
+       /**
+        * This command must return the time when the message was transmitted.
+        */
+       async command uint16_t getTransmitTime(message_t* msg);
+
+       /**
+        * Returns the start of the collision window for this received message,
+        * so transmit times in this range would be considered possible collisions.
+        */
+       async command uint16_t getCollisionWindowStart(message_t* msg);
+
+       /**
+        * Returns the size of the collision window for this received message.
+        */
+       async command uint16_t getCollisionWindowLength(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/layers/SlottedCollisionLayerC.nc b/tos/chips/rf2xx/layers/SlottedCollisionLayerC.nc
new file mode 100644 (file)
index 0000000..5a6502b
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration SlottedCollisionLayerC
+{
+       provides
+       {
+               interface RadioSend;
+               interface RadioReceive;
+       }
+       uses
+       {
+               interface RadioSend as SubSend;
+               interface RadioReceive as SubReceive;
+               interface SlottedCollisionConfig as Config;
+       }
+}
+
+implementation
+{
+       components SlottedCollisionLayerP, MainC, RadioAlarmC, RandomC;
+
+       RadioSend = SlottedCollisionLayerP;
+       RadioReceive = SlottedCollisionLayerP;
+       SubSend = SlottedCollisionLayerP;
+       SubReceive = SlottedCollisionLayerP;
+       Config = SlottedCollisionLayerP;
+       
+       SlottedCollisionLayerP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
+       SlottedCollisionLayerP.Random -> RandomC;
+       MainC.SoftwareInit -> SlottedCollisionLayerP;
+
+#ifdef RADIO_DEBUG
+       components DiagMsgC;
+       SlottedCollisionLayerP.DiagMsg -> DiagMsgC;
+#endif
+}
diff --git a/tos/chips/rf2xx/layers/SlottedCollisionLayerP.nc b/tos/chips/rf2xx/layers/SlottedCollisionLayerP.nc
new file mode 100644 (file)
index 0000000..ce1610e
--- /dev/null
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+#include <RadioAssert.h>
+
+module SlottedCollisionLayerP
+{
+       provides
+       {
+               interface RadioSend;
+               interface RadioReceive;
+               interface Init;
+       }
+       uses
+       {
+               interface RadioSend as SubSend;
+               interface RadioReceive as SubReceive;
+               interface RadioAlarm;
+               interface Random;
+               interface SlottedCollisionConfig as Config;
+#ifdef RADIO_DEBUG
+               interface DiagMsg;
+#endif
+       }
+}
+
+implementation
+{
+/* ----- random ----- */
+
+       uint16_t nextRandom;
+
+       task void calcNextRandom()
+       {
+               uint16_t a = call Random.rand16();
+               atomic nextRandom = a;
+       }
+
+       uint16_t getNextRandom()
+       {
+               uint16_t a;
+
+               atomic
+               {
+                       a = nextRandom;
+                       nextRandom += 273;
+               }
+               post calcNextRandom();
+
+               return a;
+       }
+
+/* ----- schedule selection ----- */
+
+       void printStats();
+
+       tasklet_async event bool SubReceive.header(message_t* msg)
+       {
+               return signal RadioReceive.header(msg);
+       }
+
+       // WARNING!!! Do not change these values, the error values can overflow
+       enum
+       {
+               ERROR_DECAY = 3,
+               ERROR_SWITCH = 30,              // should be a multiple of (1 << decay)
+               ERROR_COLLISION = 20,   // must be less than (255 - switch) >> decay
+               ERROR_BUSY = 1,                 // must be less than collision
+               ERROR_INITIAL = 80,             // must be less than giveup
+               ERROR_GIVEUP = 120,             // must be less than collision * (1 << decay)
+               ERROR_REPRESS = 40,             // must be more than switch
+               ERROR_MAX = 255,
+       };
+
+       /**
+        * Returns TRUE if time is between start and start + window 
+        * modulo the schedule size of (1 << exponent)
+        */
+       inline bool isBetween(uint8_t exponent, uint16_t time, uint16_t start, uint16_t length)
+       {
+               return (uint16_t)((time - start) & ((1 << exponent) - 1)) < length;
+       }
+
+       tasklet_norace uint16_t schedule1;
+       tasklet_norace uint16_t schedule2;
+
+       tasklet_norace uint8_t error1;
+       tasklet_norace uint8_t error2;
+
+       tasklet_async event message_t* SubReceive.receive(message_t* msg)
+       {
+               uint8_t exponent = call Config.getScheduleExponent();
+               uint16_t start = call Config.getCollisionWindowStart(msg);
+               uint16_t length = call Config.getCollisionWindowLength(msg);
+
+               error1 -= (error1 + (1<<ERROR_DECAY) - 1) >> ERROR_DECAY;
+               if( isBetween(exponent, schedule1, start, length) )
+                       error1 += ERROR_COLLISION; 
+
+               error2 -= (error1 + (1<<ERROR_DECAY) - 1) >> ERROR_DECAY;
+               if( isBetween(exponent, schedule2, start, length) )
+                       error2 += ERROR_COLLISION;
+
+               if( error2 + ERROR_SWITCH <= error1 )
+               {
+                       error1 = error2;
+                       schedule1 = schedule2;
+                       error2 = ERROR_GIVEUP;
+               }
+
+               if( error2 >= ERROR_GIVEUP )
+               {
+                       error2 = ERROR_INITIAL;
+                       schedule2 = getNextRandom();
+               }
+
+               printStats();
+
+               return signal RadioReceive.receive(msg);
+       }
+
+/* ------ transmit ------ */
+
+       tasklet_norace uint8_t state;
+       enum
+       {
+               STATE_READY = 0,
+               STATE_PENDING = 1,
+               STATE_SENDING = 2,
+       };
+
+       enum { DELAY_DECAY = 2 };
+
+       tasklet_norace message_t *txMsg;
+       tasklet_norace uint16_t txDelay;        // the averaged delay between schedule and timestamp
+       tasklet_norace uint16_t txTime;         // the schedule time of transmission
+
+       tasklet_async event void SubSend.ready()
+       {
+               if( state == STATE_READY && call RadioAlarm.isFree() )
+                       signal RadioSend.ready();
+       }
+
+       tasklet_async command error_t RadioSend.send(message_t* msg)
+       {
+               uint16_t backoff;
+               uint16_t time;
+
+               // TODO: we could supress transmission while error is large
+               if( state != STATE_READY || ! call RadioAlarm.isFree() || error1 >= ERROR_REPRESS )
+                       return EBUSY;
+
+               txMsg = msg;
+               state = STATE_PENDING;
+
+               time = call RadioAlarm.getNow();
+               backoff = 1 + ((schedule1 - time - (txDelay >> DELAY_DECAY))
+                       & ((1 << call Config.getScheduleExponent()) - 1));
+
+               backoff += getNextRandom() & (3 << call Config.getScheduleExponent());
+
+               call RadioAlarm.wait(backoff);
+               txTime = time + backoff;
+
+               printStats();
+
+               return SUCCESS;
+       }
+
+       tasklet_async event void RadioAlarm.fired()
+       {
+               error_t error;
+
+               ASSERT( state == STATE_PENDING );
+
+               error = call SubSend.send(txMsg);
+               if( error == SUCCESS )
+                       state = STATE_SENDING;
+               else
+               {
+                       if( error2 + ERROR_SWITCH <= error1 )
+                       {
+                               error1 = error2;
+                               schedule1 = schedule2;
+                               error2 = ERROR_INITIAL;
+                               schedule2 = getNextRandom();
+                       }
+                       else if( error1 < ERROR_MAX - ERROR_BUSY )
+                               error1 = error1 + ERROR_BUSY;
+
+                       state = STATE_READY;
+                       signal RadioSend.sendDone(error);
+               }
+       }
+
+       tasklet_async event void SubSend.sendDone(error_t error)
+       {
+               ASSERT( state == STATE_SENDING );
+
+               if( error == SUCCESS )
+               {
+                       txDelay += (call Config.getTransmitTime(txMsg) - txTime) - (txDelay >> DELAY_DECAY);
+
+                       ASSERT( (txDelay >> DELAY_DECAY) < (1 << call Config.getScheduleExponent()) );
+               }
+
+               state = STATE_READY;
+               signal RadioSend.sendDone(error);
+       }
+
+/* ------ init  ------ */
+
+       command error_t Init.init()
+       {
+               // do not use Random here because it might not be initialized
+               schedule1 = (uint16_t)(TOS_NODE_ID * 1973);
+               schedule2 = schedule1 + 0117;
+               txDelay = call Config.getInitialDelay() << DELAY_DECAY;
+
+               return SUCCESS;
+       }
+
+#ifdef RADIO_DEBUG
+       tasklet_norace uint8_t count;
+       void printStats()
+       {
+               if( ++count > 50 && call DiagMsg.record() )
+               {
+                       count = 0;
+
+                       call DiagMsg.str("slotted");
+                       call DiagMsg.uint16(txDelay >> DELAY_DECAY);
+                       call DiagMsg.uint16(schedule1);
+                       call DiagMsg.uint8(error1);
+                       call DiagMsg.uint16(schedule2);
+                       call DiagMsg.uint8(error2);
+                       call DiagMsg.send();
+               }
+       }
+#else
+       void printStats() { }
+#endif
+}
diff --git a/tos/chips/rf2xx/layers/SoftwareAckConfig.nc b/tos/chips/rf2xx/layers/SoftwareAckConfig.nc
new file mode 100755 (executable)
index 0000000..5f7b8a3
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+interface SoftwareAckConfig
+{
+       /**
+        * Returns the acknowledgement timeout (in the radio clock units),
+        * in which a sent packet must be acknowledged.
+        */
+       async command uint16_t getAckTimeout();
+
+       /**
+        * Sets the flag in the message indicating to the receiver whether
+        * the message should be acknowledged.
+        */
+       async command void setAckRequired(message_t* msg, bool ack);
+        
+       /**
+        * Returns TRUE if the layer should wait for a software acknowledgement
+        * to be received after this packet was transmitted.
+        */
+       async command bool requiresAckWait(message_t* msg);
+
+       /**
+        * Returns TRUE if the received packet is an acknowledgement packet.
+        * The AckedSend layer will filter out all received acknowledgement
+        * packets and uses  only the matching one for the acknowledgement.
+        */
+       async command bool isAckPacket(message_t* msg);
+
+       /**
+        * Returns TRUE if the acknowledgement packet corresponds to the
+        * data packet. The acknowledgement packect was already verified 
+        * to be a valid acknowledgement packet via the isAckPacket command.
+        */
+       async command bool verifyAckPacket(message_t* data, message_t* ack);
+
+       /**
+        * Returns TRUE if the received packet needs software acknowledgements
+        * to be sent back to the sender.
+        */
+       async command bool requiresAckReply(message_t* msg);
+
+       /**
+        * Creates an acknowledgement packet for the given data packet.
+        */
+       async command void createAckPacket(message_t* data, message_t* ack);
+
+       /**
+        * This command is called when a sent packet did not receive an
+        * acknowledgement.
+        */
+       tasklet_async command void reportChannelError();
+}
diff --git a/tos/chips/rf2xx/layers/SoftwareAckLayerC.nc b/tos/chips/rf2xx/layers/SoftwareAckLayerC.nc
new file mode 100755 (executable)
index 0000000..775b9cd
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration SoftwareAckLayerC
+{
+       provides
+       {
+               interface RadioSend;
+               interface RadioReceive;
+
+               interface PacketAcknowledgements;
+       }
+
+       uses
+       {
+               interface RadioSend as SubSend;
+               interface RadioReceive as SubReceive;
+
+               interface SoftwareAckConfig as Config;
+       }
+}
+
+implementation
+{
+       components SoftwareAckLayerP, RadioAlarmC, new MetadataFlagC();
+
+       RadioSend = SoftwareAckLayerP;
+       RadioReceive = SoftwareAckLayerP;
+       SubSend = SoftwareAckLayerP;
+       SubReceive = SoftwareAckLayerP;
+       Config = SoftwareAckLayerP;
+       PacketAcknowledgements = SoftwareAckLayerP;
+
+       SoftwareAckLayerP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
+       SoftwareAckLayerP.AckReceivedFlag -> MetadataFlagC;
+}
diff --git a/tos/chips/rf2xx/layers/SoftwareAckLayerP.nc b/tos/chips/rf2xx/layers/SoftwareAckLayerP.nc
new file mode 100644 (file)
index 0000000..035c67b
--- /dev/null
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+#include <RadioAssert.h>
+
+module SoftwareAckLayerP
+{
+       provides
+       {
+               interface RadioSend;
+               interface RadioReceive;
+               interface PacketAcknowledgements;
+       }
+
+       uses
+       {
+               interface RadioSend as SubSend;
+               interface RadioReceive as SubReceive;
+               interface RadioAlarm;
+
+               interface SoftwareAckConfig;
+               interface PacketFlag as AckReceivedFlag;
+       }
+}
+
+implementation
+{
+       tasklet_norace uint8_t state;
+       enum
+       {
+               STATE_READY = 0,
+               STATE_DATA_SEND = 1,
+               STATE_ACK_WAIT = 2,
+               STATE_ACK_SEND = 3,
+       };
+
+       tasklet_norace message_t *txMsg;
+       tasklet_norace message_t ackMsg;
+
+       tasklet_async event void SubSend.ready()
+       {
+               if( state == STATE_READY )
+                       signal RadioSend.ready();
+       }
+
+       tasklet_async command error_t RadioSend.send(message_t* msg)
+       {
+               error_t error;
+
+               if( state == STATE_READY )
+               {
+                       if( (error = call SubSend.send(msg)) == SUCCESS )
+                       {
+                               call AckReceivedFlag.clear(msg);
+                               state = STATE_DATA_SEND;
+                               txMsg = msg;
+                       }
+               }
+               else
+                       error = EBUSY;
+
+               return error;
+       }
+
+       tasklet_async event void SubSend.sendDone(error_t error)
+       {
+               if( state == STATE_ACK_SEND )
+               {
+                       // TODO: what if error != SUCCESS
+                       ASSERT( error == SUCCESS );
+
+                       state = STATE_READY;
+               }
+               else
+               {
+                       ASSERT( state == STATE_DATA_SEND );
+                       ASSERT( call RadioAlarm.isFree() );
+
+                       if( error == SUCCESS && call SoftwareAckConfig.requiresAckWait(txMsg) && call RadioAlarm.isFree() )
+                       {
+                               call RadioAlarm.wait(call SoftwareAckConfig.getAckTimeout());
+                               state = STATE_ACK_WAIT;
+                       }
+                       else
+                       {
+                               state = STATE_READY;
+                               signal RadioSend.sendDone(error);
+                       }
+               }
+       }
+
+       tasklet_async event void RadioAlarm.fired()
+       {
+               ASSERT( state == STATE_ACK_WAIT );
+
+               call SoftwareAckConfig.reportChannelError();
+
+               state = STATE_READY;
+               signal RadioSend.sendDone(SUCCESS);     // we have sent it, but not acked
+       }
+
+       tasklet_async event bool SubReceive.header(message_t* msg)
+       {
+               if( call SoftwareAckConfig.isAckPacket(msg) )
+                       return state == STATE_ACK_WAIT && call SoftwareAckConfig.verifyAckPacket(txMsg, msg);
+               else
+                       return signal RadioReceive.header(msg);
+       }
+
+       tasklet_async event message_t* SubReceive.receive(message_t* msg)
+       {
+               bool ack = call SoftwareAckConfig.isAckPacket(msg);
+
+               ASSERT( state == STATE_ACK_WAIT || state == STATE_READY );
+
+               if( state == STATE_ACK_WAIT )
+               {
+                       ASSERT( !ack || call SoftwareAckConfig.verifyAckPacket(txMsg, msg) );
+
+                       call RadioAlarm.cancel();
+                       call AckReceivedFlag.setValue(txMsg, ack);
+
+                       state = STATE_READY;
+                       signal RadioSend.sendDone(SUCCESS);
+               }
+
+               if( ack )
+                       return msg;
+
+               if( call SoftwareAckConfig.requiresAckReply(msg) )
+               {
+                       call SoftwareAckConfig.createAckPacket(msg, &ackMsg);
+
+                       // TODO: what to do if we are busy and cannot send an ack
+                       if( call SubSend.send(&ackMsg) == SUCCESS )
+                               state = STATE_ACK_SEND;
+                       else
+                               ASSERT(FALSE);
+               }
+
+               return signal RadioReceive.receive(msg);
+       }
+
+/*----------------- PacketAcknowledgements -----------------*/
+
+       async command error_t PacketAcknowledgements.requestAck(message_t* msg)
+       {
+               call SoftwareAckConfig.setAckRequired(msg, TRUE);
+
+               return SUCCESS;
+       }
+
+       async command error_t PacketAcknowledgements.noAck(message_t* msg)
+       {
+               call SoftwareAckConfig.setAckRequired(msg, FALSE);
+
+               return SUCCESS;
+       }
+
+       async command bool PacketAcknowledgements.wasAcked(message_t* msg)
+       {
+               return call AckReceivedFlag.get(msg);
+       }
+
+
+}
diff --git a/tos/chips/rf2xx/layers/TimeStampingLayer.h b/tos/chips/rf2xx/layers/TimeStampingLayer.h
new file mode 100644 (file)
index 0000000..dc0a43c
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __TIMESTAMPINGLAYER_H__
+#define __TIMESTAMPINGLAYER_H__
+
+typedef struct timestamp_metadata_t
+{
+       uint32_t timestamp;
+} timestamp_metadata_t;
+
+#endif//__TIMESTAMPINGLAYER_H__
diff --git a/tos/chips/rf2xx/layers/TimeStampingLayerC.nc b/tos/chips/rf2xx/layers/TimeStampingLayerC.nc
new file mode 100644 (file)
index 0000000..7bc5b0c
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration TimeStampingLayerC
+{
+       provides
+       {
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface RadioPacket;
+       }
+
+       uses
+       {
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface RadioPacket as SubPacket;
+       }
+}
+
+implementation
+{
+       components TimeStampingLayerP, LocalTimeMilliC;
+
+       PacketTimeStampMilli = TimeStampingLayerP;
+       PacketTimeStampRadio = TimeStampingLayerP;
+       RadioPacket = TimeStampingLayerP.RadioPacket;
+       SubPacket = TimeStampingLayerP.SubPacket;
+
+       LocalTimeRadio = TimeStampingLayerP;
+       TimeStampingLayerP.LocalTimeMilli -> LocalTimeMilliC;
+
+       components new MetadataFlagC() as TimeStampFlagC;
+       TimeStampingLayerP.TimeStampFlag -> TimeStampFlagC;
+}
diff --git a/tos/chips/rf2xx/layers/TimeStampingLayerP.nc b/tos/chips/rf2xx/layers/TimeStampingLayerP.nc
new file mode 100644 (file)
index 0000000..d0dec1e
--- /dev/null
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+#include <TimeStampingLayer.h>
+
+module TimeStampingLayerP
+{
+       provides
+       {
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface RadioPacket;
+       }
+
+       uses
+       {
+               interface PacketFlag as TimeStampFlag;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface LocalTime<TMilli> as LocalTimeMilli;
+
+               interface RadioPacket as SubPacket;
+       }
+}
+
+implementation
+{
+       timestamp_metadata_t* getMeta(message_t* msg)
+       {
+               return ((void*)msg) + sizeof(message_t) - call RadioPacket.metadataLength(msg);
+       }
+
+/*----------------- PacketTimeStampRadio -----------------*/
+       
+       async command bool PacketTimeStampRadio.isValid(message_t* msg)
+       {
+               return call TimeStampFlag.get(msg);
+       }
+
+       async command uint32_t PacketTimeStampRadio.timestamp(message_t* msg)
+       {
+               return getMeta(msg)->timestamp;
+       }
+
+       async command void PacketTimeStampRadio.clear(message_t* msg)
+       {
+               call TimeStampFlag.clear(msg);
+       }
+
+       async command void PacketTimeStampRadio.set(message_t* msg, uint32_t value)
+       {
+               call TimeStampFlag.set(msg);
+               getMeta(msg)->timestamp = value;
+       }
+
+/*----------------- PacketTimeStampMilli -----------------*/
+
+       async command bool PacketTimeStampMilli.isValid(message_t* msg)
+       {
+               return call PacketTimeStampRadio.isValid(msg);
+       }
+
+       async command uint32_t PacketTimeStampMilli.timestamp(message_t* msg)
+       {
+               int32_t offset = call PacketTimeStampRadio.timestamp(msg) - call LocalTimeRadio.get();
+
+               return (offset >> RADIO_ALARM_MILLI_EXP) + call LocalTimeMilli.get();
+       }
+
+       async command void PacketTimeStampMilli.clear(message_t* msg)
+       {
+               call PacketTimeStampRadio.clear(msg);
+       }
+
+       async command void PacketTimeStampMilli.set(message_t* msg, uint32_t value)
+       {
+               int32_t offset = (value - call LocalTimeMilli.get()) << RADIO_ALARM_MILLI_EXP;
+
+               call PacketTimeStampRadio.set(msg, offset + call LocalTimeRadio.get());
+       }
+
+/*----------------- RadioPacket -----------------*/
+       
+       async command uint8_t RadioPacket.headerLength(message_t* msg)
+       {
+               return call SubPacket.headerLength(msg);
+       }
+
+       async command uint8_t RadioPacket.payloadLength(message_t* msg)
+       {
+               return call SubPacket.payloadLength(msg);
+       }
+
+       async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               call SubPacket.setPayloadLength(msg, length);
+       }
+
+       async command uint8_t RadioPacket.maxPayloadLength()
+       {
+               return call SubPacket.maxPayloadLength();
+       }
+
+       async command uint8_t RadioPacket.metadataLength(message_t* msg)
+       {
+               return call SubPacket.metadataLength(msg) + sizeof(timestamp_metadata_t);
+       }
+
+       async command void RadioPacket.clear(message_t* msg)
+       {
+               // all flags are automatically cleared
+               call SubPacket.clear(msg);
+       }
+}
diff --git a/tos/chips/rf2xx/layers/TimeSyncMessageLayer.h b/tos/chips/rf2xx/layers/TimeSyncMessageLayer.h
new file mode 100644 (file)
index 0000000..7c930a6
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __TIMESYNCMESSAGELAYER_H__
+#define __TIMESYNCMESSAGELAYER_H__
+
+#include <AM.h>
+
+#ifndef AM_TIMESYNCMSG
+#define AM_TIMESYNCMSG 0x3D
+#endif
+
+// this is sent over the air
+typedef nx_int32_t timesync_relative_t;
+
+// this is stored in memory
+typedef uint32_t timesync_absolute_t;
+
+typedef struct timesync_footer_t
+{
+       nx_am_id_t type;
+       union
+       {
+               timesync_relative_t relative;
+               timesync_absolute_t absolute;
+       };
+} timesync_footer_t;
+
+#endif//__TIMESYNCMESSAGELAYER_H__
diff --git a/tos/chips/rf2xx/layers/TimeSyncMessageLayerC.nc b/tos/chips/rf2xx/layers/TimeSyncMessageLayerC.nc
new file mode 100644 (file)
index 0000000..b164352
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Timer.h>
+#include <AM.h>
+#include <RadioConfig.h>
+#include <TimeSyncMessageLayer.h>
+
+configuration TimeSyncMessageLayerC
+{
+       provides
+       {
+               interface Receive[uint8_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface AMPacket;
+               interface Packet;
+
+               interface TimeSyncAMSend<TRadio, uint32_t> as TimeSyncAMSendRadio[am_id_t id];
+               interface TimeSyncPacket<TRadio, uint32_t> as TimeSyncPacketRadio;
+
+               interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[am_id_t id];
+               interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
+       }
+
+       uses
+       {
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface PacketField<uint8_t> as PacketTimeSyncOffset;
+       }
+}
+
+implementation
+{
+       components TimeSyncMessageLayerP, LocalTimeMilliC;
+
+       AMPacket = TimeSyncMessageLayerP;
+       Packet = TimeSyncMessageLayerP;
+
+       Receive = TimeSyncMessageLayerP.Receive;
+       Snoop = TimeSyncMessageLayerP.Snoop;
+
+       TimeSyncAMSendRadio = TimeSyncMessageLayerP;
+       TimeSyncPacketRadio = TimeSyncMessageLayerP;
+
+       TimeSyncAMSendMilli = TimeSyncMessageLayerP;
+       TimeSyncPacketMilli = TimeSyncMessageLayerP;
+
+       // Ok, we use the AMSenderC infrastructure to avoid concurrent send clashes
+       components new AMSenderC(AM_TIMESYNCMSG);
+       TimeSyncMessageLayerP.SubAMSend -> AMSenderC;
+       TimeSyncMessageLayerP.SubAMPacket -> AMSenderC;
+       TimeSyncMessageLayerP.SubPacket -> AMSenderC;
+
+       components ActiveMessageC;
+       TimeSyncMessageLayerP.SubReceive -> ActiveMessageC.Receive[AM_TIMESYNCMSG];
+       TimeSyncMessageLayerP.SubSnoop -> ActiveMessageC.Snoop[AM_TIMESYNCMSG];;
+
+       PacketTimeStampRadio = TimeSyncMessageLayerP;
+       PacketTimeStampMilli = TimeSyncMessageLayerP;
+       
+       TimeSyncMessageLayerP.LocalTimeMilli -> LocalTimeMilliC;
+       LocalTimeRadio = TimeSyncMessageLayerP;
+       PacketTimeSyncOffset = TimeSyncMessageLayerP;
+}
diff --git a/tos/chips/rf2xx/layers/TimeSyncMessageLayerP.nc b/tos/chips/rf2xx/layers/TimeSyncMessageLayerP.nc
new file mode 100644 (file)
index 0000000..b7e9b4d
--- /dev/null
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <TimeSyncMessageLayer.h>
+
+module TimeSyncMessageLayerP
+{
+       provides
+       {
+               interface Receive[am_id_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface AMPacket;
+               interface Packet;
+
+               interface TimeSyncAMSend<TRadio, uint32_t> as TimeSyncAMSendRadio[am_id_t id];
+               interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[am_id_t id];
+
+               interface TimeSyncPacket<TRadio, uint32_t> as TimeSyncPacketRadio;
+               interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
+       }
+
+       uses
+       {
+               interface AMSend as SubAMSend;
+               interface Receive as SubReceive;
+               interface Receive as SubSnoop;
+               interface AMPacket as SubAMPacket;
+               interface Packet as SubPacket;
+
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface LocalTime<TMilli> as LocalTimeMilli;
+
+               interface PacketField<uint8_t> as PacketTimeSyncOffset;
+       }
+}
+
+implementation
+{
+       inline timesync_footer_t* getFooter(message_t* msg)
+       {
+               // we use the payload length that we export (the smaller one)
+               return (timesync_footer_t*)(msg->data + call Packet.payloadLength(msg));
+       }
+
+/*----------------- Packet -----------------*/
+
+       command void Packet.clear(message_t* msg)
+       {
+               call SubPacket.clear(msg);
+       }
+
+       command void Packet.setPayloadLength(message_t* msg, uint8_t len)
+       {
+               call SubPacket.setPayloadLength(msg, len + sizeof(timesync_footer_t));
+       }
+
+       command uint8_t Packet.payloadLength(message_t* msg)
+       {
+               return call SubPacket.payloadLength(msg) - sizeof(timesync_footer_t);
+       }
+
+       command uint8_t Packet.maxPayloadLength()
+       {
+               return call SubPacket.maxPayloadLength() - sizeof(timesync_footer_t);
+       }
+
+       command void* Packet.getPayload(message_t* msg, uint8_t len)
+       {
+               return call SubPacket.getPayload(msg, len + sizeof(timesync_footer_t));
+       }
+
+/*----------------- AMPacket -----------------*/
+
+       inline command am_addr_t AMPacket.address()
+       {
+               return call SubAMPacket.address();
+       }
+       inline command am_group_t AMPacket.localGroup()
+       {
+               return call SubAMPacket.localGroup();
+       }
+
+       inline command bool AMPacket.isForMe(message_t* msg)
+       {
+               return call SubAMPacket.isForMe(msg) && call SubAMPacket.type(msg) == AM_TIMESYNCMSG;
+       }
+
+       inline command am_addr_t AMPacket.destination(message_t* msg)
+       {
+               return call SubAMPacket.destination(msg);
+       }
+       inline command void AMPacket.setDestination(message_t* msg, am_addr_t addr)
+       {
+               call SubAMPacket.setDestination(msg, addr);
+       }
+
+       inline command am_addr_t AMPacket.source(message_t* msg)
+       {
+               return call SubAMPacket.source(msg);
+       }
+
+       inline command void AMPacket.setSource(message_t* msg, am_addr_t addr)
+       {
+               call SubAMPacket.setSource(msg, addr);
+       }
+
+       inline command am_id_t AMPacket.type(message_t* msg)
+       {
+               return getFooter(msg)->type;
+       }
+
+       inline command void AMPacket.setType(message_t* msg, am_id_t type)
+       {
+               getFooter(msg)->type = type;
+       }
+  
+       inline command am_group_t AMPacket.group(message_t* msg) 
+       {
+               return call SubAMPacket.group(msg);
+       }
+
+       inline command void AMPacket.setGroup(message_t* msg, am_group_t grp)
+       {
+               call SubAMPacket.setGroup(msg, grp);
+       }
+
+/*----------------- TimeSyncAMSendRadio -----------------*/
+
+       command error_t TimeSyncAMSendRadio.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len, uint32_t event_time)
+       {
+               timesync_footer_t* footer = (timesync_footer_t*)(msg->data + len);
+
+               footer->type = id;
+               footer->absolute = event_time;
+               call PacketTimeSyncOffset.set(msg, offsetof(message_t, data) + len + offsetof(timesync_footer_t, absolute));
+
+               return call SubAMSend.send(addr, msg, len + sizeof(timesync_footer_t));
+       }
+
+       command error_t TimeSyncAMSendRadio.cancel[am_id_t id](message_t* msg)
+       {
+               return call SubAMSend.cancel(msg);
+       }
+
+       default event void TimeSyncAMSendRadio.sendDone[am_id_t id](message_t* msg, error_t error)
+       {
+       }
+
+       command uint8_t TimeSyncAMSendRadio.maxPayloadLength[am_id_t id]()
+       {
+               return call SubAMSend.maxPayloadLength() - sizeof(timesync_footer_t);
+       }
+
+       command void* TimeSyncAMSendRadio.getPayload[am_id_t id](message_t* msg, uint8_t len)
+       {
+               return call SubAMSend.getPayload(msg, len + sizeof(timesync_footer_t));
+       }
+
+/*----------------- TimeSyncAMSendMilli -----------------*/
+
+       command error_t TimeSyncAMSendMilli.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len, uint32_t event_time)
+       {
+               // compute elapsed time in millisecond
+               event_time = ((int32_t)(event_time - call LocalTimeMilli.get()) << RADIO_ALARM_MILLI_EXP) + call LocalTimeRadio.get();
+
+               return call TimeSyncAMSendRadio.send[id](addr, msg, len, event_time);
+       }
+
+       command error_t TimeSyncAMSendMilli.cancel[am_id_t id](message_t* msg)
+       {
+               return call TimeSyncAMSendRadio.cancel[id](msg);
+       }
+
+       default event void TimeSyncAMSendMilli.sendDone[am_id_t id](message_t* msg, error_t error)
+       {
+       }
+
+       command uint8_t TimeSyncAMSendMilli.maxPayloadLength[am_id_t id]()
+       {
+               return call TimeSyncAMSendRadio.maxPayloadLength[id]();
+       }
+
+       command void* TimeSyncAMSendMilli.getPayload[am_id_t id](message_t* msg, uint8_t len)
+       {
+               return call TimeSyncAMSendRadio.getPayload[id](msg, len);
+       }
+
+/*----------------- SubSend.sendDone -------------------*/
+
+       event void SubAMSend.sendDone(message_t* msg, error_t error)
+       {
+               am_id_t id = call AMPacket.type(msg);
+
+               signal TimeSyncAMSendRadio.sendDone[id](msg, error);
+               signal TimeSyncAMSendMilli.sendDone[id](msg, error);
+       }
+
+/*----------------- SubReceive and SubSnoop -------------------*/
+
+       event message_t* SubReceive.receive(message_t* msg, void* payload, uint8_t len)
+       {
+               am_id_t id = call AMPacket.type(msg);
+
+               return signal Receive.receive[id](msg, payload, len - sizeof(timesync_footer_t));
+       }
+
+       default event message_t* Receive.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) { return msg; }
+
+       event message_t* SubSnoop.receive(message_t* msg, void* payload, uint8_t len)
+       {
+               am_id_t id = call AMPacket.type(msg);
+
+               return signal Snoop.receive[id](msg, payload, len - sizeof(timesync_footer_t));
+       }
+
+       default event message_t* Snoop.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) { return msg; }
+
+/*----------------- TimeSyncPacketRadio -----------------*/
+
+       command bool TimeSyncPacketRadio.isValid(message_t* msg)
+       {
+               return call PacketTimeStampRadio.isValid(msg) && getFooter(msg)->relative != 0x80000000L;
+       }
+
+       command uint32_t TimeSyncPacketRadio.eventTime(message_t* msg)
+       {
+               return getFooter(msg)->relative + call PacketTimeStampRadio.timestamp(msg);
+       }
+
+/*----------------- TimeSyncPacketMilli -----------------*/
+
+       command bool TimeSyncPacketMilli.isValid(message_t* msg)
+       {
+               return call PacketTimeStampMilli.isValid(msg) && getFooter(msg)->relative != 0x80000000L;
+       }
+
+       command uint32_t TimeSyncPacketMilli.eventTime(message_t* msg)
+       {
+               return ((int32_t)(getFooter(msg)->relative) >> RADIO_ALARM_MILLI_EXP) + call PacketTimeStampMilli.timestamp(msg);
+       }
+}
diff --git a/tos/chips/rf2xx/layers/TinyosNetworkLayer.h b/tos/chips/rf2xx/layers/TinyosNetworkLayer.h
new file mode 100644 (file)
index 0000000..5d29e5e
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __TINYOSNETWORKLAYER_H__
+#define __TINYOSNETWORKLAYER_H__
+
+#ifndef TINYOS_6LOWPAN_NETWORK_ID
+#define TINYOS_6LOWPAN_NETWORK_ID 0x3f
+#endif
+
+typedef nx_struct network_header_t
+{
+       nxle_uint8_t network;
+} network_header_t;
+
+#endif//__TINYOSNETWORKLAYER_H__
diff --git a/tos/chips/rf2xx/layers/TinyosNetworkLayerC.nc b/tos/chips/rf2xx/layers/TinyosNetworkLayerC.nc
new file mode 100644 (file)
index 0000000..385527d
--- /dev/null
@@ -0,0 +1,220 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <TinyosNetworkLayer.h>
+
+/*
+   If TFRAMES_ENABLED is defined, then only TinyOS frames will be supported
+   (with no network byte). If IEEE154FRAMES_ENABLED, then only IEEE 802.15.4 
+   frames will be supported (the network byte is part of the payload). If 
+   neither is defined, then both TinyOS frames and IEEE 802.15.4 frames will
+   be supported where TinyOS frames are the ones whose network byte is
+   TINYOS_6LOWPAN_NETWORK_ID.
+*/
+
+#if defined(TFRAMES_ENABLED) && defined(IEEE154FRAMES_ENABLED)
+#error You cannot specify both TFRAMES_ENABLED and IEEE154FRAMES_ENABLED at the same time
+#endif
+
+module TinyosNetworkLayerC
+{
+       provides
+       {
+#ifndef TFRAMES_ENABLED
+               interface BareSend as Ieee154Send;
+               interface BareReceive as Ieee154Receive;
+               interface RadioPacket as Ieee154Packet;
+#endif
+
+#ifndef IEEE154FRAMES_ENABLED
+               interface BareSend as TinyosSend;
+               interface BareReceive as TinyosReceive;
+               interface RadioPacket as TinyosPacket;
+#endif
+       }
+
+       uses
+       {
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
+               interface RadioPacket as SubPacket;
+       }
+}
+
+implementation
+{
+/*----------------- Ieee154MessageC -----------------*/
+
+#ifndef TFRAMES_ENABLED
+
+       command error_t Ieee154Send.send(message_t* msg)
+       {
+               return call SubSend.send(msg);
+       }
+
+       command error_t Ieee154Send.cancel(message_t* msg)
+       {
+               return call SubSend.cancel(msg);
+       }
+       
+       async command uint8_t Ieee154Packet.headerLength(message_t* msg)
+       {
+               return call SubPacket.headerLength(msg);
+       }
+
+       async command uint8_t Ieee154Packet.payloadLength(message_t* msg)
+       {
+               return call SubPacket.payloadLength(msg);
+       }
+
+       async command void Ieee154Packet.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               call SubPacket.setPayloadLength(msg, length);
+       }
+
+       async command uint8_t Ieee154Packet.maxPayloadLength()
+       {
+               return call SubPacket.maxPayloadLength();
+       }
+
+       async command uint8_t Ieee154Packet.metadataLength(message_t* msg)
+       {
+               return call SubPacket.metadataLength(msg);
+       }
+
+       async command void Ieee154Packet.clear(message_t* msg)
+       {
+               call SubPacket.clear(msg);
+       }
+
+#endif
+
+/*----------------- ActiveMessageC -----------------*/
+
+#ifndef IEEE154FRAMES_ENABLED
+
+       network_header_t* getHeader(message_t* msg)
+       {
+               return ((void*)msg) + call SubPacket.headerLength(msg);
+       }
+
+       command error_t TinyosSend.send(message_t* msg)
+       {
+#ifndef TFRAMES_ENABLED
+               getHeader(msg)->network = TINYOS_6LOWPAN_NETWORK_ID;
+#endif
+               return call SubSend.send(msg);
+       }
+
+       command error_t TinyosSend.cancel(message_t* msg)
+       {
+               return call SubSend.cancel(msg);
+       }
+
+       enum
+       {
+#ifndef TFRAMES_ENABLED
+               PAYLOAD_OFFSET = sizeof(network_header_t),
+#else
+               PAYLOAD_OFFSET = 0,
+#endif
+       };
+
+       async command uint8_t TinyosPacket.headerLength(message_t* msg)
+       {
+               return call SubPacket.headerLength(msg) + PAYLOAD_OFFSET;
+       }
+
+       async command uint8_t TinyosPacket.payloadLength(message_t* msg)
+       {
+               return call SubPacket.payloadLength(msg) - PAYLOAD_OFFSET;
+       }
+
+       async command void TinyosPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               call SubPacket.setPayloadLength(msg, length + PAYLOAD_OFFSET);
+       }
+
+       async command uint8_t TinyosPacket.maxPayloadLength()
+       {
+               return call SubPacket.maxPayloadLength() - PAYLOAD_OFFSET;
+       }
+
+       async command uint8_t TinyosPacket.metadataLength(message_t* msg)
+       {
+               return call SubPacket.metadataLength(msg);
+       }
+
+       async command void TinyosPacket.clear(message_t* msg)
+       {
+               call SubPacket.clear(msg);
+       }
+
+#endif
+
+/*----------------- Events -----------------*/
+
+#if defined(TFRAMES_ENABLED)
+
+       event void SubSend.sendDone(message_t* msg, error_t result)
+       {
+               signal TinyosSend.sendDone(msg, result);
+       }
+
+       event message_t* SubReceive.receive(message_t* msg)
+       {
+               return signal TinyosReceive.receive(msg);
+       }
+
+#elif defined(IEEE154FRAMES_ENABLED)
+
+       event void SubSend.sendDone(message_t* msg, error_t result)
+       {
+               signal Ieee154Send.sendDone(msg, result);
+       }
+
+       event message_t* SubReceive.receive(message_t* msg)
+       {
+               return signal Ieee154Receive.receive(msg);
+       }
+
+#else
+
+       event void SubSend.sendDone(message_t* msg, error_t result)
+       {
+               if( getHeader(msg)->network == TINYOS_6LOWPAN_NETWORK_ID )
+                       signal TinyosSend.sendDone(msg, result);
+               else
+                       signal Ieee154Send.sendDone(msg, result);
+       }
+
+       event message_t* SubReceive.receive(message_t* msg)
+       {
+               if( getHeader(msg)->network == TINYOS_6LOWPAN_NETWORK_ID )
+                       return signal TinyosReceive.receive(msg);
+               else
+                       return signal Ieee154Receive.receive(msg);
+       }
+
+#endif
+}
diff --git a/tos/chips/rf2xx/layers/TrafficMonitorConfig.nc b/tos/chips/rf2xx/layers/TrafficMonitorConfig.nc
new file mode 100755 (executable)
index 0000000..78f1437
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+interface TrafficMonitorConfig
+{
+       /**
+        * Returns the frequency (in milliseconds) when the traffic averages
+        * should be updated. 
+        */
+       async command uint16_t getUpdatePeriod();
+
+       /**
+        * Returns the amount of time this message has occupied the channel.
+        */
+       async command uint16_t getChannelTime(message_t* msg);
+
+       /**
+        * Returns the sender address of the message so we can calculate the
+        * average number of neighbors that send messages per update period.
+        */
+       async command am_addr_t getSender(message_t* msg);
+
+       /**
+        * This event should be fired if we notice some anomalies in the operation
+        * of the channel, such as not receiving acknowledgements, missing
+        * sequence numbers or packets with corrupted CRC.
+        */
+       tasklet_async event void channelError();
+
+       /**
+        * Returns the averaged (exponential decay) transmit channel time 
+        * during one update period.
+        */
+       tasklet_async event uint16_t getTransmitAverage();
+
+       /**
+        * Returns the averaged (exponential decay) receive channel time 
+        * during one update period.
+        */
+       tasklet_async event uint16_t getReceiveAverage();
+
+       /**
+        * Returns the averaged (exponential decay) number of neighbors 
+        * whose messages this component receives during one update period.
+        */
+       tasklet_async event uint8_t getNeighborAverage();
+
+       /**
+        * Returns the averaged error events during one update period.
+        */
+       tasklet_async event uint8_t getErrorAverage();
+}
diff --git a/tos/chips/rf2xx/layers/TrafficMonitorLayerC.nc b/tos/chips/rf2xx/layers/TrafficMonitorLayerC.nc
new file mode 100644 (file)
index 0000000..6bab73f
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration TrafficMonitorLayerC
+{
+       provides
+       {
+               interface RadioSend;
+               interface RadioReceive;
+               interface RadioState;
+       }
+       uses
+       {
+               interface RadioSend as SubSend;
+               interface RadioReceive as SubReceive;
+               interface RadioState as SubState;
+
+               interface TrafficMonitorConfig as Config;
+       }
+}
+
+implementation
+{
+       components TrafficMonitorLayerP, new TimerMilliC() as UpdateTimerC; 
+       components NeighborhoodC, new NeighborhoodFlagC(), TaskletC;
+
+       RadioSend = TrafficMonitorLayerP;
+       RadioReceive = TrafficMonitorLayerP;
+       RadioState = TrafficMonitorLayerP;
+       SubSend = TrafficMonitorLayerP;
+       SubReceive = TrafficMonitorLayerP;
+       SubState = TrafficMonitorLayerP;
+       Config = TrafficMonitorLayerP;
+
+       TrafficMonitorLayerP.Timer -> UpdateTimerC;
+       TrafficMonitorLayerP.Neighborhood -> NeighborhoodC;
+       TrafficMonitorLayerP.NeighborhoodFlag -> NeighborhoodFlagC;
+       TrafficMonitorLayerP.Tasklet -> TaskletC;
+
+#ifdef RADIO_DEBUG
+       components DiagMsgC;
+       TrafficMonitorLayerP.DiagMsg -> DiagMsgC;
+#endif
+}
diff --git a/tos/chips/rf2xx/layers/TrafficMonitorLayerP.nc b/tos/chips/rf2xx/layers/TrafficMonitorLayerP.nc
new file mode 100644 (file)
index 0000000..99d73ca
--- /dev/null
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, reportS, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+/*
+ * You have to make sure that the maximum channel time in one report
+ * period times (1 << TRAFFIC_MONITOR_DECAY) is less than 65535.
+ */
+#ifndef TRAFFIC_MONITOR_DECAY
+#define TRAFFIC_MONITOR_DECAY  3
+#endif
+
+module TrafficMonitorLayerP
+{
+       provides
+       {
+               interface RadioSend;
+               interface RadioReceive;
+               interface RadioState;
+       }
+
+       uses
+       {
+               interface TrafficMonitorConfig;
+               interface RadioSend as SubSend;
+               interface RadioReceive as SubReceive;
+               interface RadioState as SubState;
+               interface Timer<TMilli> as Timer;
+               interface Neighborhood;
+               interface NeighborhoodFlag;
+               interface Tasklet;
+#ifdef RADIO_DEBUG
+               interface DiagMsg;
+#endif
+       }
+}
+
+implementation
+{
+       tasklet_norace message_t *txMsg;
+       tasklet_norace uint8_t neighborCount;
+
+       tasklet_norace uint16_t txAverage;
+       tasklet_norace uint16_t rxAverage;
+       tasklet_norace uint8_t neighborAverage;
+       tasklet_norace uint8_t errorAverage;
+
+       enum
+       {
+               // the maximum average value
+               TRAFFIC_MONITOR_UINT8_MAX = 1 << (7-TRAFFIC_MONITOR_DECAY),
+
+               // the unsignificant bits of the averaged values
+               TRAFFIC_MONITOR_MASK = (1 << TRAFFIC_MONITOR_DECAY) - 1,
+
+               // to get the ceiling integer value
+               TRAFFIC_MONITOR_ROUND_UP = (1 << TRAFFIC_MONITOR_DECAY) - 1,
+       };
+
+       tasklet_async event void SubSend.ready()
+       {
+               signal RadioSend.ready();
+       }
+
+       tasklet_async command error_t RadioSend.send(message_t* msg)
+       {
+               txMsg = msg;
+               return call SubSend.send(msg);
+       }
+
+       tasklet_async event void SubSend.sendDone(error_t error)
+       {
+               if( error == SUCCESS )
+                       txAverage += call TrafficMonitorConfig.getChannelTime(txMsg);
+
+               signal RadioSend.sendDone(error);
+       }
+
+       tasklet_async event bool SubReceive.header(message_t* msg)
+       {
+               return signal RadioReceive.header(msg);
+       }
+
+       tasklet_async event message_t* SubReceive.receive(message_t* msg)
+       {
+               uint8_t index;
+
+               rxAverage += call TrafficMonitorConfig.getChannelTime(msg);
+
+               index = call Neighborhood.insertNode(call TrafficMonitorConfig.getSender(msg));
+               if( ! call NeighborhoodFlag.get(index) )
+               {
+                       if( neighborCount < TRAFFIC_MONITOR_UINT8_MAX )
+                       {
+                               ++neighborCount;
+                               call NeighborhoodFlag.set(index);
+                       }
+               }
+
+               return signal RadioReceive.receive(msg);
+       }
+
+       tasklet_async event void TrafficMonitorConfig.channelError()
+       {
+               if( errorAverage < 255 )
+                       ++errorAverage;
+       }
+
+       uint8_t debugCounter;
+
+       event void Timer.fired()
+       {
+               uint8_t fraction;
+
+               call Tasklet.suspend();
+
+               txAverage -= (txAverage >> TRAFFIC_MONITOR_DECAY);
+               rxAverage -= (rxAverage >> TRAFFIC_MONITOR_DECAY);
+               errorAverage -= (errorAverage >> TRAFFIC_MONITOR_DECAY);
+
+               // we could get stuck in the [1,7] range with no neighbors, so be more precise
+               fraction = neighborAverage >> TRAFFIC_MONITOR_DECAY;
+               if( fraction == neighborCount && (neighborAverage & TRAFFIC_MONITOR_MASK) != 0 )
+                       --neighborAverage;
+               else
+                       neighborAverage += neighborCount - fraction;
+
+               call NeighborhoodFlag.clearAll();
+               neighborCount = 0;
+
+               call Tasklet.resume();
+
+#ifdef RADIO_DEBUG
+               if( ++debugCounter >= 10 && call DiagMsg.record() )
+               {
+                       debugCounter = 0;
+
+                       call DiagMsg.str("traffic");
+                       call DiagMsg.uint16(signal TrafficMonitorConfig.getTransmitAverage());
+                       call DiagMsg.uint16(signal TrafficMonitorConfig.getReceiveAverage());
+                       call DiagMsg.uint8(signal TrafficMonitorConfig.getNeighborAverage());
+                       call DiagMsg.uint8(signal TrafficMonitorConfig.getErrorAverage());
+                       call DiagMsg.send();
+               }
+#endif
+       }
+
+       tasklet_async event void Tasklet.run()
+       {
+       }
+
+       tasklet_async event uint16_t TrafficMonitorConfig.getTransmitAverage()
+       {
+               return txAverage >> TRAFFIC_MONITOR_DECAY;
+       }
+
+       tasklet_async event uint16_t TrafficMonitorConfig.getReceiveAverage()
+       {
+               return rxAverage >> TRAFFIC_MONITOR_DECAY;
+       }
+
+       tasklet_async event uint8_t TrafficMonitorConfig.getNeighborAverage()
+       {
+               return (neighborAverage + TRAFFIC_MONITOR_ROUND_UP) >> TRAFFIC_MONITOR_DECAY;
+       }
+
+       tasklet_async event uint8_t TrafficMonitorConfig.getErrorAverage()
+       {
+               return errorAverage >> TRAFFIC_MONITOR_DECAY;
+       }
+
+       tasklet_async event void Neighborhood.evicted(uint8_t index) { }
+
+       enum
+       {
+               RADIO_CMD_NONE = 0,
+               RADIO_CMD_TURNON = 1,
+               RADIO_CMD_TURNOFF = 2,
+       };
+       tasklet_norace uint8_t radioCmd;
+
+       tasklet_async command error_t RadioState.turnOff()
+       {
+               radioCmd = RADIO_CMD_TURNOFF;
+               return call SubState.turnOff();
+       }
+
+       tasklet_async command error_t RadioState.standby()
+       {
+               radioCmd = RADIO_CMD_TURNOFF;
+               return call SubState.standby();
+       }
+
+       tasklet_async command error_t RadioState.turnOn()
+       {
+               radioCmd = RADIO_CMD_TURNON;
+               return call SubState.turnOn();
+       }
+
+       tasklet_async command error_t RadioState.setChannel(uint8_t channel)
+       {
+               radioCmd = RADIO_CMD_NONE;
+               return call SubState.setChannel(channel);
+       }
+
+       tasklet_async command uint8_t RadioState.getChannel()
+       {
+               return call SubState.getChannel();
+       }
+
+       task void startStopTimer()
+       {
+               if( radioCmd == RADIO_CMD_TURNON )
+                       call Timer.startPeriodic(call TrafficMonitorConfig.getUpdatePeriod());
+               else if( radioCmd == RADIO_CMD_TURNOFF )
+                       call Timer.stop();
+       }
+
+       tasklet_async event void SubState.done()
+       {
+               post startStopTimer();
+               signal RadioState.done();
+       }
+}
diff --git a/tos/chips/rf2xx/layers/UniqueConfig.nc b/tos/chips/rf2xx/layers/UniqueConfig.nc
new file mode 100755 (executable)
index 0000000..5f14c52
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+interface UniqueConfig
+{
+       /**
+        * Returns the sequence number of the packet.
+        */
+       async command uint8_t getSequenceNumber(message_t* msg);
+
+       /**
+        * Returns the sender of the packet. 
+        */
+       async command am_addr_t getSender(message_t* msg);
+
+       /**
+        * Sets the sequence number of the packet.
+        */
+       async command void setSequenceNumber(message_t*msg, uint8_t number);
+
+       /**
+        * This command is called when the unqiue layer detects a missing (jump 
+        * in the data sequence number) or a duplicate packet.
+        */
+       tasklet_async command void reportChannelError();
+}
diff --git a/tos/chips/rf2xx/layers/UniqueLayerC.nc b/tos/chips/rf2xx/layers/UniqueLayerC.nc
new file mode 100755 (executable)
index 0000000..e533389
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration UniqueLayerC
+{
+       provides
+       {
+               // NOTE, this is a combined layer, should be hooked up at two places
+               interface BareSend as Send;
+               interface RadioReceive;
+       }
+       uses
+       {
+               interface BareSend as SubSend;
+               interface RadioReceive as SubReceive;
+
+               interface UniqueConfig as Config;
+       }
+}
+
+implementation
+{
+       components UniqueLayerP, MainC, NeighborhoodC, new NeighborhoodFlagC();
+
+       MainC.SoftwareInit -> UniqueLayerP;
+       UniqueLayerP.Neighborhood -> NeighborhoodC;
+       UniqueLayerP.NeighborhoodFlag -> NeighborhoodFlagC;
+
+       Send = UniqueLayerP;
+       SubSend = UniqueLayerP;
+
+       RadioReceive = UniqueLayerP;
+       SubReceive = UniqueLayerP;
+       Config = UniqueLayerP;
+}
diff --git a/tos/chips/rf2xx/layers/UniqueLayerP.nc b/tos/chips/rf2xx/layers/UniqueLayerP.nc
new file mode 100755 (executable)
index 0000000..121139d
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+#include <Neighborhood.h>
+
+module UniqueLayerP
+{
+       provides
+       {
+               interface BareSend as Send;
+               interface RadioReceive;
+
+               interface Init;
+       }
+
+       uses
+       {
+               interface BareSend as SubSend;
+               interface RadioReceive as SubReceive;
+
+               interface UniqueConfig;
+               interface Neighborhood;
+               interface NeighborhoodFlag;
+       }
+}
+
+implementation
+{
+       uint8_t sequenceNumber;
+
+       command error_t Init.init()
+       {
+               sequenceNumber = TOS_NODE_ID << 4;
+               return SUCCESS;
+       }
+
+       command error_t Send.send(message_t* msg)
+       {
+               call UniqueConfig.setSequenceNumber(msg, ++sequenceNumber);
+               return call SubSend.send(msg);
+       }
+
+       command error_t Send.cancel(message_t* msg)
+       {
+               return call SubSend.cancel(msg);
+       }
+
+       event void SubSend.sendDone(message_t* msg, error_t error)
+       {
+               signal Send.sendDone(msg, error);
+       }
+
+       tasklet_async event bool SubReceive.header(message_t* msg)
+       {
+               // we could scan here, but better be lazy
+               return signal RadioReceive.header(msg);
+       }
+
+       tasklet_norace uint8_t receivedNumbers[NEIGHBORHOOD_SIZE];
+
+       tasklet_async event message_t* SubReceive.receive(message_t* msg)
+       {
+               uint8_t index = call Neighborhood.insertNode(call UniqueConfig.getSender(msg));
+               uint8_t dsn = call UniqueConfig.getSequenceNumber(msg);
+
+               if( call NeighborhoodFlag.get(index) )
+               {
+                       uint8_t diff = dsn - receivedNumbers[index];
+
+                       if( diff == 0 )
+                       {
+                               call UniqueConfig.reportChannelError();
+                               return msg;
+                       }
+               }
+               else
+                       call NeighborhoodFlag.set(index);
+
+               receivedNumbers[index] = dsn;
+
+               return signal RadioReceive.receive(msg);
+       }
+
+       tasklet_async event void Neighborhood.evicted(uint8_t index) { }
+}
diff --git a/tos/chips/rf2xx/rf212/README b/tos/chips/rf2xx/rf212/README
new file mode 100644 (file)
index 0000000..99719cd
--- /dev/null
@@ -0,0 +1,38 @@
+
+The RF212 radio driver has the following configuration options. Some of 
+these are set in the platforms/xxx/chips/rf212/RadioConfig.h header file, 
+see the meshbean900 platform for example, others can be set in your Makefile.
+
+RF212_TRX_CTRL_0_VALUE:
+
+This is the value of the TRX_CTRL_0 register which configures the output 
+pin currents and the CLKM clock:
+
+RF212_CCA_MODE_VALUE:
+
+This is the default value of the CCA_MODE field in the PHY_CC_CCA register
+which is used to configure the default mode of the clear channel assesment
+
+RF212_CCA_THRES_VALUE:
+
+This is the value of the CCA_THRES register that controls the energy levels 
+used for clear channel assesment.
+
+RF212_DEF_RFPOWER:
+
+This is the default value of the TX_PWR field of the PHY_TX_PWR register. 
+This can be cahanged via the PacketTransmitPower interface provided by the 
+RF212ActiveMessageC.
+
+RF212_DEF_CHANNEL:
+
+This is the default value of the CHANNEL field of the PHY_CC_CCA register.
+This can be cahanged via the RadioChannel interface provided by the 
+RF212ActiveMessageC.
+
+RF212_RSSI_ENERGY:
+
+If you define this, then the content of the RF212_PHY_ED_LEVEL is queried 
+instead of the RSSI value for eahc incoming message. This value can be 
+obtained with the PacketRSSI interface.
+
diff --git a/tos/chips/rf2xx/rf212/RF212ActiveMessageC.nc b/tos/chips/rf2xx/rf212/RF212ActiveMessageC.nc
new file mode 100644 (file)
index 0000000..10f7c5f
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+#ifdef IEEE154FRAMES_ENABLED
+#error "You cannot use ActiveMessageC with IEEE154FRAMES_ENABLED defined"
+#endif
+
+configuration RF212ActiveMessageC
+{
+       provides 
+       {
+               interface SplitControl;
+
+               interface AMSend[am_id_t id];
+               interface Receive[am_id_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface SendNotifier[am_id_t id];
+
+               interface Packet;
+               interface AMPacket;
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+#ifdef PACKET_LINK
+               interface PacketLink;
+#endif
+
+               interface RadioChannel;
+
+               interface PacketField<uint8_t> as PacketLinkQuality;
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF212RadioC;
+
+       SplitControl = RF212RadioC;
+
+       AMSend = RF212RadioC;
+       Receive = RF212RadioC.Receive;
+       Snoop = RF212RadioC.Snoop;
+       SendNotifier = RF212RadioC;
+
+       Packet = RF212RadioC.PacketForActiveMessage;
+       AMPacket = RF212RadioC;
+
+       PacketAcknowledgements = RF212RadioC;
+       LowPowerListening = RF212RadioC;
+#ifdef PACKET_LINK
+       PacketLink = RF212RadioC;
+#endif
+
+       RadioChannel = RF212RadioC;
+
+       PacketLinkQuality = RF212RadioC.PacketLinkQuality;
+       PacketTransmitPower = RF212RadioC.PacketTransmitPower;
+       PacketRSSI = RF212RadioC.PacketRSSI;
+
+       LocalTimeRadio = RF212RadioC;
+       PacketTimeStampMilli = RF212RadioC;
+       PacketTimeStampRadio = RF212RadioC;
+}
diff --git a/tos/chips/rf2xx/rf212/RF212DriverConfig.nc b/tos/chips/rf2xx/rf212/RF212DriverConfig.nc
new file mode 100644 (file)
index 0000000..98218bc
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface RF212DriverConfig
+{
+       /**
+        * Returns the length of a dummy header to align the payload properly.
+        */
+       async command uint8_t headerLength(message_t* msg);
+
+       /**
+        * Returns the maximum length of the PHY payload including the 
+        * length field but not counting the FCF field.
+        */
+       async command uint8_t maxPayloadLength();
+
+       /**
+        * Returns the length of a dummy metadata section to align the
+        * metadata section properly.
+        */
+       async command uint8_t metadataLength(message_t* msg);
+
+       /**
+        * Gets the number of bytes we should read before the RadioReceive.header
+        * event is fired. If the length of the packet is less than this amount, 
+        * then that event is fired earlier. The header length must be at least one.
+        */
+       async command uint8_t headerPreloadLength();
+
+       /**
+        * Returns TRUE if before sending this message we should make sure that
+        * the channel is clear via a very basic (and quick) RSSI check.
+        */
+       async command bool requiresRssiCca(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/rf212/RF212DriverLayer.h b/tos/chips/rf2xx/rf212/RF212DriverLayer.h
new file mode 100644 (file)
index 0000000..4c0fae2
--- /dev/null
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __RF212DRIVERLAYER_H__
+#define __RF212DRIVERLAYER_H__
+
+typedef nx_struct rf212_header_t
+{
+       nxle_uint8_t length;
+} rf212_header_t;
+
+typedef struct rf212_metadata_t
+{
+       uint8_t lqi;
+       union
+       {
+               uint8_t power;
+               uint8_t rssi;
+       };
+} rf212_metadata_t;
+
+enum rf212_registers_enum
+{
+       RF212_TRX_STATUS = 0x01,
+       RF212_TRX_STATE = 0x02,
+       RF212_TRX_CTRL_0 = 0x03,
+       RF212_TRX_CTRL_1 = 0x04,
+       RF212_PHY_TX_PWR = 0x05,
+       RF212_PHY_RSSI = 0x06,
+       RF212_PHY_ED_LEVEL = 0x07,
+       RF212_PHY_CC_CCA = 0x08,
+       RF212_CCA_THRES = 0x09,
+       RF212_IRQ_MASK = 0x0E,
+       RF212_IRQ_STATUS = 0x0F,
+       RF212_VREG_CTRL = 0x10,
+       RF212_BATMON = 0x11,
+       RF212_XOSC_CTRL = 0x12,
+       RF212_PLL_CF = 0x1A,
+       RF212_PLL_DCU = 0x1B,
+       RF212_PART_NUM = 0x1C,
+       RF212_VERSION_NUM = 0x1D,
+       RF212_MAN_ID_0 = 0x1E,
+       RF212_MAN_ID_1 = 0x1F,
+       RF212_SHORT_ADDR_0 = 0x20,
+       RF212_SHORT_ADDR_1 = 0x21,
+       RF212_PAN_ID_0 = 0x22,
+       RF212_PAN_ID_1 = 0x23,
+       RF212_IEEE_ADDR_0 = 0x24,
+       RF212_IEEE_ADDR_1 = 0x25,
+       RF212_IEEE_ADDR_2 = 0x26,
+       RF212_IEEE_ADDR_3 = 0x27,
+       RF212_IEEE_ADDR_4 = 0x28,
+       RF212_IEEE_ADDR_5 = 0x29,
+       RF212_IEEE_ADDR_6 = 0x2A,
+       RF212_IEEE_ADDR_7 = 0x2B,
+       RF212_XAH_CTRL = 0x2C,
+       RF212_CSMA_SEED_0 = 0x2D,
+       RF212_CSMA_SEED_1 = 0x2E,
+};
+
+enum rf212_trx_status_enums
+{
+       RF212_CCA_DONE = 1 << 7,
+       RF212_CCA_STATUS = 1 << 6,
+       RF212_TRX_STATUS_MASK = 0x1F,
+       RF212_P_ON = 0,
+       RF212_BUSY_RX = 1,
+       RF212_BUSY_TX = 2,
+       RF212_RX_ON = 6,
+       RF212_TRX_OFF = 8,
+       RF212_PLL_ON = 9,
+       RF212_SLEEP = 15,
+       RF212_BUSY_RX_AACK = 17,
+       RF212_BUSR_TX_ARET = 18,
+       RF212_RX_AACK_ON = 22,
+       RF212_TX_ARET_ON = 25,
+       RF212_RX_ON_NOCLK = 28,
+       RF212_AACK_ON_NOCLK = 29,
+       RF212_BUSY_RX_AACK_NOCLK = 30,
+       RF212_STATE_TRANSITION_IN_PROGRESS = 31,
+};
+
+enum rf212_trx_state_enums
+{
+       RF212_TRAC_STATUS_MASK = 0xE0,
+       RF212_TRAC_SUCCESS = 0,
+       RF212_TRAC_SUCCESS_DATA_PENDING = 1 << 5,
+       RF212_TRAC_SUCCESS_WAIT_FOR_ACK = 2 << 5,
+       RF212_TRAC_CHANNEL_ACCESS_FAILURE = 3 << 5,
+       RF212_TRAC_NO_ACK = 5 << 5,
+       RF212_TRAC_INVALID = 7 << 5,
+       RF212_TRX_CMD_MASK = 0x1F,
+       RF212_NOP = 0,
+       RF212_TX_START = 2,
+       RF212_FORCE_TRX_OFF = 3,
+};
+
+enum rf212_phy_rssi_enums
+{
+       RF212_RX_CRC_VALID = 1 << 7,
+       RF212_RSSI_MASK = 0x1F,
+};
+
+enum rf212_phy_cc_cca_enums
+{
+       RF212_CCA_REQUEST = 1 << 7,
+       RF212_CCA_MODE_0 = 0 << 5,
+       RF212_CCA_MODE_1 = 1 << 5,
+       RF212_CCA_MODE_2 = 2 << 5,
+       RF212_CCA_MODE_3 = 3 << 5,
+       RF212_CHANNEL_DEFAULT = 11,
+       RF212_CHANNEL_MASK = 0x1F,
+};
+
+enum rf212_irq_register_enums
+{
+       RF212_IRQ_BAT_LOW = 1 << 7,
+       RF212_IRQ_TRX_UR = 1 << 6,
+       RF212_IRQ_AMI = 1 << 5,
+       RF212_IRQ_CCA_ED_DONE = 1 << 4,
+       RF212_IRQ_TRX_END = 1 << 3,
+       RF212_IRQ_RX_START = 1 << 2,
+       RF212_IRQ_PLL_UNLOCK = 1 << 1,
+       RF212_IRQ_PLL_LOCK = 1 << 0,
+};
+
+enum rf212_batmon_enums
+{
+       RF212_BATMON_OK = 1 << 5,
+       RF212_BATMON_VHR = 1 << 4,
+       RF212_BATMON_VTH_MASK = 0x0F,
+};
+
+enum rf212_vreg_ctrl_enums
+{
+       RF212_AVREG_EXT = 1 << 7,
+       RF212_AVDD_OK = 1 << 6,
+       RF212_DVREG_EXT = 1 << 3,
+       RF212_DVDD_OK = 1 << 2,
+};
+
+enum rf212_xosc_ctrl_enums
+{
+       RF212_XTAL_MODE_OFF = 0 << 4,
+       RF212_XTAL_MODE_EXTERNAL = 4 << 4,
+       RF212_XTAL_MODE_INTERNAL = 15 << 4,
+};
+
+enum rf212_spi_command_enums
+{
+       RF212_CMD_REGISTER_READ = 0x80,
+       RF212_CMD_REGISTER_WRITE = 0xC0,
+       RF212_CMD_REGISTER_MASK = 0x3F,
+       RF212_CMD_FRAME_READ = 0x20,
+       RF212_CMD_FRAME_WRITE = 0x60,
+       RF212_CMD_SRAM_READ = 0x00,
+       RF212_CMD_SRAM_WRITE = 0x40,
+};
+
+#endif//__RF212DRIVERLAYER_H__
diff --git a/tos/chips/rf2xx/rf212/RF212DriverLayerC.nc b/tos/chips/rf2xx/rf212/RF212DriverLayerC.nc
new file mode 100644 (file)
index 0000000..73b6b5e
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+#include <RF212DriverLayer.h>
+
+configuration RF212DriverLayerC
+{
+       provides
+       {
+               interface RadioState;
+               interface RadioSend;
+               interface RadioReceive;
+               interface RadioCCA;
+               interface RadioPacket;
+
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+               interface PacketField<uint8_t> as PacketTimeSyncOffset;
+               interface PacketField<uint8_t> as PacketLinkQuality;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+       }
+
+       uses
+       {
+               interface RF212DriverConfig as Config;
+               interface PacketTimeStamp<TRadio, uint32_t>;
+       }
+}
+
+implementation
+{
+       components RF212DriverLayerP, HplRF212C, BusyWaitMicroC, TaskletC, MainC, RadioAlarmC;
+
+       RadioState = RF212DriverLayerP;
+       RadioSend = RF212DriverLayerP;
+       RadioReceive = RF212DriverLayerP;
+       RadioCCA = RF212DriverLayerP;
+       RadioPacket = RF212DriverLayerP;
+
+       LocalTimeRadio = HplRF212C;
+
+       Config = RF212DriverLayerP;
+
+       PacketTransmitPower = RF212DriverLayerP.PacketTransmitPower;
+       components new MetadataFlagC() as TransmitPowerFlagC;
+       RF212DriverLayerP.TransmitPowerFlag -> TransmitPowerFlagC;
+
+       PacketRSSI = RF212DriverLayerP.PacketRSSI;
+       components new MetadataFlagC() as RSSIFlagC;
+       RF212DriverLayerP.RSSIFlag -> RSSIFlagC;
+
+       PacketTimeSyncOffset = RF212DriverLayerP.PacketTimeSyncOffset;
+       components new MetadataFlagC() as TimeSyncFlagC;
+       RF212DriverLayerP.TimeSyncFlag -> TimeSyncFlagC;
+
+       PacketLinkQuality = RF212DriverLayerP.PacketLinkQuality;
+       PacketTimeStamp = RF212DriverLayerP.PacketTimeStamp;
+
+       RF212DriverLayerP.LocalTime -> HplRF212C;
+
+       RF212DriverLayerP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
+       RadioAlarmC.Alarm -> HplRF212C.Alarm;
+
+       RF212DriverLayerP.SELN -> HplRF212C.SELN;
+       RF212DriverLayerP.SpiResource -> HplRF212C.SpiResource;
+       RF212DriverLayerP.FastSpiByte -> HplRF212C;
+
+       RF212DriverLayerP.SLP_TR -> HplRF212C.SLP_TR;
+       RF212DriverLayerP.RSTN -> HplRF212C.RSTN;
+
+       RF212DriverLayerP.IRQ -> HplRF212C.IRQ;
+       RF212DriverLayerP.Tasklet -> TaskletC;
+       RF212DriverLayerP.BusyWait -> BusyWaitMicroC;
+
+#ifdef RADIO_DEBUG
+       components DiagMsgC;
+       RF212DriverLayerP.DiagMsg -> DiagMsgC;
+#endif
+
+       MainC.SoftwareInit -> RF212DriverLayerP.SoftwareInit;
+
+       components RealMainP;
+       RealMainP.PlatformInit -> RF212DriverLayerP.PlatformInit;
+}
diff --git a/tos/chips/rf2xx/rf212/RF212DriverLayerP.nc b/tos/chips/rf2xx/rf212/RF212DriverLayerP.nc
new file mode 100644 (file)
index 0000000..218066e
--- /dev/null
@@ -0,0 +1,978 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RF212DriverLayer.h>
+#include <Tasklet.h>
+#include <RadioAssert.h>
+#include <TimeSyncMessageLayer.h>
+#include <RadioConfig.h>
+
+module RF212DriverLayerP
+{
+       provides
+       {
+               interface Init as PlatformInit @exactlyonce();
+               interface Init as SoftwareInit @exactlyonce();
+
+               interface RadioState;
+               interface RadioSend;
+               interface RadioReceive;
+               interface RadioCCA;
+               interface RadioPacket;
+
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+               interface PacketField<uint8_t> as PacketTimeSyncOffset;
+               interface PacketField<uint8_t> as PacketLinkQuality;
+       }
+
+       uses
+       {
+               interface GeneralIO as SELN;
+               interface Resource as SpiResource;
+
+               interface FastSpiByte;
+
+               interface GeneralIO as SLP_TR;
+               interface GeneralIO as RSTN;
+
+               interface GpioCapture as IRQ;
+
+               interface BusyWait<TMicro, uint16_t>;
+               interface LocalTime<TRadio>;
+
+               interface RF212DriverConfig as Config;
+
+               interface PacketFlag as TransmitPowerFlag;
+               interface PacketFlag as RSSIFlag;
+               interface PacketFlag as TimeSyncFlag;
+
+               interface PacketTimeStamp<TRadio, uint32_t>;
+
+               interface Tasklet;
+               interface RadioAlarm;
+
+#ifdef RADIO_DEBUG
+               interface DiagMsg;
+#endif
+       }
+}
+
+implementation
+{
+       rf212_header_t* getHeader(message_t* msg)
+       {
+               return ((void*)msg) + call Config.headerLength(msg);
+       }
+
+       void* getPayload(message_t* msg)
+       {
+               return ((void*)msg) + call RadioPacket.headerLength(msg);
+       }
+
+       rf212_metadata_t* getMeta(message_t* msg)
+       {
+               return ((void*)msg) + sizeof(message_t) - call RadioPacket.metadataLength(msg);
+       }
+
+/*----------------- STATE -----------------*/
+
+       tasklet_norace uint8_t state;
+       enum
+       {
+               STATE_P_ON = 0,
+               STATE_SLEEP = 1,
+               STATE_SLEEP_2_TRX_OFF = 2,
+               STATE_TRX_OFF = 3,
+               STATE_TRX_OFF_2_RX_ON = 4,
+               STATE_RX_ON = 5,
+               STATE_BUSY_TX_2_RX_ON = 6,
+               STATE_PLL_ON_2_RX_ON = 7,
+       };
+
+       tasklet_norace uint8_t cmd;
+       enum
+       {
+               CMD_NONE = 0,                   // the state machine has stopped
+               CMD_TURNOFF = 1,                // goto SLEEP state
+               CMD_STANDBY = 2,                // goto TRX_OFF state
+               CMD_TURNON = 3,                 // goto RX_ON state
+               CMD_TRANSMIT = 4,               // currently transmitting a message
+               CMD_RECEIVE = 5,                // currently receiving a message
+               CMD_CCA = 6,                    // performing clear chanel assesment
+               CMD_CHANNEL = 7,                // changing the channel
+               CMD_SIGNAL_DONE = 8,            // signal the end of the state transition
+               CMD_DOWNLOAD = 9,               // download the received message
+       };
+
+       norace bool radioIrq;
+
+       tasklet_norace uint8_t txPower;
+       tasklet_norace uint8_t channel;
+
+       tasklet_norace message_t* rxMsg;
+       message_t rxMsgBuffer;
+
+       uint16_t capturedTime;  // the current time when the last interrupt has occured
+
+       tasklet_norace uint8_t rssiClear;
+       tasklet_norace uint8_t rssiBusy;
+
+/*----------------- REGISTER -----------------*/
+
+       inline void writeRegister(uint8_t reg, uint8_t value)
+       {
+               ASSERT( call SpiResource.isOwner() );
+               ASSERT( reg == (reg & RF212_CMD_REGISTER_MASK) );
+
+               call SELN.clr();
+               call FastSpiByte.splitWrite(RF212_CMD_REGISTER_WRITE | reg);
+               call FastSpiByte.splitReadWrite(value);
+               call FastSpiByte.splitRead();
+               call SELN.set();
+       }
+
+       inline uint8_t readRegister(uint8_t reg)
+       {
+               ASSERT( call SpiResource.isOwner() );
+               ASSERT( reg == (reg & RF212_CMD_REGISTER_MASK) );
+
+               call SELN.clr();
+               call FastSpiByte.splitWrite(RF212_CMD_REGISTER_READ | reg);
+               call FastSpiByte.splitReadWrite(0);
+               reg = call FastSpiByte.splitRead();
+               call SELN.set();
+
+               return reg;
+       }
+
+/*----------------- ALARM -----------------*/
+
+       enum
+       {
+               SLEEP_WAKEUP_TIME = (uint16_t)(880 * RADIO_ALARM_MICROSEC),
+               CCA_REQUEST_TIME = (uint16_t)(140 * RADIO_ALARM_MICROSEC),
+
+               TX_SFD_DELAY = (uint16_t)(176 * RADIO_ALARM_MICROSEC),
+               RX_SFD_DELAY = (uint16_t)(8 * RADIO_ALARM_MICROSEC),
+       };
+
+       tasklet_async event void RadioAlarm.fired()
+       {
+               if( state == STATE_SLEEP_2_TRX_OFF )
+                       state = STATE_TRX_OFF;
+               else if( cmd == CMD_CCA )
+               {
+                       uint8_t cca;
+
+                       ASSERT( state == STATE_RX_ON );
+
+                       cmd = CMD_NONE;
+                       cca = readRegister(RF212_TRX_STATUS);
+
+                       ASSERT( (cca & RF212_TRX_STATUS_MASK) == RF212_RX_ON );
+
+                       signal RadioCCA.done( (cca & RF212_CCA_DONE) ? ((cca & RF212_CCA_STATUS) ? SUCCESS : EBUSY) : FAIL );
+               }
+               else
+                       ASSERT(FALSE);
+
+               // make sure the rest of the command processing is called
+               call Tasklet.schedule();
+       }
+
+/*----------------- INIT -----------------*/
+
+       command error_t PlatformInit.init()
+       {
+               call SELN.makeOutput();
+               call SELN.set();
+               call SLP_TR.makeOutput();
+               call SLP_TR.clr();
+               call RSTN.makeOutput();
+               call RSTN.set();
+
+               rxMsg = &rxMsgBuffer;
+
+               // these are just good approximates
+               rssiClear = 0;
+               rssiBusy = 90;
+
+               return SUCCESS;
+       }
+
+       command error_t SoftwareInit.init()
+       {
+               // for powering up the radio
+               return call SpiResource.request();
+       }
+
+       void initRadio()
+       {
+               call BusyWait.wait(510);
+
+               call RSTN.clr();
+               call SLP_TR.clr();
+               call BusyWait.wait(6);
+               call RSTN.set();
+
+               writeRegister(RF212_TRX_CTRL_0, RF212_TRX_CTRL_0_VALUE);
+               writeRegister(RF212_TRX_STATE, RF212_TRX_OFF);
+
+               call BusyWait.wait(510);
+
+               writeRegister(RF212_IRQ_MASK, RF212_IRQ_TRX_UR | RF212_IRQ_PLL_LOCK | RF212_IRQ_TRX_END | RF212_IRQ_RX_START);
+               writeRegister(RF212_CCA_THRES, RF212_CCA_THRES_VALUE);
+               writeRegister(RF212_PHY_TX_PWR, RF212_DEF_RFPOWER);
+
+               txPower = RF212_DEF_RFPOWER;
+               channel = RF212_DEF_CHANNEL & RF212_CHANNEL_MASK;
+               writeRegister(RF212_PHY_CC_CCA, RF212_CCA_MODE_VALUE | channel);
+
+               call SLP_TR.set();
+               state = STATE_SLEEP;
+       }
+
+/*----------------- SPI -----------------*/
+
+       event void SpiResource.granted()
+       {
+               call SELN.makeOutput();
+               call SELN.set();
+
+               if( state == STATE_P_ON )
+               {
+                       initRadio();
+                       call SpiResource.release();
+               }
+               else
+                       call Tasklet.schedule();
+       }
+
+       bool isSpiAcquired()
+       {
+               if( call SpiResource.isOwner() )
+                       return TRUE;
+
+               if( call SpiResource.immediateRequest() == SUCCESS )
+               {
+                       call SELN.makeOutput();
+                       call SELN.set();
+
+                       return TRUE;
+               }
+
+               call SpiResource.request();
+               return FALSE;
+       }
+
+/*----------------- CHANNEL -----------------*/
+
+       tasklet_async command uint8_t RadioState.getChannel()
+       {
+               return channel;
+       }
+
+       tasklet_async command error_t RadioState.setChannel(uint8_t c)
+       {
+               c &= RF212_CHANNEL_MASK;
+
+               if( cmd != CMD_NONE )
+                       return EBUSY;
+               else if( channel == c )
+                       return EALREADY;
+
+               channel = c;
+               cmd = CMD_CHANNEL;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+
+       inline void changeChannel()
+       {
+               ASSERT( cmd == CMD_CHANNEL );
+               ASSERT( state == STATE_SLEEP || state == STATE_TRX_OFF || state == STATE_RX_ON );
+
+               if( isSpiAcquired() )
+               {
+                       writeRegister(RF212_PHY_CC_CCA, RF212_CCA_MODE_VALUE | channel);
+
+                       if( state == STATE_RX_ON )
+                               state = STATE_TRX_OFF_2_RX_ON;
+                       else
+                               cmd = CMD_SIGNAL_DONE;
+               }
+       }
+
+/*----------------- TURN ON/OFF -----------------*/
+
+       inline void changeState()
+       {
+               if( (cmd == CMD_STANDBY || cmd == CMD_TURNON)
+                       && state == STATE_SLEEP && call RadioAlarm.isFree() )
+               {
+                       call SLP_TR.clr();
+
+                       call RadioAlarm.wait(SLEEP_WAKEUP_TIME);
+                       state = STATE_SLEEP_2_TRX_OFF;
+               }
+               else if( cmd == CMD_TURNON && state == STATE_TRX_OFF && isSpiAcquired() )
+               {
+                       ASSERT( ! radioIrq );
+
+                       readRegister(RF212_IRQ_STATUS); // clear the interrupt register
+                       call IRQ.captureRisingEdge();
+
+                       // setChannel was ignored in SLEEP because the SPI was not working, so do it here
+                       writeRegister(RF212_PHY_CC_CCA, RF212_CCA_MODE_VALUE | channel);
+
+                       writeRegister(RF212_TRX_STATE, RF212_RX_ON);
+                       state = STATE_TRX_OFF_2_RX_ON;
+               }
+               else if( (cmd == CMD_TURNOFF || cmd == CMD_STANDBY) 
+                       && state == STATE_RX_ON && isSpiAcquired() )
+               {
+                       writeRegister(RF212_TRX_STATE, RF212_FORCE_TRX_OFF);
+
+                       call IRQ.disable();
+                       radioIrq = FALSE;
+
+                       state = STATE_TRX_OFF;
+               }
+
+               if( cmd == CMD_TURNOFF && state == STATE_TRX_OFF )
+               {
+                       call SLP_TR.set();
+                       state = STATE_SLEEP;
+                       cmd = CMD_SIGNAL_DONE;
+               }
+               else if( cmd == CMD_STANDBY && state == STATE_TRX_OFF )
+                       cmd = CMD_SIGNAL_DONE;
+       }
+
+       tasklet_async command error_t RadioState.turnOff()
+       {
+               if( cmd != CMD_NONE )
+                       return EBUSY;
+               else if( state == STATE_SLEEP )
+                       return EALREADY;
+
+               cmd = CMD_TURNOFF;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+       
+       tasklet_async command error_t RadioState.standby()
+       {
+               if( cmd != CMD_NONE || (state == STATE_SLEEP && ! call RadioAlarm.isFree()) )
+                       return EBUSY;
+               else if( state == STATE_TRX_OFF )
+                       return EALREADY;
+
+               cmd = CMD_STANDBY;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+
+       tasklet_async command error_t RadioState.turnOn()
+       {
+               if( cmd != CMD_NONE || (state == STATE_SLEEP && ! call RadioAlarm.isFree()) )
+                       return EBUSY;
+               else if( state == STATE_RX_ON )
+                       return EALREADY;
+
+               cmd = CMD_TURNON;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+
+       default tasklet_async event void RadioState.done() { }
+
+/*----------------- TRANSMIT -----------------*/
+
+       tasklet_async command error_t RadioSend.send(message_t* msg)
+       {
+               uint16_t time;
+               uint8_t length;
+               uint8_t* data;
+               uint8_t header;
+               uint32_t time32;
+               void* timesync;
+
+               if( cmd != CMD_NONE || state != STATE_RX_ON || ! isSpiAcquired() || radioIrq )
+                       return EBUSY;
+
+               length = call PacketTransmitPower.isSet(msg) ?
+                       call PacketTransmitPower.get(msg) : RF212_DEF_RFPOWER;
+
+               if( length != txPower )
+               {
+                       txPower = length;
+                       writeRegister(RF212_PHY_TX_PWR, txPower);
+               }
+
+               if( call Config.requiresRssiCca(msg) 
+                               && (readRegister(RF212_PHY_RSSI) & RF212_RSSI_MASK) > ((rssiClear + rssiBusy) >> 3) )
+                       return EBUSY;
+
+               writeRegister(RF212_TRX_STATE, RF212_PLL_ON);
+
+               // do something useful, just to wait a little
+               time32 = call LocalTime.get();
+               timesync = call PacketTimeSyncOffset.isSet(msg) ? ((void*)msg) + call PacketTimeSyncOffset.get(msg) : 0;
+
+               // we have missed an incoming message in this short amount of time
+               if( (readRegister(RF212_TRX_STATUS) & RF212_TRX_STATUS_MASK) != RF212_PLL_ON )
+               {
+                       ASSERT( (readRegister(RF212_TRX_STATUS) & RF212_TRX_STATUS_MASK) == RF212_BUSY_RX );
+
+                       state = STATE_PLL_ON_2_RX_ON;
+                       return EBUSY;
+               }
+
+               atomic
+               {
+                       call SLP_TR.set();
+                       time = call RadioAlarm.getNow();
+               }
+               call SLP_TR.clr();
+
+               ASSERT( ! radioIrq );
+
+               call SELN.clr();
+               call FastSpiByte.splitWrite(RF212_CMD_FRAME_WRITE);
+
+               data = getPayload(msg);
+               length = getHeader(msg)->length;
+
+               // length | data[0] ... data[length-3] | automatically generated FCS
+               call FastSpiByte.splitReadWrite(length);
+
+               // the FCS is atomatically generated (2 bytes)
+               length -= 2;
+
+               header = call Config.headerPreloadLength();
+               if( header > length )
+                       header = length;
+
+               length -= header;
+
+               // first upload the header to gain some time
+               do {
+                       call FastSpiByte.splitReadWrite(*(data++));
+               }
+               while( --header != 0 );
+
+               time32 += (int16_t)(time + TX_SFD_DELAY) - (int16_t)(time32);
+
+               if( timesync != 0 )
+                       *(timesync_relative_t*)timesync = (*(timesync_absolute_t*)timesync) - time32;
+
+               while( length-- != 0 )
+                       call FastSpiByte.splitReadWrite(*(data++));
+
+               // wait for the SPI transfer to finish
+               call FastSpiByte.splitRead();
+               call SELN.set();
+
+               /*
+                * There is a very small window (~1 microsecond) when the RF212 went 
+                * into PLL_ON state but was somehow not properly initialized because 
+                * of an incoming message and could not go into BUSY_TX. I think the
+                * radio can even receive a message, and generate a TRX_UR interrupt
+                * because of concurrent access, but that message probably cannot be
+                * recovered.
+                *
+                * TODO: this needs to be verified, and make sure that the chip is 
+                * not locked up in this case.
+                */
+
+               // go back to RX_ON state when finished
+               writeRegister(RF212_TRX_STATE, RF212_RX_ON);
+
+               if( timesync != 0 )
+                       *(timesync_absolute_t*)timesync = (*(timesync_relative_t*)timesync) + time32;
+
+               call PacketTimeStamp.set(msg, time32);
+
+#ifdef RADIO_DEBUG_MESSAGES
+               if( call DiagMsg.record() )
+               {
+                       length = getHeader(msg)->length;
+
+                       call DiagMsg.str('t');
+                       call DiagMsg.uint32(call PacketTimeStamp.isValid(rxMsg) ? call PacketTimeStamp.timestamp(rxMsg) : 0);
+                       call DiagMsg.uint16(call RadioAlarm.getNow());
+                       call DiagMsg.int8(length);
+                       call DiagMsg.hex8s(getPayload(msg), length - 2);
+                       call DiagMsg.send();
+               }
+#endif
+
+               // wait for the TRX_END interrupt
+               state = STATE_BUSY_TX_2_RX_ON;
+               cmd = CMD_TRANSMIT;
+
+               return SUCCESS;
+       }
+
+       default tasklet_async event void RadioSend.sendDone(error_t error) { }
+       default tasklet_async event void RadioSend.ready() { }
+
+/*----------------- CCA -----------------*/
+
+       tasklet_async command error_t RadioCCA.request()
+       {
+               if( cmd != CMD_NONE || state != STATE_RX_ON || ! isSpiAcquired() || ! call RadioAlarm.isFree() )
+                       return EBUSY;
+
+               // see Errata B7 of the datasheet
+               // writeRegister(RF212_TRX_STATE, RF212_PLL_ON);
+               // writeRegister(RF212_TRX_STATE, RF212_RX_ON);
+
+               writeRegister(RF212_PHY_CC_CCA, RF212_CCA_REQUEST | RF212_CCA_MODE_VALUE | channel);
+               call RadioAlarm.wait(CCA_REQUEST_TIME);
+               cmd = CMD_CCA;
+               
+               return SUCCESS;
+       }
+
+       default tasklet_async event void RadioCCA.done(error_t error) { }
+
+/*----------------- RECEIVE -----------------*/
+
+       inline void downloadMessage()
+       {
+               uint8_t length;
+               bool crcValid = FALSE;
+
+               call SELN.clr();
+               call FastSpiByte.write(RF212_CMD_FRAME_READ);
+
+               // read the length byte
+               length = call FastSpiByte.write(0);
+
+               // if correct length
+               if( length >= 3 && length <= call RadioPacket.maxPayloadLength() + 2 )
+               {
+                       uint8_t read;
+                       uint8_t* data;
+
+                       // initiate the reading
+                       call FastSpiByte.splitWrite(0);
+
+                       data = getPayload(rxMsg);
+                       getHeader(rxMsg)->length = length;
+
+                       // we do not store the CRC field
+                       length -= 2;
+
+                       read = call Config.headerPreloadLength();
+                       if( length < read )
+                               read = length;
+
+                       length -= read;
+
+                       do {
+                               *(data++) = call FastSpiByte.splitReadWrite(0);
+                       }
+                       while( --read != 0  );
+
+                       if( signal RadioReceive.header(rxMsg) )
+                       {
+                               while( length-- != 0 )
+                                       *(data++) = call FastSpiByte.splitReadWrite(0);
+
+                               call FastSpiByte.splitReadWrite(0);     // two CRC bytes
+                               call FastSpiByte.splitReadWrite(0);
+
+                               call PacketLinkQuality.set(rxMsg, call FastSpiByte.splitReadWrite(0));
+                               call FastSpiByte.splitReadWrite(0);     // ED
+                               crcValid = call FastSpiByte.splitRead() & RF212_RX_CRC_VALID;   // RX_STATUS
+                       }
+               }
+
+               call SELN.set();
+               state = STATE_RX_ON;
+
+#ifdef RADIO_DEBUG_MESSAGES
+               if( call DiagMsg.record() )
+               {
+                       length = getHeader(rxMsg)->length;
+
+                       call DiagMsg.str('r');
+                       call DiagMsg.uint32(call PacketTimeStamp.isValid(rxMsg) ? call PacketTimeStamp.timestamp(rxMsg) : 0);
+                       call DiagMsg.uint16(call RadioAlarm.getNow());
+                       call DiagMsg.int8(crcValid ? length : -length);
+                       call DiagMsg.hex8s(getPayload(rxMsg), length - 2);
+                       call DiagMsg.int8(call PacketRSSI.isSet(rxMsg) ? call PacketRSSI.get(rxMsg) : -1);
+                       call DiagMsg.uint8(call PacketLinkQuality.isSet(rxMsg) ? call PacketLinkQuality.get(rxMsg) : 0);
+                       call DiagMsg.send();
+               }
+#endif
+               
+               cmd = CMD_NONE;
+
+               // signal only if it has passed the CRC check
+               if( crcValid )
+                       rxMsg = signal RadioReceive.receive(rxMsg);
+       }
+
+/*----------------- IRQ -----------------*/
+
+       async event void IRQ.captured(uint16_t time)
+       {
+               ASSERT( ! radioIrq );
+
+               atomic
+               {
+                       capturedTime = time;
+                       radioIrq = TRUE;
+               }
+
+               call Tasklet.schedule();
+       }
+
+       void serviceRadio()
+       {
+               if( isSpiAcquired() )
+               {
+                       uint16_t time;
+                       uint32_t time32;
+                       uint8_t irq;
+                       uint8_t temp;
+                       
+                       atomic time = capturedTime;
+                       radioIrq = FALSE;
+                       irq = readRegister(RF212_IRQ_STATUS);
+
+#ifdef RADIO_DEBUG
+                       // TODO: handle this interrupt
+                       if( irq & RF212_IRQ_TRX_UR )
+                       {
+                               if( call DiagMsg.record() )
+                               {
+                                       call DiagMsg.str("assert ur");
+                                       call DiagMsg.uint16(call RadioAlarm.getNow());
+                                       call DiagMsg.hex8(readRegister(RF212_TRX_STATUS));
+                                       call DiagMsg.hex8(readRegister(RF212_TRX_STATE));
+                                       call DiagMsg.hex8(irq);
+                                       call DiagMsg.uint8(state);
+                                       call DiagMsg.uint8(cmd);
+                                       call DiagMsg.send();
+                               }
+                       }
+#endif
+
+#ifdef RF212_RSSI_ENERGY
+                       if( irq & RF212_IRQ_TRX_END )
+                       {
+                               if( irq == RF212_IRQ_TRX_END || 
+                                       (irq == (RF212_IRQ_RX_START | RF212_IRQ_TRX_END) && cmd == CMD_NONE) )
+                                       call PacketRSSI.set(rxMsg, readRegister(RF212_PHY_ED_LEVEL));
+                               else
+                                       call PacketRSSI.clear(rxMsg);
+                       }
+#endif
+
+                       if( irq & RF212_IRQ_PLL_LOCK )
+                       {
+                               if( cmd == CMD_TURNON || cmd == CMD_CHANNEL )
+                               {
+                                       ASSERT( state == STATE_TRX_OFF_2_RX_ON );
+
+                                       state = STATE_RX_ON;
+                                       cmd = CMD_SIGNAL_DONE;
+                               }
+                               else if( cmd == CMD_TRANSMIT )
+                               {
+                                       ASSERT( state == STATE_BUSY_TX_2_RX_ON );
+                               }
+                               else
+                                       ASSERT(FALSE);
+                       }
+
+                       if( irq & RF212_IRQ_RX_START )
+                       {
+                               if( cmd == CMD_CCA )
+                               {
+                                       signal RadioCCA.done(FAIL);
+                                       cmd = CMD_NONE;
+                               }
+
+                               if( cmd == CMD_NONE )
+                               {
+                                       ASSERT( state == STATE_RX_ON || state == STATE_PLL_ON_2_RX_ON );
+
+                                       // the most likely place for busy channel, with no TRX_END interrupt
+                                       if( irq == RF212_IRQ_RX_START )
+                                       {
+                                               temp = readRegister(RF212_PHY_RSSI) & RF212_RSSI_MASK;
+                                               rssiBusy += temp - (rssiBusy >> 2);
+#ifndef RF212_RSSI_ENERGY
+                                               call PacketRSSI.set(rxMsg, temp);
+                                       }
+                                       else
+                                       {
+                                               call PacketRSSI.clear(rxMsg);
+#endif
+                                       }
+
+                                       /*
+                                        * The timestamp corresponds to the first event which could not
+                                        * have been a PLL_LOCK because then cmd != CMD_NONE, so we must
+                                        * have received a message (and could also have received the 
+                                        * TRX_END interrupt in the mean time, but that is fine. Also,
+                                        * we could not be after a transmission, because then cmd = 
+                                        * CMD_TRANSMIT.
+                                        */
+                                       if( irq == RF212_IRQ_RX_START ) // just to be cautious
+                                       {
+                                               time32 = call LocalTime.get();
+                                               time32 += (int16_t)(time - RX_SFD_DELAY) - (int16_t)(time32);
+                                               call PacketTimeStamp.set(rxMsg, time32);
+                                       }
+                                       else
+                                               call PacketTimeStamp.clear(rxMsg);
+
+                                       cmd = CMD_RECEIVE;
+                               }
+                               else
+                                       ASSERT( cmd == CMD_TURNOFF );
+                       }
+
+                       if( irq & RF212_IRQ_TRX_END )
+                       {
+                               if( cmd == CMD_TRANSMIT )
+                               {
+                                       ASSERT( state == STATE_BUSY_TX_2_RX_ON );
+
+                                       state = STATE_RX_ON;
+                                       cmd = CMD_NONE;
+                                       signal RadioSend.sendDone(SUCCESS);
+
+                                       // TODO: we could have missed a received message
+                                       ASSERT( ! (irq & RF212_IRQ_RX_START) );
+                               }
+                               else if( cmd == CMD_RECEIVE )
+                               {
+                                       ASSERT( state == STATE_RX_ON || state == STATE_PLL_ON_2_RX_ON );
+
+                                       if( state == STATE_PLL_ON_2_RX_ON )
+                                       {
+                                               ASSERT( (readRegister(RF212_TRX_STATUS) & RF212_TRX_STATUS_MASK) == RF212_PLL_ON );
+
+                                               writeRegister(RF212_TRX_STATE, RF212_RX_ON);
+                                               state = STATE_RX_ON;
+                                       }
+                                       else
+                                       {
+                                               // the most likely place for clear channel (hope to avoid acks)
+                                               rssiClear += (readRegister(RF212_PHY_RSSI) & RF212_RSSI_MASK) - (rssiClear >> 2);
+                                       }
+
+                                       cmd = CMD_DOWNLOAD;
+                               }
+                               else
+                                       ASSERT(FALSE);
+                       }
+               }
+       }
+
+       default tasklet_async event bool RadioReceive.header(message_t* msg)
+       {
+               return TRUE;
+       }
+
+       default tasklet_async event message_t* RadioReceive.receive(message_t* msg)
+       {
+               return msg;
+       }
+
+/*----------------- TASKLET -----------------*/
+
+       tasklet_async event void Tasklet.run()
+       {
+               if( radioIrq )
+                       serviceRadio();
+
+               if( cmd != CMD_NONE )
+               {
+                       if( cmd == CMD_DOWNLOAD )
+                               downloadMessage();
+                       else if( CMD_TURNOFF <= cmd && cmd <= CMD_TURNON )
+                               changeState();
+                       else if( cmd == CMD_CHANNEL )
+                               changeChannel();
+                       
+                       if( cmd == CMD_SIGNAL_DONE )
+                       {
+                               cmd = CMD_NONE;
+                               signal RadioState.done();
+                       }
+               }
+
+               if( cmd == CMD_NONE && state == STATE_RX_ON && ! radioIrq )
+                       signal RadioSend.ready();
+
+               if( cmd == CMD_NONE )
+                       call SpiResource.release();
+       }
+
+/*----------------- RadioPacket -----------------*/
+       
+       async command uint8_t RadioPacket.headerLength(message_t* msg)
+       {
+               return call Config.headerLength(msg) + sizeof(rf212_header_t);
+       }
+
+       async command uint8_t RadioPacket.payloadLength(message_t* msg)
+       {
+               return getHeader(msg)->length - 2;
+       }
+
+       async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               ASSERT( 1 <= length && length <= 125 );
+               ASSERT( call RadioPacket.headerLength(msg) + length + call RadioPacket.metadataLength(msg) <= sizeof(message_t) );
+
+               // we add the length of the CRC, which is automatically generated
+               getHeader(msg)->length = length + 2;
+       }
+
+       async command uint8_t RadioPacket.maxPayloadLength()
+       {
+               ASSERT( call Config.maxPayloadLength() <= 125 );
+
+               return call Config.maxPayloadLength() - sizeof(rf212_header_t);
+       }
+
+       async command uint8_t RadioPacket.metadataLength(message_t* msg)
+       {
+               return call Config.metadataLength(msg) + sizeof(rf212_metadata_t);
+       }
+
+       async command void RadioPacket.clear(message_t* msg)
+       {
+               // all flags are automatically cleared
+       }
+
+/*----------------- PacketTransmitPower -----------------*/
+
+       async command bool PacketTransmitPower.isSet(message_t* msg)
+       {
+               return call TransmitPowerFlag.get(msg);
+       }
+
+       async command uint8_t PacketTransmitPower.get(message_t* msg)
+       {
+               return getMeta(msg)->power;
+       }
+
+       async command void PacketTransmitPower.clear(message_t* msg)
+       {
+               call TransmitPowerFlag.clear(msg);
+       }
+
+       async command void PacketTransmitPower.set(message_t* msg, uint8_t value)
+       {
+               call TransmitPowerFlag.set(msg);
+               getMeta(msg)->power = value;
+       }
+
+/*----------------- PacketRSSI -----------------*/
+
+       async command bool PacketRSSI.isSet(message_t* msg)
+       {
+               return call RSSIFlag.get(msg);
+       }
+
+       async command uint8_t PacketRSSI.get(message_t* msg)
+       {
+               return getMeta(msg)->rssi;
+       }
+
+       async command void PacketRSSI.clear(message_t* msg)
+       {
+               call RSSIFlag.clear(msg);
+       }
+
+       async command void PacketRSSI.set(message_t* msg, uint8_t value)
+       {
+               // just to be safe if the user fails to clear the packet
+               call TransmitPowerFlag.clear(msg);
+
+               call RSSIFlag.set(msg);
+               getMeta(msg)->rssi = value;
+       }
+
+/*----------------- PacketTimeSyncOffset -----------------*/
+
+       async command bool PacketTimeSyncOffset.isSet(message_t* msg)
+       {
+               return call TimeSyncFlag.get(msg);
+       }
+
+       async command uint8_t PacketTimeSyncOffset.get(message_t* msg)
+       {
+               return call RadioPacket.headerLength(msg) + call RadioPacket.payloadLength(msg) - sizeof(timesync_absolute_t);
+       }
+
+       async command void PacketTimeSyncOffset.clear(message_t* msg)
+       {
+               call TimeSyncFlag.clear(msg);
+       }
+
+       async command void PacketTimeSyncOffset.set(message_t* msg, uint8_t value)
+       {
+               // we do not store the value, the time sync field is always the last 4 bytes
+               ASSERT( call PacketTimeSyncOffset.get(msg) == value );
+
+               call TimeSyncFlag.set(msg);
+       }
+
+/*----------------- PacketLinkQuality -----------------*/
+
+       async command bool PacketLinkQuality.isSet(message_t* msg)
+       {
+               return TRUE;
+       }
+
+       async command uint8_t PacketLinkQuality.get(message_t* msg)
+       {
+               return getMeta(msg)->lqi;
+       }
+
+       async command void PacketLinkQuality.clear(message_t* msg)
+       {
+       }
+
+       async command void PacketLinkQuality.set(message_t* msg, uint8_t value)
+       {
+               getMeta(msg)->lqi = value;
+       }
+}
diff --git a/tos/chips/rf2xx/rf212/RF212Ieee154MessageC.nc b/tos/chips/rf2xx/rf212/RF212Ieee154MessageC.nc
new file mode 100644 (file)
index 0000000..d788fe2
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+#ifdef TFRAMES_ENABLED
+#error "You cannot use Ieee154MessageC with TFRAMES_ENABLED defined"
+#endif
+
+configuration RF212Ieee154MessageC
+{
+       provides 
+       {
+               interface SplitControl;
+
+               interface Ieee154Send;
+               interface Receive as Ieee154Receive;
+               interface SendNotifier;
+
+               interface Ieee154Packet;
+               interface Packet;
+               interface Resource as SendResource[uint8_t clint];
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+               interface PacketLink;
+
+               interface RadioChannel;
+
+               interface PacketField<uint8_t> as PacketLinkQuality;
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF212RadioC;
+
+       SplitControl = RF212RadioC;
+
+       Ieee154Send = RF212RadioC.Ieee154Send;
+       Ieee154Receive = RF212RadioC.Ieee154Receive;
+       SendNotifier = RF212RadioC.Ieee154Notifier;
+
+       Packet = RF212RadioC.PacketForIeee154Message;
+       Ieee154Packet = RF212RadioC;
+       SendResource = RF212RadioC;
+
+       PacketAcknowledgements = RF212RadioC;
+       LowPowerListening = RF212RadioC;
+       PacketLink = RF212RadioC;
+
+       RadioChannel = RF212RadioC;
+
+       PacketLinkQuality = RF212RadioC.PacketLinkQuality;
+       PacketTransmitPower = RF212RadioC.PacketTransmitPower;
+       PacketRSSI = RF212RadioC.PacketRSSI;
+
+       LocalTimeRadio = RF212RadioC;
+       PacketTimeStampMilli = RF212RadioC;
+       PacketTimeStampRadio = RF212RadioC;
+}
diff --git a/tos/chips/rf2xx/rf212/RF212Radio.h b/tos/chips/rf2xx/rf212/RF212Radio.h
new file mode 100644 (file)
index 0000000..ba36696
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __RF212RADIO_H__
+#define __RF212RADIO_H__
+
+#include <RadioConfig.h>
+#include <TinyosNetworkLayer.h>
+#include <Ieee154PacketLayer.h>
+#include <ActiveMessageLayer.h>
+#include <MetadataFlagsLayer.h>
+#include <RF212DriverLayer.h>
+#include <TimeStampingLayer.h>
+#include <LowPowerListeningLayer.h>
+#include <PacketLinkLayer.h>
+
+typedef nx_struct rf212packet_header_t
+{
+       rf212_header_t rf212;
+       ieee154_header_t ieee154;
+#ifndef TFRAMES_ENABLED
+       network_header_t network;
+#endif
+#ifndef IEEE154FRAMES_ENABLED
+       activemessage_header_t am;
+#endif
+} rf212packet_header_t;
+
+typedef nx_struct rf212packet_footer_t
+{
+       // the time stamp is not recorded here, time stamped messaged cannot have max length
+} rf212packet_footer_t;
+
+typedef struct rf212packet_metadata_t
+{
+#ifdef LOW_POWER_LISTENING
+       lpl_metadata_t lpl;
+#endif
+#ifdef PACKET_LINK
+       link_metadata_t link;
+#endif
+       timestamp_metadata_t timestamp;
+       flags_metadata_t flags;
+       rf212_metadata_t rf212;
+} rf212packet_metadata_t;
+
+#endif//__RF212RADIO_H__
diff --git a/tos/chips/rf2xx/rf212/RF212RadioC.nc b/tos/chips/rf2xx/rf212/RF212RadioC.nc
new file mode 100644 (file)
index 0000000..90d1f1a
--- /dev/null
@@ -0,0 +1,256 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+configuration RF212RadioC
+{
+       provides 
+       {
+               interface SplitControl;
+
+#ifndef IEEE154FRAMES_ENABLED
+               interface AMSend[am_id_t id];
+               interface Receive[am_id_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface SendNotifier[am_id_t id];
+
+               interface AMPacket;
+               interface Packet as PacketForActiveMessage;
+#endif
+
+#ifndef TFRAMES_ENABLED
+               interface Ieee154Send;
+               interface Receive as Ieee154Receive;
+               interface SendNotifier as Ieee154Notifier;
+
+               interface Resource as SendResource[uint8_t clint];
+
+               interface Ieee154Packet;
+               interface Packet as PacketForIeee154Message;
+#endif
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+
+#ifdef PACKET_LINK
+               interface PacketLink;
+#endif
+
+               interface RadioChannel;
+
+               interface PacketField<uint8_t> as PacketLinkQuality;
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF212RadioP, RadioAlarmC;
+
+#ifdef RADIO_DEBUG
+       components AssertC;
+#endif
+
+       RF212RadioP.Ieee154PacketLayer -> Ieee154PacketLayerC;
+       RF212RadioP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
+       RF212RadioP.PacketTimeStamp -> TimeStampingLayerC;
+       RF212RadioP.RF212Packet -> RF212DriverLayerC;
+
+// -------- Active Message
+
+#ifndef IEEE154FRAMES_ENABLED
+       components ActiveMessageLayerC;
+       ActiveMessageLayerC.Config -> RF212RadioP;
+       ActiveMessageLayerC.SubSend -> AutoResourceAcquireLayerC;
+       ActiveMessageLayerC.SubReceive -> TinyosNetworkLayerC.TinyosReceive;
+       ActiveMessageLayerC.SubPacket -> TinyosNetworkLayerC.TinyosPacket;
+
+       AMSend = ActiveMessageLayerC;
+       Receive = ActiveMessageLayerC.Receive;
+       Snoop = ActiveMessageLayerC.Snoop;
+       SendNotifier = ActiveMessageLayerC;
+       AMPacket = ActiveMessageLayerC;
+       PacketForActiveMessage = ActiveMessageLayerC;
+#endif
+
+// -------- Automatic RadioSend Resource
+
+#ifndef IEEE154FRAMES_ENABLED
+#ifndef TFRAMES_ENABLED
+       components new AutoResourceAcquireLayerC();
+       AutoResourceAcquireLayerC.Resource -> SendResourceC.Resource[unique(RADIO_SEND_RESOURCE)];
+#else
+       components new DummyLayerC() as AutoResourceAcquireLayerC;
+#endif
+       AutoResourceAcquireLayerC.SubSend -> TinyosNetworkLayerC.TinyosSend;
+#endif
+
+// -------- RadioSend Resource
+
+#ifndef TFRAMES_ENABLED
+       components new SimpleFcfsArbiterC(RADIO_SEND_RESOURCE) as SendResourceC;
+       SendResource = SendResourceC;
+
+// -------- Ieee154 Message
+
+       components Ieee154MessageLayerC;
+       Ieee154MessageLayerC.Ieee154PacketLayer -> Ieee154PacketLayerC;
+       Ieee154MessageLayerC.Ieee154Packet -> Ieee154PacketLayerC;
+       Ieee154MessageLayerC.SubSend -> TinyosNetworkLayerC.Ieee154Send;
+       Ieee154MessageLayerC.SubReceive -> TinyosNetworkLayerC.Ieee154Receive;
+       Ieee154MessageLayerC.RadioPacket -> TinyosNetworkLayerC.Ieee154Packet;
+
+       Ieee154Send = Ieee154MessageLayerC;
+       Ieee154Receive = Ieee154MessageLayerC;
+       Ieee154Notifier = Ieee154MessageLayerC;
+       Ieee154Packet = Ieee154PacketLayerC;
+       PacketForIeee154Message = Ieee154MessageLayerC;
+#endif
+
+// -------- Tinyos Network
+
+       components TinyosNetworkLayerC;
+
+       TinyosNetworkLayerC.SubSend -> UniqueLayerC;
+       TinyosNetworkLayerC.SubReceive -> LowPowerListeningLayerC;
+       TinyosNetworkLayerC.SubPacket -> Ieee154PacketLayerC;
+
+// -------- IEEE 802.15.4 Packet
+
+       components Ieee154PacketLayerC;
+       Ieee154PacketLayerC.SubPacket -> LowPowerListeningLayerC;
+
+// -------- UniqueLayer Send part (wired twice)
+
+       components UniqueLayerC;
+       UniqueLayerC.Config -> RF212RadioP;
+       UniqueLayerC.SubSend -> LowPowerListeningLayerC;
+
+// -------- Low Power Listening 
+
+#ifdef LOW_POWER_LISTENING
+       #warning "*** USING LOW POWER LISTENING LAYER"
+       components LowPowerListeningLayerC;
+       LowPowerListeningLayerC.Config -> RF212RadioP;
+       LowPowerListeningLayerC.PacketAcknowledgements -> SoftwareAckLayerC;
+#else  
+       components LowPowerListeningDummyC as LowPowerListeningLayerC;
+#endif
+       LowPowerListeningLayerC.SubControl -> MessageBufferLayerC;
+       LowPowerListeningLayerC.SubSend -> PacketLinkLayerC;
+       LowPowerListeningLayerC.SubReceive -> MessageBufferLayerC;
+       LowPowerListeningLayerC.SubPacket -> PacketLinkLayerC;
+       SplitControl = LowPowerListeningLayerC;
+       LowPowerListening = LowPowerListeningLayerC;
+
+// -------- Packet Link
+
+#ifdef PACKET_LINK
+       components PacketLinkLayerC;
+       PacketLink = PacketLinkLayerC;
+       PacketLinkLayerC.PacketAcknowledgements -> SoftwareAckLayerC;
+#else
+       components new DummyLayerC() as PacketLinkLayerC;
+#endif
+       PacketLinkLayerC.SubSend -> MessageBufferLayerC;
+       PacketLinkLayerC.SubPacket -> TimeStampingLayerC;
+
+// -------- MessageBuffer
+
+       components MessageBufferLayerC;
+       MessageBufferLayerC.RadioSend -> TrafficMonitorLayerC;
+       MessageBufferLayerC.RadioReceive -> UniqueLayerC;
+       MessageBufferLayerC.RadioState -> TrafficMonitorLayerC;
+       RadioChannel = MessageBufferLayerC;
+
+// -------- UniqueLayer receive part (wired twice)
+
+       UniqueLayerC.SubReceive -> TrafficMonitorLayerC;
+
+// -------- Traffic Monitor
+
+#ifdef TRAFFIC_MONITOR
+       components TrafficMonitorLayerC;
+#else
+       components new DummyLayerC() as TrafficMonitorLayerC;
+#endif
+       TrafficMonitorLayerC.Config -> RF212RadioP;
+       TrafficMonitorLayerC -> CollisionAvoidanceLayerC.RadioSend;
+       TrafficMonitorLayerC -> CollisionAvoidanceLayerC.RadioReceive;
+       TrafficMonitorLayerC -> RF212DriverLayerC.RadioState;
+
+// -------- CollisionAvoidance
+
+#ifdef SLOTTED_MAC
+       components SlottedCollisionLayerC as CollisionAvoidanceLayerC;
+#else
+       components RandomCollisionLayerC as CollisionAvoidanceLayerC;
+#endif
+       CollisionAvoidanceLayerC.Config -> RF212RadioP;
+       CollisionAvoidanceLayerC.SubSend -> SoftwareAckLayerC;
+       CollisionAvoidanceLayerC.SubReceive -> SoftwareAckLayerC;
+
+// -------- SoftwareAcknowledgement
+
+       components SoftwareAckLayerC;
+       SoftwareAckLayerC.Config -> RF212RadioP;
+       SoftwareAckLayerC.SubSend -> CsmaLayerC;
+       SoftwareAckLayerC.SubReceive -> RF212DriverLayerC;
+       PacketAcknowledgements = SoftwareAckLayerC;
+
+// -------- Carrier Sense
+
+       components new DummyLayerC() as CsmaLayerC;
+       CsmaLayerC.Config -> RF212RadioP;
+       CsmaLayerC -> RF212DriverLayerC.RadioSend;
+       CsmaLayerC -> RF212DriverLayerC.RadioCCA;
+
+// -------- TimeStamping
+
+       components TimeStampingLayerC;
+       TimeStampingLayerC.LocalTimeRadio -> RF212DriverLayerC;
+       TimeStampingLayerC.SubPacket -> MetadataFlagsLayerC;
+       PacketTimeStampRadio = TimeStampingLayerC;
+       PacketTimeStampMilli = TimeStampingLayerC;
+
+// -------- MetadataFlags
+
+       components MetadataFlagsLayerC;
+       MetadataFlagsLayerC.SubPacket -> RF212DriverLayerC;
+
+// -------- RF212 Driver
+
+       components RF212DriverLayerC;
+       RF212DriverLayerC.Config -> RF212RadioP;
+       RF212DriverLayerC.PacketTimeStamp -> TimeStampingLayerC;
+       PacketTransmitPower = RF212DriverLayerC.PacketTransmitPower;
+       PacketLinkQuality = RF212DriverLayerC.PacketLinkQuality;
+       PacketRSSI = RF212DriverLayerC.PacketRSSI;
+       LocalTimeRadio = RF212DriverLayerC;
+}
diff --git a/tos/chips/rf2xx/rf212/RF212RadioP.nc b/tos/chips/rf2xx/rf212/RF212RadioP.nc
new file mode 100644 (file)
index 0000000..16f9340
--- /dev/null
@@ -0,0 +1,335 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RF212Radio.h>
+#include <RadioConfig.h>
+#include <Tasklet.h>
+
+module RF212RadioP
+{
+       provides
+       {
+               interface RF212DriverConfig;
+               interface SoftwareAckConfig;
+               interface UniqueConfig;
+               interface CsmaConfig;
+               interface TrafficMonitorConfig;
+               interface RandomCollisionConfig;
+               interface SlottedCollisionConfig;
+               interface ActiveMessageConfig;
+               interface DummyConfig;
+
+#ifdef LOW_POWER_LISTENING
+               interface LowPowerListeningConfig;
+#endif
+       }
+
+       uses
+       {
+               interface Ieee154PacketLayer;
+               interface RadioAlarm;
+               interface RadioPacket as RF212Packet;
+
+               interface PacketTimeStamp<TRadio, uint32_t>;
+       }
+}
+
+implementation
+{
+
+/*----------------- RF212DriverConfig -----------------*/
+
+       async command uint8_t RF212DriverConfig.headerLength(message_t* msg)
+       {
+               return offsetof(message_t, data) - sizeof(rf212packet_header_t);
+       }
+
+       async command uint8_t RF212DriverConfig.maxPayloadLength()
+       {
+               return sizeof(rf212packet_header_t) + TOSH_DATA_LENGTH;
+       }
+
+       async command uint8_t RF212DriverConfig.metadataLength(message_t* msg)
+       {
+               return 0;
+       }
+
+       async command uint8_t RF212DriverConfig.headerPreloadLength()
+       {
+               // we need the fcf, dsn, destpan and dest
+               return 7;
+       }
+
+       async command bool RF212DriverConfig.requiresRssiCca(message_t* msg)
+       {
+               return call Ieee154PacketLayer.isDataFrame(msg);
+       }
+
+/*----------------- SoftwareAckConfig -----------------*/
+
+       async command bool SoftwareAckConfig.requiresAckWait(message_t* msg)
+       {
+               return call Ieee154PacketLayer.requiresAckWait(msg);
+       }
+
+       async command bool SoftwareAckConfig.isAckPacket(message_t* msg)
+       {
+               return call Ieee154PacketLayer.isAckFrame(msg);
+       }
+
+       async command bool SoftwareAckConfig.verifyAckPacket(message_t* data, message_t* ack)
+       {
+               return call Ieee154PacketLayer.verifyAckReply(data, ack);
+       }
+
+       async command void SoftwareAckConfig.setAckRequired(message_t* msg, bool ack)
+       {
+               call Ieee154PacketLayer.setAckRequired(msg, ack);
+       }
+
+       async command bool SoftwareAckConfig.requiresAckReply(message_t* msg)
+       {
+               return call Ieee154PacketLayer.requiresAckReply(msg);
+       }
+
+       async command void SoftwareAckConfig.createAckPacket(message_t* data, message_t* ack)
+       {
+               call Ieee154PacketLayer.createAckReply(data, ack);
+       }
+
+#ifndef SOFTWAREACK_TIMEOUT
+#define SOFTWAREACK_TIMEOUT    20000
+#endif
+
+       async command uint16_t SoftwareAckConfig.getAckTimeout()
+       {
+               return (uint16_t)(SOFTWAREACK_TIMEOUT * RADIO_ALARM_MICROSEC);
+       }
+
+       tasklet_async command void SoftwareAckConfig.reportChannelError()
+       {
+#ifdef TRAFFIC_MONITOR
+               signal TrafficMonitorConfig.channelError();
+#endif
+       }
+
+/*----------------- UniqueConfig -----------------*/
+
+       async command uint8_t UniqueConfig.getSequenceNumber(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDSN(msg);
+       }
+
+       async command void UniqueConfig.setSequenceNumber(message_t* msg, uint8_t dsn)
+       {
+               call Ieee154PacketLayer.setDSN(msg, dsn);
+       }
+
+       async command am_addr_t UniqueConfig.getSender(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getSrcAddr(msg);
+       }
+
+       tasklet_async command void UniqueConfig.reportChannelError()
+       {
+#ifdef TRAFFIC_MONITOR
+               signal TrafficMonitorConfig.channelError();
+#endif
+       }
+
+/*----------------- ActiveMessageConfig -----------------*/
+
+       command am_addr_t ActiveMessageConfig.destination(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDestAddr(msg);
+       }
+
+       command void ActiveMessageConfig.setDestination(message_t* msg, am_addr_t addr)
+       {
+               call Ieee154PacketLayer.setDestAddr(msg, addr);
+       }
+
+       command am_addr_t ActiveMessageConfig.source(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getSrcAddr(msg);
+       }
+
+       command void ActiveMessageConfig.setSource(message_t* msg, am_addr_t addr)
+       {
+               call Ieee154PacketLayer.setSrcAddr(msg, addr);
+       }
+
+       command am_group_t ActiveMessageConfig.group(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDestPan(msg);
+       }
+
+       command void ActiveMessageConfig.setGroup(message_t* msg, am_group_t grp)
+       {
+               call Ieee154PacketLayer.setDestPan(msg, grp);
+       }
+
+       command error_t ActiveMessageConfig.checkFrame(message_t* msg)
+       {
+               if( ! call Ieee154PacketLayer.isDataFrame(msg) )
+                       call Ieee154PacketLayer.createDataFrame(msg);
+
+               return SUCCESS;
+       }
+
+/*----------------- CsmaConfig -----------------*/
+
+       async command bool CsmaConfig.requiresSoftwareCCA(message_t* msg)
+       {
+               return call Ieee154PacketLayer.isDataFrame(msg);
+       }
+
+/*----------------- TrafficMonitorConfig -----------------*/
+
+       enum
+       {
+               TRAFFIC_UPDATE_PERIOD = 100,    // in milliseconds
+               TRAFFIC_MAX_BYTES = (uint16_t)(TRAFFIC_UPDATE_PERIOD * 1000UL / 32),    // 3125
+       };
+
+       async command uint16_t TrafficMonitorConfig.getUpdatePeriod()
+       {
+               return TRAFFIC_UPDATE_PERIOD;
+       }
+
+       async command uint16_t TrafficMonitorConfig.getChannelTime(message_t* msg)
+       {
+               /* We count in bytes, one byte is 32 microsecond. We are conservative here.
+                *
+                * pure airtime: preable (4 bytes), SFD (1 byte), length (1 byte), payload + CRC (len bytes)
+                * frame separation: 5-10 bytes
+                * ack required: 8-16 byte separation, 11 bytes airtime, 5-10 bytes separation
+                */
+
+               uint8_t len = call RF212Packet.payloadLength(msg);
+               return call Ieee154PacketLayer.getAckRequired(msg) ? len + 6 + 16 + 11 + 10 : len + 6 + 10;
+       }
+
+       async command am_addr_t TrafficMonitorConfig.getSender(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getSrcAddr(msg);
+       }
+
+/*----------------- RandomCollisionConfig -----------------*/
+
+       /*
+        * We try to use the same values as in CC2420
+        *
+        * CC2420_MIN_BACKOFF = 10 jiffies = 320 microsec
+        * CC2420_BACKOFF_PERIOD = 10 jiffies
+        * initial backoff = 0x1F * CC2420_BACKOFF_PERIOD = 310 jiffies = 9920 microsec
+        * congestion backoff = 0x7 * CC2420_BACKOFF_PERIOD = 70 jiffies = 2240 microsec
+        */
+
+       async command uint16_t RandomCollisionConfig.getMinimumBackoff()
+       {
+               return (uint16_t)(320 * RADIO_ALARM_MICROSEC);
+       }
+
+       async command uint16_t RandomCollisionConfig.getInitialBackoff(message_t* msg)
+       {
+               return (uint16_t)(9920 * RADIO_ALARM_MICROSEC);
+       }
+
+       async command uint16_t RandomCollisionConfig.getCongestionBackoff(message_t* msg)
+       {
+               return (uint16_t)(2240 * RADIO_ALARM_MICROSEC);
+       }
+
+       async command uint16_t RandomCollisionConfig.getTransmitBarrier(message_t* msg)
+       {
+               uint16_t time;
+
+               // TODO: maybe we should use the embedded timestamp of the message
+               time = call RadioAlarm.getNow();
+
+               // estimated response time (download the message, etc) is 5-8 bytes
+               if( call Ieee154PacketLayer.requiresAckReply(msg) )
+                       time += (uint16_t)(32 * (-5 + 16 + 11 + 5) * RADIO_ALARM_MICROSEC);
+               else
+                       time += (uint16_t)(32 * (-5 + 5) * RADIO_ALARM_MICROSEC);
+
+               return time;
+       }
+
+       tasklet_async event void RadioAlarm.fired()
+       {
+       }
+
+/*----------------- SlottedCollisionConfig -----------------*/
+
+       async command uint16_t SlottedCollisionConfig.getInitialDelay()
+       {
+               return 300;
+       }
+
+       async command uint8_t SlottedCollisionConfig.getScheduleExponent()
+       {
+               return 1 + RADIO_ALARM_MILLI_EXP;
+       }
+
+       async command uint16_t SlottedCollisionConfig.getTransmitTime(message_t* msg)
+       {
+               // TODO: check if the timestamp is correct
+               return call PacketTimeStamp.timestamp(msg);
+       }
+
+       async command uint16_t SlottedCollisionConfig.getCollisionWindowStart(message_t* msg)
+       {
+               // the preamble (4 bytes), SFD (1 byte), plus two extra for safety
+               return (call PacketTimeStamp.timestamp(msg)) - (uint16_t)(7 * 32 * RADIO_ALARM_MICROSEC);
+       }
+
+       async command uint16_t SlottedCollisionConfig.getCollisionWindowLength(message_t* msg)
+       {
+               return (uint16_t)(2 * 7 * 32 * RADIO_ALARM_MICROSEC);
+       }
+
+/*----------------- Dummy -----------------*/
+
+       async command void DummyConfig.nothing()
+       {
+       }
+
+/*----------------- LowPowerListening -----------------*/
+
+#ifdef LOW_POWER_LISTENING
+
+       command bool LowPowerListeningConfig.needsAutoAckRequest(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDestAddr(msg) != TOS_BCAST_ADDR;
+       }
+
+       command bool LowPowerListeningConfig.ackRequested(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getAckRequired(msg);
+       }
+
+#endif
+
+}
diff --git a/tos/chips/rf2xx/rf212/RF212TimeSyncMessageC.nc b/tos/chips/rf2xx/rf212/RF212TimeSyncMessageC.nc
new file mode 100644 (file)
index 0000000..c9dc5bd
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+configuration RF212TimeSyncMessageC
+{
+       provides
+       {
+               interface SplitControl;
+
+               interface Receive[uint8_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface Packet;
+               interface AMPacket;
+
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface TimeSyncAMSend<TRadio, uint32_t> as TimeSyncAMSendRadio[am_id_t id];
+               interface TimeSyncPacket<TRadio, uint32_t> as TimeSyncPacketRadio;
+
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+               interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[am_id_t id];
+               interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
+       }
+}
+
+implementation
+{
+       components RF212DriverLayerC, RF212ActiveMessageC, TimeSyncMessageLayerC;
+  
+       SplitControl    = RF212ActiveMessageC;
+       AMPacket        = TimeSyncMessageLayerC;
+       Receive         = TimeSyncMessageLayerC.Receive;
+       Snoop           = TimeSyncMessageLayerC.Snoop;
+       Packet          = TimeSyncMessageLayerC;
+
+       PacketTimeStampRadio    = RF212ActiveMessageC;
+       TimeSyncAMSendRadio     = TimeSyncMessageLayerC;
+       TimeSyncPacketRadio     = TimeSyncMessageLayerC;
+
+       PacketTimeStampMilli    = RF212ActiveMessageC;
+       TimeSyncAMSendMilli     = TimeSyncMessageLayerC;
+       TimeSyncPacketMilli     = TimeSyncMessageLayerC;
+
+       TimeSyncMessageLayerC.PacketTimeStampRadio -> RF212ActiveMessageC;
+       TimeSyncMessageLayerC.PacketTimeStampMilli -> RF212ActiveMessageC;
+
+       TimeSyncMessageLayerC.LocalTimeRadio -> RF212DriverLayerC;
+       TimeSyncMessageLayerC.PacketTimeSyncOffset -> RF212DriverLayerC.PacketTimeSyncOffset;
+}
diff --git a/tos/chips/rf2xx/rf230/README b/tos/chips/rf2xx/rf230/README
new file mode 100644 (file)
index 0000000..cb4e9d9
--- /dev/null
@@ -0,0 +1,56 @@
+
+The RF230 radio driver has the following configuration options. Some of 
+these are set in the platforms/xxx/chips/rf230/RadioConfig.h header file, 
+see the IRIS platform for example, others can be set in your Makefile.
+
+RF230_TRX_CTRL_0_VALUE:
+
+This is the value of the TRX_CTRL_0 register which configures the output 
+pin currents and the CLKM clock:
+
+RF230_CCA_MODE_VALUE:
+
+This is the default value of the CCA_MODE field in the PHY_CC_CCA register
+which is used to configure the default mode of the clear channel assesment
+
+RF230_CCA_THRES_VALUE:
+
+This is the value of the CCA_THRES register that controls the energy levels 
+used for clear channel assesment.
+
+RF230_DEF_RFPOWER:
+
+This is the default value of the TX_PWR field of the PHY_TX_PWR register. 
+This can be cahanged via the PacketTransmitPower interface provided by the 
+RF230ActiveMessageC.
+
+RF230_DEF_CHANNEL:
+
+This is the default value of the CHANNEL field of the PHY_CC_CCA register.
+This can be cahanged via the RadioChannel interface provided by the 
+RF230ActiveMessageC.
+
+RF230_CRCBYTE_COMMAND:
+
+This is the command used to calculate the CRC for the RF230 chip, since it 
+does not support hardware CRC checking (in rev A).
+
+RF230_SLOW_SPI:
+
+Define this if your microcontroller SPI interface is slower then 250 
+kbit/s. This delays the start of transmission to when the header is at 
+least uploaded into the TX buffer.
+
+RF230_RSSI_ENERGY:
+
+If you define this, then the content of the RF230_PHY_ED_LEVEL is queried 
+instead of the RSSI value for eahc incoming message. This value can be 
+obtained with the PacketRSSI interface.
+
+RF230_HARDWARE_ACK
+
+If you define this, then the radio stack will use hardware acknowledgements
+and address recognition. In particular, you will not be able to snoop on
+onther messages. The load on the CPU is reduced, you should be able to send
+more messages under heavy load. Note, that the PacketRSSI interface will
+return the energy level (and not the rssi value) of received packet.
diff --git a/tos/chips/rf2xx/rf230/RF230ActiveMessageC.nc b/tos/chips/rf2xx/rf230/RF230ActiveMessageC.nc
new file mode 100644 (file)
index 0000000..38f8d3d
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+#ifdef IEEE154FRAMES_ENABLED
+#error "You cannot use ActiveMessageC with IEEE154FRAMES_ENABLED defined"
+#endif
+
+configuration RF230ActiveMessageC
+{
+       provides 
+       {
+               interface SplitControl;
+
+               interface AMSend[am_id_t id];
+               interface Receive[am_id_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface SendNotifier[am_id_t id];
+
+               interface Packet;
+               interface AMPacket;
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+#ifdef PACKET_LINK
+               interface PacketLink;
+#endif
+
+               interface RadioChannel;
+
+               interface PacketField<uint8_t> as PacketLinkQuality;
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF230RadioC;
+
+       SplitControl = RF230RadioC;
+
+       AMSend = RF230RadioC;
+       Receive = RF230RadioC.Receive;
+       Snoop = RF230RadioC.Snoop;
+       SendNotifier = RF230RadioC;
+
+       Packet = RF230RadioC.PacketForActiveMessage;
+       AMPacket = RF230RadioC;
+
+       PacketAcknowledgements = RF230RadioC;
+       LowPowerListening = RF230RadioC;
+#ifdef PACKET_LINK
+       PacketLink = RF230RadioC;
+#endif
+
+       RadioChannel = RF230RadioC;
+
+       PacketLinkQuality = RF230RadioC.PacketLinkQuality;
+       PacketTransmitPower = RF230RadioC.PacketTransmitPower;
+       PacketRSSI = RF230RadioC.PacketRSSI;
+
+       LocalTimeRadio = RF230RadioC;
+       PacketTimeStampMilli = RF230RadioC;
+       PacketTimeStampRadio = RF230RadioC;
+}
diff --git a/tos/chips/rf2xx/rf230/RF230DriverConfig.nc b/tos/chips/rf2xx/rf230/RF230DriverConfig.nc
new file mode 100644 (file)
index 0000000..f67786d
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface RF230DriverConfig
+{
+       /**
+        * Returns the length of a dummy header to align the payload properly.
+        */
+       async command uint8_t headerLength(message_t* msg);
+
+       /**
+        * Returns the maximum length of the PHY payload including the 
+        * length field but not counting the FCF field.
+        */
+       async command uint8_t maxPayloadLength();
+
+       /**
+        * Returns the length of a dummy metadata section to align the
+        * metadata section properly.
+        */
+       async command uint8_t metadataLength(message_t* msg);
+
+       /**
+        * Gets the number of bytes we should read before the RadioReceive.header
+        * event is fired. If the length of the packet is less than this amount, 
+        * then that event is fired earlier. The header length must be at least one.
+        */
+       async command uint8_t headerPreloadLength();
+
+       /**
+        * Returns TRUE if before sending this message we should make sure that
+        * the channel is clear via a very basic (and quick) RSSI check.
+        */
+       async command bool requiresRssiCca(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/rf230/RF230DriverHwAckC.nc b/tos/chips/rf2xx/rf230/RF230DriverHwAckC.nc
new file mode 100644 (file)
index 0000000..271d322
--- /dev/null
@@ -0,0 +1,126 @@
+/*
+* Copyright (c) 2009, University of Szeged
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+*
+* - Redistributions of source code must retain the above copyright
+* notice, this list of conditions and the following disclaimer.
+* - Redistributions in binary form must reproduce the above
+* copyright notice, this list of conditions and the following
+* disclaimer in the documentation and/or other materials provided
+* with the distribution.
+* - Neither the name of University of Szeged nor the names of its
+* contributors may be used to endorse or promote products derived
+* from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+* OF THE POSSIBILITY OF SUCH DAMAGE.
+*
+* Author: Miklos Maroti
+*/
+
+#include <RadioConfig.h>
+#include <RF230DriverLayer.h>
+
+configuration RF230DriverHwAckC
+{
+       provides
+       {
+               interface RadioState;
+               interface RadioSend;
+               interface RadioReceive;
+               interface RadioCCA;
+               interface RadioPacket;
+
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+               interface PacketField<uint8_t> as PacketTimeSyncOffset;
+               interface PacketField<uint8_t> as PacketLinkQuality;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+
+               interface PacketAcknowledgements;
+       }
+
+       uses
+       {
+               interface RF230DriverConfig as Config;
+               interface PacketTimeStamp<TRadio, uint32_t>;
+               interface Ieee154PacketLayer;
+       }
+}
+
+implementation
+{
+       components RF230DriverHwAckP, HplRF230C, BusyWaitMicroC, TaskletC, MainC, RadioAlarmC;
+
+       RadioState = RF230DriverHwAckP;
+       RadioSend = RF230DriverHwAckP;
+       RadioReceive = RF230DriverHwAckP;
+       RadioCCA = RF230DriverHwAckP;
+       RadioPacket = RF230DriverHwAckP;
+
+       LocalTimeRadio = HplRF230C;
+
+       Config = RF230DriverHwAckP;
+
+       PacketTransmitPower = RF230DriverHwAckP.PacketTransmitPower;
+       components new MetadataFlagC() as TransmitPowerFlagC;
+       RF230DriverHwAckP.TransmitPowerFlag -> TransmitPowerFlagC;
+
+       PacketRSSI = RF230DriverHwAckP.PacketRSSI;
+       components new MetadataFlagC() as RSSIFlagC;
+       RF230DriverHwAckP.RSSIFlag -> RSSIFlagC;
+
+       PacketTimeSyncOffset = RF230DriverHwAckP.PacketTimeSyncOffset;
+       components new MetadataFlagC() as TimeSyncFlagC;
+       RF230DriverHwAckP.TimeSyncFlag -> TimeSyncFlagC;
+
+       PacketLinkQuality = RF230DriverHwAckP.PacketLinkQuality;
+       PacketTimeStamp = RF230DriverHwAckP.PacketTimeStamp;
+
+       RF230DriverHwAckP.LocalTime -> HplRF230C;
+
+       RF230DriverHwAckP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
+       RadioAlarmC.Alarm -> HplRF230C.Alarm;
+
+       RF230DriverHwAckP.SELN -> HplRF230C.SELN;
+       RF230DriverHwAckP.SpiResource -> HplRF230C.SpiResource;
+       RF230DriverHwAckP.FastSpiByte -> HplRF230C;
+
+       RF230DriverHwAckP.SLP_TR -> HplRF230C.SLP_TR;
+       RF230DriverHwAckP.RSTN -> HplRF230C.RSTN;
+
+       RF230DriverHwAckP.IRQ -> HplRF230C.IRQ;
+       RF230DriverHwAckP.Tasklet -> TaskletC;
+       RF230DriverHwAckP.BusyWait -> BusyWaitMicroC;
+
+#ifdef RADIO_DEBUG
+       components DiagMsgC;
+       RF230DriverHwAckP.DiagMsg -> DiagMsgC;
+#endif
+
+       MainC.SoftwareInit -> RF230DriverHwAckP.SoftwareInit;
+
+       components RealMainP;
+       RealMainP.PlatformInit -> RF230DriverHwAckP.PlatformInit;
+
+       components new MetadataFlagC(), ActiveMessageAddressC;
+       RF230DriverHwAckP.AckReceivedFlag -> MetadataFlagC;
+       RF230DriverHwAckP.ActiveMessageAddress -> ActiveMessageAddressC;
+       PacketAcknowledgements = RF230DriverHwAckP;
+       Ieee154PacketLayer = RF230DriverHwAckP;
+}
diff --git a/tos/chips/rf2xx/rf230/RF230DriverHwAckP.nc b/tos/chips/rf2xx/rf230/RF230DriverHwAckP.nc
new file mode 100644 (file)
index 0000000..790e79e
--- /dev/null
@@ -0,0 +1,1019 @@
+/*
+* Copyright (c) 2009, University of Szeged
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+*
+* - Redistributions of source code must retain the above copyright
+* notice, this list of conditions and the following disclaimer.
+* - Redistributions in binary form must reproduce the above
+* copyright notice, this list of conditions and the following
+* disclaimer in the documentation and/or other materials provided
+* with the distribution.
+* - Neither the name of University of Szeged nor the names of its
+* contributors may be used to endorse or promote products derived
+* from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+* OF THE POSSIBILITY OF SUCH DAMAGE.
+*
+* Author: Miklos Maroti
+*/
+
+#include <RF230DriverLayer.h>
+#include <Tasklet.h>
+#include <RadioAssert.h>
+#include <TimeSyncMessageLayer.h>
+#include <RadioConfig.h>
+
+module RF230DriverHwAckP
+{
+       provides
+       {
+               interface Init as PlatformInit @exactlyonce();
+               interface Init as SoftwareInit @exactlyonce();
+
+               interface RadioState;
+               interface RadioSend;
+               interface RadioReceive;
+               interface RadioCCA;
+               interface RadioPacket;
+
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+               interface PacketField<uint8_t> as PacketTimeSyncOffset;
+               interface PacketField<uint8_t> as PacketLinkQuality;
+
+               interface PacketAcknowledgements;
+       }
+
+       uses
+       {
+               interface GeneralIO as SELN;
+               interface Resource as SpiResource;
+
+               interface FastSpiByte;
+
+               interface GeneralIO as SLP_TR;
+               interface GeneralIO as RSTN;
+
+               interface GpioCapture as IRQ;
+
+               interface BusyWait<TMicro, uint16_t>;
+               interface LocalTime<TRadio>;
+
+               interface RF230DriverConfig as Config;
+
+               interface PacketFlag as TransmitPowerFlag;
+               interface PacketFlag as RSSIFlag;
+               interface PacketFlag as TimeSyncFlag;
+
+               interface PacketTimeStamp<TRadio, uint32_t>;
+
+               interface Tasklet;
+               interface RadioAlarm;
+
+               interface PacketFlag as AckReceivedFlag;
+               interface Ieee154PacketLayer;
+               interface ActiveMessageAddress;
+
+#ifdef RADIO_DEBUG
+               interface DiagMsg;
+#endif
+       }
+}
+
+implementation
+{
+       rf230_header_t* getHeader(message_t* msg)
+       {
+               return ((void*)msg) + call Config.headerLength(msg);
+       }
+
+       void* getPayload(message_t* msg)
+       {
+               return ((void*)msg) + call RadioPacket.headerLength(msg);
+       }
+
+       rf230_metadata_t* getMeta(message_t* msg)
+       {
+               return ((void*)msg) + sizeof(message_t) - call RadioPacket.metadataLength(msg);
+       }
+
+/*----------------- STATE -----------------*/
+
+       tasklet_norace uint8_t state;
+       enum
+       {
+               STATE_P_ON = 0,
+               STATE_SLEEP = 1,
+               STATE_SLEEP_2_TRX_OFF = 2,
+               STATE_TRX_OFF = 3,
+               STATE_TRX_OFF_2_RX_ON = 4,
+               STATE_RX_ON = 5,
+               STATE_BUSY_TX_2_RX_ON = 6,
+       };
+
+       tasklet_norace uint8_t cmd;
+       enum
+       {
+               CMD_NONE = 0,                   // the state machine has stopped
+               CMD_TURNOFF = 1,                // goto SLEEP state
+               CMD_STANDBY = 2,                // goto TRX_OFF state
+               CMD_TURNON = 3,                 // goto RX_ON state
+               CMD_TRANSMIT = 4,               // currently transmitting a message
+               CMD_CCA = 6,                    // performing clear chanel assesment
+               CMD_CHANNEL = 7,                // changing the channel
+               CMD_SIGNAL_DONE = 8,            // signal the end of the state transition
+               CMD_DOWNLOAD = 9,               // download the received message
+       };
+
+       norace bool radioIrq;
+
+       tasklet_norace uint8_t txPower;
+       tasklet_norace uint8_t channel;
+
+       tasklet_norace message_t* rxMsg;
+       message_t rxMsgBuffer;
+
+       uint16_t capturedTime;  // the current time when the last interrupt has occured
+
+/*----------------- REGISTER -----------------*/
+
+       inline void writeRegister(uint8_t reg, uint8_t value)
+       {
+               ASSERT( call SpiResource.isOwner() );
+               ASSERT( reg == (reg & RF230_CMD_REGISTER_MASK) );
+
+               call SELN.clr();
+               call FastSpiByte.splitWrite(RF230_CMD_REGISTER_WRITE | reg);
+               call FastSpiByte.splitReadWrite(value);
+               call FastSpiByte.splitRead();
+               call SELN.set();
+       }
+
+       inline uint8_t readRegister(uint8_t reg)
+       {
+               ASSERT( call SpiResource.isOwner() );
+               ASSERT( reg == (reg & RF230_CMD_REGISTER_MASK) );
+
+               call SELN.clr();
+               call FastSpiByte.splitWrite(RF230_CMD_REGISTER_READ | reg);
+               call FastSpiByte.splitReadWrite(0);
+               reg = call FastSpiByte.splitRead();
+               call SELN.set();
+
+               return reg;
+       }
+
+/*----------------- ALARM -----------------*/
+
+       enum
+       {
+               SLEEP_WAKEUP_TIME = (uint16_t)(880 * RADIO_ALARM_MICROSEC),
+               PLL_CALIBRATION_TIME = (uint16_t)(180 * RADIO_ALARM_MICROSEC),
+               CCA_REQUEST_TIME = (uint16_t)(140 * RADIO_ALARM_MICROSEC),
+
+               // 8 undocumented delay, 128 for CSMA, 16 for delay, 5*32 for preamble and SFD
+               TX_SFD_DELAY = (uint16_t)((8 + 128 + 16 + 5*32) * RADIO_ALARM_MICROSEC),
+               
+               // 32 for frame length, 16 for delay
+               RX_SFD_DELAY = (uint16_t)((32 + 16) * RADIO_ALARM_MICROSEC),
+       };
+
+       tasklet_async event void RadioAlarm.fired()
+       {
+               if( state == STATE_SLEEP_2_TRX_OFF )
+                       state = STATE_TRX_OFF;
+               else if( state == STATE_TRX_OFF_2_RX_ON )
+               {
+                       ASSERT( cmd == CMD_TURNON || cmd == CMD_CHANNEL );
+
+                       state = STATE_RX_ON;
+                       cmd = CMD_SIGNAL_DONE;
+               }
+               else if( cmd == CMD_CCA )
+               {
+                       uint8_t cca;
+
+                       ASSERT( state == STATE_RX_ON );
+
+                       cmd = CMD_NONE;
+                       cca = readRegister(RF230_TRX_STATUS);
+
+                       ASSERT( (cca & RF230_TRX_STATUS_MASK) == RF230_RX_AACK_ON );
+
+                       signal RadioCCA.done( (cca & RF230_CCA_DONE) ? ((cca & RF230_CCA_STATUS) ? SUCCESS : EBUSY) : FAIL );
+               }
+               else
+                       ASSERT(FALSE);
+
+               // make sure the rest of the command processing is called
+               call Tasklet.schedule();
+       }
+
+/*----------------- INIT -----------------*/
+
+       command error_t PlatformInit.init()
+       {
+               call SELN.makeOutput();
+               call SELN.set();
+               call SLP_TR.makeOutput();
+               call SLP_TR.clr();
+               call RSTN.makeOutput();
+               call RSTN.set();
+
+               rxMsg = &rxMsgBuffer;
+
+               return SUCCESS;
+       }
+
+       command error_t SoftwareInit.init()
+       {
+               // for powering up the radio
+               return call SpiResource.request();
+       }
+
+       void initRadio()
+       {
+               uint16_t temp;
+
+               call BusyWait.wait(510);
+
+               call RSTN.clr();
+               call SLP_TR.clr();
+               call BusyWait.wait(6);
+               call RSTN.set();
+
+               writeRegister(RF230_TRX_CTRL_0, RF230_TRX_CTRL_0_VALUE);
+               writeRegister(RF230_TRX_STATE, RF230_TRX_OFF);
+
+               call BusyWait.wait(510);
+
+               writeRegister(RF230_IRQ_MASK, RF230_IRQ_TRX_UR | RF230_IRQ_TRX_END );
+               writeRegister(RF230_CCA_THRES, RF230_CCA_THRES_VALUE);
+               writeRegister(RF230_PHY_TX_PWR, RF230_TX_AUTO_CRC_ON | (RF230_DEF_RFPOWER & RF230_TX_PWR_MASK));
+
+               txPower = RF230_DEF_RFPOWER & RF230_TX_PWR_MASK;
+               channel = RF230_DEF_CHANNEL & RF230_CHANNEL_MASK;
+               writeRegister(RF230_PHY_CC_CCA, RF230_CCA_MODE_VALUE | channel);
+
+               writeRegister(RF230_XAH_CTRL, 0);
+               writeRegister(RF230_CSMA_SEED_1, 0);
+
+               temp = call ActiveMessageAddress.amGroup();
+               writeRegister(RF230_PAN_ID_0, temp);
+               writeRegister(RF230_PAN_ID_1, temp >> 8);
+
+               call SLP_TR.set();
+               state = STATE_SLEEP;
+       }
+
+/*----------------- SPI -----------------*/
+
+       event void SpiResource.granted()
+       {
+               call SELN.makeOutput();
+               call SELN.set();
+
+               if( state == STATE_P_ON )
+               {
+                       initRadio();
+                       call SpiResource.release();
+               }
+               else
+                       call Tasklet.schedule();
+       }
+
+       bool isSpiAcquired()
+       {
+               if( call SpiResource.isOwner() )
+                       return TRUE;
+
+               if( call SpiResource.immediateRequest() == SUCCESS )
+               {
+                       call SELN.makeOutput();
+                       call SELN.set();
+
+                       return TRUE;
+               }
+
+               call SpiResource.request();
+               return FALSE;
+       }
+
+/*----------------- CHANNEL -----------------*/
+
+tasklet_async command uint8_t RadioState.getChannel()
+       {
+               return channel;
+       }
+
+       tasklet_async command error_t RadioState.setChannel(uint8_t c)
+       {
+               c &= RF230_CHANNEL_MASK;
+
+               if( cmd != CMD_NONE )
+                       return EBUSY;
+               else if( channel == c )
+                       return EALREADY;
+
+               channel = c;
+               cmd = CMD_CHANNEL;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+
+       inline void changeChannel()
+       {
+               ASSERT( cmd == CMD_CHANNEL );
+               ASSERT( state == STATE_SLEEP || state == STATE_TRX_OFF || state == STATE_RX_ON );
+
+               if( isSpiAcquired() && call RadioAlarm.isFree() )
+               {
+                       writeRegister(RF230_PHY_CC_CCA, RF230_CCA_MODE_VALUE | channel);
+
+                       if( state == STATE_RX_ON )
+                       {
+                               call RadioAlarm.wait(PLL_CALIBRATION_TIME);
+                               state = STATE_TRX_OFF_2_RX_ON;
+                       }
+                       else
+                               cmd = CMD_SIGNAL_DONE;
+               }
+       }
+
+/*----------------- TURN ON/OFF -----------------*/
+
+       inline void changeState()
+       {
+               if( (cmd == CMD_STANDBY || cmd == CMD_TURNON)
+                       && state == STATE_SLEEP && call RadioAlarm.isFree() )
+               {
+                       call SLP_TR.clr();
+
+                       call RadioAlarm.wait(SLEEP_WAKEUP_TIME);
+                       state = STATE_SLEEP_2_TRX_OFF;
+               }
+               else if( cmd == CMD_TURNON && state == STATE_TRX_OFF 
+                       && isSpiAcquired() && call RadioAlarm.isFree() )
+               {
+                       uint16_t temp;
+       
+                       ASSERT( ! radioIrq );
+
+                       readRegister(RF230_IRQ_STATUS); // clear the interrupt register
+                       call IRQ.captureRisingEdge();
+
+                       // setChannel was ignored in SLEEP because the SPI was not working, so do it here
+                       writeRegister(RF230_PHY_CC_CCA, RF230_CCA_MODE_VALUE | channel);
+
+                       temp = call ActiveMessageAddress.amAddress();
+                       writeRegister(RF230_SHORT_ADDR_0, temp);
+                       writeRegister(RF230_SHORT_ADDR_1, temp >> 8);
+
+                       call RadioAlarm.wait(PLL_CALIBRATION_TIME);
+                       writeRegister(RF230_TRX_STATE, RF230_RX_AACK_ON);
+                       state = STATE_TRX_OFF_2_RX_ON;
+               }
+               else if( (cmd == CMD_TURNOFF || cmd == CMD_STANDBY) 
+                       && state == STATE_RX_ON && isSpiAcquired() )
+               {
+                       writeRegister(RF230_TRX_STATE, RF230_FORCE_TRX_OFF);
+
+                       call IRQ.disable();
+                       radioIrq = FALSE;
+
+                       state = STATE_TRX_OFF;
+               }
+
+               if( cmd == CMD_TURNOFF && state == STATE_TRX_OFF )
+               {
+                       call SLP_TR.set();
+                       state = STATE_SLEEP;
+                       cmd = CMD_SIGNAL_DONE;
+               }
+               else if( cmd == CMD_STANDBY && state == STATE_TRX_OFF )
+                       cmd = CMD_SIGNAL_DONE;
+       }
+
+       tasklet_async command error_t RadioState.turnOff()
+       {
+               if( cmd != CMD_NONE )
+                       return EBUSY;
+               else if( state == STATE_SLEEP )
+                       return EALREADY;
+
+               cmd = CMD_TURNOFF;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+       
+       tasklet_async command error_t RadioState.standby()
+       {
+               if( cmd != CMD_NONE || (state == STATE_SLEEP && ! call RadioAlarm.isFree()) )
+                       return EBUSY;
+               else if( state == STATE_TRX_OFF )
+                       return EALREADY;
+
+               cmd = CMD_STANDBY;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+
+       tasklet_async command error_t RadioState.turnOn()
+       {
+               if( cmd != CMD_NONE || (state == STATE_SLEEP && ! call RadioAlarm.isFree()) )
+                       return EBUSY;
+               else if( state == STATE_RX_ON )
+                       return EALREADY;
+
+               cmd = CMD_TURNON;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+
+       default tasklet_async event void RadioState.done() { }
+
+       task void changeAddress()
+       {
+               call Tasklet.suspend();
+
+               if( isSpiAcquired() )
+               {
+                       uint16_t temp = call ActiveMessageAddress.amAddress();
+                       writeRegister(RF230_SHORT_ADDR_0, temp);
+                       writeRegister(RF230_SHORT_ADDR_1, temp >> 8);
+               }
+               else
+                       post changeAddress();
+
+               call Tasklet.resume();
+       }
+
+       async event void ActiveMessageAddress.changed()
+       {
+               post changeAddress();
+       }
+
+/*----------------- TRANSMIT -----------------*/
+
+       tasklet_norace message_t* txMsg;
+
+       tasklet_async command error_t RadioSend.send(message_t* msg)
+       {
+               uint16_t time;
+               uint8_t length;
+               uint8_t* data;
+               uint8_t header;
+               uint32_t time32;
+               void* timesync;
+
+               if( cmd != CMD_NONE || state != STATE_RX_ON || ! isSpiAcquired() || radioIrq )
+                       return EBUSY;
+
+               length = (call PacketTransmitPower.isSet(msg) ?
+                       call PacketTransmitPower.get(msg) : RF230_DEF_RFPOWER) & RF230_TX_PWR_MASK;
+
+               if( length != txPower )
+               {
+                       txPower = length;
+                       writeRegister(RF230_PHY_TX_PWR, RF230_TX_AUTO_CRC_ON | txPower);
+               }
+
+               writeRegister(RF230_TRX_STATE, RF230_TX_ARET_ON);
+
+               // do something useful, just to wait a little
+               time32 = call LocalTime.get();
+               timesync = call PacketTimeSyncOffset.isSet(msg) ? ((void*)msg) + call PacketTimeSyncOffset.get(msg) : 0;
+
+               // we have missed an incoming message in this short amount of time
+               if( (readRegister(RF230_TRX_STATUS) & RF230_TRX_STATUS_MASK) != RF230_TX_ARET_ON )
+               {
+                       ASSERT( (readRegister(RF230_TRX_STATUS) & RF230_TRX_STATUS_MASK) == RF230_BUSY_RX_AACK );
+
+                       writeRegister(RF230_TRX_STATE, RF230_RX_AACK_ON);
+                       return EBUSY;
+               }
+
+#ifndef RF230_SLOW_SPI
+               atomic
+               {
+                       call SLP_TR.set();
+                       time = call RadioAlarm.getNow();
+               }
+               call SLP_TR.clr();
+#endif
+
+               ASSERT( ! radioIrq );
+
+               call SELN.clr();
+               call FastSpiByte.splitWrite(RF230_CMD_FRAME_WRITE);
+
+               data = getPayload(msg);
+               length = getHeader(msg)->length;
+
+               // length | data[0] ... data[length-3] | automatically generated FCS
+               call FastSpiByte.splitReadWrite(length);
+
+               // the FCS is atomatically generated (2 bytes)
+               length -= 2;
+
+               header = call Config.headerPreloadLength();
+               if( header > length )
+                       header = length;
+
+               length -= header;
+
+               // first upload the header to gain some time
+               do {
+                       call FastSpiByte.splitReadWrite(*(data++));
+               }
+               while( --header != 0 );
+
+#ifdef RF230_SLOW_SPI
+               atomic
+               {
+                       call SLP_TR.set();
+                       time = call RadioAlarm.getNow();
+               }
+               call SLP_TR.clr();
+#endif
+
+               time32 += (int16_t)(time + TX_SFD_DELAY) - (int16_t)(time32);
+
+               if( timesync != 0 )
+                       *(timesync_relative_t*)timesync = (*(timesync_absolute_t*)timesync) - time32;
+
+               while( length-- != 0 )
+                       call FastSpiByte.splitReadWrite(*(data++));
+
+               // wait for the SPI transfer to finish
+               call FastSpiByte.splitRead();
+               call SELN.set();
+
+               /*
+                * There is a very small window (~1 microsecond) when the RF230 went 
+                * into PLL_ON state but was somehow not properly initialized because 
+                * of an incoming message and could not go into BUSY_TX. I think the
+                * radio can even receive a message, and generate a TRX_UR interrupt
+                * because of concurrent access, but that message probably cannot be
+                * recovered.
+                *
+                * TODO: this needs to be verified, and make sure that the chip is 
+                * not locked up in this case.
+                */
+
+               // go back to RX_ON state when finished
+               writeRegister(RF230_TRX_STATE, RF230_RX_AACK_ON);
+
+               if( timesync != 0 )
+                       *(timesync_absolute_t*)timesync = (*(timesync_relative_t*)timesync) + time32;
+
+               call PacketTimeStamp.set(msg, time32);
+
+#ifdef RADIO_DEBUG_MESSAGES
+               if( call DiagMsg.record() )
+               {
+                       length = getHeader(msg)->length;
+
+                       call DiagMsg.chr('t');
+                       call DiagMsg.uint32(call PacketTimeStamp.isValid(rxMsg) ? call PacketTimeStamp.timestamp(rxMsg) : 0);
+                       call DiagMsg.uint16(call RadioAlarm.getNow());
+                       call DiagMsg.int8(length);
+                       call DiagMsg.hex8s(getPayload(msg), length - 2);
+                       call DiagMsg.send();
+               }
+#endif
+
+               // wait for the TRX_END interrupt
+               txMsg = msg;
+               state = STATE_BUSY_TX_2_RX_ON;
+               cmd = CMD_TRANSMIT;
+
+               return SUCCESS;
+       }
+
+       default tasklet_async event void RadioSend.sendDone(error_t error) { }
+       default tasklet_async event void RadioSend.ready() { }
+
+/*----------------- CCA -----------------*/
+
+       tasklet_async command error_t RadioCCA.request()
+       {
+               if( cmd != CMD_NONE || state != STATE_RX_ON || ! isSpiAcquired() || ! call RadioAlarm.isFree() )
+                       return EBUSY;
+
+               // see Errata B7 of the datasheet
+               // writeRegister(RF230_TRX_STATE, RF230_PLL_ON);
+               // writeRegister(RF230_TRX_STATE, RF230_RX_AACK_ON);
+
+               writeRegister(RF230_PHY_CC_CCA, RF230_CCA_REQUEST | RF230_CCA_MODE_VALUE | channel);
+               call RadioAlarm.wait(CCA_REQUEST_TIME);
+               cmd = CMD_CCA;
+               
+               return SUCCESS;
+       }
+
+       default tasklet_async event void RadioCCA.done(error_t error) { }
+
+/*----------------- RECEIVE -----------------*/
+
+       inline void downloadMessage()
+       {
+               uint8_t length;
+               bool crcValid = FALSE;
+
+               call SELN.clr();
+               call FastSpiByte.write(RF230_CMD_FRAME_READ);
+
+               // read the length byte
+               length = call FastSpiByte.write(0);
+
+               // if correct length
+               if( length >= 3 && length <= call RadioPacket.maxPayloadLength() + 2 )
+               {
+                       uint8_t read;
+                       uint8_t* data;
+
+                       // initiate the reading
+                       call FastSpiByte.splitWrite(0);
+
+                       data = getPayload(rxMsg);
+                       getHeader(rxMsg)->length = length;
+
+                       // we do not store the CRC field
+                       length -= 2;
+
+                       read = call Config.headerPreloadLength();
+                       if( length < read )
+                               read = length;
+
+                       length -= read;
+
+                       do {
+                               *(data++) = call FastSpiByte.splitReadWrite(0);
+                       }
+                       while( --read != 0  );
+
+                       if( signal RadioReceive.header(rxMsg) )
+                       {
+                               while( length-- != 0 )
+                                       *(data++) = call FastSpiByte.splitReadWrite(0);
+
+                               call FastSpiByte.splitReadWrite(0);     // two CRC bytes
+                               call FastSpiByte.splitReadWrite(0);
+
+                               call PacketLinkQuality.set(rxMsg, call FastSpiByte.splitRead());
+
+                               // we should have no other incoming message or buffer underflow
+                               crcValid = ! radioIrq;
+                       }
+               }
+
+               call SELN.set();
+
+               if( crcValid && call PacketTimeStamp.isValid(rxMsg) )
+               {
+                       uint32_t time32 = call PacketTimeStamp.timestamp(rxMsg);
+                       length = getHeader(rxMsg)->length;
+
+/*
+ * If you hate floating point arithmetics and do not care of up to 400 microsecond time stamping errors,
+ * then define RF230_HWACK_SLOPPY_TIMESTAMP, which will be significantly faster.
+ */
+#ifdef RF230_HWACK_SLOPPY_TIMESTAMP
+                       time32 -= (uint16_t)(RX_SFD_DELAY) + ((uint16_t)(length) << (RADIO_ALARM_MILLI_EXP - 5));
+#else
+                       time32 -= (uint16_t)(RX_SFD_DELAY) + (uint16_t)(32.0 * RADIO_ALARM_MICROSEC * (uint16_t)length);
+#endif
+
+                       call PacketTimeStamp.set(rxMsg, time32);
+               }
+
+#ifdef RADIO_DEBUG_MESSAGES
+               if( call DiagMsg.record() )
+               {
+                       length = getHeader(rxMsg)->length;
+
+                       call DiagMsg.chr('r');
+                       call DiagMsg.uint32(call PacketTimeStamp.isValid(rxMsg) ? call PacketTimeStamp.timestamp(rxMsg) : 0);
+                       call DiagMsg.uint16(call RadioAlarm.getNow());
+                       call DiagMsg.int8(crcValid ? length : -length);
+                       call DiagMsg.hex8s(getPayload(rxMsg), length - 2);
+                       call DiagMsg.int8(call PacketRSSI.isSet(rxMsg) ? call PacketRSSI.get(rxMsg) : -1);
+                       call DiagMsg.uint8(call PacketLinkQuality.isSet(rxMsg) ? call PacketLinkQuality.get(rxMsg) : 0);
+                       call DiagMsg.send();
+               }
+#endif
+
+               state = STATE_RX_ON;
+               cmd = CMD_NONE;
+
+               // signal only if it has passed the CRC check
+               if( crcValid )
+                       rxMsg = signal RadioReceive.receive(rxMsg);
+       }
+
+/*----------------- IRQ -----------------*/
+
+       async event void IRQ.captured(uint16_t time)
+       {
+               ASSERT( ! radioIrq );
+
+               atomic
+               {
+                       capturedTime = time;
+                       radioIrq = TRUE;
+               }
+
+               call Tasklet.schedule();
+       }
+
+       void serviceRadio()
+       {
+               if( isSpiAcquired() )
+               {
+                       uint16_t time;
+                       uint32_t time32;
+                       uint8_t irq;
+                       uint8_t temp;
+                       
+                       atomic time = capturedTime;
+                       radioIrq = FALSE;
+                       irq = readRegister(RF230_IRQ_STATUS);
+
+#ifdef RADIO_DEBUG
+                       // TODO: handle this interrupt
+                       if( irq & RF230_IRQ_TRX_UR )
+                       {
+                               if( call DiagMsg.record() )
+                               {
+                                       call DiagMsg.str("assert ur");
+                                       call DiagMsg.uint16(call RadioAlarm.getNow());
+                                       call DiagMsg.hex8(readRegister(RF230_TRX_STATUS));
+                                       call DiagMsg.hex8(readRegister(RF230_TRX_STATE));
+                                       call DiagMsg.hex8(irq);
+                                       call DiagMsg.uint8(state);
+                                       call DiagMsg.uint8(cmd);
+                                       call DiagMsg.send();
+                               }
+                       }
+#endif
+
+                       if( irq & RF230_IRQ_TRX_END )
+                       {
+                               if( cmd == CMD_TRANSMIT )
+                               {
+                                       ASSERT( state == STATE_BUSY_TX_2_RX_ON );
+
+                                       temp = readRegister(RF230_TRX_STATE) & RF230_TRAC_STATUS_MASK;
+
+                                       if( call Ieee154PacketLayer.getAckRequired(txMsg) )
+                                               call AckReceivedFlag.setValue(txMsg, temp != RF230_TRAC_NO_ACK);
+
+                                       state = STATE_RX_ON;
+                                       cmd = CMD_NONE;
+
+                                       signal RadioSend.sendDone(temp != RF230_TRAC_CHANNEL_ACCESS_FAILURE ? SUCCESS : EBUSY);
+
+                                       // TODO: we could have missed a received message
+                                       ASSERT( ! (irq & RF230_IRQ_RX_START) );
+                               }
+                               else if( cmd == CMD_NONE )
+                               {
+                                       ASSERT( state == STATE_RX_ON );
+
+                                       if( irq == RF230_IRQ_TRX_END )
+                                       {
+                                               call PacketRSSI.set(rxMsg, readRegister(RF230_PHY_ED_LEVEL));
+
+                                               // TODO: compensate for packet transmission time when downloading
+                                               time32 = call LocalTime.get();
+                                               time32 += (int16_t)(time) - (int16_t)(time32);
+                                               call PacketTimeStamp.set(rxMsg, time32);
+                                       }
+                                       else
+                                       {
+                                               call PacketRSSI.clear(rxMsg);
+                                               call PacketTimeStamp.clear(rxMsg);
+                                       }
+
+                                       cmd = CMD_DOWNLOAD;
+                               }
+                               else
+                                       ASSERT(FALSE);
+                       }
+               }
+       }
+
+       default tasklet_async event bool RadioReceive.header(message_t* msg)
+       {
+               return TRUE;
+       }
+
+       default tasklet_async event message_t* RadioReceive.receive(message_t* msg)
+       {
+               return msg;
+       }
+
+/*----------------- TASKLET -----------------*/
+
+       tasklet_async event void Tasklet.run()
+       {
+               if( radioIrq )
+                       serviceRadio();
+
+               if( cmd != CMD_NONE )
+               {
+                       if( cmd == CMD_DOWNLOAD )
+                               downloadMessage();
+                       else if( CMD_TURNOFF <= cmd && cmd <= CMD_TURNON )
+                               changeState();
+                       else if( cmd == CMD_CHANNEL )
+                               changeChannel();
+                       
+                       if( cmd == CMD_SIGNAL_DONE )
+                       {
+                               cmd = CMD_NONE;
+                               signal RadioState.done();
+                       }
+               }
+
+               if( cmd == CMD_NONE && state == STATE_RX_ON && ! radioIrq )
+                       signal RadioSend.ready();
+
+               if( cmd == CMD_NONE )
+                       call SpiResource.release();
+       }
+
+/*----------------- RadioPacket -----------------*/
+       
+       async command uint8_t RadioPacket.headerLength(message_t* msg)
+       {
+               return call Config.headerLength(msg) + sizeof(rf230_header_t);
+       }
+
+       async command uint8_t RadioPacket.payloadLength(message_t* msg)
+       {
+               return getHeader(msg)->length - 2;
+       }
+
+       async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               ASSERT( 1 <= length && length <= 125 );
+               ASSERT( call RadioPacket.headerLength(msg) + length + call RadioPacket.metadataLength(msg) <= sizeof(message_t) );
+
+               // we add the length of the CRC, which is automatically generated
+               getHeader(msg)->length = length + 2;
+       }
+
+       async command uint8_t RadioPacket.maxPayloadLength()
+       {
+               ASSERT( call Config.maxPayloadLength() <= 125 );
+
+               return call Config.maxPayloadLength() - sizeof(rf230_header_t);
+       }
+
+       async command uint8_t RadioPacket.metadataLength(message_t* msg)
+       {
+               return call Config.metadataLength(msg) + sizeof(rf230_metadata_t);
+       }
+
+       async command void RadioPacket.clear(message_t* msg)
+       {
+               // all flags are automatically cleared
+       }
+
+/*----------------- PacketTransmitPower -----------------*/
+
+       async command bool PacketTransmitPower.isSet(message_t* msg)
+       {
+               return call TransmitPowerFlag.get(msg);
+       }
+
+       async command uint8_t PacketTransmitPower.get(message_t* msg)
+       {
+               return getMeta(msg)->power;
+       }
+
+       async command void PacketTransmitPower.clear(message_t* msg)
+       {
+               call TransmitPowerFlag.clear(msg);
+       }
+
+       async command void PacketTransmitPower.set(message_t* msg, uint8_t value)
+       {
+               call TransmitPowerFlag.set(msg);
+               getMeta(msg)->power = value;
+       }
+
+/*----------------- PacketRSSI -----------------*/
+
+       async command bool PacketRSSI.isSet(message_t* msg)
+       {
+               return call RSSIFlag.get(msg);
+       }
+
+       async command uint8_t PacketRSSI.get(message_t* msg)
+       {
+               return getMeta(msg)->rssi;
+       }
+
+       async command void PacketRSSI.clear(message_t* msg)
+       {
+               call RSSIFlag.clear(msg);
+       }
+
+       async command void PacketRSSI.set(message_t* msg, uint8_t value)
+       {
+               // just to be safe if the user fails to clear the packet
+               call TransmitPowerFlag.clear(msg);
+
+               call RSSIFlag.set(msg);
+               getMeta(msg)->rssi = value;
+       }
+
+/*----------------- PacketTimeSyncOffset -----------------*/
+
+       async command bool PacketTimeSyncOffset.isSet(message_t* msg)
+       {
+               return call TimeSyncFlag.get(msg);
+       }
+
+       async command uint8_t PacketTimeSyncOffset.get(message_t* msg)
+       {
+               return call RadioPacket.headerLength(msg) + call RadioPacket.payloadLength(msg) - sizeof(timesync_absolute_t);
+       }
+
+       async command void PacketTimeSyncOffset.clear(message_t* msg)
+       {
+               call TimeSyncFlag.clear(msg);
+       }
+
+       async command void PacketTimeSyncOffset.set(message_t* msg, uint8_t value)
+       {
+               // we do not store the value, the time sync field is always the last 4 bytes
+               ASSERT( call PacketTimeSyncOffset.get(msg) == value );
+
+               call TimeSyncFlag.set(msg);
+       }
+
+/*----------------- PacketLinkQuality -----------------*/
+
+       async command bool PacketLinkQuality.isSet(message_t* msg)
+       {
+               return TRUE;
+       }
+
+       async command uint8_t PacketLinkQuality.get(message_t* msg)
+       {
+               return getMeta(msg)->lqi;
+       }
+
+       async command void PacketLinkQuality.clear(message_t* msg)
+       {
+       }
+
+       async command void PacketLinkQuality.set(message_t* msg, uint8_t value)
+       {
+               getMeta(msg)->lqi = value;
+       }
+
+/*----------------- PacketAcknowledgements -----------------*/
+
+       async command error_t PacketAcknowledgements.requestAck(message_t* msg)
+       {
+               call Ieee154PacketLayer.setAckRequired(msg, TRUE);
+
+               return SUCCESS;
+       }
+
+       async command error_t PacketAcknowledgements.noAck(message_t* msg)
+       {
+               call Ieee154PacketLayer.setAckRequired(msg, FALSE);
+
+               return SUCCESS;
+       }
+
+       async command bool PacketAcknowledgements.wasAcked(message_t* msg)
+       {
+               return call AckReceivedFlag.get(msg);
+       }
+}
diff --git a/tos/chips/rf2xx/rf230/RF230DriverLayer.h b/tos/chips/rf2xx/rf230/RF230DriverLayer.h
new file mode 100644 (file)
index 0000000..342748f
--- /dev/null
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __RF230DRIVERLAYER_H__
+#define __RF230DRIVERLAYER_H__
+
+typedef nx_struct rf230_header_t
+{
+       nxle_uint8_t length;
+} rf230_header_t;
+
+typedef struct rf230_metadata_t
+{
+       uint8_t lqi;
+       union
+       {
+               uint8_t power;
+               uint8_t rssi;
+       };
+} rf230_metadata_t;
+
+enum rf230_registers_enum
+{
+       RF230_TRX_STATUS = 0x01,
+       RF230_TRX_STATE = 0x02,
+       RF230_TRX_CTRL_0 = 0x03,
+       RF230_PHY_TX_PWR = 0x05,
+       RF230_PHY_RSSI = 0x06,
+       RF230_PHY_ED_LEVEL = 0x07,
+       RF230_PHY_CC_CCA = 0x08,
+       RF230_CCA_THRES = 0x09,
+       RF230_IRQ_MASK = 0x0E,
+       RF230_IRQ_STATUS = 0x0F,
+       RF230_VREG_CTRL = 0x10,
+       RF230_BATMON = 0x11,
+       RF230_XOSC_CTRL = 0x12,
+       RF230_PLL_CF = 0x1A,
+       RF230_PLL_DCU = 0x1B,
+       RF230_PART_NUM = 0x1C,
+       RF230_VERSION_NUM = 0x1D,
+       RF230_MAN_ID_0 = 0x1E,
+       RF230_MAN_ID_1 = 0x1F,
+       RF230_SHORT_ADDR_0 = 0x20,
+       RF230_SHORT_ADDR_1 = 0x21,
+       RF230_PAN_ID_0 = 0x22,
+       RF230_PAN_ID_1 = 0x23,
+       RF230_IEEE_ADDR_0 = 0x24,
+       RF230_IEEE_ADDR_1 = 0x25,
+       RF230_IEEE_ADDR_2 = 0x26,
+       RF230_IEEE_ADDR_3 = 0x27,
+       RF230_IEEE_ADDR_4 = 0x28,
+       RF230_IEEE_ADDR_5 = 0x29,
+       RF230_IEEE_ADDR_6 = 0x2A,
+       RF230_IEEE_ADDR_7 = 0x2B,
+       RF230_XAH_CTRL = 0x2C,
+       RF230_CSMA_SEED_0 = 0x2D,
+       RF230_CSMA_SEED_1 = 0x2E,
+};
+
+enum rf230_trx_register_enums
+{
+       RF230_CCA_DONE = 1 << 7,
+       RF230_CCA_STATUS = 1 << 6,
+       RF230_TRX_STATUS_MASK = 0x1F,
+       RF230_P_ON = 0,
+       RF230_BUSY_RX = 1,
+       RF230_BUSY_TX = 2,
+       RF230_RX_ON = 6,
+       RF230_TRX_OFF = 8,
+       RF230_PLL_ON = 9,
+       RF230_SLEEP = 15,
+       RF230_BUSY_RX_AACK = 17,
+       RF230_BUSR_TX_ARET = 18,
+       RF230_RX_AACK_ON = 22,
+       RF230_TX_ARET_ON = 25,
+       RF230_RX_ON_NOCLK = 28,
+       RF230_AACK_ON_NOCLK = 29,
+       RF230_BUSY_RX_AACK_NOCLK = 30,
+       RF230_STATE_TRANSITION_IN_PROGRESS = 31,
+       RF230_TRAC_STATUS_MASK = 0xE0,
+       RF230_TRAC_SUCCESS = 0,
+       RF230_TRAC_SUCCESS_DATA_PENDING = 1 << 5,
+       RF230_TRAC_CHANNEL_ACCESS_FAILURE = 3 << 5,
+       RF230_TRAC_NO_ACK = 5 << 5,
+       RF212_TRAC_INVALID = 7 << 5,
+       RF230_TRX_CMD_MASK = 0x1F,
+       RF230_NOP = 0,
+       RF230_TX_START = 2,
+       RF230_FORCE_TRX_OFF = 3,
+};
+
+enum rf230_phy_register_enums
+{
+       RF230_TX_AUTO_CRC_ON = 1 << 7,
+       RF230_TX_PWR_MASK = 0x0F,
+       RF230_RSSI_MASK = 0x1F,
+       RF230_CCA_REQUEST = 1 << 7,
+       RF230_CCA_MODE_0 = 0 << 5,
+       RF230_CCA_MODE_1 = 1 << 5,
+       RF230_CCA_MODE_2 = 2 << 5,
+       RF230_CCA_MODE_3 = 3 << 5,
+       RF230_CHANNEL_DEFAULT = 11,
+       RF230_CHANNEL_MASK = 0x1F,
+       RF230_CCA_CS_THRES_SHIFT = 4,
+       RF230_CCA_ED_THRES_SHIFT = 0,
+};
+
+enum rf230_irq_register_enums
+{
+       RF230_IRQ_BAT_LOW = 1 << 7,
+       RF230_IRQ_TRX_UR = 1 << 6,
+       RF230_IRQ_TRX_END = 1 << 3,
+       RF230_IRQ_RX_START = 1 << 2,
+       RF230_IRQ_PLL_UNLOCK = 1 << 1,
+       RF230_IRQ_PLL_LOCK = 1 << 0,
+};
+
+enum rf230_control_register_enums
+{
+       RF230_AVREG_EXT = 1 << 7,
+       RF230_AVDD_OK = 1 << 6,
+       RF230_DVREG_EXT = 1 << 3,
+       RF230_DVDD_OK = 1 << 2,
+       RF230_BATMON_OK = 1 << 5,
+       RF230_BATMON_VHR = 1 << 4,
+       RF230_BATMON_VTH_MASK = 0x0F,
+       RF230_XTAL_MODE_OFF = 0 << 4,
+       RF230_XTAL_MODE_EXTERNAL = 4 << 4,
+       RF230_XTAL_MODE_INTERNAL = 15 << 4,
+};
+
+enum rf230_pll_register_enums
+{
+       RF230_PLL_CF_START = 1 << 7,
+       RF230_PLL_DCU_START = 1 << 7,
+};
+
+enum rf230_spi_command_enums
+{
+       RF230_CMD_REGISTER_READ = 0x80,
+       RF230_CMD_REGISTER_WRITE = 0xC0,
+       RF230_CMD_REGISTER_MASK = 0x3F,
+       RF230_CMD_FRAME_READ = 0x20,
+       RF230_CMD_FRAME_WRITE = 0x60,
+       RF230_CMD_SRAM_READ = 0x00,
+       RF230_CMD_SRAM_WRITE = 0x40,
+};
+
+#endif//__RF230DRIVERLAYER_H__
diff --git a/tos/chips/rf2xx/rf230/RF230DriverLayerC.nc b/tos/chips/rf2xx/rf230/RF230DriverLayerC.nc
new file mode 100644 (file)
index 0000000..b1bf4dd
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+#include <RF230DriverLayer.h>
+
+configuration RF230DriverLayerC
+{
+       provides
+       {
+               interface RadioState;
+               interface RadioSend;
+               interface RadioReceive;
+               interface RadioCCA;
+               interface RadioPacket;
+
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+               interface PacketField<uint8_t> as PacketTimeSyncOffset;
+               interface PacketField<uint8_t> as PacketLinkQuality;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+       }
+
+       uses
+       {
+               interface RF230DriverConfig as Config;
+               interface PacketTimeStamp<TRadio, uint32_t>;
+       }
+}
+
+implementation
+{
+       components RF230DriverLayerP, HplRF230C, BusyWaitMicroC, TaskletC, MainC, RadioAlarmC;
+
+       RadioState = RF230DriverLayerP;
+       RadioSend = RF230DriverLayerP;
+       RadioReceive = RF230DriverLayerP;
+       RadioCCA = RF230DriverLayerP;
+       RadioPacket = RF230DriverLayerP;
+
+       LocalTimeRadio = HplRF230C;
+
+       Config = RF230DriverLayerP;
+
+       PacketTransmitPower = RF230DriverLayerP.PacketTransmitPower;
+       components new MetadataFlagC() as TransmitPowerFlagC;
+       RF230DriverLayerP.TransmitPowerFlag -> TransmitPowerFlagC;
+
+       PacketRSSI = RF230DriverLayerP.PacketRSSI;
+       components new MetadataFlagC() as RSSIFlagC;
+       RF230DriverLayerP.RSSIFlag -> RSSIFlagC;
+
+       PacketTimeSyncOffset = RF230DriverLayerP.PacketTimeSyncOffset;
+       components new MetadataFlagC() as TimeSyncFlagC;
+       RF230DriverLayerP.TimeSyncFlag -> TimeSyncFlagC;
+
+       PacketLinkQuality = RF230DriverLayerP.PacketLinkQuality;
+       PacketTimeStamp = RF230DriverLayerP.PacketTimeStamp;
+
+       RF230DriverLayerP.LocalTime -> HplRF230C;
+
+       RF230DriverLayerP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
+       RadioAlarmC.Alarm -> HplRF230C.Alarm;
+
+       RF230DriverLayerP.SELN -> HplRF230C.SELN;
+       RF230DriverLayerP.SpiResource -> HplRF230C.SpiResource;
+       RF230DriverLayerP.FastSpiByte -> HplRF230C;
+
+       RF230DriverLayerP.SLP_TR -> HplRF230C.SLP_TR;
+       RF230DriverLayerP.RSTN -> HplRF230C.RSTN;
+
+       RF230DriverLayerP.IRQ -> HplRF230C.IRQ;
+       RF230DriverLayerP.Tasklet -> TaskletC;
+       RF230DriverLayerP.BusyWait -> BusyWaitMicroC;
+
+#ifdef RADIO_DEBUG
+       components DiagMsgC;
+       RF230DriverLayerP.DiagMsg -> DiagMsgC;
+#endif
+
+       MainC.SoftwareInit -> RF230DriverLayerP.SoftwareInit;
+
+       components RealMainP;
+       RealMainP.PlatformInit -> RF230DriverLayerP.PlatformInit;
+}
diff --git a/tos/chips/rf2xx/rf230/RF230DriverLayerP.nc b/tos/chips/rf2xx/rf230/RF230DriverLayerP.nc
new file mode 100644 (file)
index 0000000..114ac13
--- /dev/null
@@ -0,0 +1,992 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RF230DriverLayer.h>
+#include <Tasklet.h>
+#include <RadioAssert.h>
+#include <TimeSyncMessageLayer.h>
+#include <RadioConfig.h>
+
+module RF230DriverLayerP
+{
+       provides
+       {
+               interface Init as PlatformInit @exactlyonce();
+               interface Init as SoftwareInit @exactlyonce();
+
+               interface RadioState;
+               interface RadioSend;
+               interface RadioReceive;
+               interface RadioCCA;
+               interface RadioPacket;
+
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+               interface PacketField<uint8_t> as PacketTimeSyncOffset;
+               interface PacketField<uint8_t> as PacketLinkQuality;
+       }
+
+       uses
+       {
+               interface GeneralIO as SELN;
+               interface Resource as SpiResource;
+
+               interface FastSpiByte;
+
+               interface GeneralIO as SLP_TR;
+               interface GeneralIO as RSTN;
+
+               interface GpioCapture as IRQ;
+
+               interface BusyWait<TMicro, uint16_t>;
+               interface LocalTime<TRadio>;
+
+               interface RF230DriverConfig as Config;
+
+               interface PacketFlag as TransmitPowerFlag;
+               interface PacketFlag as RSSIFlag;
+               interface PacketFlag as TimeSyncFlag;
+
+               interface PacketTimeStamp<TRadio, uint32_t>;
+
+               interface Tasklet;
+               interface RadioAlarm;
+
+#ifdef RADIO_DEBUG
+               interface DiagMsg;
+#endif
+       }
+}
+
+implementation
+{
+       rf230_header_t* getHeader(message_t* msg)
+       {
+               return ((void*)msg) + call Config.headerLength(msg);
+       }
+
+       void* getPayload(message_t* msg)
+       {
+               return ((void*)msg) + call RadioPacket.headerLength(msg);
+       }
+
+       rf230_metadata_t* getMeta(message_t* msg)
+       {
+               return ((void*)msg) + sizeof(message_t) - call RadioPacket.metadataLength(msg);
+       }
+
+/*----------------- STATE -----------------*/
+
+       tasklet_norace uint8_t state;
+       enum
+       {
+               STATE_P_ON = 0,
+               STATE_SLEEP = 1,
+               STATE_SLEEP_2_TRX_OFF = 2,
+               STATE_TRX_OFF = 3,
+               STATE_TRX_OFF_2_RX_ON = 4,
+               STATE_RX_ON = 5,
+               STATE_BUSY_TX_2_RX_ON = 6,
+               STATE_PLL_ON_2_RX_ON = 7,
+       };
+
+       tasklet_norace uint8_t cmd;
+       enum
+       {
+               CMD_NONE = 0,                   // the state machine has stopped
+               CMD_TURNOFF = 1,                // goto SLEEP state
+               CMD_STANDBY = 2,                // goto TRX_OFF state
+               CMD_TURNON = 3,                 // goto RX_ON state
+               CMD_TRANSMIT = 4,               // currently transmitting a message
+               CMD_RECEIVE = 5,                // currently receiving a message
+               CMD_CCA = 6,                    // performing clear chanel assesment
+               CMD_CHANNEL = 7,                // changing the channel
+               CMD_SIGNAL_DONE = 8,            // signal the end of the state transition
+               CMD_DOWNLOAD = 9,               // download the received message
+       };
+
+       norace bool radioIrq;
+
+       tasklet_norace uint8_t txPower;
+       tasklet_norace uint8_t channel;
+
+       tasklet_norace message_t* rxMsg;
+       message_t rxMsgBuffer;
+
+       uint16_t capturedTime;  // the current time when the last interrupt has occured
+
+       tasklet_norace uint8_t rssiClear;
+       tasklet_norace uint8_t rssiBusy;
+
+/*----------------- REGISTER -----------------*/
+
+       inline void writeRegister(uint8_t reg, uint8_t value)
+       {
+               ASSERT( call SpiResource.isOwner() );
+               ASSERT( reg == (reg & RF230_CMD_REGISTER_MASK) );
+
+               call SELN.clr();
+               call FastSpiByte.splitWrite(RF230_CMD_REGISTER_WRITE | reg);
+               call FastSpiByte.splitReadWrite(value);
+               call FastSpiByte.splitRead();
+               call SELN.set();
+       }
+
+       inline uint8_t readRegister(uint8_t reg)
+       {
+               ASSERT( call SpiResource.isOwner() );
+               ASSERT( reg == (reg & RF230_CMD_REGISTER_MASK) );
+
+               call SELN.clr();
+               call FastSpiByte.splitWrite(RF230_CMD_REGISTER_READ | reg);
+               call FastSpiByte.splitReadWrite(0);
+               reg = call FastSpiByte.splitRead();
+               call SELN.set();
+
+               return reg;
+       }
+
+/*----------------- ALARM -----------------*/
+
+       enum
+       {
+               SLEEP_WAKEUP_TIME = (uint16_t)(880 * RADIO_ALARM_MICROSEC),
+               CCA_REQUEST_TIME = (uint16_t)(140 * RADIO_ALARM_MICROSEC),
+
+               TX_SFD_DELAY = (uint16_t)(176 * RADIO_ALARM_MICROSEC),
+               RX_SFD_DELAY = (uint16_t)(8 * RADIO_ALARM_MICROSEC),
+       };
+
+       tasklet_async event void RadioAlarm.fired()
+       {
+               if( state == STATE_SLEEP_2_TRX_OFF )
+                       state = STATE_TRX_OFF;
+               else if( cmd == CMD_CCA )
+               {
+                       uint8_t cca;
+
+                       ASSERT( state == STATE_RX_ON );
+
+                       cmd = CMD_NONE;
+                       cca = readRegister(RF230_TRX_STATUS);
+
+                       ASSERT( (cca & RF230_TRX_STATUS_MASK) == RF230_RX_ON );
+
+                       signal RadioCCA.done( (cca & RF230_CCA_DONE) ? ((cca & RF230_CCA_STATUS) ? SUCCESS : EBUSY) : FAIL );
+               }
+               else
+                       ASSERT(FALSE);
+
+               // make sure the rest of the command processing is called
+               call Tasklet.schedule();
+       }
+
+/*----------------- INIT -----------------*/
+
+       command error_t PlatformInit.init()
+       {
+               call SELN.makeOutput();
+               call SELN.set();
+               call SLP_TR.makeOutput();
+               call SLP_TR.clr();
+               call RSTN.makeOutput();
+               call RSTN.set();
+
+               rxMsg = &rxMsgBuffer;
+
+               // these are just good approximates
+               rssiClear = 0;
+               rssiBusy = 90;
+
+               return SUCCESS;
+       }
+
+       command error_t SoftwareInit.init()
+       {
+               // for powering up the radio
+               return call SpiResource.request();
+       }
+
+       void initRadio()
+       {
+               call BusyWait.wait(510);
+
+               call RSTN.clr();
+               call SLP_TR.clr();
+               call BusyWait.wait(6);
+               call RSTN.set();
+
+               writeRegister(RF230_TRX_CTRL_0, RF230_TRX_CTRL_0_VALUE);
+               writeRegister(RF230_TRX_STATE, RF230_TRX_OFF);
+
+               call BusyWait.wait(510);
+
+               writeRegister(RF230_IRQ_MASK, RF230_IRQ_TRX_UR | RF230_IRQ_PLL_LOCK | RF230_IRQ_TRX_END | RF230_IRQ_RX_START);
+               writeRegister(RF230_CCA_THRES, RF230_CCA_THRES_VALUE);
+               writeRegister(RF230_PHY_TX_PWR, RF230_TX_AUTO_CRC_ON | (RF230_DEF_RFPOWER & RF230_TX_PWR_MASK));
+
+               txPower = RF230_DEF_RFPOWER & RF230_TX_PWR_MASK;
+               channel = RF230_DEF_CHANNEL & RF230_CHANNEL_MASK;
+               writeRegister(RF230_PHY_CC_CCA, RF230_CCA_MODE_VALUE | channel);
+
+               call SLP_TR.set();
+               state = STATE_SLEEP;
+       }
+
+/*----------------- SPI -----------------*/
+
+       event void SpiResource.granted()
+       {
+               call SELN.makeOutput();
+               call SELN.set();
+
+               if( state == STATE_P_ON )
+               {
+                       initRadio();
+                       call SpiResource.release();
+               }
+               else
+                       call Tasklet.schedule();
+       }
+
+       bool isSpiAcquired()
+       {
+               if( call SpiResource.isOwner() )
+                       return TRUE;
+
+               if( call SpiResource.immediateRequest() == SUCCESS )
+               {
+                       call SELN.makeOutput();
+                       call SELN.set();
+
+                       return TRUE;
+               }
+
+               call SpiResource.request();
+               return FALSE;
+       }
+
+/*----------------- CHANNEL -----------------*/
+
+       tasklet_async command uint8_t RadioState.getChannel()
+       {
+               return channel;
+       }
+
+       tasklet_async command error_t RadioState.setChannel(uint8_t c)
+       {
+               c &= RF230_CHANNEL_MASK;
+
+               if( cmd != CMD_NONE )
+                       return EBUSY;
+               else if( channel == c )
+                       return EALREADY;
+
+               channel = c;
+               cmd = CMD_CHANNEL;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+
+       inline void changeChannel()
+       {
+               ASSERT( cmd == CMD_CHANNEL );
+               ASSERT( state == STATE_SLEEP || state == STATE_TRX_OFF || state == STATE_RX_ON );
+
+               if( isSpiAcquired() )
+               {
+                       writeRegister(RF230_PHY_CC_CCA, RF230_CCA_MODE_VALUE | channel);
+
+                       if( state == STATE_RX_ON )
+                               state = STATE_TRX_OFF_2_RX_ON;
+                       else
+                               cmd = CMD_SIGNAL_DONE;
+               }
+       }
+
+/*----------------- TURN ON/OFF -----------------*/
+
+       inline void changeState()
+       {
+               if( (cmd == CMD_STANDBY || cmd == CMD_TURNON)
+                       && state == STATE_SLEEP && call RadioAlarm.isFree() )
+               {
+                       call SLP_TR.clr();
+
+                       call RadioAlarm.wait(SLEEP_WAKEUP_TIME);
+                       state = STATE_SLEEP_2_TRX_OFF;
+               }
+               else if( cmd == CMD_TURNON && state == STATE_TRX_OFF && isSpiAcquired() )
+               {
+                       ASSERT( ! radioIrq );
+
+                       readRegister(RF230_IRQ_STATUS); // clear the interrupt register
+                       call IRQ.captureRisingEdge();
+
+                       // setChannel was ignored in SLEEP because the SPI was not working, so do it here
+                       writeRegister(RF230_PHY_CC_CCA, RF230_CCA_MODE_VALUE | channel);
+
+                       writeRegister(RF230_TRX_STATE, RF230_RX_ON);
+                       state = STATE_TRX_OFF_2_RX_ON;
+               }
+               else if( (cmd == CMD_TURNOFF || cmd == CMD_STANDBY) 
+                       && state == STATE_RX_ON && isSpiAcquired() )
+               {
+                       writeRegister(RF230_TRX_STATE, RF230_FORCE_TRX_OFF);
+
+                       call IRQ.disable();
+                       radioIrq = FALSE;
+
+                       state = STATE_TRX_OFF;
+               }
+
+               if( cmd == CMD_TURNOFF && state == STATE_TRX_OFF )
+               {
+                       call SLP_TR.set();
+                       state = STATE_SLEEP;
+                       cmd = CMD_SIGNAL_DONE;
+               }
+               else if( cmd == CMD_STANDBY && state == STATE_TRX_OFF )
+                       cmd = CMD_SIGNAL_DONE;
+       }
+
+       tasklet_async command error_t RadioState.turnOff()
+       {
+               if( cmd != CMD_NONE )
+                       return EBUSY;
+               else if( state == STATE_SLEEP )
+                       return EALREADY;
+
+               cmd = CMD_TURNOFF;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+       
+       tasklet_async command error_t RadioState.standby()
+       {
+               if( cmd != CMD_NONE || (state == STATE_SLEEP && ! call RadioAlarm.isFree()) )
+                       return EBUSY;
+               else if( state == STATE_TRX_OFF )
+                       return EALREADY;
+
+               cmd = CMD_STANDBY;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+
+       tasklet_async command error_t RadioState.turnOn()
+       {
+               if( cmd != CMD_NONE || (state == STATE_SLEEP && ! call RadioAlarm.isFree()) )
+                       return EBUSY;
+               else if( state == STATE_RX_ON )
+                       return EALREADY;
+
+               cmd = CMD_TURNON;
+               call Tasklet.schedule();
+
+               return SUCCESS;
+       }
+
+       default tasklet_async event void RadioState.done() { }
+
+/*----------------- TRANSMIT -----------------*/
+
+       tasklet_async command error_t RadioSend.send(message_t* msg)
+       {
+               uint16_t time;
+               uint8_t length;
+               uint8_t* data;
+               uint8_t header;
+               uint32_t time32;
+               void* timesync;
+
+               if( cmd != CMD_NONE || state != STATE_RX_ON || ! isSpiAcquired() || radioIrq )
+                       return EBUSY;
+
+               length = (call PacketTransmitPower.isSet(msg) ?
+                       call PacketTransmitPower.get(msg) : RF230_DEF_RFPOWER) & RF230_TX_PWR_MASK;
+
+               if( length != txPower )
+               {
+                       txPower = length;
+                       writeRegister(RF230_PHY_TX_PWR, RF230_TX_AUTO_CRC_ON | txPower);
+               }
+
+               if( call Config.requiresRssiCca(msg) 
+                               && (readRegister(RF230_PHY_RSSI) & RF230_RSSI_MASK) > ((rssiClear + rssiBusy) >> 3) )
+                       return EBUSY;
+
+               writeRegister(RF230_TRX_STATE, RF230_PLL_ON);
+
+               // do something useful, just to wait a little
+               time32 = call LocalTime.get();
+               timesync = call PacketTimeSyncOffset.isSet(msg) ? ((void*)msg) + call PacketTimeSyncOffset.get(msg) : 0;
+
+               // we have missed an incoming message in this short amount of time
+               if( (readRegister(RF230_TRX_STATUS) & RF230_TRX_STATUS_MASK) != RF230_PLL_ON )
+               {
+                       ASSERT( (readRegister(RF230_TRX_STATUS) & RF230_TRX_STATUS_MASK) == RF230_BUSY_RX );
+
+                       state = STATE_PLL_ON_2_RX_ON;
+                       return EBUSY;
+               }
+
+#ifndef RF230_SLOW_SPI
+               atomic
+               {
+                       call SLP_TR.set();
+                       time = call RadioAlarm.getNow();
+               }
+               call SLP_TR.clr();
+#endif
+
+               ASSERT( ! radioIrq );
+
+               call SELN.clr();
+               call FastSpiByte.splitWrite(RF230_CMD_FRAME_WRITE);
+
+               data = getPayload(msg);
+               length = getHeader(msg)->length;
+
+               // length | data[0] ... data[length-3] | automatically generated FCS
+               call FastSpiByte.splitReadWrite(length);
+
+               // the FCS is atomatically generated (2 bytes)
+               length -= 2;
+
+               header = call Config.headerPreloadLength();
+               if( header > length )
+                       header = length;
+
+               length -= header;
+
+               // first upload the header to gain some time
+               do {
+                       call FastSpiByte.splitReadWrite(*(data++));
+               }
+               while( --header != 0 );
+
+#ifdef RF230_SLOW_SPI
+               atomic
+               {
+                       call SLP_TR.set();
+                       time = call RadioAlarm.getNow();
+               }
+               call SLP_TR.clr();
+#endif
+
+               time32 += (int16_t)(time + TX_SFD_DELAY) - (int16_t)(time32);
+
+               if( timesync != 0 )
+                       *(timesync_relative_t*)timesync = (*(timesync_absolute_t*)timesync) - time32;
+
+               while( length-- != 0 )
+                       call FastSpiByte.splitReadWrite(*(data++));
+
+               // wait for the SPI transfer to finish
+               call FastSpiByte.splitRead();
+               call SELN.set();
+
+               /*
+                * There is a very small window (~1 microsecond) when the RF230 went 
+                * into PLL_ON state but was somehow not properly initialized because 
+                * of an incoming message and could not go into BUSY_TX. I think the
+                * radio can even receive a message, and generate a TRX_UR interrupt
+                * because of concurrent access, but that message probably cannot be
+                * recovered.
+                *
+                * TODO: this needs to be verified, and make sure that the chip is 
+                * not locked up in this case.
+                */
+
+               // go back to RX_ON state when finished
+               writeRegister(RF230_TRX_STATE, RF230_RX_ON);
+
+               if( timesync != 0 )
+                       *(timesync_absolute_t*)timesync = (*(timesync_relative_t*)timesync) + time32;
+
+               call PacketTimeStamp.set(msg, time32);
+
+#ifdef RADIO_DEBUG_MESSAGES
+               if( call DiagMsg.record() )
+               {
+                       length = getHeader(msg)->length;
+
+                       call DiagMsg.chr('t');
+                       call DiagMsg.uint32(call PacketTimeStamp.isValid(rxMsg) ? call PacketTimeStamp.timestamp(rxMsg) : 0);
+                       call DiagMsg.uint16(call RadioAlarm.getNow());
+                       call DiagMsg.int8(length);
+                       call DiagMsg.hex8s(getPayload(msg), length - 2);
+                       call DiagMsg.send();
+               }
+#endif
+
+               // wait for the TRX_END interrupt
+               state = STATE_BUSY_TX_2_RX_ON;
+               cmd = CMD_TRANSMIT;
+
+               return SUCCESS;
+       }
+
+       default tasklet_async event void RadioSend.sendDone(error_t error) { }
+       default tasklet_async event void RadioSend.ready() { }
+
+/*----------------- CCA -----------------*/
+
+       tasklet_async command error_t RadioCCA.request()
+       {
+               if( cmd != CMD_NONE || state != STATE_RX_ON || ! isSpiAcquired() || ! call RadioAlarm.isFree() )
+                       return EBUSY;
+
+               // see Errata B7 of the datasheet
+               // writeRegister(RF230_TRX_STATE, RF230_PLL_ON);
+               // writeRegister(RF230_TRX_STATE, RF230_RX_ON);
+
+               writeRegister(RF230_PHY_CC_CCA, RF230_CCA_REQUEST | RF230_CCA_MODE_VALUE | channel);
+               call RadioAlarm.wait(CCA_REQUEST_TIME);
+               cmd = CMD_CCA;
+               
+               return SUCCESS;
+       }
+
+       default tasklet_async event void RadioCCA.done(error_t error) { }
+
+/*----------------- RECEIVE -----------------*/
+
+       inline void downloadMessage()
+       {
+               uint8_t length;
+               uint16_t crc;
+
+               call SELN.clr();
+               call FastSpiByte.write(RF230_CMD_FRAME_READ);
+
+               // read the length byte
+               length = call FastSpiByte.write(0);
+
+               // if correct length
+               if( length >= 3 && length <= call RadioPacket.maxPayloadLength() + 2 )
+               {
+                       uint8_t read;
+                       uint8_t* data;
+
+                       // initiate the reading
+                       call FastSpiByte.splitWrite(0);
+
+                       data = getPayload(rxMsg);
+                       getHeader(rxMsg)->length = length;
+                       crc = 0;
+
+                       // we do not store the CRC field
+                       length -= 2;
+
+                       read = call Config.headerPreloadLength();
+                       if( length < read )
+                               read = length;
+
+                       length -= read;
+
+                       do {
+                               crc = RF230_CRCBYTE_COMMAND(crc, *(data++) = call FastSpiByte.splitReadWrite(0));
+                       }
+                       while( --read != 0  );
+
+                       if( signal RadioReceive.header(rxMsg) )
+                       {
+                               while( length-- != 0 )
+                                       crc = RF230_CRCBYTE_COMMAND(crc, *(data++) = call FastSpiByte.splitReadWrite(0));
+
+                               crc = RF230_CRCBYTE_COMMAND(crc, call FastSpiByte.splitReadWrite(0));
+                               crc = RF230_CRCBYTE_COMMAND(crc, call FastSpiByte.splitReadWrite(0));
+
+                               call PacketLinkQuality.set(rxMsg, call FastSpiByte.splitRead());
+                       }
+                       else
+                               crc = 1;
+               }
+               else
+                       crc = 1;
+
+               call SELN.set();
+               state = STATE_RX_ON;
+
+#ifdef RADIO_DEBUG_MESSAGES
+               if( call DiagMsg.record() )
+               {
+                       length = getHeader(rxMsg)->length;
+
+                       call DiagMsg.chr('r');
+                       call DiagMsg.uint32(call PacketTimeStamp.isValid(rxMsg) ? call PacketTimeStamp.timestamp(rxMsg) : 0);
+                       call DiagMsg.uint16(call RadioAlarm.getNow());
+                       call DiagMsg.int8(crc == 0 ? length : -length);
+                       call DiagMsg.hex8s(getPayload(rxMsg), length - 2);
+                       call DiagMsg.int8(call PacketRSSI.isSet(rxMsg) ? call PacketRSSI.get(rxMsg) : -1);
+                       call DiagMsg.uint8(call PacketLinkQuality.isSet(rxMsg) ? call PacketLinkQuality.get(rxMsg) : 0);
+                       call DiagMsg.send();
+               }
+#endif
+               
+               cmd = CMD_NONE;
+
+               // signal only if it has passed the CRC check
+               if( crc == 0 )
+                       rxMsg = signal RadioReceive.receive(rxMsg);
+       }
+
+/*----------------- IRQ -----------------*/
+
+       async event void IRQ.captured(uint16_t time)
+       {
+               ASSERT( ! radioIrq );
+
+               atomic
+               {
+                       capturedTime = time;
+                       radioIrq = TRUE;
+               }
+
+               call Tasklet.schedule();
+       }
+
+       void serviceRadio()
+       {
+               if( isSpiAcquired() )
+               {
+                       uint16_t time;
+                       uint32_t time32;
+                       uint8_t irq;
+                       uint8_t temp;
+                       
+                       atomic time = capturedTime;
+                       radioIrq = FALSE;
+                       irq = readRegister(RF230_IRQ_STATUS);
+
+#ifdef RADIO_DEBUG
+                       // TODO: handle this interrupt
+                       if( irq & RF230_IRQ_TRX_UR )
+                       {
+                               if( call DiagMsg.record() )
+                               {
+                                       call DiagMsg.str("assert ur");
+                                       call DiagMsg.uint16(call RadioAlarm.getNow());
+                                       call DiagMsg.hex8(readRegister(RF230_TRX_STATUS));
+                                       call DiagMsg.hex8(readRegister(RF230_TRX_STATE));
+                                       call DiagMsg.hex8(irq);
+                                       call DiagMsg.uint8(state);
+                                       call DiagMsg.uint8(cmd);
+                                       call DiagMsg.send();
+                               }
+                       }
+#endif
+
+#ifdef RF230_RSSI_ENERGY
+                       if( irq & RF230_IRQ_TRX_END )
+                       {
+                               if( irq == RF230_IRQ_TRX_END || 
+                                       (irq == (RF230_IRQ_RX_START | RF230_IRQ_TRX_END) && cmd == CMD_NONE) )
+                                       call PacketRSSI.set(rxMsg, readRegister(RF230_PHY_ED_LEVEL));
+                               else
+                                       call PacketRSSI.clear(rxMsg);
+                       }
+#endif
+
+                       if( irq & RF230_IRQ_PLL_LOCK )
+                       {
+                               if( cmd == CMD_TURNON || cmd == CMD_CHANNEL )
+                               {
+                                       ASSERT( state == STATE_TRX_OFF_2_RX_ON );
+
+                                       state = STATE_RX_ON;
+                                       cmd = CMD_SIGNAL_DONE;
+                               }
+                               else if( cmd == CMD_TRANSMIT )
+                               {
+                                       ASSERT( state == STATE_BUSY_TX_2_RX_ON );
+                               }
+                               else
+                                       ASSERT(FALSE);
+                       }
+
+                       if( irq & RF230_IRQ_RX_START )
+                       {
+                               if( cmd == CMD_CCA )
+                               {
+                                       signal RadioCCA.done(FAIL);
+                                       cmd = CMD_NONE;
+                               }
+
+                               if( cmd == CMD_NONE )
+                               {
+                                       ASSERT( state == STATE_RX_ON || state == STATE_PLL_ON_2_RX_ON );
+
+                                       // the most likely place for busy channel, with no TRX_END interrupt
+                                       if( irq == RF230_IRQ_RX_START )
+                                       {
+                                               temp = readRegister(RF230_PHY_RSSI) & RF230_RSSI_MASK;
+                                               rssiBusy += temp - (rssiBusy >> 2);
+#ifndef RF230_RSSI_ENERGY
+                                               call PacketRSSI.set(rxMsg, temp);
+                                       }
+                                       else
+                                       {
+                                               call PacketRSSI.clear(rxMsg);
+#endif
+                                       }
+
+                                       /*
+                                        * The timestamp corresponds to the first event which could not
+                                        * have been a PLL_LOCK because then cmd != CMD_NONE, so we must
+                                        * have received a message (and could also have received the 
+                                        * TRX_END interrupt in the mean time, but that is fine. Also,
+                                        * we could not be after a transmission, because then cmd = 
+                                        * CMD_TRANSMIT.
+                                        */
+                                       if( irq == RF230_IRQ_RX_START ) // just to be cautious
+                                       {
+                                               time32 = call LocalTime.get();
+                                               time32 += (int16_t)(time - RX_SFD_DELAY) - (int16_t)(time32);
+                                               call PacketTimeStamp.set(rxMsg, time32);
+                                       }
+                                       else
+                                               call PacketTimeStamp.clear(rxMsg);
+
+                                       cmd = CMD_RECEIVE;
+                               }
+                               else
+                                       ASSERT( cmd == CMD_TURNOFF );
+                       }
+
+                       if( irq & RF230_IRQ_TRX_END )
+                       {
+                               if( cmd == CMD_TRANSMIT )
+                               {
+                                       ASSERT( state == STATE_BUSY_TX_2_RX_ON );
+
+                                       state = STATE_RX_ON;
+                                       cmd = CMD_NONE;
+                                       signal RadioSend.sendDone(SUCCESS);
+
+                                       // TODO: we could have missed a received message
+                                       ASSERT( ! (irq & RF230_IRQ_RX_START) );
+                               }
+                               else if( cmd == CMD_RECEIVE )
+                               {
+                                       ASSERT( state == STATE_RX_ON || state == STATE_PLL_ON_2_RX_ON );
+
+                                       if( state == STATE_PLL_ON_2_RX_ON )
+                                       {
+                                               ASSERT( (readRegister(RF230_TRX_STATUS) & RF230_TRX_STATUS_MASK) == RF230_PLL_ON );
+
+                                               writeRegister(RF230_TRX_STATE, RF230_RX_ON);
+                                               state = STATE_RX_ON;
+                                       }
+                                       else
+                                       {
+                                               // the most likely place for clear channel (hope to avoid acks)
+                                               rssiClear += (readRegister(RF230_PHY_RSSI) & RF230_RSSI_MASK) - (rssiClear >> 2);
+                                       }
+
+                                       cmd = CMD_DOWNLOAD;
+                               }
+                               else
+                                       ASSERT(FALSE);
+                       }
+               }
+       }
+
+       default tasklet_async event bool RadioReceive.header(message_t* msg)
+       {
+               return TRUE;
+       }
+
+       default tasklet_async event message_t* RadioReceive.receive(message_t* msg)
+       {
+               return msg;
+       }
+
+/*----------------- TASKLET -----------------*/
+
+       tasklet_async event void Tasklet.run()
+       {
+               if( radioIrq )
+                       serviceRadio();
+
+               if( cmd != CMD_NONE )
+               {
+                       if( cmd == CMD_DOWNLOAD )
+                               downloadMessage();
+                       else if( CMD_TURNOFF <= cmd && cmd <= CMD_TURNON )
+                               changeState();
+                       else if( cmd == CMD_CHANNEL )
+                               changeChannel();
+                       
+                       if( cmd == CMD_SIGNAL_DONE )
+                       {
+                               cmd = CMD_NONE;
+                               signal RadioState.done();
+                       }
+               }
+
+               if( cmd == CMD_NONE && state == STATE_RX_ON && ! radioIrq )
+                       signal RadioSend.ready();
+
+               if( cmd == CMD_NONE )
+                       call SpiResource.release();
+       }
+
+/*----------------- RadioPacket -----------------*/
+       
+       async command uint8_t RadioPacket.headerLength(message_t* msg)
+       {
+               return call Config.headerLength(msg) + sizeof(rf230_header_t);
+       }
+
+       async command uint8_t RadioPacket.payloadLength(message_t* msg)
+       {
+               return getHeader(msg)->length - 2;
+       }
+
+       async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               ASSERT( 1 <= length && length <= 125 );
+               ASSERT( call RadioPacket.headerLength(msg) + length + call RadioPacket.metadataLength(msg) <= sizeof(message_t) );
+
+               // we add the length of the CRC, which is automatically generated
+               getHeader(msg)->length = length + 2;
+       }
+
+       async command uint8_t RadioPacket.maxPayloadLength()
+       {
+               ASSERT( call Config.maxPayloadLength() <= 125 );
+
+               return call Config.maxPayloadLength() - sizeof(rf230_header_t);
+       }
+
+       async command uint8_t RadioPacket.metadataLength(message_t* msg)
+       {
+               return call Config.metadataLength(msg) + sizeof(rf230_metadata_t);
+       }
+
+       async command void RadioPacket.clear(message_t* msg)
+       {
+               // all flags are automatically cleared
+       }
+
+/*----------------- PacketTransmitPower -----------------*/
+
+       async command bool PacketTransmitPower.isSet(message_t* msg)
+       {
+               return call TransmitPowerFlag.get(msg);
+       }
+
+       async command uint8_t PacketTransmitPower.get(message_t* msg)
+       {
+               return getMeta(msg)->power;
+       }
+
+       async command void PacketTransmitPower.clear(message_t* msg)
+       {
+               call TransmitPowerFlag.clear(msg);
+       }
+
+       async command void PacketTransmitPower.set(message_t* msg, uint8_t value)
+       {
+               call TransmitPowerFlag.set(msg);
+               getMeta(msg)->power = value;
+       }
+
+/*----------------- PacketRSSI -----------------*/
+
+       async command bool PacketRSSI.isSet(message_t* msg)
+       {
+               return call RSSIFlag.get(msg);
+       }
+
+       async command uint8_t PacketRSSI.get(message_t* msg)
+       {
+               return getMeta(msg)->rssi;
+       }
+
+       async command void PacketRSSI.clear(message_t* msg)
+       {
+               call RSSIFlag.clear(msg);
+       }
+
+       async command void PacketRSSI.set(message_t* msg, uint8_t value)
+       {
+               // just to be safe if the user fails to clear the packet
+               call TransmitPowerFlag.clear(msg);
+
+               call RSSIFlag.set(msg);
+               getMeta(msg)->rssi = value;
+       }
+
+/*----------------- PacketTimeSyncOffset -----------------*/
+
+       async command bool PacketTimeSyncOffset.isSet(message_t* msg)
+       {
+               return call TimeSyncFlag.get(msg);
+       }
+
+       async command uint8_t PacketTimeSyncOffset.get(message_t* msg)
+       {
+               return call RadioPacket.headerLength(msg) + call RadioPacket.payloadLength(msg) - sizeof(timesync_absolute_t);
+       }
+
+       async command void PacketTimeSyncOffset.clear(message_t* msg)
+       {
+               call TimeSyncFlag.clear(msg);
+       }
+
+       async command void PacketTimeSyncOffset.set(message_t* msg, uint8_t value)
+       {
+               // we do not store the value, the time sync field is always the last 4 bytes
+               ASSERT( call PacketTimeSyncOffset.get(msg) == value );
+
+               call TimeSyncFlag.set(msg);
+       }
+
+/*----------------- PacketLinkQuality -----------------*/
+
+       async command bool PacketLinkQuality.isSet(message_t* msg)
+       {
+               return TRUE;
+       }
+
+       async command uint8_t PacketLinkQuality.get(message_t* msg)
+       {
+               return getMeta(msg)->lqi;
+       }
+
+       async command void PacketLinkQuality.clear(message_t* msg)
+       {
+       }
+
+       async command void PacketLinkQuality.set(message_t* msg, uint8_t value)
+       {
+               getMeta(msg)->lqi = value;
+       }
+}
diff --git a/tos/chips/rf2xx/rf230/RF230Ieee154MessageC.nc b/tos/chips/rf2xx/rf230/RF230Ieee154MessageC.nc
new file mode 100644 (file)
index 0000000..7b9700b
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+#ifdef TFRAMES_ENABLED
+#error "You cannot use Ieee154MessageC with TFRAMES_ENABLED defined"
+#endif
+
+configuration RF230Ieee154MessageC
+{
+       provides 
+       {
+               interface SplitControl;
+
+               interface Ieee154Send;
+               interface Receive as Ieee154Receive;
+               interface SendNotifier;
+
+               interface Ieee154Packet;
+               interface Packet;
+               interface Resource as SendResource[uint8_t clint];
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+               interface PacketLink;
+
+               interface RadioChannel;
+
+               interface PacketField<uint8_t> as PacketLinkQuality;
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF230RadioC;
+
+       SplitControl = RF230RadioC;
+
+       Ieee154Send = RF230RadioC.Ieee154Send;
+       Ieee154Receive = RF230RadioC.Ieee154Receive;
+       SendNotifier = RF230RadioC.Ieee154Notifier;
+
+       Packet = RF230RadioC.PacketForIeee154Message;
+       Ieee154Packet = RF230RadioC;
+       SendResource = RF230RadioC;
+
+       PacketAcknowledgements = RF230RadioC;
+       LowPowerListening = RF230RadioC;
+       PacketLink = RF230RadioC;
+
+       RadioChannel = RF230RadioC;
+
+       PacketLinkQuality = RF230RadioC.PacketLinkQuality;
+       PacketTransmitPower = RF230RadioC.PacketTransmitPower;
+       PacketRSSI = RF230RadioC.PacketRSSI;
+
+       LocalTimeRadio = RF230RadioC;
+       PacketTimeStampMilli = RF230RadioC;
+       PacketTimeStampRadio = RF230RadioC;
+}
diff --git a/tos/chips/rf2xx/rf230/RF230Radio.h b/tos/chips/rf2xx/rf230/RF230Radio.h
new file mode 100644 (file)
index 0000000..58efd6e
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __RF230RADIO_H__
+#define __RF230RADIO_H__
+
+#include <RadioConfig.h>
+#include <TinyosNetworkLayer.h>
+#include <Ieee154PacketLayer.h>
+#include <ActiveMessageLayer.h>
+#include <MetadataFlagsLayer.h>
+#include <RF230DriverLayer.h>
+#include <TimeStampingLayer.h>
+#include <LowPowerListeningLayer.h>
+#include <PacketLinkLayer.h>
+
+typedef nx_struct rf230packet_header_t
+{
+       rf230_header_t rf230;
+       ieee154_header_t ieee154;
+#ifndef TFRAMES_ENABLED
+       network_header_t network;
+#endif
+#ifndef IEEE154FRAMES_ENABLED
+       activemessage_header_t am;
+#endif
+} rf230packet_header_t;
+
+typedef nx_struct rf230packet_footer_t
+{
+       // the time stamp is not recorded here, time stamped messaged cannot have max length
+} rf230packet_footer_t;
+
+typedef struct rf230packet_metadata_t
+{
+#ifdef LOW_POWER_LISTENING
+       lpl_metadata_t lpl;
+#endif
+#ifdef PACKET_LINK
+       link_metadata_t link;
+#endif
+       timestamp_metadata_t timestamp;
+       flags_metadata_t flags;
+       rf230_metadata_t rf230;
+} rf230packet_metadata_t;
+
+#endif//__RF230RADIO_H__
diff --git a/tos/chips/rf2xx/rf230/RF230RadioC.nc b/tos/chips/rf2xx/rf230/RF230RadioC.nc
new file mode 100644 (file)
index 0000000..4527003
--- /dev/null
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+configuration RF230RadioC
+{
+       provides 
+       {
+               interface SplitControl;
+
+#ifndef IEEE154FRAMES_ENABLED
+               interface AMSend[am_id_t id];
+               interface Receive[am_id_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface SendNotifier[am_id_t id];
+
+               interface AMPacket;
+               interface Packet as PacketForActiveMessage;
+#endif
+
+#ifndef TFRAMES_ENABLED
+               interface Ieee154Send;
+               interface Receive as Ieee154Receive;
+               interface SendNotifier as Ieee154Notifier;
+
+               interface Resource as SendResource[uint8_t clint];
+
+               interface Ieee154Packet;
+               interface Packet as PacketForIeee154Message;
+#endif
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+
+#ifdef PACKET_LINK
+               interface PacketLink;
+#endif
+
+               interface RadioChannel;
+
+               interface PacketField<uint8_t> as PacketLinkQuality;
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF230RadioP, RadioAlarmC;
+
+#ifdef RADIO_DEBUG
+       components AssertC;
+#endif
+
+       RF230RadioP.Ieee154PacketLayer -> Ieee154PacketLayerC;
+       RF230RadioP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
+       RF230RadioP.PacketTimeStamp -> TimeStampingLayerC;
+       RF230RadioP.RF230Packet -> RF230DriverLayerC;
+
+// -------- Active Message
+
+#ifndef IEEE154FRAMES_ENABLED
+       components ActiveMessageLayerC;
+       ActiveMessageLayerC.Config -> RF230RadioP;
+       ActiveMessageLayerC.SubSend -> AutoResourceAcquireLayerC;
+       ActiveMessageLayerC.SubReceive -> TinyosNetworkLayerC.TinyosReceive;
+       ActiveMessageLayerC.SubPacket -> TinyosNetworkLayerC.TinyosPacket;
+
+       AMSend = ActiveMessageLayerC;
+       Receive = ActiveMessageLayerC.Receive;
+       Snoop = ActiveMessageLayerC.Snoop;
+       SendNotifier = ActiveMessageLayerC;
+       AMPacket = ActiveMessageLayerC;
+       PacketForActiveMessage = ActiveMessageLayerC;
+#endif
+
+// -------- Automatic RadioSend Resource
+
+#ifndef IEEE154FRAMES_ENABLED
+#ifndef TFRAMES_ENABLED
+       components new AutoResourceAcquireLayerC();
+       AutoResourceAcquireLayerC.Resource -> SendResourceC.Resource[unique(RADIO_SEND_RESOURCE)];
+#else
+       components new DummyLayerC() as AutoResourceAcquireLayerC;
+#endif
+       AutoResourceAcquireLayerC.SubSend -> TinyosNetworkLayerC.TinyosSend;
+#endif
+
+// -------- RadioSend Resource
+
+#ifndef TFRAMES_ENABLED
+       components new SimpleFcfsArbiterC(RADIO_SEND_RESOURCE) as SendResourceC;
+       SendResource = SendResourceC;
+
+// -------- Ieee154 Message
+
+       components Ieee154MessageLayerC;
+       Ieee154MessageLayerC.Ieee154PacketLayer -> Ieee154PacketLayerC;
+       Ieee154MessageLayerC.Ieee154Packet -> Ieee154PacketLayerC;
+       Ieee154MessageLayerC.SubSend -> TinyosNetworkLayerC.Ieee154Send;
+       Ieee154MessageLayerC.SubReceive -> TinyosNetworkLayerC.Ieee154Receive;
+       Ieee154MessageLayerC.RadioPacket -> TinyosNetworkLayerC.Ieee154Packet;
+
+       Ieee154Send = Ieee154MessageLayerC;
+       Ieee154Receive = Ieee154MessageLayerC;
+       Ieee154Notifier = Ieee154MessageLayerC;
+       Ieee154Packet = Ieee154PacketLayerC;
+       PacketForIeee154Message = Ieee154MessageLayerC;
+#endif
+
+// -------- Tinyos Network
+
+       components TinyosNetworkLayerC;
+
+       TinyosNetworkLayerC.SubSend -> UniqueLayerC;
+       TinyosNetworkLayerC.SubReceive -> LowPowerListeningLayerC;
+       TinyosNetworkLayerC.SubPacket -> Ieee154PacketLayerC;
+
+// -------- IEEE 802.15.4 Packet
+
+       components Ieee154PacketLayerC;
+       Ieee154PacketLayerC.SubPacket -> LowPowerListeningLayerC;
+
+// -------- UniqueLayer Send part (wired twice)
+
+       components UniqueLayerC;
+       UniqueLayerC.Config -> RF230RadioP;
+       UniqueLayerC.SubSend -> LowPowerListeningLayerC;
+
+// -------- Low Power Listening 
+
+#ifdef LOW_POWER_LISTENING
+       #warning "*** USING LOW POWER LISTENING LAYER"
+       components LowPowerListeningLayerC;
+       LowPowerListeningLayerC.Config -> RF230RadioP;
+#ifdef RF230_HARDWARE_ACK
+       LowPowerListeningLayerC.PacketAcknowledgements -> RF230DriverLayerC;
+#else
+       LowPowerListeningLayerC.PacketAcknowledgements -> SoftwareAckLayerC;
+#endif
+#else  
+       components LowPowerListeningDummyC as LowPowerListeningLayerC;
+#endif
+       LowPowerListeningLayerC.SubControl -> MessageBufferLayerC;
+       LowPowerListeningLayerC.SubSend -> PacketLinkLayerC;
+       LowPowerListeningLayerC.SubReceive -> MessageBufferLayerC;
+       LowPowerListeningLayerC.SubPacket -> PacketLinkLayerC;
+       SplitControl = LowPowerListeningLayerC;
+       LowPowerListening = LowPowerListeningLayerC;
+
+// -------- Packet Link
+
+#ifdef PACKET_LINK
+       components PacketLinkLayerC;
+       PacketLink = PacketLinkLayerC;
+#ifdef RF230_HARDWARE_ACK
+       PacketLinkLayerC.PacketAcknowledgements -> RF230DriverLayerC;
+#else
+       PacketLinkLayerC.PacketAcknowledgements -> SoftwareAckLayerC;
+#endif
+#else
+       components new DummyLayerC() as PacketLinkLayerC;
+#endif
+       PacketLinkLayerC.SubSend -> MessageBufferLayerC;
+       PacketLinkLayerC.SubPacket -> TimeStampingLayerC;
+
+// -------- MessageBuffer
+
+       components MessageBufferLayerC;
+       MessageBufferLayerC.RadioSend -> TrafficMonitorLayerC;
+       MessageBufferLayerC.RadioReceive -> UniqueLayerC;
+       MessageBufferLayerC.RadioState -> TrafficMonitorLayerC;
+       RadioChannel = MessageBufferLayerC;
+
+// -------- UniqueLayer receive part (wired twice)
+
+       UniqueLayerC.SubReceive -> TrafficMonitorLayerC;
+
+// -------- Traffic Monitor
+
+#ifdef TRAFFIC_MONITOR
+       components TrafficMonitorLayerC;
+#else
+       components new DummyLayerC() as TrafficMonitorLayerC;
+#endif
+       TrafficMonitorLayerC.Config -> RF230RadioP;
+       TrafficMonitorLayerC -> CollisionAvoidanceLayerC.RadioSend;
+       TrafficMonitorLayerC -> CollisionAvoidanceLayerC.RadioReceive;
+       TrafficMonitorLayerC -> RF230DriverLayerC.RadioState;
+
+// -------- CollisionAvoidance
+
+#ifdef SLOTTED_MAC
+       components SlottedCollisionLayerC as CollisionAvoidanceLayerC;
+#else
+       components RandomCollisionLayerC as CollisionAvoidanceLayerC;
+#endif
+       CollisionAvoidanceLayerC.Config -> RF230RadioP;
+#ifdef RF230_HARDWARE_ACK
+       CollisionAvoidanceLayerC.SubSend -> CsmaLayerC;
+       CollisionAvoidanceLayerC.SubReceive -> RF230DriverLayerC;
+#else
+       CollisionAvoidanceLayerC.SubSend -> SoftwareAckLayerC;
+       CollisionAvoidanceLayerC.SubReceive -> SoftwareAckLayerC;
+#endif
+
+// -------- SoftwareAcknowledgement
+
+#ifndef RF230_HARDWARE_ACK
+       components SoftwareAckLayerC;
+       SoftwareAckLayerC.Config -> RF230RadioP;
+       SoftwareAckLayerC.SubSend -> CsmaLayerC;
+       SoftwareAckLayerC.SubReceive -> RF230DriverLayerC;
+       PacketAcknowledgements = SoftwareAckLayerC;
+#endif
+
+// -------- Carrier Sense
+
+       components new DummyLayerC() as CsmaLayerC;
+       CsmaLayerC.Config -> RF230RadioP;
+       CsmaLayerC -> RF230DriverLayerC.RadioSend;
+       CsmaLayerC -> RF230DriverLayerC.RadioCCA;
+
+// -------- TimeStamping
+
+       components TimeStampingLayerC;
+       TimeStampingLayerC.LocalTimeRadio -> RF230DriverLayerC;
+       TimeStampingLayerC.SubPacket -> MetadataFlagsLayerC;
+       PacketTimeStampRadio = TimeStampingLayerC;
+       PacketTimeStampMilli = TimeStampingLayerC;
+
+// -------- MetadataFlags
+
+       components MetadataFlagsLayerC;
+       MetadataFlagsLayerC.SubPacket -> RF230DriverLayerC;
+
+// -------- RF230 Driver
+
+#ifdef RF230_HARDWARE_ACK
+       components RF230DriverHwAckC as RF230DriverLayerC;
+       PacketAcknowledgements = RF230DriverLayerC;
+       RF230DriverLayerC.Ieee154PacketLayer -> Ieee154PacketLayerC;
+#else
+       components RF230DriverLayerC;
+#endif
+       RF230DriverLayerC.Config -> RF230RadioP;
+       RF230DriverLayerC.PacketTimeStamp -> TimeStampingLayerC;
+       PacketTransmitPower = RF230DriverLayerC.PacketTransmitPower;
+       PacketLinkQuality = RF230DriverLayerC.PacketLinkQuality;
+       PacketRSSI = RF230DriverLayerC.PacketRSSI;
+       LocalTimeRadio = RF230DriverLayerC;
+}
diff --git a/tos/chips/rf2xx/rf230/RF230RadioP.nc b/tos/chips/rf2xx/rf230/RF230RadioP.nc
new file mode 100644 (file)
index 0000000..f4b0eab
--- /dev/null
@@ -0,0 +1,335 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RF230Radio.h>
+#include <RadioConfig.h>
+#include <Tasklet.h>
+
+module RF230RadioP
+{
+       provides
+       {
+               interface RF230DriverConfig;
+               interface SoftwareAckConfig;
+               interface UniqueConfig;
+               interface CsmaConfig;
+               interface TrafficMonitorConfig;
+               interface RandomCollisionConfig;
+               interface SlottedCollisionConfig;
+               interface ActiveMessageConfig;
+               interface DummyConfig;
+
+#ifdef LOW_POWER_LISTENING
+               interface LowPowerListeningConfig;
+#endif
+       }
+
+       uses
+       {
+               interface Ieee154PacketLayer;
+               interface RadioAlarm;
+               interface RadioPacket as RF230Packet;
+
+               interface PacketTimeStamp<TRadio, uint32_t>;
+       }
+}
+
+implementation
+{
+
+/*----------------- RF230DriverConfig -----------------*/
+
+       async command uint8_t RF230DriverConfig.headerLength(message_t* msg)
+       {
+               return offsetof(message_t, data) - sizeof(rf230packet_header_t);
+       }
+
+       async command uint8_t RF230DriverConfig.maxPayloadLength()
+       {
+               return sizeof(rf230packet_header_t) + TOSH_DATA_LENGTH;
+       }
+
+       async command uint8_t RF230DriverConfig.metadataLength(message_t* msg)
+       {
+               return 0;
+       }
+
+       async command uint8_t RF230DriverConfig.headerPreloadLength()
+       {
+               // we need the fcf, dsn, destpan and dest
+               return 7;
+       }
+
+       async command bool RF230DriverConfig.requiresRssiCca(message_t* msg)
+       {
+               return call Ieee154PacketLayer.isDataFrame(msg);
+       }
+
+/*----------------- SoftwareAckConfig -----------------*/
+
+       async command bool SoftwareAckConfig.requiresAckWait(message_t* msg)
+       {
+               return call Ieee154PacketLayer.requiresAckWait(msg);
+       }
+
+       async command bool SoftwareAckConfig.isAckPacket(message_t* msg)
+       {
+               return call Ieee154PacketLayer.isAckFrame(msg);
+       }
+
+       async command bool SoftwareAckConfig.verifyAckPacket(message_t* data, message_t* ack)
+       {
+               return call Ieee154PacketLayer.verifyAckReply(data, ack);
+       }
+
+       async command void SoftwareAckConfig.setAckRequired(message_t* msg, bool ack)
+       {
+               call Ieee154PacketLayer.setAckRequired(msg, ack);
+       }
+
+       async command bool SoftwareAckConfig.requiresAckReply(message_t* msg)
+       {
+               return call Ieee154PacketLayer.requiresAckReply(msg);
+       }
+
+       async command void SoftwareAckConfig.createAckPacket(message_t* data, message_t* ack)
+       {
+               call Ieee154PacketLayer.createAckReply(data, ack);
+       }
+
+#ifndef SOFTWAREACK_TIMEOUT
+#define SOFTWAREACK_TIMEOUT    1000
+#endif
+
+       async command uint16_t SoftwareAckConfig.getAckTimeout()
+       {
+               return (uint16_t)(SOFTWAREACK_TIMEOUT * RADIO_ALARM_MICROSEC);
+       }
+
+       tasklet_async command void SoftwareAckConfig.reportChannelError()
+       {
+#ifdef TRAFFIC_MONITOR
+               signal TrafficMonitorConfig.channelError();
+#endif
+       }
+
+/*----------------- UniqueConfig -----------------*/
+
+       async command uint8_t UniqueConfig.getSequenceNumber(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDSN(msg);
+       }
+
+       async command void UniqueConfig.setSequenceNumber(message_t* msg, uint8_t dsn)
+       {
+               call Ieee154PacketLayer.setDSN(msg, dsn);
+       }
+
+       async command am_addr_t UniqueConfig.getSender(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getSrcAddr(msg);
+       }
+
+       tasklet_async command void UniqueConfig.reportChannelError()
+       {
+#ifdef TRAFFIC_MONITOR
+               signal TrafficMonitorConfig.channelError();
+#endif
+       }
+
+/*----------------- ActiveMessageConfig -----------------*/
+
+       command am_addr_t ActiveMessageConfig.destination(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDestAddr(msg);
+       }
+
+       command void ActiveMessageConfig.setDestination(message_t* msg, am_addr_t addr)
+       {
+               call Ieee154PacketLayer.setDestAddr(msg, addr);
+       }
+
+       command am_addr_t ActiveMessageConfig.source(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getSrcAddr(msg);
+       }
+
+       command void ActiveMessageConfig.setSource(message_t* msg, am_addr_t addr)
+       {
+               call Ieee154PacketLayer.setSrcAddr(msg, addr);
+       }
+
+       command am_group_t ActiveMessageConfig.group(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDestPan(msg);
+       }
+
+       command void ActiveMessageConfig.setGroup(message_t* msg, am_group_t grp)
+       {
+               call Ieee154PacketLayer.setDestPan(msg, grp);
+       }
+
+       command error_t ActiveMessageConfig.checkFrame(message_t* msg)
+       {
+               if( ! call Ieee154PacketLayer.isDataFrame(msg) )
+                       call Ieee154PacketLayer.createDataFrame(msg);
+
+               return SUCCESS;
+       }
+
+/*----------------- CsmaConfig -----------------*/
+
+       async command bool CsmaConfig.requiresSoftwareCCA(message_t* msg)
+       {
+               return call Ieee154PacketLayer.isDataFrame(msg);
+       }
+
+/*----------------- TrafficMonitorConfig -----------------*/
+
+       enum
+       {
+               TRAFFIC_UPDATE_PERIOD = 100,    // in milliseconds
+               TRAFFIC_MAX_BYTES = (uint16_t)(TRAFFIC_UPDATE_PERIOD * 1000UL / 32),    // 3125
+       };
+
+       async command uint16_t TrafficMonitorConfig.getUpdatePeriod()
+       {
+               return TRAFFIC_UPDATE_PERIOD;
+       }
+
+       async command uint16_t TrafficMonitorConfig.getChannelTime(message_t* msg)
+       {
+               /* We count in bytes, one byte is 32 microsecond. We are conservative here.
+                *
+                * pure airtime: preable (4 bytes), SFD (1 byte), length (1 byte), payload + CRC (len bytes)
+                * frame separation: 5-10 bytes
+                * ack required: 8-16 byte separation, 11 bytes airtime, 5-10 bytes separation
+                */
+
+               uint8_t len = call RF230Packet.payloadLength(msg);
+               return call Ieee154PacketLayer.getAckRequired(msg) ? len + 6 + 16 + 11 + 10 : len + 6 + 10;
+       }
+
+       async command am_addr_t TrafficMonitorConfig.getSender(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getSrcAddr(msg);
+       }
+
+/*----------------- RandomCollisionConfig -----------------*/
+
+       /*
+        * We try to use the same values as in CC2420
+        *
+        * CC2420_MIN_BACKOFF = 10 jiffies = 320 microsec
+        * CC2420_BACKOFF_PERIOD = 10 jiffies
+        * initial backoff = 0x1F * CC2420_BACKOFF_PERIOD = 310 jiffies = 9920 microsec
+        * congestion backoff = 0x7 * CC2420_BACKOFF_PERIOD = 70 jiffies = 2240 microsec
+        */
+
+       async command uint16_t RandomCollisionConfig.getMinimumBackoff()
+       {
+               return (uint16_t)(320 * RADIO_ALARM_MICROSEC);
+       }
+
+       async command uint16_t RandomCollisionConfig.getInitialBackoff(message_t* msg)
+       {
+               return (uint16_t)(9920 * RADIO_ALARM_MICROSEC);
+       }
+
+       async command uint16_t RandomCollisionConfig.getCongestionBackoff(message_t* msg)
+       {
+               return (uint16_t)(2240 * RADIO_ALARM_MICROSEC);
+       }
+
+       async command uint16_t RandomCollisionConfig.getTransmitBarrier(message_t* msg)
+       {
+               uint16_t time;
+
+               // TODO: maybe we should use the embedded timestamp of the message
+               time = call RadioAlarm.getNow();
+
+               // estimated response time (download the message, etc) is 5-8 bytes
+               if( call Ieee154PacketLayer.requiresAckReply(msg) )
+                       time += (uint16_t)(32 * (-5 + 16 + 11 + 5) * RADIO_ALARM_MICROSEC);
+               else
+                       time += (uint16_t)(32 * (-5 + 5) * RADIO_ALARM_MICROSEC);
+
+               return time;
+       }
+
+       tasklet_async event void RadioAlarm.fired()
+       {
+       }
+
+/*----------------- SlottedCollisionConfig -----------------*/
+
+       async command uint16_t SlottedCollisionConfig.getInitialDelay()
+       {
+               return 300;
+       }
+
+       async command uint8_t SlottedCollisionConfig.getScheduleExponent()
+       {
+               return 1 + RADIO_ALARM_MILLI_EXP;
+       }
+
+       async command uint16_t SlottedCollisionConfig.getTransmitTime(message_t* msg)
+       {
+               // TODO: check if the timestamp is correct
+               return call PacketTimeStamp.timestamp(msg);
+       }
+
+       async command uint16_t SlottedCollisionConfig.getCollisionWindowStart(message_t* msg)
+       {
+               // the preamble (4 bytes), SFD (1 byte), plus two extra for safety
+               return (call PacketTimeStamp.timestamp(msg)) - (uint16_t)(7 * 32 * RADIO_ALARM_MICROSEC);
+       }
+
+       async command uint16_t SlottedCollisionConfig.getCollisionWindowLength(message_t* msg)
+       {
+               return (uint16_t)(2 * 7 * 32 * RADIO_ALARM_MICROSEC);
+       }
+
+/*----------------- Dummy -----------------*/
+
+       async command void DummyConfig.nothing()
+       {
+       }
+
+/*----------------- LowPowerListening -----------------*/
+
+#ifdef LOW_POWER_LISTENING
+
+       command bool LowPowerListeningConfig.needsAutoAckRequest(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getDestAddr(msg) != TOS_BCAST_ADDR;
+       }
+
+       command bool LowPowerListeningConfig.ackRequested(message_t* msg)
+       {
+               return call Ieee154PacketLayer.getAckRequired(msg);
+       }
+
+#endif
+
+}
diff --git a/tos/chips/rf2xx/rf230/RF230TimeSyncMessageC.nc b/tos/chips/rf2xx/rf230/RF230TimeSyncMessageC.nc
new file mode 100644 (file)
index 0000000..548e658
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+configuration RF230TimeSyncMessageC
+{
+       provides
+       {
+               interface SplitControl;
+
+               interface Receive[uint8_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface Packet;
+               interface AMPacket;
+
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface TimeSyncAMSend<TRadio, uint32_t> as TimeSyncAMSendRadio[am_id_t id];
+               interface TimeSyncPacket<TRadio, uint32_t> as TimeSyncPacketRadio;
+
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+               interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[am_id_t id];
+               interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
+       }
+}
+
+implementation
+{
+       components RF230ActiveMessageC, TimeSyncMessageLayerC;
+  
+       SplitControl    = RF230ActiveMessageC;
+       AMPacket        = TimeSyncMessageLayerC;
+       Receive         = TimeSyncMessageLayerC.Receive;
+       Snoop           = TimeSyncMessageLayerC.Snoop;
+       Packet          = TimeSyncMessageLayerC;
+
+       PacketTimeStampRadio    = RF230ActiveMessageC;
+       TimeSyncAMSendRadio     = TimeSyncMessageLayerC;
+       TimeSyncPacketRadio     = TimeSyncMessageLayerC;
+
+       PacketTimeStampMilli    = RF230ActiveMessageC;
+       TimeSyncAMSendMilli     = TimeSyncMessageLayerC;
+       TimeSyncPacketMilli     = TimeSyncMessageLayerC;
+
+       TimeSyncMessageLayerC.PacketTimeStampRadio -> RF230ActiveMessageC;
+       TimeSyncMessageLayerC.PacketTimeStampMilli -> RF230ActiveMessageC;
+
+#ifdef RF230_HARDWARE_ACK
+       components RF230DriverHwAckC as RF230DriverLayerC;
+#else
+       components RF230DriverLayerC;
+#endif
+       TimeSyncMessageLayerC.LocalTimeRadio -> RF230DriverLayerC;
+       TimeSyncMessageLayerC.PacketTimeSyncOffset -> RF230DriverLayerC.PacketTimeSyncOffset;
+}
diff --git a/tos/chips/rf2xx/util/BareReceive.nc b/tos/chips/rf2xx/util/BareReceive.nc
new file mode 100644 (file)
index 0000000..5a6efc7
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface BareReceive
+{
+       /**
+        * Signals the reception of a message, but only for those messages for
+        * which SUCCESS was returned in the header event. The usual owner rules 
+        * apply to the message pointers.
+        */
+       event message_t* receive(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/util/BareSend.nc b/tos/chips/rf2xx/util/BareSend.nc
new file mode 100644 (file)
index 0000000..29a398d
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface BareSend
+{
+       /**
+        * Starts the transmission of the given message. This command must not
+        * be called while another send is in progress (so one must wait for the
+        * sendDone event). Returns EBUSY if a reception is in progress or for
+        * some other reason the request cannot be temporarily satisfied (e.g.
+        * the SPI bus access could not be acquired). In this case the send 
+        * command could be retried from a task. Returns SUCCESS if the 
+        * transmission could be started. In this case sendDone will be fired.
+        */
+       command error_t send(message_t* msg);
+       
+       /**
+        * Signals the completion of the send command, exactly once for each 
+        * successfull send command. If the returned error code is SUCCESS, then 
+        * the message was sent (may not have been acknowledged), otherwise 
+        * the message was not transmitted over the air.
+        */
+       event void sendDone(message_t* msg, error_t error);
+
+       /**
+        * Cancel a requested transmission. Returns SUCCESS if the 
+        * transmission was cancelled properly (not sent in its
+        * entirety). Note that the component may not know
+        * if the send was successfully cancelled, if the radio is
+        * handling much of the logic; in this case, a component
+        * should be conservative and return an appropriate error code.
+        */
+       command error_t cancel(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/util/MetadataFlagC.nc b/tos/chips/rf2xx/util/MetadataFlagC.nc
new file mode 100644 (file)
index 0000000..1091eb5
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+generic configuration MetadataFlagC()
+{
+       provides
+       {
+               interface PacketFlag;
+       }
+}
+
+implementation
+{
+       components MetadataFlagsLayerC;
+
+       PacketFlag = MetadataFlagsLayerC.PacketFlag[unique("PacketFlags")];
+}
diff --git a/tos/chips/rf2xx/util/Neighborhood.h b/tos/chips/rf2xx/util/Neighborhood.h
new file mode 100755 (executable)
index 0000000..40884e3
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __NEIGHBORHOOD_H__
+#define __NEIGHBORHOOD_H__
+
+#ifndef NEIGHBORHOOD_SIZE
+#define NEIGHBORHOOD_SIZE      5
+#endif
+
+#endif//__NEIGHBORHOOD_H__
diff --git a/tos/chips/rf2xx/util/Neighborhood.nc b/tos/chips/rf2xx/util/Neighborhood.nc
new file mode 100644 (file)
index 0000000..cc4b7db
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+/**
+ * Every component maintains its own neighborhood data. The Neighboorhood
+ * component maintains only the nodeids and ages of the neighbors, and
+ * evicts old entries from the table when necessary.
+ */
+interface Neighborhood
+{
+       /**
+        * Returns the index of the neighbor in the table. If the node was not 
+        * found in the table, then the value NEIGHBORHOOD is  returned, 
+        * otherwise an index in the range [0, NEIGHBORHOOD-1] is returned.
+        */
+       tasklet_async command uint8_t getIndex(am_addr_t id);
+
+       /**
+        * Returns the age of the given entry. The age is incremented by one
+        * every time a new node is inserted into the neighborhood table that
+        * is not already at the very end. If the age would get too large to
+        * fit into a byte, then it is periodically reset to a smaller value.
+        */
+       tasklet_async command uint8_t getAge(uint8_t index);
+
+       /**
+        * Returns the node address for the given entry.
+        */
+       tasklet_async command am_addr_t getNode(uint8_t index);
+
+       /**
+        * Adds a new node into the neighborhood table. If this node was already
+        * in the table, then it is just brought to the front (its age is reset
+        * to zero). If the node was not in the table, then the oldest is evicted
+        * and its entry is replaced with this node. The index of the entry
+        * is returned in the range [0, NEIGHBORHOOD-1]. 
+        */
+       tasklet_async command uint8_t insertNode(am_addr_t id);
+
+       /**
+        * This event is fired when the oldest entry is replaced with a new
+        * node. The same interface is used by many users, so all of them
+        * will receive this event and can clear the corresponding entry.
+        * After this event is fired, all flags for this entry are cleared
+        * (see the NeighborhoodFlag interface)
+        */
+       tasklet_async event void evicted(uint8_t index);
+}
diff --git a/tos/chips/rf2xx/util/NeighborhoodC.nc b/tos/chips/rf2xx/util/NeighborhoodC.nc
new file mode 100755 (executable)
index 0000000..e2ba9b5
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration NeighborhoodC
+{
+       provides interface Neighborhood;
+}
+
+implementation
+{
+       components NeighborhoodP, MainC;
+
+       Neighborhood = NeighborhoodP;
+       MainC.SoftwareInit -> NeighborhoodP;
+}
diff --git a/tos/chips/rf2xx/util/NeighborhoodFlag.nc b/tos/chips/rf2xx/util/NeighborhoodFlag.nc
new file mode 100755 (executable)
index 0000000..e1dda90
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+/**
+ * This interface provides one bit storage for each neighbor in a very
+ * fast and conveint way (without using shifts for example). 
+ */
+interface NeighborhoodFlag
+{
+       /**
+        * Returns the value of the flag for the given index
+        */
+       tasklet_async command bool get(uint8_t index);
+       
+       /**
+        * Sets the flag for the given index
+        */
+       tasklet_async command void set(uint8_t index);
+
+       /**
+        * Clears the flag for the given index. The flag is automatically
+        * cleared after the Neighborhood.evicted event is fired.
+        */
+       tasklet_async command void clear(uint8_t index);
+
+       /**
+        * Clears the flag for all indices
+        */
+       tasklet_async command void clearAll();
+}
diff --git a/tos/chips/rf2xx/util/NeighborhoodFlagC.nc b/tos/chips/rf2xx/util/NeighborhoodFlagC.nc
new file mode 100755 (executable)
index 0000000..2f064eb
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+generic configuration NeighborhoodFlagC()
+{
+       provides interface NeighborhoodFlag;
+}
+
+implementation
+{
+       components NeighborhoodP;
+
+       // TODO: make sure that no more than 8 flags are used at a time
+       NeighborhoodFlag = NeighborhoodP.NeighborhoodFlag[unique("NeighborhoodFlag")];
+}
diff --git a/tos/chips/rf2xx/util/NeighborhoodP.nc b/tos/chips/rf2xx/util/NeighborhoodP.nc
new file mode 100755 (executable)
index 0000000..fb84dc8
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Neighborhood.h>
+
+module NeighborhoodP
+{
+       provides
+       {
+               interface Init;
+               interface Neighborhood;
+               interface NeighborhoodFlag[uint8_t bit];
+       }
+}
+
+implementation
+{
+       tasklet_norace am_addr_t nodes[NEIGHBORHOOD_SIZE];
+       tasklet_norace uint8_t ages[NEIGHBORHOOD_SIZE];
+       tasklet_norace uint8_t flags[NEIGHBORHOOD_SIZE];
+       tasklet_norace uint8_t time;
+       tasklet_norace uint8_t last;
+
+       command error_t Init.init()
+       {
+               uint8_t i;
+
+               for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
+                       nodes[i] = AM_BROADCAST_ADDR;
+       
+               return SUCCESS;
+       }
+
+       inline tasklet_async command am_addr_t Neighborhood.getNode(uint8_t index)
+       {
+               return nodes[index];
+       }
+
+       inline tasklet_async command uint8_t Neighborhood.getAge(uint8_t index)
+       {
+               return time - ages[index];
+       }
+
+       tasklet_async uint8_t command Neighborhood.getIndex(am_addr_t node)
+       {
+               uint8_t i;
+
+               if( nodes[last] == node )
+                       return last;
+
+               for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
+               {
+                       if( nodes[i] == node )
+                       {
+                               last = i;
+                               break;
+                       }
+               }
+
+               return i;
+       }
+
+       tasklet_async uint8_t command Neighborhood.insertNode(am_addr_t node)
+       {
+               uint8_t i;
+               uint8_t maxAge;
+
+               if( nodes[last] == node )
+               {
+                       if( ages[last] == time )
+                               return last;
+
+                       ages[last] = ++time;
+                       maxAge = 0x80;
+               }
+               else
+               {
+                       uint8_t oldest = 0;
+                       maxAge = 0;
+
+                       for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
+                       {
+                               uint8_t age;
+
+                               if( nodes[i] == node )
+                               {
+                                       last = i;
+                                       if( ages[i] == time )
+                                               return i;
+
+                                       ages[i] = ++time;
+                                       maxAge = 0x80;
+                                       break;
+                               }
+
+                               age = time - ages[i];
+                               if( age > maxAge )
+                               {
+                                       maxAge = age;
+                                       oldest = i;
+                               }
+                       }
+
+                       if( i == NEIGHBORHOOD_SIZE )
+                       {
+                               signal Neighborhood.evicted(oldest);
+
+                               last = oldest;
+                               nodes[oldest] = node;
+                               ages[oldest] = ++time;
+                               flags[oldest] = 0;
+                       }
+               }
+
+               if( (time & 0x7F) == 0x7F && maxAge >= 0x7F )
+               {
+                       for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
+                       {
+                               if( (ages[i] | 0x7F) != time )
+                                       ages[i] = time & 0x80;
+                       }
+               }
+
+               return last;
+       }
+
+       inline tasklet_async command bool NeighborhoodFlag.get[uint8_t bit](uint8_t index)
+       {
+               return flags[index] & (1 << bit);
+       }
+
+       inline tasklet_async command void NeighborhoodFlag.set[uint8_t bit](uint8_t index)
+       {
+               flags[index] |= (1 << bit);
+       }
+
+       inline tasklet_async command void NeighborhoodFlag.clear[uint8_t bit](uint8_t index)
+       {
+               flags[index] &= ~(1 << bit);
+       }
+
+       tasklet_async command void NeighborhoodFlag.clearAll[uint8_t bit]()
+       {
+               uint8_t i;
+
+               bit = ~(1 << bit);
+
+               for(i = 0; i < NEIGHBORHOOD_SIZE; ++i)
+                       flags[i] &= bit;
+       }
+}
diff --git a/tos/chips/rf2xx/util/PacketField.nc b/tos/chips/rf2xx/util/PacketField.nc
new file mode 100644 (file)
index 0000000..3f90293
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface PacketField<value_type>
+{
+       /**
+        * Returns TRUE if the value is set for this message.
+        */
+       async command bool isSet(message_t* msg);
+
+       /**
+        * Returns the stored value of this field in the message. If the
+        * value is not set, then the returned value is undefined.
+        */
+       async command value_type get(message_t* msg);
+
+       /**
+        * Clears the isSet flag.
+        */
+       async command void clear(message_t* msg);
+
+       /**
+        * Sets the isSet false to TRUE and the time stamp value to the 
+        * specified value.
+        */
+       async command void set(message_t* msg, value_type value);
+}
diff --git a/tos/chips/rf2xx/util/PacketFlag.nc b/tos/chips/rf2xx/util/PacketFlag.nc
new file mode 100644 (file)
index 0000000..3efabdb
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface PacketFlag
+{
+       /**
+        * Returns if the flag is set for this message. 
+        */
+       async command bool get(message_t* msg);
+
+       /**
+        * Sets the flag in this message to the specified value.
+        */
+       async command void setValue(message_t* msg, bool value);
+
+       /**
+        * Sets the flag in this message to TRUE
+        */
+       async command void set(message_t* msg);
+
+       /**
+        * Sets the flag in this message to FALSE
+        */
+       async command void clear(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/util/RadioAlarm.nc b/tos/chips/rf2xx/util/RadioAlarm.nc
new file mode 100755 (executable)
index 0000000..d09c4f0
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+interface RadioAlarm
+{
+       /**
+        * Returns TRUE if the alarm is free and ready to be used. Once the alarm
+        * is free, it cannot become nonfree in the same tasklet block. Note,
+        * if the alarm is currently set (even if for ourselves) then it is not free.
+        */
+       tasklet_async command bool isFree();
+
+       /**
+        * Waits till the specified timeout period expires. The alarm must be free.
+        */
+       tasklet_async command void wait(uint16_t timeout);
+
+       /**
+        * Cancels the running alarm. The alarm must be pending.
+        */
+       tasklet_async command void cancel();
+
+       /**
+        * This event is fired when the specified timeout period expires.
+        */
+       tasklet_async event void fired();
+
+       /**
+        * Returns the current time as measured by the radio stack.
+        */
+       async command uint16_t getNow();
+}
diff --git a/tos/chips/rf2xx/util/RadioAlarmC.nc b/tos/chips/rf2xx/util/RadioAlarmC.nc
new file mode 100644 (file)
index 0000000..68f53d5
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration RadioAlarmC
+{
+       provides
+       {
+               interface RadioAlarm[uint8_t id]; // use unique("RadioAlarm")
+       }
+
+       uses
+       {
+               interface Alarm<TRadio, uint16_t> @exactlyonce();
+       }
+}
+
+implementation
+{
+       components RadioAlarmP, TaskletC;
+
+       RadioAlarm = RadioAlarmP;
+       Alarm = RadioAlarmP;
+       RadioAlarmP.Tasklet -> TaskletC;
+}
diff --git a/tos/chips/rf2xx/util/RadioAlarmP.nc b/tos/chips/rf2xx/util/RadioAlarmP.nc
new file mode 100644 (file)
index 0000000..537b76a
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+#include <RadioAssert.h>
+
+module RadioAlarmP
+{
+       provides
+       {
+               interface RadioAlarm[uint8_t id];
+       }
+
+       uses
+       {
+               interface Alarm<TRadio, uint16_t>;
+               interface Tasklet;
+       }
+}
+
+implementation
+{
+       norace uint8_t state;
+       enum
+       {
+               STATE_READY = 0,
+               STATE_WAIT = 1,
+               STATE_FIRED = 2,
+       };
+
+       tasklet_norace uint8_t alarm;
+
+       async event void Alarm.fired()
+       {
+               atomic
+               {
+                       if( state == STATE_WAIT )
+                               state = STATE_FIRED;
+               }
+
+               call Tasklet.schedule();
+       }
+
+       inline async command uint16_t RadioAlarm.getNow[uint8_t id]()
+       {
+               return call Alarm.getNow();
+       }
+
+       tasklet_async event void Tasklet.run()
+       {
+               if( state == STATE_FIRED )
+               {
+                       state = STATE_READY;
+                       signal RadioAlarm.fired[alarm]();
+               }
+       }
+
+       default tasklet_async event void RadioAlarm.fired[uint8_t id]()
+       {
+       }
+
+       inline tasklet_async command bool RadioAlarm.isFree[uint8_t id]()
+       {
+               return state == STATE_READY;
+       }
+
+       tasklet_async command void RadioAlarm.wait[uint8_t id](uint16_t timeout)
+       {
+               ASSERT( state == STATE_READY );
+
+               alarm = id;
+               state = STATE_WAIT;
+               call Alarm.start(timeout);
+       }
+
+       tasklet_async command void RadioAlarm.cancel[uint8_t id]()
+       {
+               ASSERT( alarm == id );
+               ASSERT( state != STATE_READY );
+
+               call Alarm.stop();
+               state = STATE_READY;
+       }
+}
diff --git a/tos/chips/rf2xx/util/RadioAssert.h b/tos/chips/rf2xx/util/RadioAssert.h
new file mode 100644 (file)
index 0000000..79ff180
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __RADIOASSERT_H__
+#define __RADIOASSERT_H__
+
+#ifdef RADIO_DEBUG
+
+       void assert(bool condition, const char* file, uint16_t line);
+       #define ASSERT(COND) assert(COND, __FILE__, __LINE__)
+
+#else
+
+       #define ASSERT(COND) for(;0;)
+
+#endif
+
+#endif//__RADIOASSERT_H__
diff --git a/tos/chips/rf2xx/util/RadioCCA.nc b/tos/chips/rf2xx/util/RadioCCA.nc
new file mode 100755 (executable)
index 0000000..78e1694
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+interface RadioCCA
+{
+       /**
+        * Starts the clear channel assesment procedure. Returns EBUSY if the radio
+        * is currently servicing a clear channel assesment, and SUCCESS otherwise.
+        * The check will be performed only in the RX_READY state.
+        */
+       tasklet_async command error_t request();
+
+       /**
+        * Signals the completion of the clear channel assesment send command.
+        * SUCCESS means the channel is clear, EBUSY means the channel is not
+        * clear, and FAIL means that the clear channel assesment could not
+        * be finished or the operation was cancelled.
+        */
+       tasklet_async event void done(error_t error);
+}
diff --git a/tos/chips/rf2xx/util/RadioChannel.nc b/tos/chips/rf2xx/util/RadioChannel.nc
new file mode 100644 (file)
index 0000000..5fa6c24
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface RadioChannel
+{
+       /**
+        * Sets the current channel. Returns EBUSY if the stack is unable
+        * to change the channel this time (some other operation is in progress),
+        * EALREADY if the selected channel is already set, SUCCESS otherwise.
+        */
+       command error_t setChannel(uint8_t channel);
+
+       /**
+        * This event is signaled exactly once for each sucessfully posted state 
+        * setChannel command when it is completed.
+        */
+       event void setChannelDone();
+
+       /**
+        * Returns the currently selected channel.
+        */
+       command uint8_t getChannel();
+}
diff --git a/tos/chips/rf2xx/util/RadioPacket.nc b/tos/chips/rf2xx/util/RadioPacket.nc
new file mode 100644 (file)
index 0000000..17979ea
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+interface RadioPacket
+{
+       /**
+        * This command returns the length of the header. The header
+        * starts at the first byte of the message_t structure 
+        * (some layers may add dummy bytes to allign the payload to
+        * the msg->data section).
+        */
+       async command uint8_t headerLength(message_t* msg);
+
+       /**
+        * Returns the length of the payload. The payload starts right
+        * after th header.
+        */
+       async command uint8_t payloadLength(message_t* msg);
+
+       /**
+        * Sets the length of the payload.
+        */
+       async command void setPayloadLength(message_t* msg, uint8_t length);
+
+       /**
+        * Returns the maximum length that can be set for this message.
+        */
+       async command uint8_t maxPayloadLength();
+
+       /**
+        * Returns the length of the metadata section. The metadata section
+        * is at the very end of the message_t structure and grows downwards.
+        */
+       async command uint8_t metadataLength(message_t* msg);
+
+       /**
+        * Clears all metadata and sets all default values in the headers.
+        */
+       async command void clear(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/util/RadioReceive.nc b/tos/chips/rf2xx/util/RadioReceive.nc
new file mode 100755 (executable)
index 0000000..0e8330f
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+interface RadioReceive
+{
+       /**
+        * This event is fired when the header is received/downloaded and the 
+        * higher layers are consulted whether it needs to be downloaded and 
+        * further processed. Return FALSE if the message should be discarded.
+        * In particular, the message buffer layer returns FALSE if there is
+        * no space for a new message, so this message will not get acknowledged.
+        */
+       tasklet_async event bool header(message_t* msg);
+
+       /**
+        * Signals the reception of a message, but only for those messages for
+        * which SUCCESS was returned in the header event. The usual owner rules 
+        * apply to the message pointers.
+        */
+       tasklet_async event message_t* receive(message_t* msg);
+}
diff --git a/tos/chips/rf2xx/util/RadioSend.nc b/tos/chips/rf2xx/util/RadioSend.nc
new file mode 100755 (executable)
index 0000000..5943794
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+interface RadioSend
+{
+       /**
+        * Starts the transmission of the given message. This command must not
+        * be called while another send is in progress (so one must wait for the
+        * sendDone event). Returns EBUSY if a reception is in progress or for
+        * some other reason the request cannot be temporarily satisfied (e.g.
+        * the SPI bus access could not be acquired). In this case the send 
+        * command could be retried from a tasklet. Returns SUCCESS if the 
+        * transmission could be started. In this case sendDone will be fired.
+        */
+       tasklet_async command error_t send(message_t* msg);
+       
+       /**
+        * Signals the completion of the send command, exactly once for each 
+        * successfull send command. If the returned error code is SUCCESS, then 
+        * the message was sent (may not have been acknowledged), otherwise 
+        * the message was not transmitted over the air.
+        */
+       tasklet_async event void sendDone(error_t error);
+
+       /**
+        * This event is fired when the component is most likely able to accept 
+        * a send request. If the send command has returned with a failure, then
+        * this event will be called at least once in the near future.
+        */
+       tasklet_async event void ready();
+}
diff --git a/tos/chips/rf2xx/util/RadioState.nc b/tos/chips/rf2xx/util/RadioState.nc
new file mode 100644 (file)
index 0000000..cae7781
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+interface RadioState
+{
+       /**
+        * Moves to radio into sleep state with the lowest power consumption but 
+        * highest wakeup time. The radio cannot send or receive in this state 
+        * and releases all access to shared resources (e.g. SPI bus). 
+        */
+       tasklet_async command error_t turnOff();
+
+       /**
+        * The same as the turnOff command, except it is not as deep sleep, and
+        * it is quicker to recover from this state.
+        */
+       tasklet_async command error_t standby();
+
+       /**
+        * Goes into receive state. The radio continuously receive messages 
+        * and able to transmit.
+        */
+       tasklet_async command error_t turnOn();
+
+       /**
+        * Sets the current channel. Returns EBUSY if the stack is unable
+        * to change the channel this time (some other operation is in progress)
+        * SUCCESS otherwise.
+        */
+       tasklet_async command error_t setChannel(uint8_t channel);
+
+       /**
+        * This event is signaled exactly once for each sucessfully posted state 
+        * transition and setChannel command when it is completed.
+        */
+       tasklet_async event void done();
+
+       /**
+        * Returns the currently selected channel.
+        */
+       tasklet_async command uint8_t getChannel();
+}
diff --git a/tos/chips/rf2xx/util/Tasklet.h b/tos/chips/rf2xx/util/Tasklet.h
new file mode 100644 (file)
index 0000000..e4cd520
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __TASKLET_H__
+#define __TASKLET_H__
+
+#ifdef TASKLET_IS_TASK
+
+       #define tasklet_async
+       #define tasklet_norace
+
+#else
+
+       #define tasklet_async   async   
+       #define tasklet_norace  norace
+
+#endif
+
+#endif//__TASKLET_H__
diff --git a/tos/chips/rf2xx/util/Tasklet.nc b/tos/chips/rf2xx/util/Tasklet.nc
new file mode 100755 (executable)
index 0000000..527400a
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+
+/**
+ * This interface is useful in building state machines when the state 
+ * transitions should be executed atomically but with interrupts enabled. 
+ * All state transitions should take place in the run event handler or
+ * in blocks protected by the suspend and resume commands.
+ */
+interface Tasklet
+{
+       /**
+        * This method is executed atomically. 
+        */
+       tasklet_async event void run();
+
+       /**
+        * Makes sure that the run event is called at least once more. If the 
+        * run event is currently not executing, then it  is called immediately 
+        * and this command returns only after the completion of the run event. 
+        * If the run event is currently executed, then this method returns at 
+        * once, and makes sure that the run event is called once more when 
+        * it is finished. If this method is called from a task, then by the 
+        * above rules, the run event will be called from a task as well.
+        */
+       async command void schedule();
+
+       /**
+        * Enters a critical section of the code and meakes sure that the
+        * run event is not called while in this section. No long running
+        * computation should be called from the critical session, and
+        * in particular no user event should be fired. This call is only
+        * possible from task context, otherwise we cannot guarantee that
+        * the run event is not currently running. The suspend calls
+        * can be nested. It is very important that the same number of
+        * resume commands must be called in all control paths, e.g. be very
+        * careful with the return and break commands.
+        */
+       command void suspend();
+
+       /**
+        * Leaves the critical section. This call is conly possible from 
+        * task context. If there were scheduled executions of the run
+        * event, then those will be called before this command returns.
+        */
+       command void resume();
+}
diff --git a/tos/chips/rf2xx/util/TaskletC.nc b/tos/chips/rf2xx/util/TaskletC.nc
new file mode 100755 (executable)
index 0000000..360f54f
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <Tasklet.h>
+#include <RadioAssert.h>
+
+module TaskletC
+{
+       provides interface Tasklet;
+}
+
+implementation
+{
+#ifdef TASKLET_IS_TASK
+
+       task void tasklet()
+       {
+               signal Tasklet.run();
+       }
+
+       inline async command void Tasklet.schedule()
+       {
+               post tasklet();
+       }
+
+       inline command void Tasklet.suspend()
+       {
+       }
+
+       inline command void Tasklet.resume()
+       {
+       }
+
+#else
+       
+       /**
+        * The lower 7 bits contain the number of suspends plus one if the run 
+        * event is currently beeing executed. The highest bit is set if the run 
+        * event needs to be called again when the suspend count goes down to zero.
+        */
+       uint8_t state;
+
+       void doit()
+       {
+               for(;;)
+               {
+                       signal Tasklet.run();
+
+                       atomic
+                       {
+                               if( state == 1 )
+                               {
+                                       state = 0;
+                                       return;
+                               }
+
+                               ASSERT( state == 0x81 );
+                               state = 1;
+                       }
+               }
+       }
+
+       inline command void Tasklet.suspend()
+       {
+               atomic ++state;
+       }
+
+       command void Tasklet.resume()
+       {
+               atomic
+               {
+                       if( --state != 0x80 )
+                               return;
+
+                       state = 1;
+               }
+
+               doit();
+       }
+
+       async command void Tasklet.schedule()
+       {
+               atomic
+               {
+                       if( state != 0 )
+                       {
+                               state |= 0x80;
+                               return;
+                       }
+
+                       state = 1;
+               }
+
+               doit();
+       }
+
+#endif
+}
index 9bab590445078f3a6e83c7ab814c413a99daf4e1..0fef9da32bc6fad0fe50d878cb61793e18312eff 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Header definitions for the SCP1000.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #ifndef SCP1000_H
 #define SCP1000_H
 
index d84a665179d67036197f3f29c3892e9c7bd6d4be..f9be62f25f7bacadc5a5268b63854d012f2b0b11 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Main user component for the SCP1000 pressure sensor.  This is a highly
  * abstracted component designed for infrequent pressure measurements where
  * energy costs are to be minimized.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "Scp1000.h"
 
 configuration Scp1000C {
index 7d9789f7f6d20184cddfa0c185721fb4bb890cab..7ff57aa968437ac822f3f8a8380195d0c061f177 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * scp1000 implementation.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
 
 #include "Scp1000.h"
+
 generic module Scp1000P() @safe()
 {
   provides interface ReadRef<scp1000_t>;
index 6140f42ba80a65d92bbd21f3f50c31c255756707..d4f51e8b1b5ce0c2a1a9240b76293b033f80ef6d 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * This BusyWait interface is solely designed for use in providing the
  * necessary 5us timing when bit-banging the SHT1X sensibus clock pin in
  * is designed for such platforms.  Platforms using higher performance
  * microprocessors may need to override this component with a platform-specific
  * one to provide the necessary wait time.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 module SensirionBusyWaitC {
   provides interface BusyWait<TMicro, uint8_t>;
 }
index 12019b56577ae8cf36c5c5a2ec71df7fbb361627..e454de79d88c27d03d5b8dafb4aca2e937632343 100644 (file)
@@ -161,7 +161,7 @@ implementation {
     
     // don't allow appends larger than maximum record size
     if ( len > MAX_RECORD_SIZE )
-      return ESIZE;
+      return EINVAL;
     
     // move to next block if current block doesn't have enough space
     if ( sizeof( m_header ) + len > bytes_left )
@@ -201,7 +201,7 @@ implementation {
   
   uint8_t calcSector( uint8_t client, stm25p_addr_t addr ) {
     uint8_t sector = call Sector.getNumSectors[ client ]();
-    return (uint8_t)( addr >> STM25P_SECTOR_SIZE_LOG2 ) % sector;
+    return (uint8_t)(( addr >> STM25P_SECTOR_SIZE_LOG2 ) % sector);
   }
 
   stm25p_addr_t calcAddr( uint8_t client, stm25p_addr_t addr  ) {
@@ -342,7 +342,7 @@ implementation {
        else {
          log_info->write_addr += sizeof( m_addr );
          m_rw_state = S_SEARCH_RECORDS;
-         call Sector.read[ id ]( log_info->write_addr, &m_header,
+         call Sector.read[ id ]( calcAddr(id, log_info->write_addr), &m_header,
                                  sizeof( m_header ) );
        }
       }
@@ -373,7 +373,7 @@ implementation {
        log_info->read_addr += sizeof( m_header ) + m_header;
        // if not yet at cookie, keep searching
        if ( log_info->read_addr < m_log_state[ id ].cookie ) {
-         call Sector.read[ id ]( log_info->read_addr, &m_header,
+         call Sector.read[ id ]( calcAddr(id, log_info->read_addr), &m_header,
                                  sizeof( m_header ) );
        }
        // at or passed cookie, stop
index 1b2cfba4db52ce624549e6c05e67f2bdba7f370a..4810c5a5339fe939af016830a7ae6e726f90920b 100644 (file)
@@ -53,8 +53,7 @@ configuration CsmaMacC {
   }
 }
 implementation {
-  components  MainC,
-      Tda5250RadioC,    
+  components  Tda5250RadioC,    
       CsmaMacP,
       RssiFixedThresholdCMC as Cca,
       new Alarm32khz16C() as Timer,
@@ -67,8 +66,6 @@ implementation {
       ,PlatformLedsC
 #endif
       ;
-              
-    MainC.SoftwareInit -> CsmaMacP;
     
     SplitControl = CsmaMacP;
     
@@ -104,11 +101,9 @@ implementation {
     CsmaMacP.TimeDiff16 -> TimeDiffC;
     CsmaMacP.LocalTime32kHz -> LocalTimeC;
 
-#ifdef MAC_DEBUG
-    CsmaMacP.Led0 -> PlatformLedsC.Led0;
-    CsmaMacP.Led1 -> PlatformLedsC.Led1;
-    CsmaMacP.Led2 -> PlatformLedsC.Led2;
-    CsmaMacP.Led3 -> PlatformLedsC.Led3;
+#ifdef MACM_DEBUG
+    components new SerialDebugC() as SD;
+    CsmaMacP.SerialDebug -> SD;
 #endif    
 }
 
index 2b8b57fecd8f93836c518f94b939edaccd3a8996..7f17e4145d0ef57d8fd763f2ceea178dd0d0cac0 100644 (file)
@@ -45,7 +45,6 @@
 // #define MACM_DEBUG                 // debug...
 module CsmaMacP {
     provides {
-        interface Init;
         interface SplitControl;
         interface MacSend;
         interface MacReceive;
@@ -79,16 +78,22 @@ module CsmaMacP {
         interface LocalTime<T32khz> as LocalTime32kHz;
         
 #ifdef MACM_DEBUG
-        interface GeneralIO as Led0;
-        interface GeneralIO as Led1;
-        interface GeneralIO as Led2;
-        interface GeneralIO as Led3;
+        interface SerialDebug;
 #endif
     }
 }
 implementation
 {
+    /****** debug vars & defs & functions  ***********************/
+#ifdef MACM_DEBUG
+    void sdDebug(uint16_t p) {
+        call SerialDebug.putPlace(p);
+    };
+#else
+    void sdDebug(uint16_t p) {};
+#endif
 
+    /******* constants and type definitions *********************/
     enum {
 
         BYTE_TIME=ENCODED_32KHZ_BYTE_TIME,           // phy encoded
@@ -143,17 +148,17 @@ implementation
     } flags_t;
 
     /* Packet vars */
-    message_t* txBufPtr;
+    message_t* txBufPtr = NULL;
     message_t ackMsg;
 
     uint8_t txLen;
-    uint8_t shortRetryCounter;
+    uint8_t shortRetryCounter = 0;
 
-    uint8_t longRetryCounter;
+    uint8_t longRetryCounter = 0;
     unsigned checkCounter;
     
-    macState_t macState;
-    uint8_t flags;
+    macState_t macState = INIT;
+    uint8_t flags = 0;
     uint8_t seqNo;
     
     uint16_t restLaufzeit;
@@ -162,77 +167,6 @@ implementation
 
     uint32_t rxTime = 0;
     
-    /****** debug vars & defs & functions  ***********************/
-#ifdef MACM_DEBUG
-#define HISTORY_ENTRIES 100
-    typedef struct {
-        int index;
-        macState_t state;
-        int        place;
-    } history_t;
-    
-    history_t history[HISTORY_ENTRIES];
-    unsigned histIndex;
-    void storeOldState(int p) {
-        atomic {
-            history[histIndex].index = histIndex;
-            history[histIndex].state = macState;
-            history[histIndex].place = p;
-            histIndex++;
-            if(histIndex >= HISTORY_ENTRIES) histIndex = 0;
-        }
-    }
-#else
-    void storeOldState(int p) {};
-#endif
-
-    void signalFailure(uint8_t place) {
-#ifdef MACM_DEBUG
-        unsigned long i;
-        atomic {
-            for(;;) {
-                call Led0.set();
-                call Led1.clr();
-                call Led2.clr();
-                call Led3.clr();
-                
-                for(i = 0; i < 1000000; i++) {
-                    ;
-                }
-
-                (place & 1) ? call Led0.set() : call Led0.clr();
-                (place & 2) ? call Led1.set() : call Led1.clr();
-                (place & 4) ? call Led2.set() : call Led2.clr();
-                (place & 8) ? call Led3.set() : call Led3.clr();
-
-                for(i = 0; i < 1000000; i++) {
-                    ;
-                }
-
-                (macState & 1) ? call Led0.set() : call Led0.clr();
-                (macState & 2) ? call Led1.set() : call Led1.clr();
-                (macState & 4) ? call Led2.set() : call Led2.clr();
-                (macState & 8) ? call Led3.set() : call Led3.clr();
-
-                for(i = 0; i < 1000000; i++) {
-                    ;
-                }
-            }
-        }
-#endif
-    }
-
-    void signalMacState() {
-#ifdef MACM_DEBUG
-/*
-         (macState & 1) ? call Led0.set() : call Led0.clr();
-         (macState & 2) ? call Led1.set() : call Led1.clr();
-         (macState & 4) ? call Led2.set() : call Led2.clr();
-         (macState & 8) ? call Led3.set() : call Led3.clr();
-*/
-#endif
-    }
-    
     /****** Secure switching of radio modes ***/
     
     task void SetRxModeTask();
@@ -356,7 +290,7 @@ implementation
         longRetryCounter++;
         shortRetryCounter = 1;
         if(longRetryCounter > MAX_LONG_RETRY) {
-            storeOldState(13);
+            sdDebug(13);
             getMetadata(txBufPtr)->ack = WAS_NOT_ACKED;
             signalSendDone(FAIL);
         }
@@ -379,7 +313,7 @@ implementation
             setFlag(&flags, RESUME_BACKOFF);
             restLaufzeit = backoff(longRetryCounter);
             updateRetryCounters();
-            storeOldState(92);
+            sdDebug(92);
         }
     }
 
@@ -396,14 +330,13 @@ implementation
     void checkSend() {
         if((txBufPtr != NULL) && (macState == RX) && (!call Timer.isRunning())) {
             macState = CCA;
-            signalMacState();
             checkCounter = 0;
             requestAdc();
             call Timer.start(DATA_DETECT_TIME);
-            storeOldState(170);
+            sdDebug(170);
         }
         else {
-            storeOldState(171);
+            sdDebug(171);
             post ReleaseAdcTask();
         }
     }
@@ -455,29 +388,11 @@ implementation
         return isFlagSet(&token, TOKEN_ACK_FLAG);
     }
     
-    /**************** Init ************************/
-    
-    command error_t Init.init(){
-        atomic {
-            txBufPtr = NULL;
-            macState = INIT;
-            signalMacState();
-            shortRetryCounter = 0;
-            longRetryCounter = 0;
-            flags = 0;
-#ifdef MACM_DEBUG
-            histIndex = 0;
-#endif
-        }
-        return SUCCESS;
-    }
-
     /****************  SplitControl  *****************/
 
     task void StartDoneTask() {
         atomic {
             macState = RX;
-            signalMacState();
             call UartPhyControl.setNumPreambles(MIN_PREAMBLE_BYTES);
         }
         post ReleaseAdcTask();
@@ -488,9 +403,9 @@ implementation
         call CcaStdControl.start();
         atomic {
             macState = INIT;
-            signalMacState();
+            
             setRxMode();
-            storeOldState(1);
+            sdDebug(1);
         }
         return SUCCESS;
     }
@@ -499,11 +414,15 @@ implementation
         atomic {
             if (macState != RX) {
                 post StopDone();
-                storeOldState(2);
+                sdDebug(2);
             } else {
-                storeOldState(3);
+                sdDebug(3);
                 call Timer.stop();
-                call Init.init();
+                txBufPtr = NULL;
+                macState = INIT;
+                shortRetryCounter = 0;
+                longRetryCounter = 0;
+                flags = 0;
                 signal SplitControl.stopDone(SUCCESS); 
             }
         }
@@ -511,7 +430,7 @@ implementation
     
     command error_t SplitControl.stop() {
         call CcaStdControl.stop();
-        storeOldState(4);
+        sdDebug(4);
         post StopDone();
         return SUCCESS;
     }
@@ -542,13 +461,13 @@ implementation
         atomic  {
             setFlag(&flags, RSSI_STABLE);
             if(macState == INIT) {
-                storeOldState(11);
+                sdDebug(11);
                 if(call RssiAdcResource.isOwner()) {
                     call ChannelMonitorControl.updateNoiseFloor();
                 }
             }
             else {
-                storeOldState(12);
+                sdDebug(12);
             }
         }
     }
@@ -557,9 +476,9 @@ implementation
         post postponeReRx();
         atomic {
             if(macState == SW_RX) {
-                storeOldState(21);
+                sdDebug(21);
                 macState = RX;
-                signalMacState();
+                
                 if(isFlagSet(&flags, RESUME_BACKOFF)) {
                     clearFlag(&flags, RESUME_BACKOFF);
                     call Timer.start(restLaufzeit);
@@ -568,16 +487,14 @@ implementation
                 }
             }
             else if(macState == SW_RX_ACK) {
-                storeOldState(22);
+                sdDebug(22);
                 macState = RX_ACK;
-                signalMacState();
             }
             else if(macState == INIT) {
-                storeOldState(24);
+                sdDebug(24);
             }
             else {
-                storeOldState(25);
-                signalFailure(1);
+                sdDebug(25);
             }
         }
     }
@@ -586,31 +503,27 @@ implementation
         post postponeReRx();
         atomic {
             if(macState == SW_TX) {
-                storeOldState(30);
+                sdDebug(30);
                 if(txBufPtr) {
                     macState = TX;
-                    signalMacState();
                     if(call PacketSend.send(txBufPtr, txLen) == SUCCESS) {
-                        storeOldState(31);
+                        sdDebug(31);
                     } else {
-                        storeOldState(32);
-                        signalFailure(2);
+                        sdDebug(32);
                     }
                 }
             }
             else if(macState == SW_TX_ACK) {
                 macState = TX_ACK;
-                signalMacState();
+                
                 if(call PacketSend.send(&ackMsg, 0) == SUCCESS) {
-                    storeOldState(53);
+                    sdDebug(53);
                 } else {
-                    storeOldState(54);
-                    signalFailure(6);
+                    sdDebug(54);
                 }
             }
             else {
-                storeOldState(33);
-                signalFailure(3);
+                sdDebug(33);
             }
         }
     }
@@ -620,11 +533,13 @@ implementation
         error_t err = SUCCESS;
         atomic {
             if((shortRetryCounter == 0) && (txBufPtr == NULL) && (macState != INIT)) { 
-              storeOldState(40);
+              sdDebug(40);
                 shortRetryCounter = 1;
                 longRetryCounter = 1;
                 txBufPtr = msg;
                 txLen = len;
+                sdDebug(10);
+                sdDebug(len);
                 seqNo++;
                 if(seqNo >= TOKEN_ACK_FLAG) seqNo = 1;
                 getHeader(msg)->token = seqNo;
@@ -632,7 +547,7 @@ implementation
                 if(macState != RX_P) checkSend();
             }
             else {
-                storeOldState(41);
+                sdDebug(41);
                 err = EBUSY;
             }
         }
@@ -643,14 +558,14 @@ implementation
         error_t err = SUCCESS;
         if((shortRetryCounter != 0) && (txBufPtr == msg) &&
            (macState != TX) && (macState != RX_ACK) && (macState != SW_RX_ACK)) {
-            storeOldState(50);
+            sdDebug(50);
             shortRetryCounter = 0;
             txBufPtr = NULL;
             txLen = 0;
             signal MacSend.sendDone(msg, ECANCEL);
         }
         else {
-            storeOldState(51);
+            sdDebug(51);
             err = FAIL;
         }
         return err;
@@ -660,28 +575,27 @@ implementation
     async event void PacketReceive.receiveDetected() {
         rssiValue = INVALID_SNR;
         if(macState <= RX_ACK) {
-            storeOldState(60);
+            sdDebug(60);
             interruptBackoffTimer();
             if(macState == CCA) computeBackoff();
         }
         if(macState <= RX) {
-            storeOldState(61);
+            sdDebug(61);
             macState = RX_P;
-            signalMacState();
+            
             requestAdc();
         }
         else if(macState <= RX_ACK) {
-            storeOldState(62);
+            sdDebug(62);
             macState = RX_ACK_P;
-            signalMacState();
+            
         }
         else if(macState == INIT) {
-            storeOldState(63);
+            sdDebug(63);
         }
         else {
           post ReleaseAdcTask();  
-          storeOldState(64);
-          signalFailure(4);    
+          sdDebug(64);
         } 
     }
     
@@ -691,7 +605,7 @@ implementation
         macState_t action = RX;
         if(macState == RX_P) {
             if(error == SUCCESS) {
-                storeOldState(82);
+                sdDebug(82);
                 isCnt = isControl(msg);
                 if(msgIsForMe(msg)) {
                     if(!isCnt) {
@@ -701,43 +615,43 @@ implementation
                             rememberMsg(m);   
                         }
                         if(needsAckRx(msg)) {
-                            storeOldState(87);
+                            sdDebug(87);
                             action = CCA_ACK;
                         } else {
-                            storeOldState(88);
+                            sdDebug(88);
                         }
                     }
                     else {
-                        storeOldState(89);
+                        sdDebug(89);
                     }
                 }
                 else {
-                    storeOldState(90);
+                    sdDebug(90);
                 }
             }
             else {
-                storeOldState(91);
+                sdDebug(91);
             }
         }
         else if(macState == RX_ACK_P) {
             if(error == SUCCESS) {
                 if(ackIsForMe(msg)) {
-                    storeOldState(92);
+                    sdDebug(92);
                     (getMetadata(txBufPtr))->ack = WAS_ACKED;
                     signalSendDone(SUCCESS);
                 }
                 else {
-                    storeOldState(93);
+                    sdDebug(93);
                     updateLongRetryCounters();
                 }
             }
             else {
                 if(call Timer.isRunning()) {
-                    storeOldState(94);
+                    sdDebug(94);
                     action = RX_ACK;
                 }
                 else {
-                    storeOldState(95);
+                    sdDebug(95);
                     if(needsAckTx(txBufPtr)) {
                         updateLongRetryCounters();
                     }
@@ -753,16 +667,16 @@ implementation
         if(action == CCA_ACK) {
             prepareAck(msg);
             macState = CCA_ACK;
-            signalMacState();
+            
             call Timer.start(RX_SETUP_TIME - TX_SETUP_TIME + ADDED_DELAY);
         }
         else if(action == RX_ACK) {
             macState = RX_ACK;
-            signalMacState();
+            
         }
         else if(action == RX) {
             macState = RX;
-            signalMacState();
+            
             if(isFlagSet(&flags, RESUME_BACKOFF)) {
                 clearFlag(&flags, RESUME_BACKOFF);
                 call Timer.start(restLaufzeit);
@@ -773,15 +687,14 @@ implementation
         }
         else if(action == TX) {
             macState = SW_TX;
-            signalMacState();
+            
             setTxMode();
         }
         else if(action == INIT) {
             
         }
         else {
-            storeOldState(94);
-            signalFailure(11);
+            sdDebug(94);
         }
         post ReleaseAdcTask();
         return m;        
@@ -789,28 +702,24 @@ implementation
 
     async event void PacketSend.sendDone(message_t* msg, error_t error) {
         if(macState == TX) {
-            if(msg != txBufPtr) signalFailure(12);
             if(needsAckTx(msg)) {
-                storeOldState(97);
+                sdDebug(97);
                 macState = SW_RX_ACK;
-                signalMacState();
+                
                 call Timer.start(RX_ACK_TIMEOUT);
             } else {
-                storeOldState(99);
+                sdDebug(99);
                 signalSendDone(error);
                 macState = SW_RX;
-                signalMacState();
+                
             }
             setRxMode();
         }
         else if(macState == TX_ACK) {
             macState = SW_RX;
-            signalMacState();
+            
             setRxMode();
         }
-        else {
-            signalFailure(13);
-        }
         post ReleaseAdcTask();
     }
        
@@ -821,8 +730,8 @@ implementation
             computeBackoff();
             macState = RX;
             requestAdc();
-            storeOldState(150);
-            signalMacState();
+            sdDebug(150);
+            
             if(!call Timer.isRunning()) call Timer.start(TX_GAP_TIME >> 1);
         } else if(macState == RX) {
             if(!call Timer.isRunning()) call Timer.start(TX_GAP_TIME + backoff(0));
@@ -836,30 +745,30 @@ implementation
         else if(macState == CCA) {
             checkCounter++;
             if(checkCounter < 3) {
-                storeOldState(158);                
+                sdDebug(158);                
                 call Timer.start((TX_GAP_TIME + backoff(0))>>1);
                 requestAdc();
             }
             else {
                 call Timer.stop();
-                storeOldState(159);
+                sdDebug(159);
                 macState = SW_TX;
-                signalMacState();
+                
                 setTxMode();
             }
         }
     }
     
     async event void Timer.fired() {
-        storeOldState(100);
+        sdDebug(100);
         if(macState == CCA) {
             if((!call RssiAdcResource.isOwner()) || (call ChannelMonitor.start() != SUCCESS)) {
                 if(call UartPhyControl.isBusy()) {
-                    storeOldState(101);
+                    sdDebug(101);
                     checkOnBusy();
                 }
                 else {
-                    storeOldState(102);
+                    sdDebug(102);
                     checkOnIdle();
                 }
             } else {
@@ -868,31 +777,30 @@ implementation
         }
         else if(macState == RX_ACK) {
             if(needsAckTx(txBufPtr)) {
-                storeOldState(103);
+                sdDebug(103);
                 updateLongRetryCounters();
                 macState = RX;
                 call Timer.start(backoff(longRetryCounter));
             }
             else {
-                storeOldState(104);
-                signalFailure(7);                
+                sdDebug(104);
             }
         }
         else if(macState == CCA_ACK) {
-            storeOldState(160);
+            sdDebug(160);
             macState = SW_TX_ACK;
-            signalMacState();
+            
             setTxMode();
         }
         else if((macState == RX_ACK_P) || (macState == RX_P)) {
-            storeOldState(108);
+            sdDebug(108);
         }
         else if(macState == INIT) {
-            storeOldState(109);
+            sdDebug(109);
             post StartDoneTask();
         }
         else {
-            storeOldState(110);
+            sdDebug(110);
             checkSend();
         }
     }
@@ -901,13 +809,13 @@ implementation
 
     async event void ChannelMonitor.channelBusy() {
       clearFlag(&flags, CCA_PENDING);  
-      storeOldState(120);
+      sdDebug(120);
         checkOnBusy();
     }
 
     async event void ChannelMonitor.channelIdle() {
       clearFlag(&flags, CCA_PENDING);  
-      storeOldState(121);
+      sdDebug(121);
         checkOnIdle();
     }
 
@@ -916,11 +824,10 @@ implementation
     
     event void ChannelMonitorControl.updateNoiseFloorDone() {
         if(macState == INIT) {
-            storeOldState(122);
+            sdDebug(122);
             post StartDoneTask();
         } else {
-            storeOldState(124);
-            signalFailure(11);
+            sdDebug(124);
         }
     }
 
@@ -973,11 +880,11 @@ implementation
         macState_t ms;
         atomic ms = macState;
         if((ms == INIT) && isFlagSet(&flags, RSSI_STABLE)) {
-            storeOldState(145);
+            sdDebug(145);
             call ChannelMonitorControl.updateNoiseFloor();            
         }
         else {
-            storeOldState(146);
+            sdDebug(146);
             call RssiAdcResource.release();
         }
     }
index d734b492e17f9b7be6b634c810aa7005dcd91193..d0de4d0e4b5f0aba95df81735928e491a80095f1 100644 (file)
@@ -147,12 +147,14 @@ implementation
         SUB_HEADER_TIME=PHY_HEADER_TIME + sizeof(message_header_t)*BYTE_TIME,
         SUB_FOOTER_TIME=2*BYTE_TIME, // 2 bytes crc 
         // DEFAULT_SLEEP_TIME=1625,
+#ifndef DEFAULT_SLEEP_TIME
         DEFAULT_SLEEP_TIME=2048,
         // DEFAULT_SLEEP_TIME=4096,
         // DEFAULT_SLEEP_TIME=8192,
         // DEFAULT_SLEEP_TIME=16384,
         // DEFAULT_SLEEP_TIME=32768U,
         // DEFAULT_SLEEP_TIME=65535U,
+#endif
         DATA_DETECT_TIME=17,
         RX_SETUP_TIME=102,    // time to set up receiver
         TX_SETUP_TIME=58,     // time to set up transmitter
@@ -384,7 +386,7 @@ implementation
             sT = networkSleeptime;
         }
         if(msg == NULL) return;
-        macHdr = (red_mac_header_t *)call SubPacket.getPayload(msg, sizeof(red_mac_header_t) + length);
+        macHdr = (red_mac_header_t *)call SubPacket.getPayload(msg, sizeof(red_mac_header_t));
         macHdr->repetitionCounter = sT/(length * BYTE_TIME + SUB_HEADER_TIME + SUB_FOOTER_TIME + 
                                         TX_GAP_TIME) + 1;
         atomic {
@@ -403,6 +405,8 @@ implementation
                     call Timer.start((call Random.rand16() >> 3) & ZERO_BACKOFF_MASK);
                 }
                 else {
+                    sdDebug(332);
+                    sdDebug(macHdr->repetitionCounter);
                     call Timer.start(backoff(longRetryCounter));
                 }
             }
@@ -857,7 +861,7 @@ implementation
         rxStat.duplicate = PERF_UNKNOWN;
         rxStat.repCounter = 0xff;
 #endif
-        sdDebug(190);
+        // sdDebug(190);
         if(macState == RX_P) {
             // sdDebug(191);
             if(error == SUCCESS) {
@@ -1055,7 +1059,6 @@ implementation
         if(macState == RX_P) {
             rxTime = call LocalTime32kHz.get();
             call ChannelMonitor.rxSuccess();
-            sdDebug(221);
         }
     }
     
index bc904ebf6711929686dba886f7a1e8330a74933b..daa64e713da604a94f87a48e55079be891d71ee3 100644 (file)
@@ -140,6 +140,7 @@ implementation
         
         SUB_HEADER_TIME=PHY_HEADER_TIME + sizeof(message_header_t)*BYTE_TIME,
         SUB_FOOTER_TIME=2*BYTE_TIME, // 2 bytes crc 
+#ifndef DEFAULT_SLEEP_TIME
         DEFAULT_SLEEP_TIME=1625,
         // DEFAULT_SLEEP_TIME=3250,
         // DEFAULT_SLEEP_TIME=6500,
@@ -147,6 +148,7 @@ implementation
         // DEFAULT_SLEEP_TIME=16384,
         // DEFAULT_SLEEP_TIME=32768U,
         // DEFAULT_SLEEP_TIME=65535U,
+#endif
         DATA_DETECT_TIME=17,
         RX_SETUP_TIME=102,    // time to set up receiver
         TX_SETUP_TIME=58,     // time to set up transmitter
@@ -346,7 +348,7 @@ implementation
             sT = networkSleeptime;
         }
         if(msg == NULL) return;
-        macHdr = (red_mac_header_t *)call SubPacket.getPayload(msg, sizeof(red_mac_header_t) + length);
+        macHdr = (red_mac_header_t *)call SubPacket.getPayload(msg, sizeof(red_mac_header_t));
         macHdr->repetitionCounter = sT/(length * BYTE_TIME + SUB_HEADER_TIME + SUB_FOOTER_TIME) + 1;
         atomic {
             getHeader(msg)->token = seqNo;
@@ -539,6 +541,7 @@ implementation
                 MIN_BACKOFF_MASK = (MIN_BACKOFF_MASK << 1) + 1;
             }
             MIN_BACKOFF_MASK >>= 2;
+            if(MIN_BACKOFF_MASK < 0x3ff) MIN_BACKOFF_MASK=0x3ff;
         }
 #ifdef SPECKMAC_DEBUG
         call SerialDebug.putShortDesc("SpeckMacP");
@@ -950,9 +953,9 @@ implementation
     
     async event void RadioTimeStamping.transmittedSFD(uint16_t time, message_t* p_msg ) {
         if((macState == TX) && (p_msg == txBufPtr)) {
-            getMetadata(msg)->sfdtime = call LocalTime32kHz.get();
+            getMetadata(p_msg)->sfdtime = call LocalTime32kHz.get();
             txMacHdr->time =
-                call TimeDiff32.computeDelta(getMetadata(msg)->sfdtime,
+                call TimeDiff32.computeDelta(getMetadata(p_msg)->sfdtime,
                                              getMetadata(p_msg)->time);
         }
     }
index fcb8c7b7abb81782f0a955a6b542eded4ae02ced..9d11b1c4728024d8440da7e1f27568d1ea9e5a79 100644 (file)
@@ -380,7 +380,9 @@ implementation {
     }
 
     command void Packet.clear(message_t* msg) {
-       memset(msg, 0, sizeof(message_t));
+      memset(getHeader(msg), 0, sizeof(xe1205_header_t));
+      memset(getFooter(msg), 0, sizeof(xe1205_footer_t));
+      memset(getMetadata(msg), 0, sizeof(xe1205_metadata_t));
     }
 
     command uint8_t Packet.payloadLength(message_t* msg) {
index f588b84828d6f954abdec84568734b95e64cd64b..7aedd4fd5df7882ac90ff54d9727709f5f6801cf 100644 (file)
@@ -73,7 +73,11 @@ implementation {
     uint8_t rxFrameLen = 0;
     uint8_t nextTxLen=0;
     uint8_t nextRxLen;
-    char rxFrame[xe1205_mtu];
+    // Bugfix 29.1.2010: Plus 2 Bytes for the xe1205_phy_header_t 
+    // defined in XE1205SendReceiveP.nc
+    // This is just a hack to make it work, this entire code needs
+    // to be cleaned up & documented!
+    char rxFrame[xe1205_mtu + 2];
     uint8_t headerLen = 4;
 
     uint16_t stats_rxOverruns;
diff --git a/tos/interfaces/FastSpiByte.nc b/tos/interfaces/FastSpiByte.nc
new file mode 100644 (file)
index 0000000..42ef4ea
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+/**
+ * This is a natural extension of the SpiByte interface which allows fast 
+ * data transfers comparable to the SpiStream interface. You may want to
+ * use the following code sequence to write a buffer as fast as possible
+ *
+ *     call FastSpiByte.spiSplitWrite(data[0]); // start the first byte
+ *     for(i = 1; i < length; ++i) {
+ *        // finish the previous one and write the next one
+ *       call FastSpiByte.spiSplitReadWrite(data[i]);
+ *     }
+ *     call FastSpiByte.spiSlitRead(); // finish the last byte
+ *
+ * You can also do some useful computation (like calculate a CRC) while the
+ * hardware is sending the byte.
+ */
+interface FastSpiByte
+{
+       /**
+        * Starts a split-phase SPI data transfer with the given data.
+        * A splitRead/splitReadWrite command must follow this command even 
+        * if the result is unimportant.
+        */
+       async command void splitWrite(uint8_t data);
+
+       /**
+        * Finishes the split-phase SPI data transfer by waiting till 
+        * the write command comletes and returning the received data.
+        */
+       async command uint8_t splitRead();
+
+       /**
+        * This command first reads the SPI register and then writes
+        * there the new data, then returns. 
+        */
+       async command uint8_t splitReadWrite(uint8_t data);
+
+       /**
+        * This is the standard SpiByte.write command but a little
+        * faster as we should not need to adjust the power state there.
+        * (To be consistent, this command could have be named splitWriteRead).
+        */
+       async command uint8_t write(uint8_t data);
+}
diff --git a/tos/interfaces/Ieee154Packet.nc b/tos/interfaces/Ieee154Packet.nc
new file mode 100644 (file)
index 0000000..3f635ec
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#include <Ieee154.h>
+
+interface Ieee154Packet {
+
+  command ieee154_saddr_t address();
+  command ieee154_saddr_t destination(message_t* msg);
+  command ieee154_saddr_t source(message_t* msg);
+
+  command void setDestination(message_t* msg, ieee154_saddr_t addr);
+
+  command void setSource(message_t* msg, ieee154_saddr_t addr);
+
+  command bool isForMe(message_t* msg);
+
+  command ieee154_panid_t pan(message_t* msg);
+
+  command void setPan(message_t* msg, ieee154_panid_t grp);
+
+  command ieee154_panid_t localPan();
+}
diff --git a/tos/interfaces/Ieee154Send.nc b/tos/interfaces/Ieee154Send.nc
new file mode 100644 (file)
index 0000000..3d998f5
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <TinyError.h>
+#include <message.h>
+#include <Ieee154.h>
+
+/*
+ *
+ * The only change from the AMSend interface is that instead of
+ * sending to an AMID, we now send to a ieee154_saddr_t.
+ *
+ */
+
+interface Ieee154Send {
+
+  /** 
+    * Send a packet with a data payload of <tt>len</tt> to address
+    * <tt>addr</tt>. To determine the maximum available size, use the
+    * Packet interface of the component providing AMSend. If send
+    * returns SUCCESS, then the component will signal the sendDone
+    * event in the future; if send returns an error, it will not
+    * signal the event.  Note that a component may accept a send
+    * request which it later finds it cannot satisfy; in this case, it
+    * will signal sendDone with error code.
+    *
+    * @param addr   address to which to send the packet
+    * @param msg    the packet
+    * @param len    the length of the data in the packet payload
+    * @return       SUCCESS if the request to send succeeded and a
+    *               sendDone will be signaled later, EBUSY if the
+    *               abstraction cannot send now but will be able to
+    *               later, or FAIL if the communication layer is not
+    *               in a state that can send (e.g., off).
+    * @see          sendDone
+    */ 
+  command error_t send(ieee154_saddr_t addr, message_t* msg, uint8_t len);
+
+  /**
+    * Cancel a requested transmission. Returns SUCCESS if the 
+    * transmission was canceled properly (not sent in its
+    * entirety). Note that the component may not know
+    * if the send was successfully canceled, if the radio is
+    * handling much of the logic; in this case, a component
+    * should be conservative and return an appropriate error code.
+    * A successful call to cancel must always result in a 
+    * sendFailed event, and never a sendSucceeded event.
+    * 
+    * @param  msg     the packet whose transmission should be cancelled.
+    * @return SUCCESS if the transmission was cancelled, FAIL otherwise.
+    * @see    sendDone
+    */
+  command error_t cancel(message_t* msg);
+
+  /** 
+    * Signaled in response to an accepted send request. <tt>msg</tt> is
+    * the message buffer sent, and <tt>error</tt> indicates whether
+    * the send was successful.
+    *
+    * @param  msg   the packet which was submitted as a send request
+    * @param  error SUCCESS if it was sent successfully, FAIL if it was not,
+    *               ECANCEL if it was cancelled
+    * @see send
+    * @see cancel
+    */ 
+
+  event void sendDone(message_t* msg, error_t error);
+
+
+   /**
+   * Return the maximum payload length that this communication layer
+   * can provide. This command behaves identically to
+   * <tt>Packet.maxPayloadLength</tt> and is included in this
+   * interface as a convenience.
+   *
+   * @return the maximum payload length
+   */
+
+  
+  command uint8_t maxPayloadLength();
+
+
+   /**
+    * Return a pointer to a protocol's payload region in a packet.
+    * This command behaves identically to <tt>Packet.getPayload</tt>
+    * (minus the length parameter) and is included in this interface
+    * as a convenience.
+    *
+    * @param  msg    the packet
+    * @return        the payload of the packet
+    */
+  command void* getPayload(message_t* msg, uint8_t len);
+
+  
+}
diff --git a/tos/interfaces/LocalIeeeEui64.nc b/tos/interfaces/LocalIeeeEui64.nc
new file mode 100644 (file)
index 0000000..c92ec67
--- /dev/null
@@ -0,0 +1,38 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ * Author: Gilman Tolle, Jonathan Hui (TEP 122)
+ */
+
+#include "IeeeEui64.h"
+
+/**
+ * Interface to read the 64-bit IEEE EUI.
+ *
+ */
+interface LocalIeeeEui64 {
+  /**
+   * Get the 64-bit IEEE EUI.
+   * @returns the 64-bit IEEE EUI type, defined in tos/types/IeeeEui64.h
+   */
+  command ieee_eui64_t getId();
+}
index b5225c4fe10c9e6333244aafa78aa435d93411d7..68d9cc4a56000ae5823903242f59252f28b5ff51 100644 (file)
  * @author Jonathan Hui
  * @author David Moss
  */
+
 #include "message.h"
-interface LowPowerListening {
 
+interface LowPowerListening {
   /**
-   * Set this this node's radio sleep interval, in milliseconds.
-   * Once every interval, the node will sleep and perform an Rx check 
-   * on the radio.  Setting the sleep interval to 0 will keep the radio
-   * always on.
-   *
-   * This is the equivalent of setting the local duty cycle rate.
-   *
-   * @param sleepIntervalMs the length of this node's Rx check interval, in [ms]
-   */
-  command void setLocalSleepInterval(uint16_t sleepIntervalMs);
-  
-  /**
-   * @return the local node's sleep interval, in [ms]
-   */
-  command uint16_t getLocalSleepInterval();
-  
-  /**
-   * Set this node's radio duty cycle rate, in units of [percentage*100].
-   * For example, to get a 0.05% duty cycle,
-   * <code>
-   *   call LowPowerListening.setDutyCycle(5);
-   * </code>
+   * Set this this node's radio wakeup interval, in milliseconds. After
+   * each interval, the node will wakeup and check for radio activity.
    *
-   * For a 100% duty cycle (always on),
-   * <code>
-   *   call LowPowerListening.setDutyCycle(10000);
-   * </code>
+   * Note: The wakeup interval can be set to 0 to indicate that the radio
+   * should stay on all the time but in order to get a startDone this
+   * should only be done when the duty-cycling is off (after a stopDone).
    *
-   * This is the equivalent of setting the local sleep interval explicitly.
-   * 
-   * @param dutyCycle The duty cycle percentage, in units of [percentage*100]
-   */
-  command void setLocalDutyCycle(uint16_t dutyCycle);
-  
-  /**
-   * @return this node's radio duty cycle rate, in units of [percentage*100]
-   */
-  command uint16_t getLocalDutyCycle();
-  
-  
-  /**
-   * Configure this outgoing message so it can be transmitted to a neighbor mote
-   * with the specified Rx sleep interval.
-   * @param 'message_t* ONE msg' Pointer to the message that will be sent
-   * @param sleepInterval The receiving node's sleep interval, in [ms]
+   * @param intervalMs the length of this node's Rx check interval, in [ms]
    */
-  command void setRxSleepInterval(message_t *msg, uint16_t sleepIntervalMs);
+  command void setLocalWakeupInterval(uint16_t intervalMs);
   
   /**
-   * @param 'message_t* ONE msg'
-   * @return the destination node's sleep interval configured in this message
+   * @return the local node's wakeup interval, in [ms]
    */
-  command uint16_t getRxSleepInterval(message_t *msg);
-  
+  command uint16_t getLocalWakeupInterval();
+
   /**
    * Configure this outgoing message so it can be transmitted to a neighbor mote
-   * with the specified Rx duty cycle rate.
-   * Duty cycle is in units of [percentage*100], i.e. 0.25% duty cycle = 25.
-   * 
+   * with the specified wakeup interval.
    * @param 'message_t* ONE msg' Pointer to the message that will be sent
-   * @param dutyCycle The duty cycle of the receiving mote, in units of 
-   *     [percentage*100]
+   * @param intervalMs The receiving node's wakeup interval, in [ms]
    */
-  command void setRxDutyCycle(message_t *msg, uint16_t dutyCycle);
-  
+  command void setRemoteWakeupInterval(message_t *msg, uint16_t intervalMs);
+
   /**
    * @param 'message_t* ONE msg'
-   * @return the destination node's duty cycle configured in this message
-   *     in units of [percentage*100]
-   */
-  command uint16_t getRxDutyCycle(message_t *msg);
-  
-  /**
-   * Convert a duty cycle, in units of [percentage*100], to
-   * the sleep interval of the mote in milliseconds
-   * @param dutyCycle The duty cycle in units of [percentage*100]
-   * @return The equivalent sleep interval, in units of [ms]
+   * @return the destination node's wakeup interval configured in this message
    */
-  command uint16_t dutyCycleToSleepInterval(uint16_t dutyCycle);
-  
-  /**
-   * Convert a sleep interval, in units of [ms], to a duty cycle
-   * in units of [percentage*100]
-   * @param sleepInterval The sleep interval in units of [ms]
-   * @return The duty cycle in units of [percentage*100]
-   */
-  command uint16_t sleepIntervalToDutyCycle(uint16_t sleepInterval);
-  
+  command uint16_t getRemoteWakeupInterval(message_t *msg);
 }
index 3b135b85931d5391666e92db122f1ec921f3c10f..74a77ede966fc53fdbf5167a5a3f4f6c2067f68c 100644 (file)
@@ -43,7 +43,7 @@ interface ResourceQueue {
   async command bool isEmpty();
   
   /**
-   * Check to see if a given cleint id has already been enqueued
+   * Check to see if a given client id has already been enqueued
    * and is waiting to be processed.
    *
    * @return TRUE  if the client id is in the queue. <br>
@@ -52,17 +52,17 @@ interface ResourceQueue {
   async command bool isEnqueued(resource_client_id_t id);
   
   /**
-   * Retreive the cleint id of the next resource in the queue. 
+   * Retreive the client id of the next resource in the queue. 
    * If the queue is empty, the return value is undefined.
    *
-   * @return The cleint id at the head of the queue.
+   * @return The client id at the head of the queue.
    */
   async command resource_client_id_t dequeue();
 
   /**
-   * Enqueue a cleint id
+   * Enqueue a client id
    *
-   * @param cleintId - the cleint id to enqueue
+   * @param clientId - the client id to enqueue
    * @return SUCCESS if the client id was enqueued successfully <br>
    *         EBUSY   if it has already been enqueued.
    */
diff --git a/tos/interfaces/SystemLowPowerListening.nc b/tos/interfaces/SystemLowPowerListening.nc
new file mode 100644 (file)
index 0000000..d64bcca
--- /dev/null
@@ -0,0 +1,8 @@
+interface SystemLowPowerListening
+{
+  command void setDefaultRemoteWakeupInterval(uint16_t intervalMs);
+  command void setDelayAfterReceive(uint16_t intervalMs);
+
+  command uint16_t getDefaultRemoteWakeupInterval();
+  command uint16_t getDelayAfterReceive();
+}
diff --git a/tos/interfaces/UartControl.nc b/tos/interfaces/UartControl.nc
new file mode 100644 (file)
index 0000000..f0226b4
--- /dev/null
@@ -0,0 +1,120 @@
+/* $Id$ */
+/*
+ * Copyright (c) 2009 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ *  A hardware-independent (HIL) interface for configuring a UART.
+ *  Allows setting speed, parity bits, stop bits, and duplex mode.
+ *  Parameters are generally TinyOS enum constants, defined within a 
+ *  chip's header files, such that using an unsupported setting
+ *  will reference an undefined constant and lead to a compilation
+ *  error.
+ *
+ *  @author Philip Levis
+ *  @date   $Date$
+ */
+
+
+interface UartControl {
+
+  /** Set the UART speed for both reception and transmission.
+    * This command should be called only when both reception
+    * and transmission are disabled, either through a power interface
+    * or setDuplexMode(). The parameter is a constant of the
+    * form TOS_UART_XX, where XX is the speed, such as 
+    * TOS_UART_57600. Different platforms support different speeds.
+    * A compilation error on the constant indicates the platform
+    * does not support that speed.
+    *
+    *  @param speed The UART speed to change to.
+    */
+  async command error_t setSpeed(uart_speed_t speed);
+
+  /**
+    * Returns the current UART speed. 
+    */
+  async command uart_speed_t speed();
+
+  /**
+    * Set the duplex mode of the UART. Valid modes are
+    * TOS_UART_OFF, TOS_UART_RONLY, TOS_UART_TONLY, and
+    * TOS_UART_DUPLEX. Some platforms may support only
+    * a subset of these modes: trying to use an unsupported
+    * mode is a compile-time error. The duplex mode setting
+    * affects what kinds of interrupts the UART will issue.
+    *
+    *  @param duplex The duplex mode to change to.
+    */
+  async command error_t setDuplexMode(uart_duplex_t duplex);
+
+  /**
+    * Return the current duplex mode. 
+    */
+  async command uart_duplex_t duplexMode();
+
+  /**
+    * Set whether UART bytes have even parity bits, odd
+    * parity bits, or no parity bits. This command should
+    * only be called when both the receive and transmit paths
+    * are disabled, either through a power control interface
+    * or setDuplexMode. Valid parity settings are
+    * TOS_UART_PARITY_NONE, TOS_UART_PARITY_EVEN, 
+    * and TOS_UART_PARITY_ODD.
+    *
+    *  @param parity The parity mode to change to.
+    */
+
+  async command error_t setParity(uart_parity_t parity);
+
+  /**
+    * Return the current parity mode.
+    */
+  async command uart_parity_t parity();
+
+  /**
+    * Enable stop bits. This command should only be called
+    * when both the receive and transmits paths are disabled,
+    * either through a power control interface or setDuplexMode.
+    */
+  async command error_t setStop();
+
+  /**
+    * Disable stop bits. This command should only be called
+    * when both the receive and transmits paths are disabled,
+    * either through a power control interface or setDuplexMode.
+    */
+  async command error_t setNoStop();
+
+  /**
+    * Returns whether stop bits are enabled.
+    */
+  async command bool stopBits();
+}
index 9ddbcce2b46f270cf8abf65373a7371538c9b2e8..ea92501431072429980f8e492cad5dbf6f782d11 100644 (file)
  */
 
 module PacketSerializerP {
-  provides {
-    interface Init;
-    interface PhySend;
-    interface PhyReceive;
-    interface Packet;
-    interface RadioTimeStamping;
-  }
-  uses {
-    interface RadioByteComm;
-    interface PhyPacketTx;
-    interface PhyPacketRx;
-  }
+    provides {
+        interface PhySend;
+        interface PhyReceive;
+        interface Packet;
+        interface RadioTimeStamping;
+    }
+    uses {
+        interface RadioByteComm;
+        interface PhyPacketTx;
+        interface PhyPacketRx;
+#ifdef PACKETSERIALIZER_DEBUG
+        interface SerialDebug;
+#endif
+    }
 }
 implementation {
-  /* Module Global Variables */
+    
+#ifdef PACKETSERIALIZER_DEBUG
+    void sdDebug(uint16_t p) {
+        call SerialDebug.putPlace(p);
+    }
+#else
+    void sdDebug(uint16_t p) {};
+#endif
 
-  message_t *txBufPtr;  // pointer to tx buffer
-  message_t *rxBufPtr;  // pointer to rx buffer
-  message_t rxMsg;      // rx message buffer
-  uint16_t crc;         // CRC value of either the current incoming or outgoing packet
-  uint8_t byteCnt;      // index into current datapacket
+    /* Module Global Variables */
+
+    message_t rxMsg;      // rx message buffer
+    message_t *rxBufPtr = &rxMsg;  // pointer to rx buffer
+    message_t *txBufPtr = NULL;  // pointer to tx buffer
+    uint16_t crc = 0;         // CRC value of either the current incoming or outgoing packet
+    uint8_t byteCnt = 0;      // index into current datapacket
       
-  /* Local Function Declarations */
-  void TransmitNextByte();
-  void ReceiveNextByte(uint8_t data);
+    /* Local Function Declarations */
+    void TransmitNextByte();
+    void ReceiveNextByte(uint8_t data);
 
-  typedef enum {
-      SFD_OFFSET = sizeof(message_header_t) - sizeof(message_radio_header_t) + 2
-  } pserializer_constants_t;
+    typedef enum {
+        SFD_OFFSET  =  sizeof(message_header_t) - sizeof(message_radio_header_t) + 2
+    } pserializer_constants_t;
   
-  /* Radio Init  */
-  command error_t Init.init(){
-    atomic {
-      crc = 0;
-      txBufPtr = NULL;
-      rxBufPtr = &rxMsg;
-      byteCnt = 0;
-    }
-    return SUCCESS;
-  }
-
-  /*- Radio Send */
-  async command error_t PhySend.send(message_t* msg, uint8_t len) {
-    message_radio_header_t* header = getHeader(msg);
-    atomic {
-      crc = 0;
-      txBufPtr = msg;
-      header->length = len;
-      // message_header_t can contain more than only the message_radio_header_t
-      byteCnt = (sizeof(message_header_t) - sizeof(message_radio_header_t)); // offset
-    }
-    call PhyPacketTx.sendHeader();
-    return SUCCESS;
-  }
+    /*- Radio Send */
+    async command error_t PhySend.send(message_t* msg, uint8_t len) {
+        atomic {
+            crc = 0;
+            txBufPtr = msg;
+            // assume "right (LSB) aligned" unions -- highly compiler and platform specific
+            byteCnt = sizeof(message_header_t) - sizeof(message_radio_header_t);
+            getHeader(msg)->length = len;
+            sdDebug(4000 + getHeader(msg)->token);
+        }
+        call PhyPacketTx.sendHeader();
+        return SUCCESS;
+    }
   
-  async event void PhyPacketTx.sendHeaderDone() {
-      TransmitNextByte();
-  }
+    async event void PhyPacketTx.sendHeaderDone() {
+        TransmitNextByte();
+    }
 
-  async event void RadioByteComm.txByteReady(error_t error) {
-    if(error == SUCCESS) {
-      TransmitNextByte();
-    } else {
-      signal PhySend.sendDone((message_t*)txBufPtr, FAIL);
+    async event void RadioByteComm.txByteReady(error_t error) {
+        if(error == SUCCESS) {
+            TransmitNextByte();
+        } else {
+            signal PhySend.sendDone(txBufPtr, FAIL);
+        }
     }
-  }
 
-  void TransmitNextByte() {
-    message_radio_header_t* header = getHeader((message_t*) txBufPtr);
-    if (byteCnt < header->length + sizeof(message_header_t) ) {  // send (data + header), compute crc
-        if(byteCnt == SFD_OFFSET) {
-            signal RadioTimeStamping.transmittedSFD(0, (message_t*)txBufPtr);
+    void TransmitNextByte() {
+        if(byteCnt < sizeof(message_header_t) + getHeader(txBufPtr)->length) {
+            // transmit the data part
+            uint8_t* buf = (uint8_t *)(txBufPtr);
+            crc = crcByte(crc, buf[byteCnt]);
+            call RadioByteComm.txByte(buf[byteCnt]);
+            byteCnt++;
+            if(byteCnt == SFD_OFFSET) {
+                signal RadioTimeStamping.transmittedSFD(0, txBufPtr);
+            }
+        }
+        else if(byteCnt == sizeof(message_header_t) + getHeader(txBufPtr)->length) {
+            call RadioByteComm.txByte(crc);
+            byteCnt++;            
+        }
+        else if(byteCnt == sizeof(message_header_t) + getHeader(txBufPtr)->length + 1) {
+            call RadioByteComm.txByte(crc >> 8);
+            byteCnt++;
+        }
+        else {
+            call PhyPacketTx.sendFooter();
         }
-        crc = crcByte(crc, ((uint8_t *)(txBufPtr))[byteCnt]);
-        call RadioByteComm.txByte(((uint8_t *)(txBufPtr))[byteCnt++]);
     }
-    else if (byteCnt == (header->length + sizeof(message_header_t))) {
-      ++byteCnt;
-      call RadioByteComm.txByte((uint8_t)crc);
+    
+    async event void PhyPacketTx.sendFooterDone() {
+        sdDebug(6000 + getHeader(txBufPtr)->token);
+        signal PhySend.sendDone((message_t*)txBufPtr, SUCCESS);
     }
-    else if  (byteCnt == (header->length + sizeof(message_header_t)+1)) {
-      ++byteCnt;
-      call RadioByteComm.txByte((uint8_t)(crc >> 8));
+  
+    /* Radio Receive */
+    async event void PhyPacketRx.recvHeaderDone(error_t error) {
+        if(error == SUCCESS) {
+            byteCnt = sizeof(message_header_t) - sizeof(message_radio_header_t);
+            getHeader(rxBufPtr)->length = sizeof(message_radio_header_t);
+            crc = 0;
+            signal PhyReceive.receiveDetected();
+        }
     }
-    else { /* (byteCnt > (header->length + sizeof(message_header_t)+1)) */
-        call PhyPacketTx.sendFooter();
+    
+    async event void RadioByteComm.rxByteReady(uint8_t data) {
+        ReceiveNextByte(data);
     }
-  }
-
-  async event void PhyPacketTx.sendFooterDone() {
-    signal PhySend.sendDone((message_t*)txBufPtr, SUCCESS);
-  }
-  
-  /* Radio Receive */
-  async event void PhyPacketRx.recvHeaderDone(error_t error) {
-    if(error == SUCCESS) {
-      byteCnt = (sizeof(message_header_t) - sizeof(message_radio_header_t));
-      crc = 0;
-      getHeader(rxBufPtr)->length = sizeof(message_radio_header_t); 
-      signal PhyReceive.receiveDetected();
-    }
-  }
-
-  async event void RadioByteComm.rxByteReady(uint8_t data) {
-    ReceiveNextByte(data);
-  }
 
-  async event void PhyPacketRx.recvFooterDone(error_t error) {
-    message_radio_header_t* header = getHeader((message_t*)(rxBufPtr));
-    message_radio_footer_t* footer = getFooter((message_t*)rxBufPtr);
-    // we care about wrong crc in this layer
-    if (footer->crc != 1) error = FAIL;
-    rxBufPtr = signal PhyReceive.receiveDone((message_t*)rxBufPtr, ((message_t*)rxBufPtr)->data, header->length, error);
-  }
-
-  /* Receive the next Byte from the USART */
-  void ReceiveNextByte(uint8_t data) { 
-    message_radio_footer_t* footer = getFooter((message_t*)rxBufPtr);
-    ((uint8_t *)(rxBufPtr))[byteCnt++] = data;
-    if(byteCnt < getHeader(rxBufPtr)->length + sizeof(message_radio_header_t)) {
-      if(byteCnt == SFD_OFFSET) {
-          signal RadioTimeStamping.receivedSFD(0);
-      }
-      crc = crcByte(crc, data);
-      if (getHeader(rxBufPtr)->length > TOSH_DATA_LENGTH) { 
-        // this packet is surely corrupt, so whatever...
-        footer->crc = 0;
-        call PhyPacketRx.recvFooter();
-      }
-    } else if (byteCnt == (getHeader(rxBufPtr)->length + sizeof(message_radio_header_t))) {
-      crc = crcByte(crc, data);
-      byteCnt = offsetof(message_t, footer) + offsetof(message_radio_footer_t, crc);
-    } else if (byteCnt == (offsetof(message_t, footer) + sizeof(message_radio_footer_t))) {
-      footer->crc = (footer->crc == crc);
-      call PhyPacketRx.recvFooter();
-    }
-  }
-
-  
-  /* Packet interface */
+    async event void PhyPacketRx.recvFooterDone(error_t error) {
+        // we care about wrong crc in this layer
+        if(!getFooter(rxBufPtr)->crc) {
+            error = FAIL;
+        }
+        else {
+            
+        }
+        byteCnt = 0;
+        rxBufPtr = signal PhyReceive.receiveDone(rxBufPtr, rxBufPtr->data, getHeader(rxBufPtr)->length, error);
+    }
+    
+    /* Receive the next Byte from the USART */
+    void ReceiveNextByte(uint8_t data) {
+        uint8_t* buf = (uint8_t *)(rxBufPtr);
+        buf[byteCnt++] = data;
+        if(byteCnt <= sizeof(message_header_t) + getHeader(rxBufPtr)->length) {
+            crc = crcByte(crc, data);
+            if(byteCnt == SFD_OFFSET) {
+                signal RadioTimeStamping.receivedSFD(0);
+            }
+            else if(byteCnt == sizeof(message_header_t) + getHeader(rxBufPtr)->length) {
+                byteCnt = offsetof(message_t, footer) + offsetof(message_radio_footer_t, crc);
+            }
+            if(getHeader(rxBufPtr)->length > TOSH_DATA_LENGTH) {
+                getFooter(rxBufPtr)->crc = 0;
+                call PhyPacketRx.recvFooter();
+            }
+        }
+        else if(byteCnt >= offsetof(message_t, footer) + offsetof(message_radio_footer_t, crc) + sizeof(crc)) {
+            message_radio_footer_t* footer = getFooter(rxBufPtr);
+            footer->crc = (footer->crc == crc);
+            call PhyPacketRx.recvFooter();
+            sdDebug(5000 + getHeader(rxBufPtr)->token);
+        }
+    }
+    
+    /* Packet interface */
       
-  command void Packet.clear(message_t* msg) {
-    memset(msg, 0, sizeof(message_t));
-  }
-
-  command uint8_t Packet.payloadLength(message_t* msg) {
-    return (getHeader(msg))->length;
-  }
+    command void Packet.clear(message_t* msg) {
+        memset(msg, 0, sizeof(message_t));
+    }
 
-  command void Packet.setPayloadLength(message_t* msg, uint8_t len) {
-    getHeader(msg)->length  = len;
-  }
-  command uint8_t Packet.maxPayloadLength() {
-    return TOSH_DATA_LENGTH;
-  }
+    command uint8_t Packet.payloadLength(message_t* msg) {
+        return (getHeader(msg))->length;
+    }
 
-  command void* Packet.getPayload(message_t* msg, uint8_t len) {
-    if (len <= TOSH_DATA_LENGTH) {
-      return (void*)msg->data;
+    command void Packet.setPayloadLength(message_t* msg, uint8_t len) {
+        getHeader(msg)->length  = len;
     }
-    else {
-      return NULL;
+    command uint8_t Packet.maxPayloadLength() {
+        return TOSH_DATA_LENGTH;
+    }
+
+    command void* Packet.getPayload(message_t* msg, uint8_t len) {
+        if (len <= TOSH_DATA_LENGTH) {
+            return (void*)msg->data;
+        }
+        else {
+            return NULL;
+        }
     }
-  }
   
-  // Default events for radio send/receive coordinators do nothing.
-  // Be very careful using these, or you'll break the stack.
-  default async event void RadioTimeStamping.transmittedSFD(uint16_t time, message_t* msgBuff) { }
-  default async event void RadioTimeStamping.receivedSFD(uint16_t time) { }
+    // Default events for radio send/receive coordinators do nothing.
+    // Be very careful using these, or you'll break the stack.
+    default async event void RadioTimeStamping.transmittedSFD(uint16_t time, message_t* msgBuff) { }
+    default async event void RadioTimeStamping.receivedSFD(uint16_t time) { }
 }
index 5d53fa9886fc7c7a3fd19f54f84ef146b05ffa25..a3ab250c216e0f87807bb94be1cc525d0854f0f1 100644 (file)
@@ -40,13 +40,13 @@ components NoDiagMsgC;
                AM_DIAG_MSG = 0xB1,
        };
 
-       components DiagMsgM, MainC, SerialActiveMessageC;
+       components DiagMsgP, MainC, SerialActiveMessageC;
 
-       DiagMsg = DiagMsgM.DiagMsg;
+       DiagMsg = DiagMsgP.DiagMsg;
 
-       MainC.SoftwareInit -> DiagMsgM.Init;
-       DiagMsgM.AMSend -> SerialActiveMessageC.AMSend[AM_DIAG_MSG];
-       DiagMsgM.Packet -> SerialActiveMessageC;
+       MainC.SoftwareInit -> DiagMsgP.Init;
+       DiagMsgP.AMSend -> SerialActiveMessageC.AMSend[AM_DIAG_MSG];
+       DiagMsgP.Packet -> SerialActiveMessageC;
 
 #endif
 }
diff --git a/tos/lib/diagmsg/DiagMsgM.nc b/tos/lib/diagmsg/DiagMsgM.nc
deleted file mode 100644 (file)
index 669a04b..0000000
+++ /dev/null
@@ -1,314 +0,0 @@
-/*
- * Copyright (c) 2002-2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#include <message.h>
-
-module DiagMsgM
-{
-       provides 
-       {
-               interface DiagMsg;
-               interface Init;
-       }
-
-       uses 
-       {
-               interface AMSend;
-               interface Packet;
-       }
-}
-
-#ifndef DIAGMSG_BASE_STATION
-#define        DIAGMSG_BASE_STATION    AM_BROADCAST_ADDR
-#endif
-
-#ifndef DIAGMSG_RETRY_COUNT
-#define        DIAGMSG_RETRY_COUNT     2
-#endif
-
-#ifndef DIAGMSG_RECORDED_MSGS
-#define DIAGMSG_RECORDED_MSGS  10
-#endif
-
-implementation
-{
-       enum
-       {
-               STATE_READY = 1,
-               STATE_RECORDING_FIRST = 2,      // recording the first 4-bit descriptor
-               STATE_RECORDING_SECOND = 3,     // recording the second 4-bit descriptor
-               STATE_MSG_FULL = 4,
-               STATE_BUFFER_FULL = 5,
-       };
-
-       norace volatile uint8_t state;  // the state of the recording
-
-       message_t msgs[DIAGMSG_RECORDED_MSGS];  // circular buffer of messages
-
-       norace message_t *recording;    // the message that is beeing or going to be recorded
-       message_t *sending;     // the message that is beeing sent, or the null pointer
-
-       norace uint8_t nextData;        // points to the next unsued byte
-       norace uint8_t prevType;        // points to the type descriptor
-       norace uint8_t retries; // number of remaining retries
-
-       command error_t Init.init()
-       {
-               state = STATE_READY;
-               recording = msgs;
-               sending = 0;
-
-               return SUCCESS;
-       }
-
-       // two type fields are stored in on byte
-       enum
-       {
-               TYPE_END = 0,
-               TYPE_INT8 = 1,
-               TYPE_UINT8 = 2,
-               TYPE_HEX8 = 3,
-               TYPE_INT16 = 4,
-               TYPE_UINT16 = 5,
-               TYPE_HEX16 = 6,
-               TYPE_INT32 = 7,
-               TYPE_UINT32 = 8,
-               TYPE_HEX32 = 9,
-               TYPE_FLOAT = 10,
-               TYPE_CHAR = 11,
-               TYPE_INT64 = 12,
-               TYPE_UINT64 = 13,
-               TYPE_ARRAY = 15,
-       };
-
-/*
-       The format of the payload is as follows: 
-       
-       Each value has an associated data type descriptor. The descriptor takes 4-bits,
-       and two descriptors are packed into one byte. The double-descriptor is followed
-       by the data bytes needed to store the corresponding value. Two sample layouts are:
-
-       [D2, D1] [V1] ... [V1] [V2] ... [V2]
-       [D2, D1] [V1] ... [V1] [V2] ... [V2] [0, D3] [V3] ... [V3]
-
-       where D1, D2, D3 denotes the data type descriptors, and V1, V2 and V3
-       denotes the bytes where the corresponding values are stored. If there is an odd
-       number of data descriptors, then a zero data descriptor <code>TYPE_END</code> 
-       is inserted.
-
-       Each data type (except arrays) uses a fixed number of bytes to store the value.
-       For arrays, the first byte of the array holds the data type of the array (higer
-       4 bits) and the length of the array (lower 4 bits). The actual data follows 
-       this first byte.
-*/
-
-       async command bool DiagMsg.record()
-       {
-               atomic
-               {
-                       // currently recording or no more space
-                       if( state != STATE_READY )
-                               return FALSE;
-
-                       state = STATE_RECORDING_FIRST;
-                       nextData = 0;
-               }
-
-               return TRUE;
-       }
-
-       /**
-        * Allocates space in the message for <code>size</code> bytes
-        * and sets the type information to <code>type</code>. 
-        * Returns the index in <code>msg.data</code> where the data 
-        * should be stored or <code>-1</code> if no more space is avaliable.
-        */
-       int8_t allocate(uint8_t size, uint8_t type)
-       {
-               int8_t ret = -1;
-
-               if( state == STATE_RECORDING_FIRST )
-               {
-                       if( nextData + 1 + size <= TOSH_DATA_LENGTH )
-                       {
-                               state = STATE_RECORDING_SECOND;
-
-                               prevType = nextData++;
-                               ((uint8_t*) &(recording->data))[prevType] = type;
-                               ret = nextData;
-                               nextData += size;
-                       }
-                       else
-                               state = STATE_MSG_FULL;
-               }
-               else if( state == STATE_RECORDING_SECOND )
-               {
-                       if( nextData + size <= TOSH_DATA_LENGTH )
-                       {
-                               state = STATE_RECORDING_FIRST;
-
-                               ((uint8_t*) &(recording->data))[prevType] += (type << 4);
-                               ret = nextData;
-                               nextData += size;
-                       }
-                       else
-                               state = STATE_MSG_FULL;
-               }
-
-               return ret;
-       }
-
-#define IMPLEMENT(NAME, TYPE, TYPE2) \
-       async command void DiagMsg.NAME(TYPE value) \
-       { \
-               int8_t start = allocate(sizeof(TYPE), TYPE2); \
-               if( start >= 0 ) \
-                       *(TYPE*)((uint8_t*) &(recording->data) + start) = value; \
-       } \
-       async command void DiagMsg.NAME##s(const TYPE *value, uint8_t len) \
-       { \
-               int8_t start; \
-               if( len > 15 ) len = 15; \
-               start = allocate(sizeof(TYPE)*len + 1, TYPE_ARRAY); \
-               if( start >= 0 ) \
-               { \
-                       ((uint8_t*) &(recording->data))[start++] = (TYPE2 << 4) + len; \
-                       while( len-- != 0 ) \
-                               ((TYPE*)((uint8_t*) &(recording->data) + start))[len] = value[len]; \
-               } \
-       }
-
-       IMPLEMENT(int8, int8_t, TYPE_INT8)
-       IMPLEMENT(uint8, uint8_t, TYPE_UINT8)
-       IMPLEMENT(hex8, uint8_t, TYPE_HEX8)
-       IMPLEMENT(int16, int16_t, TYPE_INT16)
-       IMPLEMENT(uint16, uint16_t, TYPE_UINT16)
-       IMPLEMENT(hex16, uint16_t, TYPE_HEX16)
-       IMPLEMENT(int32, int32_t, TYPE_INT32)
-       IMPLEMENT(uint32, uint32_t, TYPE_UINT32)
-       IMPLEMENT(hex32, uint32_t, TYPE_HEX32)
-       IMPLEMENT(int64, int64_t, TYPE_INT64)
-       IMPLEMENT(uint64, uint64_t, TYPE_UINT64)
-       IMPLEMENT(real, float, TYPE_FLOAT)
-       IMPLEMENT(chr, char, TYPE_CHAR)
-
-       async command void DiagMsg.str(const char* str)
-       {
-               int8_t len = 0;
-               while( str[len] != 0 && len < 15 )
-                       ++len;
-               
-               call DiagMsg.chrs(str, len);
-       }
-
-       // TODO: this is a hack because setPayloadLength should be async
-       inline void setPayloadLength(message_t* msg, uint8_t length)
-       {
-               (*(uint8_t*) &(msg->header)) = length;
-       }
-
-       inline uint8_t getPayloadLength(message_t* msg)
-       {
-               return *(uint8_t*) &(msg->header);
-       }
-
-       task void send()
-       {
-               message_t* msg;
-
-               atomic msg = sending;
-
-               if( call AMSend.send(DIAGMSG_BASE_STATION, msg, getPayloadLength(msg)) != SUCCESS )
-                       post send();
-       }
-
-       // calculates the next message_t pointer in the <code>msgs</code> circular buffer
-       static inline message_t* nextPointer(message_t* ptr)
-       {
-               if( ++ptr >= msgs + DIAGMSG_RECORDED_MSGS )
-                       return msgs;
-               else
-                       return ptr;
-       }
-
-       async command void DiagMsg.send()
-       {
-               // no message recorded
-               if( state == STATE_READY )
-                       return;
-
-               // store the length
-               setPayloadLength(recording, nextData);
-
-               atomic
-               {
-                       if( sending == 0 )
-                       {
-                               sending = recording;
-                               retries = DIAGMSG_RETRY_COUNT;
-                               post send();
-                       }
-       
-                       recording = nextPointer(recording);
-
-                       if( recording == sending )
-                               state = STATE_BUFFER_FULL;
-                       else
-                               state = STATE_READY;
-               }
-       }
-
-       event void AMSend.sendDone(message_t* p, error_t error)
-       {
-               atomic
-               {
-                       // retry if not successful
-                       if( error != SUCCESS && --retries > 0 )
-                               post send();
-                       else
-                       {
-                               p = nextPointer(sending);
-                               if( p != recording )
-                               {
-                                       sending = p;
-                                       retries = DIAGMSG_RETRY_COUNT;
-                                       post send();
-                               }
-                               else
-                               {
-                                       sending = 0;
-
-                                       if( state == STATE_BUFFER_FULL )
-                                       {
-                                               state = STATE_READY;
-                                               if( call DiagMsg.record() )
-                                               {
-                                                       call DiagMsg.str("DiagMsgOverflow");
-                                                       call DiagMsg.send();
-                                               }
-                                       }
-                               }
-                       }
-               }
-       }
-}
diff --git a/tos/lib/diagmsg/DiagMsgP.nc b/tos/lib/diagmsg/DiagMsgP.nc
new file mode 100644 (file)
index 0000000..85fab06
--- /dev/null
@@ -0,0 +1,320 @@
+/*
+ * Copyright (c) 2002-2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <message.h>
+
+module DiagMsgP
+{
+       provides 
+       {
+               interface DiagMsg;
+               interface Init;
+       }
+
+       uses 
+       {
+               interface AMSend;
+               interface Packet;
+       }
+}
+
+#ifndef DIAGMSG_BASE_STATION
+#define        DIAGMSG_BASE_STATION    AM_BROADCAST_ADDR
+#endif
+
+#ifndef DIAGMSG_RETRY_COUNT
+#define        DIAGMSG_RETRY_COUNT     2
+#endif
+
+#ifndef DIAGMSG_RECORDED_MSGS
+#define DIAGMSG_RECORDED_MSGS  10
+#endif
+
+implementation
+{
+       enum
+       {
+               STATE_READY = 1,
+               STATE_RECORDING_FIRST = 2,      // recording the first 4-bit descriptor
+               STATE_RECORDING_SECOND = 3,     // recording the second 4-bit descriptor
+               STATE_MSG_FULL = 4,
+               STATE_BUFFER_FULL = 5,
+       };
+
+       norace volatile uint8_t state;  // the state of the recording
+
+       message_t msgs[DIAGMSG_RECORDED_MSGS];  // circular buffer of messages
+
+       norace message_t *recording;    // the message that is beeing or going to be recorded
+       message_t *sending;     // the message that is beeing sent, or the null pointer
+
+       norace uint8_t nextData;        // points to the next unsued byte
+       norace uint8_t prevType;        // points to the type descriptor
+       norace uint8_t retries; // number of remaining retries
+
+       command error_t Init.init()
+       {
+               state = STATE_READY;
+               recording = msgs;
+               sending = 0;
+
+               return SUCCESS;
+       }
+
+       // two type fields are stored in on byte
+       enum
+       {
+               TYPE_END = 0,
+               TYPE_INT8 = 1,
+               TYPE_UINT8 = 2,
+               TYPE_HEX8 = 3,
+               TYPE_INT16 = 4,
+               TYPE_UINT16 = 5,
+               TYPE_HEX16 = 6,
+               TYPE_INT32 = 7,
+               TYPE_UINT32 = 8,
+               TYPE_HEX32 = 9,
+               TYPE_FLOAT = 10,
+               TYPE_CHAR = 11,
+               TYPE_INT64 = 12,
+               TYPE_UINT64 = 13,
+               TYPE_ARRAY = 15,
+       };
+
+/*
+       The format of the payload is as follows: 
+       
+       Each value has an associated data type descriptor. The descriptor takes 4-bits,
+       and two descriptors are packed into one byte. The double-descriptor is followed
+       by the data bytes needed to store the corresponding value. Two sample layouts are:
+
+       [D2, D1] [V1] ... [V1] [V2] ... [V2]
+       [D2, D1] [V1] ... [V1] [V2] ... [V2] [0, D3] [V3] ... [V3]
+
+       where D1, D2, D3 denotes the data type descriptors, and V1, V2 and V3
+       denotes the bytes where the corresponding values are stored. If there is an odd
+       number of data descriptors, then a zero data descriptor <code>TYPE_END</code> 
+       is inserted.
+
+       Each data type (except arrays) uses a fixed number of bytes to store the value.
+       For arrays, the first byte of the array holds the data type of the array (higer
+       4 bits) and the length of the array (lower 4 bits). The actual data follows 
+       this first byte.
+*/
+
+       async command bool DiagMsg.record()
+       {
+               atomic
+               {
+                       // currently recording or no more space
+                       if( state != STATE_READY )
+                               return FALSE;
+
+                       state = STATE_RECORDING_FIRST;
+                       nextData = 0;
+               }
+
+               return TRUE;
+       }
+
+       /**
+        * Allocates space in the message for <code>size</code> bytes
+        * and sets the type information to <code>type</code>. 
+        * Returns the index in <code>msg.data</code> where the data 
+        * should be stored or <code>-1</code> if no more space is avaliable.
+        */
+       int8_t allocate(uint8_t size, uint8_t type)
+       {
+               int8_t ret = -1;
+
+               if( state == STATE_RECORDING_FIRST )
+               {
+                       if( nextData + 1 + size <= TOSH_DATA_LENGTH )
+                       {
+                               state = STATE_RECORDING_SECOND;
+
+                               prevType = nextData++;
+                               ((uint8_t*) &(recording->data))[prevType] = type;
+                               ret = nextData;
+                               nextData += size;
+                       }
+                       else
+                               state = STATE_MSG_FULL;
+               }
+               else if( state == STATE_RECORDING_SECOND )
+               {
+                       if( nextData + size <= TOSH_DATA_LENGTH )
+                       {
+                               state = STATE_RECORDING_FIRST;
+
+                               ((uint8_t*) &(recording->data))[prevType] += (type << 4);
+                               ret = nextData;
+                               nextData += size;
+                       }
+                       else
+                               state = STATE_MSG_FULL;
+               }
+
+               return ret;
+       }
+
+       void copyData(uint8_t size, uint8_t type2, const void* data)
+       {
+               int8_t start = allocate(size, type2);
+               if( start >= 0 )
+                       memcpy(&(recording->data[start]), data, size);
+       }
+
+       void copyArray(uint8_t size, uint8_t type2, const void* data, uint8_t len)
+       {
+               int8_t start;
+
+               if( len > 15 )
+                       len = 15;
+
+               start = allocate(size*len + 1, TYPE_ARRAY);
+               if( start >= 0 )
+               {
+                       recording->data[start] = (type2 << 4) + len;
+                       memcpy(&(recording->data[start + 1]), data, size*len);
+               }
+       }
+       
+#define IMPLEMENT(NAME, TYPE, TYPE2) \
+       async command void DiagMsg.NAME(TYPE value) { copyData(sizeof(TYPE), TYPE2, &value); } \
+       async command void DiagMsg.NAME##s(const TYPE *value, uint8_t len) { copyArray(sizeof(TYPE), TYPE2, value, len); }
+
+       IMPLEMENT(int8, int8_t, TYPE_INT8)
+       IMPLEMENT(uint8, uint8_t, TYPE_UINT8)
+       IMPLEMENT(hex8, uint8_t, TYPE_HEX8)
+       IMPLEMENT(int16, int16_t, TYPE_INT16)
+       IMPLEMENT(uint16, uint16_t, TYPE_UINT16)
+       IMPLEMENT(hex16, uint16_t, TYPE_HEX16)
+       IMPLEMENT(int32, int32_t, TYPE_INT32)
+       IMPLEMENT(uint32, uint32_t, TYPE_UINT32)
+       IMPLEMENT(hex32, uint32_t, TYPE_HEX32)
+       IMPLEMENT(int64, int64_t, TYPE_INT64)
+       IMPLEMENT(uint64, uint64_t, TYPE_UINT64)
+       IMPLEMENT(real, float, TYPE_FLOAT)
+       IMPLEMENT(chr, char, TYPE_CHAR)
+
+       async command void DiagMsg.str(const char* str)
+       {
+               int8_t len = 0;
+               while( str[len] != 0 && len < 15 )
+                       ++len;
+               
+               call DiagMsg.chrs(str, len);
+       }
+
+       // TODO: this is a hack because setPayloadLength should be async
+       inline void setPayloadLength(message_t* msg, uint8_t length)
+       {
+               (*(uint8_t*) &(msg->header)) = length;
+       }
+
+       inline uint8_t getPayloadLength(message_t* msg)
+       {
+               return *(uint8_t*) &(msg->header);
+       }
+
+       task void send()
+       {
+               message_t* msg;
+
+               atomic msg = sending;
+
+               if( call AMSend.send(DIAGMSG_BASE_STATION, msg, getPayloadLength(msg)) != SUCCESS )
+                       post send();
+       }
+
+       // calculates the next message_t pointer in the <code>msgs</code> circular buffer
+       static inline message_t* nextPointer(message_t* ptr)
+       {
+               if( ++ptr >= msgs + DIAGMSG_RECORDED_MSGS )
+                       return msgs;
+               else
+                       return ptr;
+       }
+
+       async command void DiagMsg.send()
+       {
+               // no message recorded
+               if( state == STATE_READY )
+                       return;
+
+               // store the length
+               setPayloadLength(recording, nextData);
+
+               atomic
+               {
+                       if( sending == 0 )
+                       {
+                               sending = recording;
+                               retries = DIAGMSG_RETRY_COUNT;
+                               post send();
+                       }
+       
+                       recording = nextPointer(recording);
+
+                       if( recording == sending )
+                               state = STATE_BUFFER_FULL;
+                       else
+                               state = STATE_READY;
+               }
+       }
+
+       event void AMSend.sendDone(message_t* p, error_t error)
+       {
+               atomic
+               {
+                       // retry if not successful
+                       if( error != SUCCESS && --retries > 0 )
+                               post send();
+                       else
+                       {
+                               p = nextPointer(sending);
+                               if( p != recording )
+                               {
+                                       sending = p;
+                                       retries = DIAGMSG_RETRY_COUNT;
+                                       post send();
+                               }
+                               else
+                               {
+                                       sending = 0;
+
+                                       if( state == STATE_BUFFER_FULL )
+                                       {
+                                               state = STATE_READY;
+                                               if( call DiagMsg.record() )
+                                               {
+                                                       call DiagMsg.str("DiagMsgOverflow");
+                                                       call DiagMsg.send();
+                                               }
+                                       }
+                               }
+                       }
+               }
+       }
+}
old mode 100644 (file)
new mode 100755 (executable)
index f709829..6eddcd2
@@ -41,6 +41,12 @@ configuration TimeSync32kC
 
 implementation
 {
+#if defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB)
+;
+#else
+#error "LPL timesync is not available for your platform"
+#endif
+
   components new TimeSyncP(T32khz) as TimeSyncP;
 
   GlobalTime      =   TimeSyncP;
@@ -53,8 +59,8 @@ implementation
 
   components TimeSyncMessageC as ActiveMessageC;
   TimeSyncP.RadioControl    ->  ActiveMessageC;
-  TimeSyncP.Send            ->  ActiveMessageC.TimeSyncAMSend32khz[AM_TIMESYNCMSG];
-  TimeSyncP.Receive         ->  ActiveMessageC.Receive[AM_TIMESYNCMSG];
+  TimeSyncP.Send            ->  ActiveMessageC.TimeSyncAMSend32khz[TIMESYNC_AM_FTSP];
+  TimeSyncP.Receive         ->  ActiveMessageC.Receive[TIMESYNC_AM_FTSP];
   TimeSyncP.TimeSyncPacket  ->  ActiveMessageC;
 
   components Counter32khz32C, new CounterToLocalTimeC(T32khz) as LocalTime32khzC;
@@ -64,6 +70,9 @@ implementation
   components new TimerMilliC() as TimerC;
   TimeSyncP.Timer ->  TimerC;
 
+  components RandomC;
+  TimeSyncP.Random -> RandomC;
+  
 #if defined(TIMESYNC_LEDS)
   components LedsC;
 #else
@@ -72,8 +81,7 @@ implementation
   TimeSyncP.Leds  ->  LedsC;
 
 #ifdef LOW_POWER_LISTENING
-  components CC2420ActiveMessageC;
-  TimeSyncP.LowPowerListening -> CC2420ActiveMessageC;
+  TimeSyncP.LowPowerListening -> ActiveMessageC;
 #endif
 
 
index 8022d8a9f6a354fcb06023aa9c1c191ff30a0e65..61cbcd93578f991aaf25de8fe0b5b6c2dac731e3 100644 (file)
@@ -52,8 +52,8 @@ implementation
 
   components TimeSyncMessageC as ActiveMessageC;
   TimeSyncP.RadioControl    ->  ActiveMessageC;
-  TimeSyncP.Send            ->  ActiveMessageC.TimeSyncAMSendMilli[AM_TIMESYNCMSG];
-  TimeSyncP.Receive         ->  ActiveMessageC.Receive[AM_TIMESYNCMSG];
+  TimeSyncP.Send            ->  ActiveMessageC.TimeSyncAMSendMilli[TIMESYNC_AM_FTSP];
+  TimeSyncP.Receive         ->  ActiveMessageC.Receive[TIMESYNC_AM_FTSP];
   TimeSyncP.TimeSyncPacket  ->  ActiveMessageC;
 
   components HilTimerMilliC;
@@ -62,6 +62,9 @@ implementation
   components new TimerMilliC() as TimerC;
   TimeSyncP.Timer ->  TimerC;
 
+  components RandomC;
+  TimeSyncP.Random -> RandomC;
+
 #if defined(TIMESYNC_LEDS)
   components LedsC;
 #else
index f45c2b346f68aa5da56be9b38f2d833f1b5fb66c..74a90197ae601cb5e77a9f15c91c38406ab74902 100644 (file)
@@ -49,7 +49,7 @@ typedef nx_struct TimeSyncMsg
 } TimeSyncMsg;
 
 enum {
-    AM_TIMESYNCMSG = 0x3E,
+    TIMESYNC_AM_FTSP = 0x3E,
     TIMESYNCMSG_LEN = sizeof(TimeSyncMsg) - sizeof(nx_uint32_t),
     TS_TIMER_MODE = 0,      // see TimeSyncMode interface
     TS_USER_MODE = 1,       // see TimeSyncMode interface
index 3c3affe83d12528d0d7ef1ece43dfbe316742875..6a17381db172e17fc18e04081fc29f3bca3ad3e8 100644 (file)
@@ -43,6 +43,7 @@ generic module TimeSyncP(typedef precision_tag)
         interface TimeSyncAMSend<precision_tag,uint32_t> as Send;
         interface Receive;
         interface Timer<TMilli>;
+        interface Random;
         interface Leds;
         interface TimeSyncPacket<precision_tag,uint32_t>;
         interface LocalTime<precision_tag> as LocalTime;
@@ -283,7 +284,7 @@ implementation
 
         if( msg->rootID < outgoingMsg->rootID &&
             // jw: after becoming the root ignore other roots messages (in send period)
-            ~(heartBeats < IGNORE_ROOT_MSG && outgoingMsg->rootID == TOS_NODE_ID) ){
+            !(heartBeats < IGNORE_ROOT_MSG && outgoingMsg->rootID == TOS_NODE_ID) ){
             outgoingMsg->rootID = msg->rootID;
             outgoingMsg->seqNum = msg->seqNum;
         }
@@ -316,6 +317,7 @@ implementation
         if( diff < -16 || diff > 16 )
             return msg;
 #endif
+
         if( (state & STATE_PROCESSING) == 0
             && call TimeSyncPacket.isValid(msg)) {
             message_t* old = processedMsg;
@@ -358,9 +360,8 @@ implementation
         }
 
         outgoingMsg->globalTime = globalTime;
-
 #ifdef LOW_POWER_LISTENING
-        call LowPowerListening.setRxSleepInterval(&outgoingMsgBuffer, LPL_INTERVAL);
+        call LowPowerListening.setRemoteWakeupInterval(&outgoingMsgBuffer, LPL_INTERVAL);
 #endif
         // we don't send time sync msg, if we don't have enough data
         if( numEntries < ENTRY_SEND_LIMIT && outgoingMsg->rootID != TOS_NODE_ID ){
@@ -414,11 +415,8 @@ implementation
     }
 
     command error_t TimeSyncMode.setMode(uint8_t mode_){
-        if (mode == mode_)
-            return SUCCESS;
-
         if (mode_ == TS_TIMER_MODE){
-            call Timer.startPeriodic((uint32_t)1000 * BEACON_RATE);
+            call Timer.startPeriodic((uint32_t)(896U+(call Random.rand16()&0xFF)) * BEACON_RATE);
         }
         else
             call Timer.stop();
@@ -466,10 +464,9 @@ implementation
 
     command error_t StdControl.start()
     {
-        mode = TS_TIMER_MODE;
         heartBeats = 0;
         outgoingMsg->nodeID = TOS_NODE_ID;
-        call Timer.startPeriodic((uint32_t)1000 * BEACON_RATE);
+        call TimeSyncMode.setMode(TS_TIMER_MODE);
 
         return SUCCESS;
     }
index fd8f34455cc1285880974019154ea3384fbf5df7..494745fb8352b9c0f07ea0688e79cd9e1687174e 100644 (file)
@@ -42,7 +42,6 @@ module AssociateP
   {
     interface Init;
     interface MLME_ASSOCIATE;
-    interface MLME_DISASSOCIATE;
     interface MLME_COMM_STATUS;
   }
   uses
@@ -52,14 +51,6 @@ module AssociateP
     interface FrameExtracted as AssociationResponseExtracted;
     interface FrameTx as AssociationResponseTx;
 
-    interface FrameTx as DisassociationIndirectTx;
-    interface FrameTx as DisassociationDirectTx;
-    interface FrameTx as DisassociationToCoord;
-
-    interface FrameRx as DisassociationDirectRxFromCoord;
-    interface FrameExtracted as DisassociationExtractedFromCoord;
-    interface FrameRx as DisassociationRxFromDevice;
-
     interface DataRequest;
     interface Timer<TSymbolIEEE802154> as ResponseTimeout;
     interface Pool<ieee154_txframe_t> as TxFramePool;
@@ -68,9 +59,7 @@ module AssociateP
     interface MLME_SET;
     interface FrameUtility;
     interface IEEE154Frame as Frame;
-    interface Leds;
     interface Get<uint64_t> as LocalExtendedAddress;
-    interface Ieee802154Debug as Debug;
   }
 }
 implementation
@@ -79,29 +68,25 @@ implementation
     S_IDLE = 0xFF,
   };
   uint8_t m_payloadAssocRequest[2];
-  uint8_t m_payloadDisassocRequest[2];
   uint8_t m_payloadAssocResponse[MAX_PENDING_ASSOC_RESPONSES][4];
   uint8_t m_coordAddrMode;
   uint8_t m_assocRespStatus;
   uint16_t m_shortAddress;
   bool m_associationOngoing;
-  bool m_disAssociationOngoing;
 
   command error_t Init.init()
   {
     uint8_t i;
     call ResponseTimeout.stop();
     m_payloadAssocRequest[0] = S_IDLE;
-    m_payloadDisassocRequest[0] = S_IDLE;
     m_coordAddrMode = 0;
     m_associationOngoing = FALSE;
-    m_disAssociationOngoing = FALSE;
     for (i=0; i<MAX_PENDING_ASSOC_RESPONSES; i++)
       m_payloadAssocResponse[i][0] = S_IDLE;
     return SUCCESS;
   }
 
-/* ------------------- MLME_ASSOCIATE Request ------------------- */
+  /* ------------------- MLME_ASSOCIATE Request ------------------- */
 
   command ieee154_status_t MLME_ASSOCIATE.request  (
                           uint8_t LogicalChannel,
@@ -110,8 +95,7 @@ implementation
                           uint16_t CoordPANID,
                           ieee154_address_t CoordAddress,
                           ieee154_CapabilityInformation_t CapabilityInformation,
-                          ieee154_security_t *security
-                        )
+                          ieee154_security_t *security)
   {
     ieee154_status_t status = IEEE154_SUCCESS;
     ieee154_txframe_t *txFrame=0;
@@ -126,11 +110,11 @@ implementation
       status = IEEE154_INVALID_PARAMETER;
     else if (m_associationOngoing || !(txFrame = call TxFramePool.get()))
       status = IEEE154_TRANSACTION_OVERFLOW;
-    else if (!(txControl = call TxControlPool.get())){
+    else if (!(txControl = call TxControlPool.get())) {
       call TxFramePool.put(txFrame);
       status = IEEE154_TRANSACTION_OVERFLOW;
     }
-    if (status == IEEE154_SUCCESS){
+    if (status == IEEE154_SUCCESS) {
       m_assocRespStatus = IEEE154_NO_DATA;
       m_shortAddress = 0xFFFF;
       call MLME_SET.phyCurrentChannel(LogicalChannel);
@@ -160,13 +144,13 @@ implementation
       txFrame->payload = m_payloadAssocRequest;
       txFrame->payloadLen = 2;
       m_associationOngoing = TRUE;
-      if ((status = call AssociationRequestTx.transmit(txFrame)) != IEEE154_SUCCESS){
+      if ((status = call AssociationRequestTx.transmit(txFrame)) != IEEE154_SUCCESS) {
         m_associationOngoing = FALSE;
         call TxFramePool.put(txFrame);
         call TxControlPool.put(txControl);
       }
     }
-    call Debug.log(LEVEL_INFO, AssociateP_REQUEST, status, 0, 0);
+    dbg_serial("AssociationP", "MLME_ASSOCIATE.request -> result: %lu\n", (uint32_t) status);
     return status;
   }
 
@@ -174,15 +158,15 @@ implementation
   {
     call TxControlPool.put((ieee154_txcontrol_t*) ((uint8_t*) txFrame->header - offsetof(ieee154_txcontrol_t, header)));
     call TxFramePool.put(txFrame);
-    if (status != IEEE154_SUCCESS){
+    if (status != IEEE154_SUCCESS) {
+      dbg_serial("AssociationP", "transmitDone() failed!\n");
       m_associationOngoing = FALSE;
       signal MLME_ASSOCIATE.confirm(0xFFFF, status, 0);
     } else {
       call ResponseTimeout.startOneShot(call MLME_GET.macResponseWaitTime()*IEEE154_aBaseSuperframeDuration);
-      call Debug.log(LEVEL_INFO, AssociateP_SETTIMER
-          call MLME_GET.macResponseWaitTime()*IEEE154_aBaseSuperframeDuration, 0, 0);
+      dbg_serial("AssociationP", "transmitDone() ok, waiting for %lu\n"
+          (uint32_t) (call MLME_GET.macResponseWaitTime() * IEEE154_aBaseSuperframeDuration));
     }
-    call Debug.log(LEVEL_INFO, AssociateP_TXDONE, status, 0, 0);
   }
   
   event void ResponseTimeout.fired()
@@ -191,22 +175,24 @@ implementation
     if (!m_associationOngoing)
       return;
     // have not received an AssociationResponse yet, poll the coordinator now
+    dbg_serial("AssociationP", "Polling the coordinator for an AssociationResponse now...\n");
     if (m_coordAddrMode == ADDR_MODE_SHORT_ADDRESS)
       *((nxle_uint16_t*) &coordAddress) = call MLME_GET.macCoordShortAddress();
     else
       call FrameUtility.copyCoordExtendedAddressLE(coordAddress);
     if (call DataRequest.poll(m_coordAddrMode, call MLME_GET.macPANId(), 
-          coordAddress, ADDR_MODE_EXTENDED_ADDRESS) != IEEE154_SUCCESS){
+          coordAddress, ADDR_MODE_EXTENDED_ADDRESS) != IEEE154_SUCCESS) {
       m_shortAddress = 0xFFFF;
       m_assocRespStatus = IEEE154_TRANSACTION_OVERFLOW;
       signal DataRequest.pollDone();
+      dbg_serial("AssociationP", "Poll failed (locally)...\n");
     }
   }
 
   event message_t* AssociationResponseExtracted.received(message_t* frame, ieee154_txframe_t *txFrame)
   {
     uint8_t *payload = (uint8_t *) &frame->data;
-    if (m_associationOngoing){
+    if (m_associationOngoing) {
       m_shortAddress =  *((nxle_uint16_t*) (payload + 1));
       m_assocRespStatus = *(payload + 3);
     }
@@ -215,15 +201,18 @@ implementation
 
   event void DataRequest.pollDone()
   {
-    if (m_associationOngoing){
-      call Debug.log(LEVEL_INFO, AssociateP_POLL_DONE, m_payloadAssocRequest[0], m_assocRespStatus, 0);
+    if (m_associationOngoing) {
       call ResponseTimeout.stop();
       m_associationOngoing = FALSE;
+      if (m_assocRespStatus == IEEE154_ASSOCIATION_SUCCESSFUL)
+        call MLME_SET.macShortAddress(m_shortAddress);
       signal MLME_ASSOCIATE.confirm(m_shortAddress, m_assocRespStatus, 0);
+      dbg_serial("AssociationP", "confirm, status:  %lu, my new address: 0x%lx\n", 
+          (uint32_t) m_assocRespStatus, (uint32_t) m_shortAddress);
     }
   }
 
-/* ------------------- MLME_ASSOCIATE Response ------------------- */
+  /* ------------------- MLME_ASSOCIATE Response ------------------- */
 
   event message_t* AssociationRequestRx.received(message_t* frame)
   {
@@ -240,8 +229,7 @@ implementation
                           uint64_t deviceAddress,
                           uint16_t assocShortAddress,
                           ieee154_association_status_t status,
-                          ieee154_security_t *security
-                        )
+                          ieee154_security_t *security)
   {
     uint8_t i;
     ieee154_status_t txStatus = IEEE154_SUCCESS;
@@ -252,9 +240,11 @@ implementation
     for (i=0; i<MAX_PENDING_ASSOC_RESPONSES;i++)
       if (m_payloadAssocResponse[i][0] == S_IDLE)
         break;    
-    if (i == MAX_PENDING_ASSOC_RESPONSES || !(txFrame = call TxFramePool.get()))
+    if (security && security->SecurityLevel)
+      txStatus = IEEE154_UNSUPPORTED_SECURITY;
+    else if (i == MAX_PENDING_ASSOC_RESPONSES || !(txFrame = call TxFramePool.get()))
       txStatus = IEEE154_TRANSACTION_OVERFLOW;
-    else if (!(txControl = call TxControlPool.get())){
+    else if (!(txControl = call TxControlPool.get())) {
       call TxFramePool.put(txFrame);
       txStatus = IEEE154_TRANSACTION_OVERFLOW;
     } else {
@@ -277,7 +267,7 @@ implementation
       *((nxle_uint16_t*) &txFrame->payload[1]) = assocShortAddress;
       txFrame->payload[3] = status;
       txFrame->payloadLen = 4;
-      if ((txStatus = call AssociationResponseTx.transmit(txFrame)) != IEEE154_SUCCESS){
+      if ((txStatus = call AssociationResponseTx.transmit(txFrame)) != IEEE154_SUCCESS) {
         txFrame->payload[0] = S_IDLE;
         call TxFramePool.put(txFrame);
         call TxControlPool.put(txControl);
@@ -302,164 +292,16 @@ implementation
                           status, 0);
   }
 
+  /* ------------------- Defaults ------------------- */
 
-/* ------------------- MLME_DISASSOCIATE (initiating) ------------------- */
-
-  command ieee154_status_t MLME_DISASSOCIATE.request  (
-                          uint8_t DeviceAddrMode,
-                          uint16_t DevicePANID,
-                          ieee154_address_t DeviceAddress,
-                          ieee154_disassociation_reason_t DisassociateReason,
-                          bool TxIndirect,
-                          ieee154_security_t *security
-                        )
-  {
-    ieee154_status_t status = IEEE154_SUCCESS;
-    ieee154_txframe_t *txFrame=0;
-    ieee154_txcontrol_t *txControl=0;
-    ieee154_address_t srcAddress;
-
-    if (security && security->SecurityLevel)
-      status = IEEE154_UNSUPPORTED_SECURITY;
-    else if (call MLME_GET.macPANId() != DevicePANID || 
-        (DeviceAddrMode != ADDR_MODE_SHORT_ADDRESS && DeviceAddrMode != ADDR_MODE_EXTENDED_ADDRESS))
-      status = IEEE154_INVALID_PARAMETER;
-    else if (m_disAssociationOngoing || !(txFrame = call TxFramePool.get()))
-      status = IEEE154_TRANSACTION_OVERFLOW;
-    else if (!(txControl = call TxControlPool.get())){
-      call TxFramePool.put(txFrame);
-      status = IEEE154_TRANSACTION_OVERFLOW;
-    } 
-    if (status == IEEE154_SUCCESS){
-      txFrame->header = &txControl->header;
-      txFrame->metadata = &txControl->metadata;
-      srcAddress.extendedAddress = call LocalExtendedAddress.get();
-      txFrame->headerLen = call FrameUtility.writeHeader(
-          txFrame->header->mhr,
-          DeviceAddrMode,
-          call MLME_GET.macPANId(),
-          &DeviceAddress,
-          ADDR_MODE_EXTENDED_ADDRESS,
-          call MLME_GET.macPANId(),
-          &srcAddress,
-          TRUE);
-      txFrame->header->mhr[MHR_INDEX_FC1] = FC1_ACK_REQUEST | FC1_FRAMETYPE_CMD | FC1_PAN_ID_COMPRESSION;
-      txFrame->header->mhr[MHR_INDEX_FC2] = FC2_SRC_MODE_EXTENDED |
-        (DeviceAddrMode == ADDR_MODE_SHORT_ADDRESS ? FC2_DEST_MODE_SHORT : FC2_DEST_MODE_EXTENDED);
-      m_payloadDisassocRequest[0] = CMD_FRAME_DISASSOCIATION_NOTIFICATION;
-      m_payloadDisassocRequest[1] = DisassociateReason;
-      txFrame->payload = m_payloadDisassocRequest;
-      txFrame->payloadLen = 2;
-      m_disAssociationOngoing = TRUE;
-      if ((DeviceAddrMode == ADDR_MODE_SHORT_ADDRESS &&
-            DeviceAddress.shortAddress == call MLME_GET.macCoordShortAddress()) ||
-          (DeviceAddrMode == ADDR_MODE_EXTENDED_ADDRESS &&
-           DeviceAddress.extendedAddress == call MLME_GET.macCoordExtendedAddress())){
-        status = call DisassociationToCoord.transmit(txFrame);
-      } else if (TxIndirect) {
-        status = call DisassociationIndirectTx.transmit(txFrame);
-      } else {
-        status = call DisassociationDirectTx.transmit(txFrame);
-      }
-      if (status != IEEE154_SUCCESS){
-        m_disAssociationOngoing = FALSE;
-        call TxFramePool.put(txFrame);
-        call TxControlPool.put(txControl);
-      }
-    }
-    call Debug.log(LEVEL_INFO, DISSASSOCIATE_REQUEST, status, 0, 0);
-    return status;
-  }
-
-  event void DisassociationToCoord.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) 
-  { 
-    // transmitted a disassociation notification to our coordinator
-    uint8_t *mhr = MHR(data), srcAddrOffset = 7;
-    uint8_t DeviceAddrMode = (mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) >> FC2_SRC_MODE_OFFSET;
-    uint16_t DevicePANID = *((nxle_uint16_t*) (&(mhr[MHR_INDEX_ADDRESS])));
-    ieee154_address_t DeviceAddress;
-    if ((mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_MASK) == FC2_DEST_MODE_EXTENDED)
-      srcAddrOffset += 6;
-    call FrameUtility.convertToNative(&DeviceAddress.extendedAddress, &mhr[srcAddrOffset]);
-    call TxControlPool.put((ieee154_txcontrol_t*) ((uint8_t*) data->header - offsetof(ieee154_txcontrol_t, header)));
-    call TxFramePool.put(data);
-    call Debug.log(LEVEL_INFO, DISSASSOCIATE_TXDONE, status, 2, 0);
-    m_disAssociationOngoing = FALSE;
-    signal MLME_DISASSOCIATE.confirm(status, DeviceAddrMode, DevicePANID, DeviceAddress);
-  }
-
-  event void DisassociationIndirectTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) 
-  {
-    signal DisassociationDirectTx.transmitDone(data, status);
-  }
-
-  event void DisassociationDirectTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) 
-  { 
-    // transmitted a disassociation notification to a device
-    uint8_t *mhr = MHR(data), dstAddrOffset = 5;
-    uint8_t DeviceAddrMode = (mhr[1] & FC2_DEST_MODE_MASK) >> FC2_DEST_MODE_OFFSET;
-    uint16_t DevicePANID = *((nxle_uint16_t*) (&(mhr[MHR_INDEX_ADDRESS])));
-    ieee154_address_t DeviceAddress;
-    call FrameUtility.convertToNative(&DeviceAddress.extendedAddress, &mhr[dstAddrOffset]);
-    call Debug.log(LEVEL_INFO, DISSASSOCIATE_TXDONE, status, 1, 0);
-    call TxControlPool.put((ieee154_txcontrol_t*) ((uint8_t*) data->header - offsetof(ieee154_txcontrol_t, header)));
-    call TxFramePool.put(data);
-    call Debug.log(LEVEL_INFO, DISSASSOCIATE_TXDONE, status, 2, 0);
-    m_disAssociationOngoing = FALSE;
-    signal MLME_DISASSOCIATE.confirm(status, DeviceAddrMode, DevicePANID, DeviceAddress);
-  }
-
-/* ------------------- MLME_DISASSOCIATE (receiving) ------------------- */
-
-  event message_t* DisassociationDirectRxFromCoord.received(message_t* frame)
-  {
-    // received a disassociation notification from the coordinator (direct tx)
-    ieee154_address_t address;
-    address.extendedAddress = call LocalExtendedAddress.get();
-    signal MLME_DISASSOCIATE.indication(address.extendedAddress, frame->data[1], NULL);
-    return frame;
-  }
-
-  event message_t* DisassociationExtractedFromCoord.received(message_t* frame, ieee154_txframe_t *txFrame)
-  {
-    // received a disassociation notification from the coordinator (indirect transmission)
-    return signal DisassociationDirectRxFromCoord.received(frame);
-  }
-
-  event message_t* DisassociationRxFromDevice.received(message_t* frame)
-  {
-    // received a disassociation notification from the device
-    ieee154_address_t address;
-    call Debug.log(LEVEL_INFO, DISSASSOCIATE_RX, 0, 0, 0);
-    if (call Frame.getSrcAddrMode(frame) == ADDR_MODE_EXTENDED_ADDRESS && 
-        call Frame.getSrcAddr(frame, &address) == SUCCESS)
-      signal MLME_DISASSOCIATE.indication(address.extendedAddress, frame->data[1], NULL);
-    return frame;
-  }
-
-/* ------------------- Defaults ------------------- */
-
-  default event void MLME_DISASSOCIATE.indication (
-                          uint64_t DeviceAddress,
-                          ieee154_disassociation_reason_t DisassociateReason,
-                          ieee154_security_t *security
-                        ){}
-  default event void MLME_DISASSOCIATE.confirm    (
-                          ieee154_status_t status,
-                          uint8_t DeviceAddrMode,
-                          uint16_t DevicePANID,
-                          ieee154_address_t DeviceAddress
-                        ){}
   default event void MLME_ASSOCIATE.indication (
                           uint64_t DeviceAddress,
                           ieee154_CapabilityInformation_t CapabilityInformation,
-                          ieee154_security_t *security
-                        ){}
+                          ieee154_security_t *security) {}
   default event void MLME_ASSOCIATE.confirm    (
                           uint16_t AssocShortAddress,
                           uint8_t status,
-                          ieee154_security_t *security
-                        ){}
+                          ieee154_security_t *security) {}
   default event void MLME_COMM_STATUS.indication (
                           uint16_t PANId,
                           uint8_t SrcAddrMode,
@@ -467,6 +309,5 @@ implementation
                           uint8_t DstAddrMode,
                           ieee154_address_t DstAddr,
                           ieee154_status_t status,
-                          ieee154_security_t *security
-                        ){}
+                          ieee154_security_t *security) {}
 }
diff --git a/tos/lib/mac/tkn154/BeaconRequestRxP.nc b/tos/lib/mac/tkn154/BeaconRequestRxP.nc
new file mode 100644 (file)
index 0000000..11adf0e
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) 2009, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+
+#include "TKN154_MAC.h"
+#include "TKN154.h"
+module BeaconRequestRxP
+{
+  provides
+  {
+    interface Init as Reset;
+    interface IEEE154TxBeaconPayload;
+  }
+  uses
+  {
+    interface FrameRx as BeaconRequestRx;
+    interface FrameTx as BeaconRequestResponseTx;
+    interface MLME_GET;
+    interface FrameUtility;
+    interface IEEE154Frame as Frame;
+
+  }
+}
+implementation
+{
+  /* variables that describe the beacon (payload) */
+  norace ieee154_txframe_t  m_beaconFrame;
+  ieee154_header_t          m_header;
+  ieee154_metadata_t        m_metadata;  
+  uint8_t                   m_beaconPayloadLen;
+  uint8_t                   m_payload[IEEE154_aMaxBeaconPayloadLength];
+
+  /* ------------------- Init ------------------- */
+
+  command error_t Reset.init()
+  {
+    m_beaconPayloadLen = 0;
+    m_beaconFrame.header = &m_header;
+    m_beaconFrame.headerLen = 0;
+    m_beaconFrame.payload = m_payload;
+    m_beaconFrame.payloadLen = 4;  // first 4 bytes belong to superframe- & gts-fields
+    m_beaconFrame.metadata = &m_metadata;
+
+    dbg_serial("BeaconRequestResponderP","Init()\n");
+    return SUCCESS;
+  }
+
+  /* ------------------- Beacon-Request Response ------------------- */
+
+  task void sendBeaconTask(){
+    call BeaconRequestResponseTx.transmit(&m_beaconFrame);
+  }
+
+  event message_t* BeaconRequestRx.received(message_t* frame) 
+  {
+    uint8_t offset = 0;
+    ieee154_macShortAddress_t shortAddress = call MLME_GET.macShortAddress();
+    bool isShortAddr;
+
+    shortAddress = call MLME_GET.macShortAddress();
+    isShortAddr = (shortAddress != 0xFFFE);
+    m_beaconFrame.header->mhr[MHR_INDEX_FC1] = FC1_FRAMETYPE_BEACON;
+    m_beaconFrame.header->mhr[MHR_INDEX_FC2] = isShortAddr ? FC2_SRC_MODE_SHORT : FC2_SRC_MODE_EXTENDED;
+    offset = MHR_INDEX_ADDRESS;
+    *((nxle_uint16_t*) &m_beaconFrame.header->mhr[offset]) = call MLME_GET.macPANId();
+    offset += sizeof(ieee154_macPANId_t);
+    if (isShortAddr) {
+      *((nxle_uint16_t*) &m_beaconFrame.header->mhr[offset]) = shortAddress;
+      offset += sizeof(ieee154_macShortAddress_t);
+    } else {
+      call FrameUtility.copyLocalExtendedAddressLE(&m_beaconFrame.header->mhr[offset]);
+      offset += 8;
+    }
+    m_beaconFrame.headerLen = offset;
+
+    // Superframe-spec
+    m_payload[BEACON_INDEX_SF_SPEC1] = 0xff; // beacon- and superframe order always 15 in nonbeacon-enabled mode
+    m_payload[BEACON_INDEX_SF_SPEC2] = 0x00; 
+    if (call MLME_GET.macPanCoordinator() == TRUE) 
+      m_payload[BEACON_INDEX_SF_SPEC2] |= SF_SPEC2_PAN_COORD;
+    if (call MLME_GET.macAssociationPermit() == TRUE) 
+      m_payload[BEACON_INDEX_SF_SPEC2] |= SF_SPEC2_ASSOCIATION_PERMIT;
+    if (call MLME_GET.macBattLifeExt() == TRUE) 
+      m_payload[BEACON_INDEX_SF_SPEC2] |= SF_SPEC2_BATT_LIFE_EXT;
+    // GTS-spec
+    m_payload[BEACON_INDEX_GTS_SPEC] = 0;
+    // Pending-Address-spec (behind empty single-byte GTS field)
+    m_payload[BEACON_INDEX_GTS_SPEC + 1] = 0;
+
+    signal IEEE154TxBeaconPayload.aboutToTransmit(); 
+    post sendBeaconTask();
+
+    return frame;
+
+  }
+  event void BeaconRequestResponseTx.transmitDone(ieee154_txframe_t *txFrame, ieee154_status_t status){
+    signal IEEE154TxBeaconPayload.beaconTransmitted();
+  }
+
+  /* ----------------------- Beacon Payload ----------------------- */
+
+  command error_t IEEE154TxBeaconPayload.setBeaconPayload(void *beaconPayload, uint8_t length) {
+    dbg_serial("BeaconRequestResponderP","IEEE154TxBeaconPayload.setBeaconPayload\n\n");
+    if (length < IEEE154_aMaxBeaconPayloadLength){
+      memcpy(&m_payload[4], beaconPayload, length);
+      m_beaconFrame.payloadLen = 4 + length;
+      signal IEEE154TxBeaconPayload.setBeaconPayloadDone(beaconPayload, length); 
+      return SUCCESS;
+    } else 
+      return ESIZE;
+  }
+
+  command const void* IEEE154TxBeaconPayload.getBeaconPayload(){
+    return &m_payload[4]; // the first four bytes are non-user bytes
+  }
+
+  command uint8_t IEEE154TxBeaconPayload.getBeaconPayloadLength(){
+    return m_beaconFrame.payloadLen - 4; // Beacon-Payload in NonBeaconed mode at least 4 bytes (non-user payload) 
+  }
+
+  command error_t IEEE154TxBeaconPayload.modifyBeaconPayload(uint8_t offset, void *buffer, uint8_t bufferLength){
+    uint16_t totalLen = offset + bufferLength;
+    if (totalLen > IEEE154_aMaxBeaconPayloadLength ||
+        call IEEE154TxBeaconPayload.getBeaconPayloadLength() < totalLen)
+      return ESIZE;
+    else {
+      memcpy(&m_payload[4+offset], buffer, bufferLength);
+      signal IEEE154TxBeaconPayload.modifyBeaconPayloadDone(offset, buffer , bufferLength); 
+    }
+    return SUCCESS;
+  }
+
+  default event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) {}
+  default event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) {}
+  default event void IEEE154TxBeaconPayload.aboutToTransmit() {}
+  default event void IEEE154TxBeaconPayload.beaconTransmitted() {}
+
+}
+
index e7c39110a2a2f6cba0bc48281ddebd4e3dd0b6f9..ff2a0c0061438d1b75fdd1b00e8e741f01ed00aa 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * This module is responsible for periodic beacon tracking in a 
+ * beacon-enabled PAN.
+ */
 
 #include "TKN154_MAC.h"
-#include "TKN154_DEBUG.h"
 
 module BeaconSynchronizeP
 {
@@ -45,345 +48,411 @@ module BeaconSynchronizeP
     interface MLME_SYNC;
     interface MLME_BEACON_NOTIFY;
     interface MLME_SYNC_LOSS;
+    interface SuperframeStructure as IncomingSF;
     interface GetNow<bool> as IsTrackingBeacons;
-    interface GetNow<uint32_t> as CapStart;
-    interface GetNow<ieee154_reftime_t*> as CapStartRefTime; 
-    interface GetNow<uint32_t> as CapLen;
-    interface GetNow<uint32_t> as CapEnd;
-    interface GetNow<uint32_t> as CfpEnd;
-    interface GetNow<uint32_t> as CfpLen;
-    interface GetNow<uint32_t> as BeaconInterval; 
-    interface GetNow<bool> as IsBLEActive; 
-    interface GetNow<uint16_t> as BLELen; 
-    interface GetNow<uint8_t*> as GtsField;
-    interface GetNow<uint32_t> as SfSlotDuration; 
-    interface GetNow<uint8_t> as FinalCapSlot; 
-    interface GetNow<uint8_t> as NumGtsSlots;
-    interface GetNow<bool> as IsRxBroadcastPending; 
+    interface SplitControl as TrackSingleBeacon;
   }
   uses
   {
     interface MLME_GET;
     interface MLME_SET;
     interface FrameUtility;
-    interface Notify<bool> as FindBeacon;
     interface IEEE154BeaconFrame as BeaconFrame;
     interface Alarm<TSymbolIEEE802154,uint32_t> as TrackAlarm;
     interface RadioRx as BeaconRx;
     interface RadioOff;
-    interface Get<bool> as IsBeaconEnabledPAN;
     interface DataRequest;
     interface FrameRx as CoordRealignmentRx;
-    interface Resource as Token;
-    interface ResourceTransfer as TokenToCap;
+    interface TransferableResource as RadioToken;
     interface TimeCalc;
     interface IEEE154Frame as Frame;
     interface Leds;
-    interface Ieee802154Debug as Debug;
   }
 }
 implementation
 {
+  /* state variables */
+  norace uint8_t m_state;
+  norace uint8_t m_numBeaconsMissed;
 
-  enum {
-    S_PREPARE = 0,
-    S_RXNOW = 1,
-    S_RADIO_OFF = 2,
-    S_FIRST_SCAN= 3,
-
-    RX_DURATION = 1000,    // listen for a beacon for RX_DURATION symbols
-    RX_LAG = 100,          // start to listen for a RX_LAG before expected arrival
-  };
-
-  norace bool m_tracking = FALSE;
-  bool m_updatePending = FALSE;
+  /* temporary buffers for the MLME-SYNC parameters */
   uint8_t m_updateLogicalChannel;
   bool m_updateTrackBeacon;
-  bool m_stopTracking = FALSE;
-  bool m_internalRequest = FALSE;
-
-  uint8_t m_numBeaconsLost;
-  uint8_t m_coordAddress[8];
-  message_t m_beaconBuffer;
-  norace message_t *m_beaconBufferPtr = &m_beaconBuffer;
-  norace bool m_beaconSwapBufferReady = TRUE;
-  norace uint32_t m_beaconInterval;
+
+  /* variables that describe the current beacon configuration */
+  norace ieee154_macBeaconOrder_t m_beaconOrder;
   norace uint32_t m_dt;
   norace uint32_t m_lastBeaconRxTime;
-  norace ieee154_reftime_t m_lastBeaconRxRefTime;
-  norace uint8_t m_state;
-  norace uint8_t m_beaconOrder;
+  norace ieee154_timestamp_t m_lastBeaconRxRefTime;
+  message_t m_beacon;
+  norace message_t *m_beaconPtr = &m_beacon;
+
+  /* variables that describe the latest superframe */
   norace uint32_t m_sfSlotDuration;
-  norace uint8_t m_finalCapSlot;
+  norace bool m_framePendingBit;
+  norace uint8_t m_numCapSlots;
   norace uint8_t m_numGtsSlots;
-  norace uint16_t m_BLELen;
-  norace bool m_broadcastPending;
+  norace uint16_t m_battLifeExtDuration;
   uint8_t m_gtsField[1+1+3*7];
+  
+  enum {
+    RX_PREPARE = 0x00,
+    RX_RECEIVING = 0x01,
+    RX_RADIO_OFF = 0x02,
+    RX_FIRST_SCAN= 0x03,
+    RX_MASK = 0x03,
+
+    MODE_INACTIVE = 0x00,
+    MODE_TRACK_SINGLE = 0x04,
+    MODE_TRACK_CONTINUOUS = 0x08,
+    MODE_MASK = 0x0C,
+
+    BEACON_RECEIVED = 0x10,
+    UPDATE_PENDING = 0x20,
+    INTERNAL_REQUEST = 0x40,
+    EXTERNAL_REQUEST = 0x80,
+  };
+
+  /* function/task prototypes */
+  void trackNextBeacon();
+  uint32_t getBeaconInterval(ieee154_macBeaconOrder_t BO);
   task void processBeaconTask();
+  task void signalGrantedTask();
 
+  /* accessing/manipulating the current state */
+  void setBeaconReceived() { m_state |= BEACON_RECEIVED; }
+  void resetBeaconReceived() { m_state &= ~BEACON_RECEIVED; }
+  bool wasBeaconReceived() { return (m_state & BEACON_RECEIVED) ? TRUE : FALSE; }
+  void setUpdatePending() { m_state |= UPDATE_PENDING; }
+  void resetUpdatePending() { m_state &= ~UPDATE_PENDING; }
+  bool isUpdatePending() { return (m_state & UPDATE_PENDING) ? TRUE : FALSE; }
+  void setInternalRequest() { m_state |= INTERNAL_REQUEST; }
+  void resetInternalRequest() { m_state &= ~INTERNAL_REQUEST; }
+  bool isInternalRequest() { return (m_state & INTERNAL_REQUEST) ? TRUE : FALSE; }
+  void setExternalRequest() { m_state |= EXTERNAL_REQUEST; }
+  void resetExternalRequest() { m_state &= ~EXTERNAL_REQUEST; }
+  bool isExternalRequest() { return (m_state & EXTERNAL_REQUEST) ? TRUE : FALSE; }
+  uint8_t getMode() { return (m_state & MODE_MASK); }
+  void setMode(uint8_t mode) { m_state &= ~MODE_MASK; m_state |= (mode & MODE_MASK); }
+  uint8_t getRxState() { return (m_state & RX_MASK); }
+  void setRxState(uint8_t state) { m_state &= ~RX_MASK; m_state |= (state & RX_MASK); }  
+  
   command error_t Reset.init()
   {
-    if (call Token.isOwner()){
-      call Leds.led0On(); // internal error
-      return FAIL;
-    }    
-    if (m_tracking || m_updatePending)
+    // Reset this component - will only be called while we're not owning the token
+    if (call IsTrackingBeacons.getNow() || 
+        (isUpdatePending() && isExternalRequest() && m_updateTrackBeacon))
       signal MLME_SYNC_LOSS.indication(
           IEEE154_BEACON_LOSS,
           call MLME_GET.macPANId(),
           call MLME_GET.phyCurrentChannel(),
           call MLME_GET.phyCurrentPage(),
           NULL);
-    m_updatePending = m_stopTracking = m_tracking = FALSE;
+    if (isInternalRequest())
+      signal TrackSingleBeacon.startDone(FAIL);
+    resetUpdatePending();
+    resetInternalRequest();
+    resetExternalRequest();
+    setMode(MODE_INACTIVE); 
     return SUCCESS;
   }  
 
-/* ----------------------- MLME-SYNC ----------------------- */
-/*
* Allows to synchronize with a coordinator.
- */
+  /* ----------------------- MLME-SYNC ----------------------- */
+  /*
  * Allows to synchronize with the beacons from a coordinator.
  */
 
   command ieee154_status_t MLME_SYNC.request  (
       uint8_t logicalChannel,
       uint8_t channelPage,
       bool trackBeacon)
   {
+    error_t status = IEEE154_SUCCESS;
     uint32_t supportedChannels = IEEE154_SUPPORTED_CHANNELS;
     uint32_t currentChannelBit = 1;
 
     currentChannelBit <<= logicalChannel;
     if (!(currentChannelBit & supportedChannels) || (call MLME_GET.macPANId() == 0xFFFF) ||
-        (channelPage != IEEE154_SUPPORTED_CHANNELPAGE) || !call IsBeaconEnabledPAN.get())
-      return IEEE154_INVALID_PARAMETER;
-
-    call Debug.log(LEVEL_INFO,SyncP_REQUEST, logicalChannel, channelPage, trackBeacon);
-    if (!trackBeacon && m_tracking){
-      // stop tracking after next received beacon
-      m_stopTracking = TRUE;
-    } else {
-      m_stopTracking = FALSE;
-      m_updateLogicalChannel = logicalChannel;
+        (channelPage != IEEE154_SUPPORTED_CHANNELPAGE) || !IEEE154_BEACON_ENABLED_PAN)
+      status = IEEE154_INVALID_PARAMETER;
+    else {
       m_updateTrackBeacon = trackBeacon;
-      m_updatePending = TRUE;
-      m_internalRequest = FALSE;
-      call Debug.log(LEVEL_INFO,SyncP_RESOURCE_REQUEST, 0, 0, 0);
-      call Token.request();
+      m_updateLogicalChannel = logicalChannel;
+      setExternalRequest();
+      setUpdatePending();
+      call RadioToken.request();
     }
-    call Debug.flush();
-    return IEEE154_SUCCESS;
+
+    dbg_serial("BeaconSynchronizeP", "MLME_SYNC.request -> result: %lu\n", (uint32_t) status);
+    return status;
   }
 
-  event void FindBeacon.notify( bool val )
+  event void RadioToken.granted()
   {
-    if (!m_tracking && !m_updatePending){
-      // find a single beacon now (treat this like a user request)
-      m_updateLogicalChannel = call MLME_GET.phyCurrentChannel();
-      m_updateTrackBeacon = FALSE;
-      m_updatePending = TRUE;
-      m_internalRequest = TRUE;
-      call Token.request();
-    }
+    if (isUpdatePending()) {
+      dbg_serial("BeaconSynchronizeP", "Updating configuration...\n"); 
+      if (m_updateTrackBeacon)
+        setMode(MODE_TRACK_CONTINUOUS);
+      else
+        setMode(MODE_TRACK_SINGLE);
+      call MLME_SET.phyCurrentChannel(m_updateLogicalChannel);
+      m_beaconOrder = call MLME_GET.macBeaconOrder();
+      m_dt = getBeaconInterval(m_beaconOrder);
+      m_numBeaconsMissed = IEEE154_aMaxLostBeacons;  // will be reset when first beacon is received
+      resetUpdatePending();
+      setRxState(RX_FIRST_SCAN);
+    } 
+    trackNextBeacon();
+  }
+
+  async event void RadioToken.transferredFrom(uint8_t clientFrom)
+  {
+    dbg_serial("BeaconSynchronizeP", "Got token (transferred).\n");
+    if (isUpdatePending())
+      post signalGrantedTask();
+    else
+      trackNextBeacon();
   }
 
-  event void Token.granted()
+  task void signalGrantedTask()
+  {
+    signal RadioToken.granted();
+  }
+
+  void trackNextBeacon()
   {
     bool missed = FALSE;
-    call Debug.flush();
-    call Debug.log(LEVEL_INFO,SyncP_GOT_RESOURCE, m_lastBeaconRxTime+m_beaconInterval, 
-        m_beaconInterval, (m_updatePending<<1)+m_tracking);
-    if (m_updatePending){
-      m_state = S_FIRST_SCAN;
-      m_updatePending = FALSE;      
-      m_beaconOrder = call MLME_GET.macBeaconOrder();
-      if (m_beaconOrder >= 15)
-        m_beaconOrder = 14;
-      call MLME_SET.phyCurrentChannel(m_updateLogicalChannel);
-      m_tracking = m_updateTrackBeacon;
-      m_beaconInterval = ((uint32_t) 1 << m_beaconOrder) * (uint32_t) IEEE154_aBaseSuperframeDuration; 
-      m_dt = m_beaconInterval;
-      m_numBeaconsLost = IEEE154_aMaxLostBeacons;  // will be reset when beacon is received
-      call Debug.log(LEVEL_INFO,SyncP_UPDATING, call MLME_GET.macCoordShortAddress(), 
-          call MLME_GET.macPANId(), m_updateLogicalChannel);
-    } else {
-      m_state = S_PREPARE;
-      if (!m_tracking){
-        call Debug.log(LEVEL_INFO,SyncP_RELEASE_RESOURCE, 0, 0, 0);
-        call Token.release();
-        return;
-      }
-      while (call TimeCalc.hasExpired(m_lastBeaconRxTime, m_dt)){ // missed a beacon
-        call Debug.log(LEVEL_INFO,SyncP_BEACON_MISSED_1, m_lastBeaconRxTime, m_dt, missed);
-        m_dt += m_beaconInterval;
-        m_numBeaconsLost++;
+
+    if (getMode() == MODE_INACTIVE) {
+      // nothing to do, just give up the token
+      dbg_serial("BeaconSynchronizeP", "Stop tracking.\n");
+      call RadioToken.release();
+      return;
+    }
+
+    if (getRxState() != RX_FIRST_SCAN) {
+
+      dbg_serial("BeaconSynchronizeP","Token.transferred(), expecting beacon in %lu symbols.\n",
+        (uint32_t) ((m_lastBeaconRxTime + m_dt) - call TrackAlarm.getNow())); 
+
+      // we have received at least one previous beacon, get ready for the next
+      setRxState(RX_PREPARE);
+
+      while (call TimeCalc.hasExpired(m_lastBeaconRxTime, m_dt)) { // missed a beacon!
+        dbg_serial("BeaconSynchronizeP", "Missed a beacon, expected it: %lu, now: %lu\n", 
+            m_lastBeaconRxTime + m_dt, call TrackAlarm.getNow());
         missed = TRUE;
+        m_dt += getBeaconInterval(m_beaconOrder);
+        m_numBeaconsMissed++;
       }
-      if (m_numBeaconsLost >= IEEE154_aMaxLostBeacons){
+
+      if (m_numBeaconsMissed >= IEEE154_aMaxLostBeacons) {
+        dbg_serial("BeaconSynchronizeP", "Missed too many beacons.\n");
         post processBeaconTask();
         return;
       }
-      if (missed){
-        call Token.request();
-        call Debug.log(LEVEL_INFO,SyncP_RELEASE_RESOURCE, m_lastBeaconRxTime, m_dt, missed);
-        call Token.release();
+
+      if (missed) {
+        // let other components get a chance to use the radio
+        call RadioToken.request();
+        dbg_serial("BeaconSynchronizeP", "Skipping a beacon.\n");
+        call RadioToken.release();
         return;
       }
     }
-    if (!call RadioOff.isOff())
-      call RadioOff.off();
-    else
+
+    if (call RadioOff.isOff())
       signal RadioOff.offDone();
+    else if (call RadioOff.off() != SUCCESS) 
+      ASSERT(0);
   }
 
-  async event void TrackAlarm.fired()
+  async event void RadioOff.offDone()
   {
-    call Debug.log(LEVEL_IMPORTANT,SyncP_TRACK_ALARM, m_state,m_lastBeaconRxTime,m_dt);
-    atomic {
-      switch (m_state)
-      {
-        case S_PREPARE:
-          call BeaconRx.prepare();
-          break;
-        case S_RADIO_OFF: 
-          call RadioOff.off(); 
-          break;
-      }
+    uint32_t delay = IEEE154_RADIO_RX_DELAY + IEEE154_MAX_BEACON_JITTER(m_beaconOrder);
+
+    if (getRxState() == RX_FIRST_SCAN) {
+      // initial scan: switch to Rx immediately
+      call BeaconRx.enableRx(0, 0);
+    } else if (getRxState() == RX_PREPARE) {
+      if (!call TimeCalc.hasExpired(m_lastBeaconRxTime - delay, m_dt))
+        call TrackAlarm.startAt(m_lastBeaconRxTime - delay, m_dt);
+      else
+        signal TrackAlarm.fired();
+    } else {
+      post processBeaconTask();
     }
   }
 
-  async event void BeaconRx.prepareDone()
+  async event void BeaconRx.enableRxDone()
   {
-    error_t result;
-    if (m_state == S_FIRST_SCAN){
-      m_state = S_RADIO_OFF;
-      atomic {
-        call BeaconRx.receive(NULL, 0);
-        call TrackAlarm.start((((uint32_t) 1 << m_beaconOrder) + (uint32_t) 1) * 
-            (uint32_t) IEEE154_aBaseSuperframeDuration * (uint32_t) IEEE154_aMaxLostBeacons);
-      }
-    } else {
-      m_state = S_RADIO_OFF;
-      result = call BeaconRx.receive(&m_lastBeaconRxRefTime, m_dt-RX_LAG);
-      call Debug.log(LEVEL_IMPORTANT,SyncP_RX_ON, m_lastBeaconRxTime, call TrackAlarm.getNow(), m_dt+RX_DURATION);
-      if (result != SUCCESS)
-        call Debug.log(LEVEL_IMPORTANT,SyncP_RADIO_BUSY, result, 0, 0);
-      call TrackAlarm.startAt(m_lastBeaconRxTime, m_dt + RX_DURATION);
+    uint32_t dt;
+    uint8_t previousState = getRxState();
+
+    setRxState(RX_RECEIVING);
+
+    switch (previousState)
+    {
+      case RX_FIRST_SCAN: 
+        // "To acquire beacon synchronization, a device shall enable its 
+        // receiver and search for at most [aBaseSuperframeDuration * (2^n + 1)]
+        // symbols, where n is the value of macBeaconOrder [...] Once the number
+        // of missed beacons reaches aMaxLostBeacons, the MLME shall notify the 
+        // next higher layer." (Sect. 7.5.4.1)
+        dt = (((uint32_t) 1 << m_beaconOrder) + (uint32_t) 1) * 
+          (uint32_t) IEEE154_aBaseSuperframeDuration * 
+          (uint32_t) IEEE154_aMaxLostBeacons;
+        call TrackAlarm.start(dt);
+        dbg_serial("BeaconSynchronizeP","Rx enabled, expecting first beacon within next %lu symbols.\n", dt);
+        break;
+      case RX_PREPARE:
+        dt = m_dt + IEEE154_MAX_BEACON_LISTEN_TIME(m_beaconOrder);
+        call TrackAlarm.startAt(m_lastBeaconRxTime, dt);
+        dbg_serial("BeaconSynchronizeP","Rx enabled, expecting beacon within next %lu symbols.\n",
+            (uint32_t) ((m_lastBeaconRxTime + dt) - call TrackAlarm.getNow())); 
+        break;
+      default:
+        ASSERT(0);
+        break;
     }
   }
 
-  event message_t* BeaconRx.received(message_t *frame, ieee154_reftime_t *timestamp)
+  async event void TrackAlarm.fired()
   {
-    uint8_t *mhr = MHR(frame);
-    call Debug.log(LEVEL_INFO,SyncP_RX_PACKET,*((nxle_uint32_t*) &mhr[MHR_INDEX_ADDRESS]), 
-        mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK,mhr[MHR_INDEX_SEQNO]);
-    if (!m_beaconSwapBufferReady || !call FrameUtility.isBeaconFromCoord(frame))
-    {
-      call Debug.log(LEVEL_IMPORTANT,SyncP_RX_GARBAGE, m_beaconSwapBufferReady, 0, 0);
+    if (getRxState() == RX_PREPARE) { // enable Rx
+      uint32_t maxBeaconJitter = IEEE154_MAX_BEACON_JITTER(m_beaconOrder);
+      if (maxBeaconJitter > m_dt)
+        maxBeaconJitter = m_dt; // receive immediately
+      call BeaconRx.enableRx(m_lastBeaconRxTime, m_dt - maxBeaconJitter);
+    } else { // disable Rx
+      error_t error = call RadioOff.off();
+      ASSERT(getRxState() == RX_RECEIVING && error == SUCCESS); 
+    }
+  }
+
+  event message_t* BeaconRx.received(message_t *frame, const ieee154_timestamp_t *timestamp)
+  {
+    if (wasBeaconReceived()) {
+      dbg_serial("BeaconSynchronizeP", "Got another beacon! -> ignoring it ...\n");
+      return frame;
+    } else if (!call FrameUtility.isBeaconFromCoord(frame)) {
+      dbg_serial("BeaconSynchronizeP", "Got a beacon, but not from my coordinator.\n");
       return frame;
     } else {
-      message_t *tmp = m_beaconBufferPtr;
-      call TrackAlarm.stop();
-      m_beaconSwapBufferReady = FALSE;
-      m_beaconBufferPtr = frame;
+      message_t *tmp = m_beaconPtr;
+      setBeaconReceived();
+      m_beaconPtr = frame;
       if (timestamp != NULL)
-        memcpy(&m_lastBeaconRxRefTime, timestamp, sizeof(ieee154_reftime_t));
-      call RadioOff.off();
+        memcpy(&m_lastBeaconRxRefTime, timestamp, sizeof(ieee154_timestamp_t));
+      if (getRxState() == RX_RECEIVING) { 
+        call TrackAlarm.stop(); // may fail
+        call RadioOff.off();    // may fail
+      }
       return tmp;
     }
   }
 
-  async event void RadioOff.offDone()
-  {
-    if (m_state == S_FIRST_SCAN)
-      call BeaconRx.prepare();
-    else if (m_state == S_PREPARE)
-      call TrackAlarm.startAt(m_lastBeaconRxTime, m_dt - IEEE154_RADIO_RX_PREPARE_DELAY);
-    else
-      post processBeaconTask();
-  }
+
 
   task void processBeaconTask()
   {
+    // task will be executed after every (un)successful attempt to track a beacon
+    bool wasInternalRequest = isInternalRequest();
+    
+    if (wasBeaconReceived() && !call Frame.isTimestampValid(m_beaconPtr)) {
+      dbg_serial("BeaconSynchronizeP", "Received beacon has invalid timestamp, discarding it!\n");
+      resetBeaconReceived();
+    }
 
-    // valid beacon timestamp is pre-condition for slotted CSMA-CA
-    if (m_beaconSwapBufferReady || !call Frame.isTimestampValid(m_beaconBufferPtr)){
-      // missed a beacon!
-      m_numBeaconsLost++;
-      m_dt += m_beaconInterval;
-      call Debug.log(LEVEL_IMPORTANT, SyncP_BEACON_MISSED_3,m_numBeaconsLost,0,m_lastBeaconRxTime);
-      if (m_numBeaconsLost >= IEEE154_aMaxLostBeacons){
-        m_tracking = FALSE;
-        call Debug.log(LEVEL_IMPORTANT, SyncP_LOST_SYNC,0,0,0);
-        call Leds.led2Off();
-        if (m_internalRequest)
-          call TokenToCap.transfer();
-        else
-          signal MLME_SYNC_LOSS.indication(
-              IEEE154_BEACON_LOSS, 
-              call MLME_GET.macPANId(),
-              call MLME_GET.phyCurrentChannel(),
-              call MLME_GET.phyCurrentPage(), 
-              NULL // security
-              );
-      } else
-        call Token.request(); // make another request again (before giving the token up)
-      call Debug.log(LEVEL_INFO,SyncP_RELEASE_RESOURCE, 0, 0, 0);
-      call Token.release();
+    if (getMode() == MODE_TRACK_SINGLE)
+      setMode(MODE_INACTIVE); // we're done with a single shot
+    resetInternalRequest();
+
+    // whether we next release the token or pass it to the CAP 
+    // component, we want it back (because we decide later
+    // whether we'll actually stop tracking the beacon in future)
+    call RadioToken.request();  
+
+    if (!wasBeaconReceived()) {
+
+      resetBeaconReceived(); // buffer ready
+      m_numBeaconsMissed += 1;
+      m_dt += getBeaconInterval(m_beaconOrder);
+      dbg_serial("BeaconSynchronizeP", "Missed a beacon (total missed: %lu).\n", (uint32_t) m_numBeaconsMissed);
+
+      if (wasInternalRequest) {
+        // note: if it only was an internal request, the
+        // mode was reset above already (SINGLE_SHOT)
+        signal TrackSingleBeacon.startDone(FAIL);
+      } 
+      if (isExternalRequest() && m_numBeaconsMissed >= IEEE154_aMaxLostBeacons) {
+        resetExternalRequest();
+        setMode(MODE_INACTIVE);
+        dbg_serial("BeaconSynchronizeP", "MLME_SYNC_LOSS!\n");
+        signal MLME_SYNC_LOSS.indication( 
+            IEEE154_BEACON_LOSS, 
+            call MLME_GET.macPANId(),
+            call MLME_GET.phyCurrentChannel(),
+            call MLME_GET.phyCurrentPage(), 
+            NULL);
+      }
+
+      call RadioToken.release();
+    
     } else { 
-      // got the beacon!
-      uint8_t *payload = (uint8_t *) m_beaconBufferPtr->data;
+      // received the beacon!
+      uint8_t *payload = (uint8_t *) m_beaconPtr->data;
       ieee154_macAutoRequest_t autoRequest = call MLME_GET.macAutoRequest();
       uint8_t pendAddrSpecOffset = 3 + (((payload[2] & 7) > 0) ? 1 + (payload[2] & 7) * 3: 0); // skip GTS
       uint8_t pendAddrSpec = payload[pendAddrSpecOffset];
       uint8_t *beaconPayload = payload + pendAddrSpecOffset + 1;
-      uint8_t beaconPayloadSize = call BeaconFrame.getBeaconPayloadLength(m_beaconBufferPtr);
+      uint8_t beaconPayloadSize = call BeaconFrame.getBeaconPayloadLength(m_beaconPtr);
       uint8_t pendingAddrMode = ADDR_MODE_NOT_PRESENT;
-      uint8_t coordBeaconOrder;
-      uint8_t *mhr = MHR(m_beaconBufferPtr);
-      uint8_t frameLen = ((uint8_t*) m_beaconBufferPtr)[0] & FRAMECTL_LENGTH_MASK;
+      uint8_t *mhr = MHR(m_beaconPtr);
+      uint8_t frameLen = ((uint8_t*) m_beaconPtr)[0] & FRAMECTL_LENGTH_MASK;
       uint8_t gtsFieldLength;
-      uint32_t timestamp = call Frame.getTimestamp(m_beaconBufferPtr);
+      uint32_t timestamp = call Frame.getTimestamp(m_beaconPtr);
 
-      call Debug.log(LEVEL_INFO, SyncP_BEACON_RX, m_lastBeaconRxTime, timestamp, mhr[2]);
+      dbg_serial("BeaconSynchronizeP", "Got beacon, timestamp: %lu, offset to previous: %lu\n", 
+        (uint32_t) timestamp, (uint32_t) (timestamp - m_lastBeaconRxTime));
+
+      m_numBeaconsMissed = 0;
       m_numGtsSlots = (payload[2] & 7);
       gtsFieldLength = 1 + ((m_numGtsSlots > 0) ? 1 + m_numGtsSlots * 3: 0);
       m_lastBeaconRxTime = timestamp;
-      m_finalCapSlot = (payload[1] & 0x0F);
+      m_numCapSlots = (payload[1] & 0x0F) + 1;
       m_sfSlotDuration = (((uint32_t) 1) << ((payload[0] & 0xF0) >> 4)) * IEEE154_aBaseSlotDuration;
       memcpy(m_gtsField, &payload[2], gtsFieldLength);
 
       // check for battery life extension
-      if (payload[1] & 0x10){
+      if (payload[1] & 0x10) {
         // BLE is active; calculate the time offset from slot0
-        m_BLELen = IEEE154_SHR_DURATION + frameLen * IEEE154_SYMBOLS_PER_OCTET;
+        m_battLifeExtDuration = IEEE154_SHR_DURATION + frameLen * IEEE154_SYMBOLS_PER_OCTET;
         if (frameLen > IEEE154_aMaxSIFSFrameSize)
-          m_BLELen += call MLME_GET.macMinLIFSPeriod();
+          m_battLifeExtDuration += call MLME_GET.macMinLIFSPeriod();
         else
-          m_BLELen += call MLME_GET.macMinSIFSPeriod();
-        m_BLELen += call MLME_GET.macBattLifeExtPeriods();
+          m_battLifeExtDuration += call MLME_GET.macMinSIFSPeriod();
+        m_battLifeExtDuration = m_battLifeExtDuration + call MLME_GET.macBattLifeExtPeriods() * 20;
       } else
-        m_BLELen = 0;
-      m_broadcastPending = mhr[MHR_INDEX_FC1] & FC1_FRAME_PENDING ? TRUE : FALSE;
-      coordBeaconOrder = (payload[0] & 0x0F); 
-      m_dt = m_beaconInterval = ((uint32_t) 1 << coordBeaconOrder) * (uint32_t) IEEE154_aBaseSuperframeDuration; 
-      if (m_stopTracking){
-        m_tracking = FALSE;
-        call Debug.log(LEVEL_INFO,SyncP_RELEASE_RESOURCE, 0, 0, 0);
-        call Token.release();
-      } else {
-        error_t req = call Token.request();
-        call Debug.log(LEVEL_INFO,SyncP_TRANSFER_RESOURCE, req, 0, 0);
-        call TokenToCap.transfer(); 
-      }
+        m_battLifeExtDuration = 0;
+
+      m_framePendingBit = mhr[MHR_INDEX_FC1] & FC1_FRAME_PENDING ? TRUE : FALSE;
+      m_beaconOrder = (payload[0] & 0x0F); 
+      m_dt = getBeaconInterval(m_beaconOrder);
+
+      dbg_serial("BeaconSynchronizeP", "Handing over to CAP.\n");
+      call RadioToken.transferTo(RADIO_CLIENT_DEVICECAP); 
       
       if (pendAddrSpec & PENDING_ADDRESS_SHORT_MASK)
         beaconPayload += (pendAddrSpec & PENDING_ADDRESS_SHORT_MASK) * 2;
       if (pendAddrSpec & PENDING_ADDRESS_EXT_MASK)
         beaconPayload += ((pendAddrSpec & PENDING_ADDRESS_EXT_MASK) >> 4) * 8;
+
       // check for pending data (once we signal MLME_BEACON_NOTIFY we cannot
-      // touch the frame anymore)
+      // touch this frame anymore!)
       if (autoRequest)
-        pendingAddrMode = call BeaconFrame.isLocalAddrPending(m_beaconBufferPtr);
-      if (pendingAddrMode != ADDR_MODE_NOT_PRESENT){
+        pendingAddrMode = call BeaconFrame.isLocalAddrPending(m_beaconPtr);
+      if (pendingAddrMode != ADDR_MODE_NOT_PRESENT) {
         // the coord has pending data
         uint8_t CoordAddrMode;
         uint16_t CoordPANId;
@@ -397,55 +466,102 @@ implementation
         CoordPANId = *((nxle_uint16_t*) &(mhr[MHR_INDEX_ADDRESS]));
         call DataRequest.poll(CoordAddrMode, CoordPANId, CoordAddress, SrcAddrMode);
       }
-      // Beacon Tracking: update state
-      call Debug.log(LEVEL_INFO, SyncP_NEXT_RX_TIME, 0, timestamp, m_beaconInterval);
-      m_numBeaconsLost = 0;
-      // TODO: check PAN ID conflict here?
+
       if (!autoRequest || beaconPayloadSize)
-        m_beaconBufferPtr = signal MLME_BEACON_NOTIFY.indication(m_beaconBufferPtr);
-      m_beaconSwapBufferReady = TRUE;
+        m_beaconPtr = signal MLME_BEACON_NOTIFY.indication(m_beaconPtr);
+      resetBeaconReceived(); // buffer ready
     }
+    dbg_serial_flush();
   }
 
-  async command bool IsTrackingBeacons.getNow(){ return m_tracking;}
-
-  default event message_t* MLME_BEACON_NOTIFY.indication (message_t* frame){return frame;}
+  command error_t TrackSingleBeacon.start()
+  {
+    // Track a single beacon now
+    dbg_serial("BeaconSynchronizeP", "Internal request.\n");
+    setInternalRequest();
+    call RadioToken.request();
+    if (!isUpdatePending()) {
+      m_updateLogicalChannel = call MLME_GET.phyCurrentChannel();
+      m_updateTrackBeacon = FALSE;
+      setUpdatePending();
+    }
+    return SUCCESS;
+  }
 
-  default event void MLME_SYNC_LOSS.indication (
-                          ieee154_status_t lossReason,
-                          uint16_t panID,
-                          uint8_t logicalChannel,
-                          uint8_t channelPage,
-                          ieee154_security_t *security){}
+  command error_t TrackSingleBeacon.stop()
+  {
+    // we will stop automatically after beacon was tracked/not found
+    return FAIL;
+  }
   
-  event void DataRequest.pollDone(){}
-
-  async command uint8_t* GtsField.getNow() { return m_gtsField; }
-  async command uint32_t SfSlotDuration.getNow() { return m_sfSlotDuration; }
-  async command uint8_t FinalCapSlot.getNow() { return m_finalCapSlot; }
-  async command uint32_t CapStart.getNow() { return m_lastBeaconRxTime; }
-  async command ieee154_reftime_t* CapStartRefTime.getNow() { return &m_lastBeaconRxRefTime; }
-  async command uint32_t CapLen.getNow() { return call SfSlotDuration.getNow() * (call FinalCapSlot.getNow() + 1);}
-  async command uint32_t CapEnd.getNow() 
+  /* -----------------------  SF Structure, etc. ----------------------- */
+
+  async command uint32_t IncomingSF.sfStartTime()
+  { 
+    return m_lastBeaconRxTime; 
+  }
+
+  async command uint16_t IncomingSF.sfSlotDuration()
+  { 
+    return m_sfSlotDuration;
+  }
+
+  async command uint8_t IncomingSF.numCapSlots()
   {
-    return call CapStart.getNow() + call CapLen.getNow();
+    return m_numCapSlots;
   }
-  async command uint32_t CfpEnd.getNow() 
+
+  async command uint8_t IncomingSF.numGtsSlots()
   {
-    return call CapStart.getNow() + call SfSlotDuration.getNow() * IEEE154_aNumSuperframeSlots;
+    return m_numGtsSlots;
   }
-  async command uint32_t CfpLen.getNow()
+
+  async command uint16_t IncomingSF.battLifeExtDuration()
+  {
+    return m_battLifeExtDuration;
+  }
+
+  async command const uint8_t* IncomingSF.gtsFields()
   {
-    return call SfSlotDuration.getNow() * (15 - call FinalCapSlot.getNow());
+    return m_gtsField;
   }
-  async command uint32_t BeaconInterval.getNow()
+
+  async command uint16_t IncomingSF.guardTime()
+  {
+    return IEEE154_MAX_BEACON_JITTER(m_beaconOrder) + IEEE154_RADIO_RX_DELAY;
+  }
+
+  async command const ieee154_timestamp_t* IncomingSF.sfStartTimeRef()
   {
-    return m_beaconInterval;
+    return &m_lastBeaconRxRefTime;
   }
-  async command uint8_t NumGtsSlots.getNow() { return m_numGtsSlots; }
-  async command bool IsBLEActive.getNow(){ return m_BLELen>0;}
-  async command uint16_t BLELen.getNow(){ return m_BLELen;}
-  async command bool IsRxBroadcastPending.getNow() { return m_broadcastPending; }
+
+  async command bool IncomingSF.isBroadcastPending()
+  {
+    return m_framePendingBit;
+  }
+
+  async command bool IsTrackingBeacons.getNow()
+  { 
+    return (getMode() == MODE_TRACK_CONTINUOUS);
+  }
+
+  uint32_t getBeaconInterval(ieee154_macBeaconOrder_t BO)
+  {
+    if (BO >= 15)
+      BO = 14;
+    return (((uint32_t) 1 << BO) * (uint32_t) IEEE154_aBaseSuperframeDuration);
+  }
+
+  event void DataRequest.pollDone() {}
+
+  default event message_t* MLME_BEACON_NOTIFY.indication (message_t* frame) {return frame;}
+  default event void MLME_SYNC_LOSS.indication (
+                          ieee154_status_t lossReason,
+                          uint16_t panID,
+                          uint8_t logicalChannel,
+                          uint8_t channelPage,
+                          ieee154_security_t *security) {}
 
   event message_t* CoordRealignmentRx.received(message_t* frame)
   {
@@ -457,8 +573,7 @@ implementation
           panID,                 // PANId
           payload[5],            // LogicalChannel,
           call Frame.getPayloadLength(frame) == 9 ? payload[8] : call MLME_GET.phyCurrentPage(),
-          NULL
-          );
+          NULL);
     return frame;
   }
 }
index 3d0dd438868e2ffc290d7b6aa36890e5ed3b52f5..7ddc5a284746da7e24372e5a2d1378fa4d4e43f4 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * This module is responsible for periodic beacon transmission in a 
+ * beacon-enabled PAN.
+ */
+
 #include "TKN154_MAC.h"
 #include "TKN154_PHY.h"
 module BeaconTransmitP
@@ -41,36 +46,20 @@ module BeaconTransmitP
   {
     interface Init as Reset;
     interface MLME_START;
-    interface WriteBeaconField as SuperframeSpecWrite;
-    interface Get<bool> as IsSendingBeacons;
-    interface GetNow<uint32_t> as CapStart; 
-    interface GetNow<ieee154_reftime_t*> as CapStartRefTime; 
-    interface GetNow<uint32_t> as CapLen; 
-    interface GetNow<uint32_t> as CapEnd; 
-    interface GetNow<uint32_t> as CfpEnd; 
-    interface GetNow<uint32_t> as CfpLen; 
-    interface GetNow<bool> as IsBLEActive; 
-    interface GetNow<uint16_t> as BLELen; 
-    interface GetNow<uint8_t*> as GtsField; 
-    interface GetNow<uint32_t> as SfSlotDuration; 
-    interface GetNow<uint32_t> as BeaconInterval; 
-    interface GetNow<uint8_t> as FinalCapSlot;
-    interface GetNow<uint8_t> as NumGtsSlots;
-    interface GetNow<bool> as BeaconFramePendingBit;
     interface IEEE154TxBeaconPayload;
+    interface SuperframeStructure as OutgoingSF;
+    interface GetNow<bool> as IsSendingBeacons;
   } uses {
     interface Notify<bool> as GtsSpecUpdated;
     interface Notify<bool> as PendingAddrSpecUpdated;
     interface Notify<const void*> as PIBUpdate[uint8_t attributeID];
-    interface Alarm<TSymbolIEEE802154,uint32_t> as BeaconTxAlarm;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as BeaconSendAlarm;
     interface Timer<TSymbolIEEE802154> as BeaconPayloadUpdateTimer;
     interface RadioOff;
-    interface Get<bool> as IsBeaconEnabledPAN;
     interface RadioTx as BeaconTx;
     interface MLME_GET;
     interface MLME_SET;
-    interface Resource as Token;
-    interface ResourceTransfer as TokenToBroadcast;
+    interface TransferableResource as RadioToken;
     interface FrameTx as RealignmentBeaconEnabledTx;
     interface FrameTx as RealignmentNonBeaconEnabledTx;
     interface FrameRx as BeaconRequestRx;
@@ -78,20 +67,63 @@ module BeaconTransmitP
     interface WriteBeaconField as PendingAddrWrite;
     interface FrameUtility;
     interface GetNow<bool> as IsTrackingBeacons;
-    interface GetNow<uint32_t> as LastBeaconRxTime;
-    interface GetNow<ieee154_reftime_t*> as LastBeaconRxRefTime; 
-    interface Ieee802154Debug as Debug;
+    interface SuperframeStructure as IncomingSF;
     interface Set<ieee154_macSuperframeOrder_t> as SetMacSuperframeOrder;
     interface Set<ieee154_macBeaconTxTime_t> as SetMacBeaconTxTime;
     interface Set<ieee154_macPanCoordinator_t> as SetMacPanCoordinator;
     interface GetSet<ieee154_txframe_t*> as GetSetRealignmentFrame;
     interface GetNow<bool> as IsBroadcastReady; 
     interface TimeCalc;
+    interface Random;
     interface Leds;
   }
 }
 implementation
 {
+  /* state variables */
+  norace uint8_t m_requestBitmap;
+  norace uint8_t m_txState;
+  uint8_t m_payloadState;
+  norace bool m_txOneBeaconImmediately;
+
+  /* variables that describe the current superframe configuration */
+  norace uint32_t m_startTime;
+  norace uint8_t m_beaconOrder;
+  norace uint8_t m_superframeOrder;
+  norace uint32_t m_beaconInterval;
+  norace uint32_t m_previousBeaconInterval;
+  norace uint32_t m_dt;
+  norace uint32_t m_lastBeaconTxTime;
+  norace ieee154_timestamp_t m_lastBeaconTxRefTime;
+  norace ieee154_macBattLifeExtPeriods_t m_battLifeExtPeriods;
+
+  /* variables that describe the latest superframe */
+  norace uint32_t m_sfSlotDuration;
+  norace bool m_framePendingBit;
+  norace uint8_t m_numCapSlots;
+  norace uint8_t m_numGtsSlots;
+  norace uint16_t m_battLifeExtDuration;
+  uint8_t m_gtsField[1+1+3*7];
+
+  /* variables that describe the beacon (payload) */
+  norace ieee154_txframe_t m_beaconFrame;
+  ieee154_header_t m_header; 
+  ieee154_metadata_t m_metadata; 
+  void *m_updateBeaconPayload;
+  uint8_t m_updateBeaconOffset;
+  uint8_t m_updateBeaconLength;
+  uint8_t m_beaconPayloadLen;
+  uint8_t m_pendingAddrLen;
+  uint8_t m_pendingGtsLen;
+
+  /* buffers for the parameters of the MLME-START request */
+  uint16_t m_updatePANId;
+  uint8_t m_updateLogicalChannel;
+  uint32_t m_updateStartTime;
+  norace uint8_t m_updateBeaconOrder;
+  uint8_t m_updateSuperframeOrder;
+  bool m_updatePANCoordinator;
+  bool m_updateBatteryLifeExtension;
 
   enum {
     MAX_BEACON_PAYLOAD_SIZE =  IEEE154_aMaxBeaconOverhead + IEEE154_aMaxBeaconPayloadLength,
@@ -114,87 +146,46 @@ implementation
     S_TX_LOCKED = 1,
     S_TX_WAITING = 2,
   };
-
-  norace ieee154_txframe_t m_beaconFrame;
-  ieee154_header_t m_header; 
   uint8_t m_payload[MAX_BEACON_PAYLOAD_SIZE]; 
-  ieee154_metadata_t m_metadata; 
-  uint8_t m_gtsField[1+1+3*7];
-
-  void *m_updateBeaconPayload;
-  uint8_t m_updateBeaconOffset;
-  uint8_t m_updateBeaconLength;
-  uint8_t m_beaconPayloadLen;
-  uint8_t m_pendingAddrLen;
-  uint8_t m_pendingGtsLen;
-
-  norace uint8_t m_requests; // TODO: check why norace?
-  norace uint8_t m_txState;
-  uint8_t m_payloadState;
-  norace bool m_txOneBeaconImmediately;
-
-  uint16_t m_PANId;
-  norace uint32_t m_startTime;
-  uint8_t m_logicalChannel;
-  norace uint8_t m_beaconOrder;
-  norace uint8_t m_superframeOrder;
-  ieee154_macBattLifeExt_t m_batteryLifeExtension;
-  bool m_PANCoordinator;
-  norace uint32_t m_beaconInterval;
-  norace uint32_t m_previousBeaconInterval;
-  norace uint32_t m_dt;
-  norace uint8_t m_bsn;
-  norace uint32_t m_lastBeaconTxTime;
-  norace ieee154_reftime_t m_lastBeaconTxRefTime;
-  norace uint32_t m_coordCapLen;
-  norace uint32_t m_coordCfpEnd;
-  norace uint32_t m_sfSlotDuration;
-  norace uint8_t m_finalCAPSlot;
-  norace uint8_t m_numGtsSlots;
-  norace uint16_t m_BLELen;
-  norace ieee154_macBattLifeExtPeriods_t m_battLifeExtPeriods;
-  norace bool m_framePendingBit;
-
-  uint16_t m_updatePANId;
-  uint8_t m_updateLogicalChannel;
-  uint32_t m_updateStartTime;
-  uint8_t m_updateBeaconOrder;
-  uint8_t m_updateSuperframeOrder;
-  bool m_updatePANCoordinator;
-  bool m_updateBatteryLifeExtension;
 
+  /* function/task prototypes */
   task void txDoneTask();
   task void signalStartConfirmSuccessTask();
-  void prepareNextBeaconTransmission();
+  void nextRound();
+  void prepareBeaconTransmission();
   void continueStartRequest();
   void finishRealignment(ieee154_txframe_t *frame, ieee154_status_t status);
 
   command error_t Reset.init()
   {
+    // reset this component, will only be called while we're not owning the token
+    // TODO: check to signal MLME_START.confirm ?
+
+    call MLME_SET.macBSN(call Random.rand16());
     m_beaconFrame.header = &m_header;
     m_beaconFrame.headerLen = 0;
     m_beaconFrame.payload = m_payload;
     m_beaconFrame.payloadLen = 0;
     m_beaconFrame.metadata = &m_metadata;
-    m_updateBeaconPayload = 0;
+    m_updateBeaconPayload = NULL;
     m_updateBeaconLength = 0;
-    m_requests = m_payloadState = m_txState = 0;
-    m_PANCoordinator = FALSE;
+    m_requestBitmap = m_payloadState = m_txState = 0;
     m_beaconPayloadLen = m_pendingAddrLen = m_pendingGtsLen = 0;
     m_gtsField[0] = 0;
-    m_finalCAPSlot = 15;
+    m_numCapSlots = 0;
+    m_numGtsSlots = 0;
     m_beaconOrder = 15;
     call BeaconPayloadUpdateTimer.stop();
-    call BeaconTxAlarm.stop();
+    call BeaconSendAlarm.stop();
     return SUCCESS;
   }
 
-/* ----------------------- MLME-START ----------------------- */
-/* "The MLME-START.request primitive allows the PAN coordinator to initiate a
- * new PAN or to begin using a new superframe configuration. This primitive may
- * also be used by a device already associated with an existing PAN to begin
- * using a new superframe configuration." (IEEE 802.15.4-2006 Sect. 7.1.14.1)
- **/
+  /* ----------------------- MLME-START ----------------------- */
+  /* "The MLME-START.request primitive allows the PAN coordinator to initiate a
  * new PAN or to begin using a new superframe configuration. This primitive may
  * also be used by a device already associated with an existing PAN to begin
  * using a new superframe configuration." (IEEE 802.15.4-2006 Sect. 7.1.14.1)
  **/
 
   command ieee154_status_t MLME_START.request  (
                           uint16_t panID,
@@ -209,9 +200,10 @@ implementation
                           ieee154_security_t *coordRealignSecurity,
                           ieee154_security_t *beaconSecurity)
   {
-    ieee154_macShortAddress_t shortAddress = call MLME_GET.macShortAddress();
     ieee154_status_t status = IEEE154_SUCCESS;
+    ieee154_macShortAddress_t shortAddress = call MLME_GET.macShortAddress();
 
+    // check parameters
     if ((coordRealignSecurity && coordRealignSecurity->SecurityLevel) ||
         (beaconSecurity && beaconSecurity->SecurityLevel))
       status = IEEE154_UNSUPPORTED_SECURITY;
@@ -224,23 +216,18 @@ implementation
       status =  IEEE154_INVALID_PARAMETER;
     else if (startTime && !call IsTrackingBeacons.getNow())
       status = IEEE154_TRACKING_OFF;
-    else if (startTime && 0xFF000000)
+    else if (startTime & 0xFF000000)
       status = IEEE154_INVALID_PARAMETER;
-    else if (m_requests & (REQUEST_CONFIRM_PENDING | REQUEST_UPDATE_SF))
+    else if (m_requestBitmap & (REQUEST_CONFIRM_PENDING | REQUEST_UPDATE_SF))
       status = IEEE154_TRANSACTION_OVERFLOW;
-    else if ((call IsBeaconEnabledPAN.get() && beaconOrder > 14) ||
-              (!call IsBeaconEnabledPAN.get() && beaconOrder < 15))
-      status = IEEE154_INVALID_PARAMETER;
     else {
-      // new configuration *will* be put in operation
-      status = IEEE154_SUCCESS;
+
+      // New configuration *will* be put in operation, we'll buffer
+      // the parameters now, and continue once we get the token.
       if (panCoordinator)
-        startTime = 0; // start immediately
-      call Debug.log(LEVEL_INFO, StartP_REQUEST, logicalChannel, beaconOrder, superframeOrder);
-      if (beaconOrder == 15){
-        // beaconless PAN
-        superframeOrder = 15;
-      }
+        startTime = 0;        // start immediately
+      if (beaconOrder == 15)
+        superframeOrder = 15; // beaconless PAN 
       m_updatePANId = panID;
       m_updateLogicalChannel = logicalChannel;
       m_updateStartTime = startTime;
@@ -248,12 +235,18 @@ implementation
       m_updateSuperframeOrder = superframeOrder;
       m_updatePANCoordinator = panCoordinator;
       m_updateBatteryLifeExtension = batteryLifeExtension;   
-      m_requests = (REQUEST_CONFIRM_PENDING | REQUEST_UPDATE_SF); // lock
+      m_requestBitmap = (REQUEST_CONFIRM_PENDING | REQUEST_UPDATE_SF); // lock
+
       if (coordRealignment)
-        m_requests |= REQUEST_REALIGNMENT;
-      if (!call IsSendingBeacons.get())
-        call Token.request();
+        m_requestBitmap |= REQUEST_REALIGNMENT;
+      if (m_beaconOrder == 15) {
+        // We're not already transmitting beacons, i.e. we have to request the token
+        // (otherwise we'd get the token "automatically" for the next scheduled beacon).
+        call RadioToken.request();
+      }
+      // We'll continue the MLME_START operation in continueStartRequest() once we have the token
     }
+    dbg_serial("BeaconTransmitP", "MLME_START.request -> result: %lu\n", (uint32_t) status);
     return status;
   }
 
@@ -264,12 +257,12 @@ implementation
     bool isShortAddr;
 
     // (1) coord realignment?
-    if (m_requests & REQUEST_REALIGNMENT){
+    if (m_requestBitmap & REQUEST_REALIGNMENT) {
       ieee154_txframe_t *realignmentFrame = call GetSetRealignmentFrame.get();
-      m_requests &= ~REQUEST_REALIGNMENT;
-      if (realignmentFrame == NULL){
+      m_requestBitmap &= ~REQUEST_REALIGNMENT;
+      if (realignmentFrame == NULL) {
         // allocation failed!
-        m_requests = 0;
+        m_requestBitmap = 0;
         signal MLME_START.confirm(IEEE154_TRANSACTION_OVERFLOW);
         return;
       }
@@ -282,11 +275,11 @@ implementation
       *((nxle_uint16_t*) &realignmentFrame->payload[6]) = 0xFFFF;
       realignmentFrame->payloadLen = 8;
       
-      if (call IsSendingBeacons.get()){
+      if (m_beaconOrder < 15) {
         // we're already transmitting beacons; the realignment frame
         // must be sent (broadcast) after the next beacon
-        if (call RealignmentBeaconEnabledTx.transmit(realignmentFrame) != IEEE154_SUCCESS){
-          m_requests = 0;
+        if (call RealignmentBeaconEnabledTx.transmit(realignmentFrame) != IEEE154_SUCCESS) {
+          m_requestBitmap = 0;
           call GetSetRealignmentFrame.set(realignmentFrame);
           signal MLME_START.confirm(IEEE154_TRANSACTION_OVERFLOW);
         } else {
@@ -294,12 +287,12 @@ implementation
           // the next beacon - the result will be signalled in 
           // RealignmentBeaconEnabledTx.transmitDone(). Only then the superframe
           // structure is updated and MLME_START.confirm signalled.
-          m_requests |= REQUEST_REALIGNMENT_DONE_PENDING; // lock
+          m_requestBitmap |= REQUEST_REALIGNMENT_DONE_PENDING; // lock
         }
       } else {
         // send realignment frame in unslotted csma-ca now
-        if (call RealignmentNonBeaconEnabledTx.transmit(realignmentFrame) != IEEE154_SUCCESS){
-          m_requests = 0;
+        if (call RealignmentNonBeaconEnabledTx.transmit(realignmentFrame) != IEEE154_SUCCESS) {
+          m_requestBitmap = 0;
           call GetSetRealignmentFrame.set(realignmentFrame);
           signal MLME_START.confirm(IEEE154_TRANSACTION_OVERFLOW);
         } else {
@@ -307,7 +300,7 @@ implementation
           // be signalled in RealignmentNonBeaconEnabledTx.transmitDone(). Only 
           // then the superframe structure is updated and MLME_START.confirm 
           // signalled.
-          m_requests |= REQUEST_REALIGNMENT_DONE_PENDING; // lock
+          m_requestBitmap |= REQUEST_REALIGNMENT_DONE_PENDING; // lock
         }
       }
       return; 
@@ -317,52 +310,48 @@ implementation
     m_startTime = m_updateStartTime;
     m_txOneBeaconImmediately = FALSE;
     m_previousBeaconInterval = 0;
-    if (m_startTime){
-      m_lastBeaconTxRefTime = *call LastBeaconRxRefTime.getNow();
-      m_lastBeaconTxTime = call LastBeaconRxTime.getNow();
+    if (m_startTime) {
+      memcpy(&m_lastBeaconTxRefTime, call IncomingSF.sfStartTimeRef(), sizeof(ieee154_timestamp_t));
+      m_lastBeaconTxTime = call IncomingSF.sfStartTime();
     } else {
       // no StartTime defined by next higher layer - but
       // if a realignment frame was transmitted, the next
       // beacon tx time must take the old BI into consideration
-      if (m_requests & REQUEST_REALIGNMENT_DONE_PENDING)
+      if (m_requestBitmap & REQUEST_REALIGNMENT_DONE_PENDING)
         m_previousBeaconInterval = m_beaconInterval;
       else
         m_txOneBeaconImmediately = TRUE;
     }
-    m_PANId = m_updatePANId;
-    m_logicalChannel = m_updateLogicalChannel;
     m_beaconOrder = m_updateBeaconOrder; 
     m_superframeOrder = m_updateSuperframeOrder;
-    m_PANCoordinator = m_updatePANCoordinator;
-    if (m_beaconOrder < 15){
-      m_batteryLifeExtension = m_updateBatteryLifeExtension;   
+    if (m_beaconOrder < 15) {
       m_beaconInterval = ((uint32_t) 1 << m_updateBeaconOrder) * IEEE154_aBaseSuperframeDuration;
     } else {
-      m_batteryLifeExtension = FALSE;   
       m_beaconInterval = 0;
     }
+    m_dt = m_beaconInterval;
     m_txState = S_TX_IDLE;
-    m_bsn = call MLME_GET.macBSN()+1;
     m_battLifeExtPeriods = call MLME_GET.macBattLifeExtPeriods();
 
     // (3) update PIB
     call MLME_SET.macBeaconOrder(m_beaconOrder);
     call SetMacSuperframeOrder.set(m_superframeOrder);
-    call MLME_SET.macPANId(m_PANId);
-    call MLME_SET.phyCurrentChannel(m_logicalChannel);
+    call MLME_SET.macPANId(m_updatePANId);
+    call MLME_SET.phyCurrentChannel(m_updateLogicalChannel);
     if (m_beaconOrder < 15)
-      call MLME_SET.macBattLifeExt(m_batteryLifeExtension);
-    call SetMacPanCoordinator.set(m_PANCoordinator);
+      call MLME_SET.macBattLifeExt(m_updateBatteryLifeExtension);
+    call SetMacPanCoordinator.set(m_updatePANCoordinator);
 
     // (4) assemble beacon header and payload
     shortAddress = call MLME_GET.macShortAddress();
     isShortAddr = (shortAddress != 0xFFFE);
     m_beaconFrame.header->mhr[MHR_INDEX_FC1] = FC1_FRAMETYPE_BEACON;
     m_beaconFrame.header->mhr[MHR_INDEX_FC2] = isShortAddr ? FC2_SRC_MODE_SHORT : FC2_SRC_MODE_EXTENDED;
+    m_beaconFrame.header->mhr[MHR_INDEX_SEQNO] = call MLME_GET.macBSN() + 1;
     offset = MHR_INDEX_ADDRESS;
-    *((nxle_uint16_t*) &m_beaconFrame.header->mhr[offset]) = m_PANId;
+    *((nxle_uint16_t*) &m_beaconFrame.header->mhr[offset]) = m_updatePANId;
     offset += sizeof(ieee154_macPANId_t);
-    if (isShortAddr){
+    if (isShortAddr) {
       *((nxle_uint16_t*) &m_beaconFrame.header->mhr[offset]) = shortAddress;
       offset += sizeof(ieee154_macShortAddress_t);
     } else {
@@ -373,190 +362,228 @@ implementation
     m_payloadState |= MODIFIED_SPECS_MASK;    // update beacon payload
     signal BeaconPayloadUpdateTimer.fired();  // assemble initial beacon payload
 
-    if (m_beaconOrder < 15){
+    if (m_beaconOrder < 15) {
       // beacon-enabled PAN, signal confirm after next 
       // beacon has been transmitted (see MSC, Fig. 38)
-      m_requests = REQUEST_CONFIRM_PENDING;
+      m_requestBitmap = REQUEST_CONFIRM_PENDING;
     } else {
       // beaconless PAN, we're done
-      m_requests = 0;
+      m_requestBitmap = 0;
       signal MLME_START.confirm(IEEE154_SUCCESS);
     }
   }
 
-  task void grantedTask()
+  task void signalGrantedTask()
   {
-    signal Token.granted();
+    signal RadioToken.granted();
   }
 
-  event void Token.granted()
+  event void RadioToken.granted()
   {
-    call Debug.flush();
-    call Debug.log(LEVEL_INFO, StartP_GOT_RESOURCE, m_lastBeaconTxTime, m_beaconInterval, m_requests);
-    if (m_requests & REQUEST_REALIGNMENT_DONE_PENDING){
-      // unlikely to occur: we have not yet received a done()
+    dbg_serial("BeaconSynchronizeP","Token granted.\n");
+    if (m_requestBitmap & REQUEST_REALIGNMENT_DONE_PENDING) {
+      // very unlikely: we have not yet received a done()
       // event after sending out a realignment frame 
-      post grantedTask(); // spin
+      dbg_serial("BeaconTransmitP", "Realignment pending (request: %lu) !\n", (uint32_t) m_requestBitmap);
+      post signalGrantedTask(); // spin
       return;
-    }
-    if (m_requests & REQUEST_UPDATE_SF){
-      m_requests &= ~REQUEST_UPDATE_SF;
+    } else if (m_requestBitmap & REQUEST_UPDATE_SF) {
+      dbg_serial("BeaconTransmitP","Putting new superframe spec into operation\n"); 
+      m_requestBitmap &= ~REQUEST_UPDATE_SF;
       continueStartRequest();
-      call Debug.log(LEVEL_INFO, StartP_UPDATE_STATE, 0, 0, 0);
     }
+    nextRound();
+  }
+
+  void nextRound()
+  {
     if (call RadioOff.isOff())
-      prepareNextBeaconTransmission();
+      prepareBeaconTransmission();
     else
-      call RadioOff.off();
+      ASSERT(call RadioOff.off() == SUCCESS); // will continue in prepareBeaconTransmission()
   }
 
+  async event void RadioToken.transferredFrom(uint8_t fromClientID)
+  {
+    dbg_serial("BeaconSynchronizeP","Token transferred, will Tx beacon in %lu\n",
+        (uint32_t) ((m_lastBeaconTxTime + m_dt) - call BeaconSendAlarm.getNow())); 
+    if (m_requestBitmap & (REQUEST_REALIGNMENT_DONE_PENDING | REQUEST_UPDATE_SF))
+      post signalGrantedTask(); // need to be in sync context
+    else
+      nextRound();
+  }  
+
   async event void RadioOff.offDone()
   {
-    prepareNextBeaconTransmission();
+    prepareBeaconTransmission();
   }
 
-  void prepareNextBeaconTransmission()
+  void prepareBeaconTransmission()
   {
-    if (m_txState == S_TX_LOCKED){
+    if (m_txState == S_TX_LOCKED) {
       // have not had time to finish processing the last sent beacon
-      post grantedTask();
-      call Debug.log(LEVEL_CRITICAL, StartP_OWNER_TOO_FAST, 0, 0, 0);
-      return;
-    } else if (m_beaconOrder > 14){
-      call Token.release();
+      dbg_serial("BeaconTransmitP", "Token was returned too fast!\n");
+      post signalGrantedTask();
+    } else if (m_beaconOrder == 15) {
+      // we're not sending any beacons!?
+      dbg_serial("BeaconTransmitP", "Stop sending beacons.\n");
+      call RadioToken.release();
     } else {
+      // get ready for next beacon transmission
       atomic {
+        uint32_t delay = IEEE154_RADIO_TX_DELAY; 
         m_txState = S_TX_WAITING;
-        if (m_txOneBeaconImmediately){
-          signal BeaconTxAlarm.fired();
+        if (m_txOneBeaconImmediately) {
+          // transmit the beacon now
+          dbg_serial("BeaconTransmitP", "Sending a beacon immediately.\n");
+          signal BeaconSendAlarm.fired();
           return;
-        } else if (m_startTime != 0){
-          // a new sf spec was put into operation, with a user-defined StartTime 
+        } else if (m_startTime != 0) {
+          // a new sf spec was put into operation, with a user-defined StartTime    
           // here m_lastBeaconTxTime is actually the last time a beacon was received
+
+          dbg_serial("BeaconTransmitP", "First beacon to be sent at %lu.\n", m_startTime);
           m_dt = m_startTime;
           m_startTime = 0;
-        } else if (m_previousBeaconInterval != 0){
-          // a new sf spec was put into operation, after a realignment frame was
+        } else if (m_previousBeaconInterval != 0) {
+          // a new sf spec was put into operation, after a realignment frame 
           // broadcast; the next beacon time should still be calculated using the
           // old BI (one last time)
+
+          dbg_serial("BeaconTransmitP", "Sending beacon after realignment dt=%lu.\n", m_previousBeaconInterval);
           m_dt = m_previousBeaconInterval;
           m_previousBeaconInterval = 0;
-          if (m_requests & REQUEST_CONFIRM_PENDING){
+          if (m_requestBitmap & REQUEST_CONFIRM_PENDING) {
             // only now the next higher layer is to be informed 
-            m_requests &= ~REQUEST_CONFIRM_PENDING;
+            m_requestBitmap &= ~REQUEST_CONFIRM_PENDING;
             post signalStartConfirmSuccessTask();
           }
-        } else {
-          // the usual case: next beacon tx time = last time + BI
-          m_dt = m_beaconInterval;
         }
-        while (call TimeCalc.hasExpired(m_lastBeaconTxTime, m_dt)){ // missed sending a beacon
-          call Debug.log(LEVEL_INFO, StartP_SKIPPED_BEACON, m_lastBeaconTxTime, m_dt, 0);
+
+        // The next beacon should be transmitted at time m_lastBeaconTxTime + m_dt, where m_dt
+        // is typically the beacon interval. First we check if we're still in time.
+        while (call TimeCalc.hasExpired(m_lastBeaconTxTime, m_dt)) { 
+          // too late, we need to skip a beacon!
+          dbg_serial("BeaconTransmitP", "Skipping a beacon: scheduled=%lu, now=%lu.\n", 
+              (uint32_t) m_lastBeaconTxTime + m_dt, (uint32_t) call BeaconSendAlarm.getNow());
           m_dt += m_beaconInterval;
         }
-        if (m_dt < IEEE154_RADIO_TX_PREPARE_DELAY)
-          m_dt = IEEE154_RADIO_TX_PREPARE_DELAY;
-        // don't call BeaconTx.load just yet, otherwise the next
-        // higher layer cannot modify the beacon payload anymore;
-        // rather, set an alarm 
-        call BeaconTxAlarm.startAt(m_lastBeaconTxTime, m_dt - IEEE154_RADIO_TX_PREPARE_DELAY);
+        if (!call TimeCalc.hasExpired(m_lastBeaconTxTime - delay, m_dt)) {
+          // don't load the beacon frame in the radio just yet - rather set a timer and
+          // give the next higher layer the chance to modify the beacon payload 
+          call BeaconSendAlarm.startAt(m_lastBeaconTxTime - delay, m_dt);
+        } else
+          signal BeaconSendAlarm.fired();
       }
     }
   }
 
-  async event void BeaconTxAlarm.fired()
+  task void signalStartConfirmSuccessTask()
   {
-    atomic {
-      switch (m_txState)
-      {
-        case S_TX_WAITING: 
-          m_txState = S_TX_LOCKED;
-          if (call IsBroadcastReady.getNow())
-            m_beaconFrame.header->mhr[MHR_INDEX_FC1] |= FC1_FRAME_PENDING;
-          else
-            m_beaconFrame.header->mhr[MHR_INDEX_FC1] &= ~FC1_FRAME_PENDING;
-          m_beaconFrame.header->mhr[MHR_INDEX_SEQNO] = m_bsn; // update beacon seqno
-          call Debug.log(LEVEL_INFO, StartP_PREPARE_TX, 0, m_lastBeaconTxTime, 0);
-          call BeaconTx.load(&m_beaconFrame); 
-          break;
-        case S_TX_LOCKED: 
-          call Debug.log(LEVEL_INFO, StartP_TRANSMIT, m_lastBeaconTxTime, m_dt, ((uint32_t)m_lastBeaconTxRefTime));
-          call BeaconTx.transmit(&m_lastBeaconTxRefTime, m_dt, 0, FALSE);
-          break;
-      }
-    }
+    signal MLME_START.confirm(SUCCESS);
   }
 
-  async event void BeaconTx.loadDone()
+  async event void BeaconSendAlarm.fired()
   {
-    atomic {
-      call Debug.log(LEVEL_INFO, StartP_PREPARE_TXDONE, 0, m_lastBeaconTxTime, 0);
-      if (m_txOneBeaconImmediately){
-        m_txOneBeaconImmediately = FALSE;
-        call BeaconTx.transmit(0, 0, 0, FALSE); // now!
-      } else 
-        call BeaconTxAlarm.startAt(m_lastBeaconTxTime, m_dt - IEEE154_RADIO_TX_SEND_DELAY);
+    // start/schedule beacon transmission
+    ieee154_timestamp_t *timestamp = &m_lastBeaconTxRefTime;
+    m_txState = S_TX_LOCKED;
+
+    if (call IsBroadcastReady.getNow())
+      m_beaconFrame.header->mhr[MHR_INDEX_FC1] |= FC1_FRAME_PENDING;
+    else
+      m_beaconFrame.header->mhr[MHR_INDEX_FC1] &= ~FC1_FRAME_PENDING;
+
+    if (m_txOneBeaconImmediately) {
+      m_txOneBeaconImmediately = FALSE;
+      timestamp = NULL;
     }
+    call BeaconTx.transmit(&m_beaconFrame, timestamp, m_dt);
+    dbg_serial("BeaconTransmitP","Beacon Tx scheduled for %lu.\n", (uint32_t) (*timestamp + m_dt));
   }
-    
-  async event void BeaconTx.transmitDone(ieee154_txframe_t *frame, 
-      ieee154_reftime_t *referenceTime, bool pendingFlag, error_t error)
+
+  async event void BeaconTx.transmitDone(ieee154_txframe_t *frame, const ieee154_timestamp_t *timestamp, error_t result)
   {
-    // Coord CAP has just started...
+    // The beacon frame was transmitted, i.e. the CAP has just started
+    // update the state then pass the token on to the next component 
+
     uint8_t gtsFieldLength;
-    // Sec. 7.5.1.1: "start of slot 0 is defined as the point at which 
-    // the first symbol of the beacon PPDU is transmitted" 
-    call Debug.log(LEVEL_INFO, StartP_BEACON_TRANSMITTED, frame->metadata->timestamp, m_lastBeaconTxTime, m_dt);
-    m_lastBeaconTxTime = frame->metadata->timestamp;
-    memcpy(&m_lastBeaconTxRefTime, referenceTime, sizeof(ieee154_reftime_t));
-    m_numGtsSlots = (frame->payload[2] & 0x07);
+
+    ASSERT(result == SUCCESS); // must succeed, we're sending without CCA or ACK request
+    if (timestamp != NULL) {
+      m_lastBeaconTxTime = frame->metadata->timestamp;
+      memcpy(&m_lastBeaconTxRefTime, timestamp, sizeof(ieee154_timestamp_t));
+      m_dt = m_beaconInterval; // transmit the next beacon at m_lastBeaconTxTime + m_dt 
+      dbg_serial("BeaconTransmitP", "Beacon Tx success at %lu\n", (uint32_t) m_lastBeaconTxTime);
+    } else {
+      // Timestamp is invalid; this is bad. We need the beacon timestamp for the 
+      // slotted CSMA-CA, because it defines the slot reference time. We can't use this superframe
+      // TODO: check if this was the initial beacon (then m_lastBeaconTxRefTime is invalid)
+      dbg_serial("BeaconTransmitP", "Invalid timestamp!\n");
+      m_dt += m_beaconInterval;
+      call RadioToken.request();
+      call RadioToken.release();      
+      return;
+    }
+
+    // update superframe-related variables
+    m_numGtsSlots = 
+      (frame->payload[BEACON_INDEX_GTS_SPEC] & GTS_DESCRIPTOR_COUNT_MASK) >> GTS_DESCRIPTOR_COUNT_OFFSET;
     gtsFieldLength = 1 + ((m_numGtsSlots > 0) ? 1 + m_numGtsSlots * 3: 0);
-    m_finalCAPSlot = (frame->payload[1] & 0x0F);
-    m_sfSlotDuration = (((uint32_t) 1) << ((frame->payload[0] & 0xF0) >> 4)) * IEEE154_aBaseSlotDuration;
-    if (frame->header->mhr[0] & FC1_FRAME_PENDING)
+    m_numCapSlots = 
+      ((frame->payload[BEACON_INDEX_SF_SPEC2] & SF_SPEC2_FINAL_CAPSLOT_MASK) >> SF_SPEC2_FINAL_CAPSLOT_OFFSET) + 1;
+    m_sfSlotDuration = 
+      (((uint32_t) 1) << ((frame->payload[BEACON_INDEX_SF_SPEC1] & SF_SPEC1_SO_MASK) >> SF_SPEC1_SO_OFFSET)) * 
+      IEEE154_aBaseSlotDuration;
+
+    if (frame->header->mhr[MHR_INDEX_FC1] & FC1_FRAME_PENDING)
       m_framePendingBit = TRUE;
     else
       m_framePendingBit = FALSE;
-    memcpy(m_gtsField, &frame->payload[2], gtsFieldLength);
-    if (frame->payload[1] & 0x10){
-      // BLE is active; calculate the time offset from slot0
-      m_BLELen = IEEE154_SHR_DURATION + 
-        (frame->headerLen + frame->payloadLen) * IEEE154_SYMBOLS_PER_OCTET; 
-      if (frame->headerLen + frame->payloadLen > IEEE154_aMaxSIFSFrameSize)
-        m_BLELen += IEEE154_MIN_LIFS_PERIOD;
+    memcpy(m_gtsField, &frame->payload[BEACON_INDEX_GTS_SPEC], gtsFieldLength);
+    if (frame->payload[BEACON_INDEX_SF_SPEC2] & SF_SPEC2_BATT_LIFE_EXT) {
+      // BLE is active; calculate the time offset from slot 0
+      m_battLifeExtDuration = IEEE154_SHR_DURATION + 
+        (frame->headerLen + frame->payloadLen + 2) * IEEE154_SYMBOLS_PER_OCTET; 
+      if (frame->headerLen + frame->payloadLen + 2 > IEEE154_aMaxSIFSFrameSize)
+        m_battLifeExtDuration += IEEE154_MIN_LIFS_PERIOD;
       else
-        m_BLELen += IEEE154_MIN_SIFS_PERIOD;
-      m_BLELen += m_battLifeExtPeriods;
+        m_battLifeExtDuration += IEEE154_MIN_SIFS_PERIOD;
+      m_battLifeExtDuration = m_battLifeExtDuration + m_battLifeExtPeriods * 20;
     } else
-      m_BLELen = 0;
-    call Token.request();             // register another request, before ...
-    call TokenToBroadcast.transfer(); // ... we let Broadcast module take over
+      m_battLifeExtDuration = 0;
+
+    // we pass on the token now, but make a reservation to get it back 
+    // to transmit the next beacon (at the start of the next superframe)
+    call RadioToken.request();  
+    call RadioToken.transferTo(RADIO_CLIENT_COORDBROADCAST); 
     post txDoneTask();
   }
 
   task void txDoneTask()
   {
-    call MLME_SET.macBSN(m_bsn++);
+    call MLME_SET.macBSN(m_beaconFrame.header->mhr[MHR_INDEX_SEQNO]);
+    m_beaconFrame.header->mhr[MHR_INDEX_SEQNO] += 1; // may be overwritten by the next higher layer
     call SetMacBeaconTxTime.set(m_lastBeaconTxTime); // start of slot0, ie. first preamble byte of beacon
     call BeaconPayloadUpdateTimer.startOneShotAt(m_lastBeaconTxTime, 
         (m_beaconInterval>BEACON_PAYLOAD_UPDATE_INTERVAL) ? (m_beaconInterval - BEACON_PAYLOAD_UPDATE_INTERVAL): 0);
-    if (m_requests & REQUEST_CONFIRM_PENDING){
-      m_requests &= ~REQUEST_CONFIRM_PENDING;
+    if (m_requestBitmap & REQUEST_CONFIRM_PENDING) {
+      m_requestBitmap &= ~REQUEST_CONFIRM_PENDING;
       signal MLME_START.confirm(IEEE154_SUCCESS);
     }
     m_txState = S_TX_IDLE;
     signal IEEE154TxBeaconPayload.beaconTransmitted();
-    call Debug.flush();
+    dbg_serial_flush();
   }
 
 
-/* ----------------------- Beacon Payload ----------------------- */
-/*
- * All access to the payload fields in the beacon happen
- * through a set of temporary variables/flags, and just before 
- * the frame is loaded into the radio these changes are 
* propagated into the actual payload portion of the beacon frame.
- */
+  /* ----------------------- Beacon Payload ----------------------- */
+  /*
  * All access to the payload fields in the beacon happen
  * through a set of temporary variables/flags, and just before 
  * the frame is loaded into the radio these changes are 
  * written into the actual payload portion of the beacon frame.
  */
 
   command error_t IEEE154TxBeaconPayload.setBeaconPayload(void *beaconPayload, uint8_t length)
   {
@@ -628,7 +655,7 @@ implementation
   uint8_t getNumGtsSlots(uint8_t *gtsInfoField)
   {
     uint8_t i, num=0;
-    for (i=0; i<(gtsInfoField[0] & GTS_DESCRIPTOR_COUNT_MASK); i++)
+    for (i=0; i<((gtsInfoField[0] & GTS_DESCRIPTOR_COUNT_MASK) >> GTS_DESCRIPTOR_COUNT_OFFSET); i++)
       num += ((gtsInfoField[4+i*3] & GTS_LENGTH_MASK) >> GTS_LENGTH_OFFSET);
     return num;
   }
@@ -638,56 +665,72 @@ implementation
     // in this order the MAC payload is updated:
     // (1) pending addresses
     // (2) GTS spec
-    // (3) sf spec
+    // (3) SF spec
     // (4) beacon payload (if there's enough time)
     uint8_t len=0, *beaconSpecs = &m_payload[IEEE154_aMaxBeaconOverhead]; // going backwards
-    uint8_t beaconPayloadUpdated = 0, numGtsSlots = 15 - m_finalCAPSlot;
+    uint8_t beaconPayloadUpdated = 0, numGtsSlots = m_numGtsSlots;
 
     atomic {
       if (m_txState == S_TX_LOCKED) 
       {
-        call Debug.log(LEVEL_INFO, StartP_BEACON_UPDATE, 0, 0, m_txState);
+        dbg_serial("BeaconTransmitP", "BeaconPayloadUpdateTimer fired too late!\n");
         return; // too late !
       }
-      if (m_payloadState & MODIFIED_PENDING_ADDR_FIELD){
+
+      // (1) update pending addresses
+      if (m_payloadState & MODIFIED_PENDING_ADDR_FIELD) {
         len = call PendingAddrWrite.getLength();
         beaconSpecs -= len;
         call PendingAddrWrite.write(beaconSpecs, len);
-        if (len != m_pendingAddrLen){
+        if (len != m_pendingAddrLen) {
           m_pendingAddrLen = len;
           m_payloadState |= MODIFIED_SPECS_MASK; // need to rewrite specs before
         }
       } else 
         beaconSpecs -= m_pendingAddrLen;
-      if (m_payloadState & MODIFIED_GTS_FIELD){
+      
+      // (2) update GTS spec
+      if (m_payloadState & MODIFIED_GTS_FIELD) {
         len = call GtsInfoWrite.getLength();
         beaconSpecs -= len;
         call GtsInfoWrite.write(beaconSpecs, len);
         numGtsSlots = getNumGtsSlots(beaconSpecs);
-        if (len != m_pendingGtsLen || ((15-numGtsSlots) != m_finalCAPSlot)){
+        if (len != m_pendingGtsLen || ((15-numGtsSlots) != m_numCapSlots-1)) {
           m_pendingGtsLen = len;
           m_payloadState |= MODIFIED_SPECS_MASK; // need to rewrite specs before
         }
       } else 
         beaconSpecs -= m_pendingGtsLen;
+
+      // (3) update SF spec
       beaconSpecs -= 2; // sizeof SF Spec
-      if (m_payloadState & MODIFIED_SF_SPEC){
-        call SuperframeSpecWrite.write(beaconSpecs, 2);
-        beaconSpecs[1] &= 0xF0; // clear FinalCAPSlot field
-        beaconSpecs[1] |= ((15-numGtsSlots) & 0x0F); // update FinalCAPSlot field
+      if (m_payloadState & MODIFIED_SF_SPEC) {
+        beaconSpecs[BEACON_INDEX_SF_SPEC1] = 
+          (m_beaconOrder << SF_SPEC1_BO_OFFSET) | (m_superframeOrder << SF_SPEC1_SO_OFFSET);
+        beaconSpecs[BEACON_INDEX_SF_SPEC2] = 0;
+        if (call MLME_GET.macAssociationPermit())
+          beaconSpecs[BEACON_INDEX_SF_SPEC2] |= SF_SPEC2_ASSOCIATION_PERMIT;        
+        if (call MLME_GET.macPanCoordinator())
+          beaconSpecs[BEACON_INDEX_SF_SPEC2] |= SF_SPEC2_PAN_COORD;
+        beaconSpecs[BEACON_INDEX_SF_SPEC2] |= 
+          ((15-numGtsSlots) & SF_SPEC2_FINAL_CAPSLOT_MASK);
       }
       m_beaconFrame.payloadLen = (m_pendingAddrLen + m_pendingGtsLen + 2) + m_beaconPayloadLen;
       m_beaconFrame.payload = beaconSpecs;
       m_payloadState &= ~MODIFIED_SPECS_MASK; // clear flags
-    } // end atomic (give BeaconTxAlarm.fired() the chance to execute)
+    } // end atomic (give BeaconSendAlarm.fired() the chance to execute)
+
     signal IEEE154TxBeaconPayload.aboutToTransmit();
+    m_beaconFrame.header->mhr[MHR_INDEX_SEQNO] = call MLME_GET.macBSN() + 1;
+
     atomic {
+      // (4) try to update beacon payload 
       if (m_txState == S_TX_LOCKED) 
       {
-        call Debug.log(LEVEL_INFO, StartP_BEACON_UPDATE_2, 0, 0, m_txState);
+        dbg_serial("BeaconTransmitP", "Not enough time for beacon payload update!\n");
         return; // too late !
       }
-      if (m_payloadState & MODIFIED_BEACON_PAYLOAD){
+      if (m_payloadState & MODIFIED_BEACON_PAYLOAD) {
         memcpy(&m_payload[IEEE154_aMaxBeaconOverhead + m_updateBeaconOffset], 
             m_updateBeaconPayload, m_updateBeaconLength);
         beaconPayloadUpdated = (m_payloadState & MODIFIED_BEACON_PAYLOAD_MASK);
@@ -697,7 +740,7 @@ implementation
       m_beaconFrame.payloadLen = (m_pendingAddrLen + m_pendingGtsLen + 2) + m_beaconPayloadLen;
       m_payloadState &= ~MODIFIED_BEACON_PAYLOAD_MASK;
     }
-    if (beaconPayloadUpdated){
+    if (beaconPayloadUpdated) {
       if ((beaconPayloadUpdated & MODIFIED_BEACON_PAYLOAD_NEW))
         signal IEEE154TxBeaconPayload.setBeaconPayloadDone(m_updateBeaconPayload, m_updateBeaconLength);
       else
@@ -706,32 +749,12 @@ implementation
     }
   }
 
-/* -----------------------  SuperframeSpec ----------------------- */
-
-  command uint8_t SuperframeSpecWrite.write(uint8_t *superframeSpecField, uint8_t maxlen)
-  {
-    if (call SuperframeSpecWrite.getLength() > maxlen)
-      return 0;
-    superframeSpecField[0] = m_beaconOrder | (m_superframeOrder << 4);
-    superframeSpecField[1] = m_finalCAPSlot;
-    if (m_PANCoordinator)
-      superframeSpecField[1] |= SF_SPEC2_PAN_COORD;
-    if (call MLME_GET.macAssociationPermit())
-      superframeSpecField[1] |= SF_SPEC2_ASSOCIATION_PERMIT;
-    return 2;
-  }
-
-  command uint8_t SuperframeSpecWrite.getLength()
-  {
-    return 2;
-  }
-
-/* ----------------------- Realignment ----------------------- */
-/* In beacon-enabled mode a realignment frame was broadcast in the CAP
- * immediately after the beacon was transmitted.  In non-beacon-enabled mode a
- * realignment frame was sent using unslotted CSMA. In both cases, if the
- * transmission was successful, the superframe spec must be updated now.
- **/
+  /* ----------------------- Realignment ----------------------- */
+  /* In beaconenabled mode a realignment frame is broadcast in the CAP
+   * immediately after the beacon was transmitted.  In non-beaconenabled mode a
+   * realignment frame is sent using unslotted CSMA. In both cases, if the
+   * transmission was successful, the superframe spec should be updated now.
+   **/
 
   event void RealignmentBeaconEnabledTx.transmitDone(ieee154_txframe_t *frame, ieee154_status_t status)
   {
@@ -746,71 +769,83 @@ implementation
   void finishRealignment(ieee154_txframe_t *frame, ieee154_status_t status)
   {
     call GetSetRealignmentFrame.set(frame);
-    if (status == IEEE154_SUCCESS){
+    if (status == IEEE154_SUCCESS) {
       continueStartRequest();
-      m_requests &= ~REQUEST_REALIGNMENT_DONE_PENDING; // unlock
+      m_requestBitmap &= ~REQUEST_REALIGNMENT_DONE_PENDING; // unlock
       // signal confirm where we calculate the next beacon transmission time
     } else {
-      m_requests = 0;
+      m_requestBitmap = 0;
       signal MLME_START.confirm(status);
     }
   }
 
-/* ----------------------- BeaconRequest ----------------------- */
+  /* ----------------------- BeaconRequest ----------------------- */
 
   event message_t* BeaconRequestRx.received(message_t* frame)
   {
-    if (!call IsSendingBeacons.get()){
+    if (m_beaconOrder == 15) {
       // transmit the beacon frame using unslotted CSMA-CA
       // TODO
     }
     return frame;
   }
 
-/* -----------------------  Defaults, etc. ----------------------- */
+  /* -----------------------  SF Structure, etc. ----------------------- */
 
-  task void signalStartConfirmSuccessTask()
-  {
-    signal MLME_START.confirm(SUCCESS);
+  async command uint32_t OutgoingSF.sfStartTime()
+  { 
+    return m_lastBeaconTxTime; 
   }
 
-  command bool IsSendingBeacons.get(){ return m_beaconOrder < 15;}
+  async command uint16_t OutgoingSF.sfSlotDuration()
+  { 
+    return m_sfSlotDuration;
+  }
 
-  async command uint32_t BeaconInterval.getNow() { return m_beaconInterval; }
-  async command uint32_t CapStart.getNow() { return m_lastBeaconTxTime; }
-  async command ieee154_reftime_t* CapStartRefTime.getNow() { return &m_lastBeaconTxRefTime; }
-  async command uint32_t CapLen.getNow() { return call SfSlotDuration.getNow() * (call FinalCapSlot.getNow() + 1);}
-  async command uint32_t CapEnd.getNow() 
+  async command uint8_t OutgoingSF.numCapSlots()
   {
-    return call CapStart.getNow() + call CapLen.getNow();
+    return m_numCapSlots;
   }
-  async command uint32_t CfpEnd.getNow() 
+
+  async command uint8_t OutgoingSF.numGtsSlots()
   {
-    return call CapStart.getNow() + call SfSlotDuration.getNow() * IEEE154_aNumSuperframeSlots;
+    return m_numGtsSlots;
   }
-  async command uint32_t CfpLen.getNow()
+
+  async command uint16_t OutgoingSF.battLifeExtDuration()
   {
-    return call SfSlotDuration.getNow() * (15 - call FinalCapSlot.getNow());
+    return m_battLifeExtDuration;
   }
-  async command bool IsBLEActive.getNow(){ return m_BLELen>0;}
-  async command uint16_t BLELen.getNow(){ return m_BLELen;}
-  async command bool BeaconFramePendingBit.getNow(){ return m_framePendingBit;}
 
-  async command uint8_t* GtsField.getNow() { return m_gtsField; }
-  async command uint32_t SfSlotDuration.getNow() { return m_sfSlotDuration; }
-  async command uint8_t FinalCapSlot.getNow() { return m_finalCAPSlot; }
-  async command uint8_t NumGtsSlots.getNow() { return m_numGtsSlots; }
+  async command const uint8_t* OutgoingSF.gtsFields()
+  {
+    return m_gtsField;
+  }
 
-  default event void MLME_START.confirm    (
-                          ieee154_status_t status
-                        ){}
+  async command uint16_t OutgoingSF.guardTime()
+  {
+    return IEEE154_MAX_BEACON_JITTER(m_beaconOrder) + IEEE154_RADIO_TX_DELAY;
+  }
 
-  default event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length){}
+  async command const ieee154_timestamp_t* OutgoingSF.sfStartTimeRef()
+  {
+    return &m_lastBeaconTxRefTime;
+  }
 
-  default event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength){}
+  async command bool OutgoingSF.isBroadcastPending()
+  {
+    return m_framePendingBit;
+  }
 
-  default event void IEEE154TxBeaconPayload.aboutToTransmit(){}
+  async command bool IsSendingBeacons.getNow()
+  { 
+    return (m_beaconOrder < 15) || ((m_requestBitmap & REQUEST_CONFIRM_PENDING) && m_updateBeaconOrder < 15);
+  }
 
-  default event void IEEE154TxBeaconPayload.beaconTransmitted(){}
+  default event void MLME_START.confirm(ieee154_status_t status) {}
+  default event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length) {}
+  default event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength) {}
+  default event void IEEE154TxBeaconPayload.aboutToTransmit() {}
+  default event void IEEE154TxBeaconPayload.beaconTransmitted() {}
 
 }
diff --git a/tos/lib/mac/tkn154/CapP.nc b/tos/lib/mac/tkn154/CapP.nc
deleted file mode 100644 (file)
index 2fec1c0..0000000
+++ /dev/null
@@ -1,753 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#include "TKN154_PHY.h"
-#include "TKN154_MAC.h"
-
-/** 
- * This module is responsible for sending/receiving frames during the
- * contention access period (CAP in beacon-enabled mode). It does slightly
- * different things depending on whether it is the CAP for an outgoing
- * superframe (superframeDirection = OUTGOING_SUPERFRAME), i.e. the CAP from
- * the perspective of a coordinator after it has transmitted its own beacon; or
- * for an incoming superframe (superframeDirection = INCOMING_SUPERFRAME), i.e.
- * the CAP from the perspective of a device after it has received a beacon from
- * its coordinator (e.g. in the CAP a coordinator will usually listen for 
- * incoming frames from the devices, and a device will usually switch the
- * radio off unless it has a frame to transmit).
- */
-
-generic module CapP(uint8_t superframeDirection)
-{
-  provides
-  {
-    interface Init as Reset;
-    interface FrameTx as CapTx;
-    interface FrameRx as FrameRx[uint8_t frameType];
-    interface FrameExtracted as FrameExtracted[uint8_t frameType];
-    interface FrameTxNow as BroadcastTx;
-    interface Notify<bool> as WasRxEnabled;
-    interface Notify<bool> as FindBeacon;
-  }
-  uses
-  {
-    interface Random;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as CapEndAlarm;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as BLEAlarm;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as IndirectTxWaitAlarm;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as BroadcastAlarm;
-    interface Resource as Token;
-    interface ResourceTransfer as TokenToCfp;
-    interface ResourceTransferred as TokenTransferred;
-    interface ResourceRequested as TokenRequested;
-    interface GetNow<bool> as IsTokenRequested;
-    interface GetNow<uint32_t> as CapStart; 
-    interface GetNow<ieee154_reftime_t*> as CapStartRefTime; 
-    interface GetNow<uint32_t> as CapLen; 
-    interface GetNow<bool> as IsBLEActive; 
-    interface GetNow<uint16_t> as BLELen; 
-    interface GetNow<bool> as IsRxBroadcastPending; 
-    interface GetNow<bool> as IsRxEnableActive; 
-    interface Notify<bool> as RxEnableStateChange;
-    interface GetNow<bool> as IsTrackingBeacons;
-    interface FrameUtility;
-    interface RadioTx;
-    interface RadioRx;
-    interface RadioOff;
-    interface Get<bool> as IsBeaconEnabledPAN;
-    interface MLME_GET;
-    interface MLME_SET;
-    interface Ieee802154Debug as Debug;
-    interface TimeCalc;
-    interface Leds;
-    interface SetNow<ieee154_cap_frame_backup_t*> as FrameBackup;
-    interface GetNow<ieee154_cap_frame_backup_t*> as FrameRestore;
-  }
-}
-implementation
-{
-  typedef enum {
-    SWITCH_OFF,
-    LOAD_TX,
-    PREPARE_RX,
-    DO_NOTHING,
-    WAIT_FOR_TXDONE,
-  } next_state_t;
-
-  typedef enum {
-    INDIRECT_TX_ALARM,
-    BROADCAST_ALARM,
-    NO_ALARM,
-  } rx_alarm_t;
-
-  enum {
-    COORD_ROLE = (superframeDirection == OUTGOING_SUPERFRAME),
-    DEVICE_ROLE = !COORD_ROLE,
-  };
-
-  norace bool m_lock;
-  norace ieee154_txframe_t *m_currentFrame;
-  norace ieee154_txframe_t *m_bcastFrame;
-  norace ieee154_txframe_t *m_lastFrame;
-  norace ieee154_macMaxBE_t m_BE;
-  norace ieee154_macMaxBE_t m_NB;
-  norace ieee154_macMaxBE_t m_numCCA;
-  norace ieee154_macMaxCSMABackoffs_t m_macMaxCSMABackoffs;
-  norace ieee154_macMaxFrameRetries_t m_macMaxFrameRetries;
-  norace ieee154_macMaxBE_t m_macMaxBE;
-  norace ieee154_macMinBE_t m_macMinBE;
-  norace uint16_t m_backoff;
-  norace uint16_t m_backoffElapsed;
-  norace ieee154_status_t m_result;
-  norace uint32_t m_transactionTime;
-  norace bool m_indirectTxPending = FALSE;
-  norace bool m_broadcastRxPending;
-  norace ieee154_macMaxFrameTotalWaitTime_t m_macMaxFrameTotalWaitTime;
-  norace bool m_isBeaconEnabledPAN;
-
-  uint16_t generateRandomBackoff(uint8_t BE);
-  void stopAllAlarms();
-  next_state_t tryReceive(rx_alarm_t alarmType);
-  next_state_t tryTransmit();
-  next_state_t trySwitchOff();
-  void backupCurrentFrame();
-  void restoreFrameFromBackup();  
-  void updateState();
-  void setCurrentFrame(ieee154_txframe_t *frame);
-  void signalTxBroadcastDone(ieee154_txframe_t *frame, ieee154_status_t error);
-  task void signalTxDoneTask();
-  task void setupTxBroadcastTask();
-  task void wasRxEnabledTask();
-
-  command error_t Reset.init()
-  {
-    if (call Token.isOwner()){
-      call Leds.led0On(); // internal error
-      return FAIL;
-    }
-    if (m_currentFrame)
-      signal CapTx.transmitDone(m_currentFrame, IEEE154_TRANSACTION_OVERFLOW);
-    if (m_lastFrame)
-      signal CapTx.transmitDone(m_lastFrame, IEEE154_TRANSACTION_OVERFLOW);
-    if (m_bcastFrame)
-      signalTxBroadcastDone(m_bcastFrame, IEEE154_TRANSACTION_OVERFLOW);
-    m_currentFrame = m_lastFrame = m_bcastFrame = NULL;
-    m_macMaxFrameTotalWaitTime = call MLME_GET.macMaxFrameTotalWaitTime();
-    m_isBeaconEnabledPAN = call IsBeaconEnabledPAN.get();
-    stopAllAlarms();
-    return SUCCESS;
-  }
-
-  event void TokenTransferred.transferred()
-  {
-    // we got the token, i.e. CAP has just started    
-    uint32_t actualCapLen = call CapLen.getNow();
-    if (m_isBeaconEnabledPAN && (DEVICE_ROLE && !call IsTrackingBeacons.getNow())){
-      // rare case: we're on a beacon-enabled PAN, not tracking beacons, searched
-      // and didn't find a beacon for aBaseSuperframeDuration*(2n+1) symbols
-      // -> transmit current frame using unslotted CSMA-CA
-      m_numCCA = 1;
-      signal Token.granted();
-      return;
-    }
-    else if (actualCapLen < IEEE154_RADIO_GUARD_TIME){
-      call Debug.log(LEVEL_IMPORTANT, CapP_TOO_SHORT, superframeDirection, actualCapLen, IEEE154_RADIO_GUARD_TIME);
-      call TokenToCfp.transfer();
-      return;
-    } else {
-      actualCapLen -= IEEE154_RADIO_GUARD_TIME;
-      if (DEVICE_ROLE)
-        m_broadcastRxPending = call IsRxBroadcastPending.getNow();
-      else { 
-        // COORD_ROLE
-        if (m_bcastFrame != NULL) {
-          // we have to transmit a broadcast frame immediately; this  
-          // (possibly) requires a backup of the previously active frame
-          // and a reinitializing the CSMA parameters -> will do it
-          // in task context and then continue
-          m_lock = TRUE;
-          post setupTxBroadcastTask(); 
-        }
-      }
-      call CapEndAlarm.startAt(call CapStart.getNow(), actualCapLen);
-      if (call IsBLEActive.getNow())
-        call BLEAlarm.startAt(call CapStart.getNow(), call BLELen.getNow());
-      call Debug.log(LEVEL_IMPORTANT, CapP_SET_CAP_END, call CapStart.getNow(), 
-          actualCapLen, call CapStart.getNow()+ actualCapLen);
-    }
-    updateState();
-    call Debug.flush();
-  }
-
-  command ieee154_status_t CapTx.transmit(ieee154_txframe_t *frame)
-  {
-    // this frame (DATA or COMMAND) should be transmitted in the CAP
-    if (m_currentFrame != NULL)
-      return IEEE154_TRANSACTION_OVERFLOW;
-    else {
-      setCurrentFrame(frame);
-      if (!m_isBeaconEnabledPAN){
-        call Token.request(); // prepare for unslotted CSMA-CA
-      } else {
-        // a beacon must be found before transmitting in a beacon-enabled PAN
-        if (DEVICE_ROLE && !call IsTrackingBeacons.getNow()){
-          signal FindBeacon.notify(TRUE);
-          // we'll receive the Token at latest after aBaseSuperframeDuration*(2n+1) symbols; 
-          // if the beacon was not found, then we'll send the frame using unslotted CSMA-CA
-        }
-        updateState();
-      }
-      return IEEE154_SUCCESS;
-    }
-  }
-
-  task void setupTxBroadcastTask()
-  {
-    ieee154_macDSN_t tmp;
-    ieee154_txframe_t *oldFrame = m_currentFrame;
-    if (COORD_ROLE){
-      if (m_bcastFrame != NULL){
-        // broadcasts should be transmitted *immediately* after the beacon,
-        // which may interrupt a pending transmit operation from the previous
-        // CAP; back up the last active frame configuration (may be none)
-        // and restore it after the broadcast frame has been transmitted; 
-        // do this through interfaces and don't wire them for DEVICE_ROLE, 
-        // so we don't waste the RAM of devices
-        backupCurrentFrame();
-        setCurrentFrame(m_bcastFrame);
-        if (oldFrame){
-          // now the sequence number are out of order... swap them back
-          tmp = m_bcastFrame->header->mhr[MHR_INDEX_SEQNO];
-          m_bcastFrame->header->mhr[MHR_INDEX_SEQNO] = 
-            oldFrame->header->mhr[MHR_INDEX_SEQNO];
-          oldFrame->header->mhr[MHR_INDEX_SEQNO] = tmp;
-        }
-      }
-    }
-    m_lock = FALSE;
-    updateState(); 
-  }
-
-  void setCurrentFrame(ieee154_txframe_t *frame)
-  {
-    ieee154_macDSN_t dsn = call MLME_GET.macDSN();
-    frame->header->mhr[MHR_INDEX_SEQNO] = dsn++;
-    call MLME_SET.macDSN(dsn);
-    m_macMaxCSMABackoffs =  call MLME_GET.macMaxCSMABackoffs();
-    m_macMaxFrameRetries =  call MLME_GET.macMaxFrameRetries();
-    m_macMaxBE = call MLME_GET.macMaxBE();
-    m_macMinBE = call MLME_GET.macMinBE();
-    if (call MLME_GET.macBattLifeExt() && m_macMinBE > 2)
-      m_macMinBE = 2;
-    m_BE = m_macMinBE;
-    if (m_isBeaconEnabledPAN)
-      m_numCCA = 2;
-    else
-      m_numCCA = 1;
-    m_NB = 0;
-    m_transactionTime = IEEE154_SHR_DURATION + 
-      (frame->headerLen + frame->payloadLen) * IEEE154_SYMBOLS_PER_OCTET;
-    if (frame->header->mhr[MHR_INDEX_FC1] & FC1_ACK_REQUEST)
-      m_transactionTime += (IEEE154_aTurnaroundTime + IEEE154_aUnitBackoffPeriod + 
-          11 * IEEE154_SYMBOLS_PER_OCTET);
-    if (frame->headerLen + frame->payloadLen > IEEE154_aMaxSIFSFrameSize)
-      m_transactionTime += call MLME_GET.macMinLIFSPeriod();
-    else
-      m_transactionTime += call MLME_GET.macMinSIFSPeriod();
-    m_backoff = generateRandomBackoff(m_BE) * IEEE154_aUnitBackoffPeriod; // initial backoff
-    m_macMaxFrameTotalWaitTime = call MLME_GET.macMaxFrameTotalWaitTime();
-    m_backoffElapsed = 0;
-    m_currentFrame = frame;
-  }
-
-  uint16_t generateRandomBackoff(uint8_t BE)
-  {
-    // return random number from [0,(2^BE) - 1] (uniform distr.)
-    uint16_t res = call Random.rand16();
-    uint16_t mask = 0xFFFF;
-    mask <<= BE;
-    mask = ~mask;
-    res &= mask;
-    return res;
-  }
-  void stopAllAlarms()
-  {
-    call CapEndAlarm.stop();
-    if (DEVICE_ROLE){
-      call IndirectTxWaitAlarm.stop();
-      call BroadcastAlarm.stop();
-    }
-    call BLEAlarm.stop();
-  }
-
-  /** 
-   * The updateState() function is called whenever some event happened that
-   * might require a state change; it implements a lock mechanism (m_lock) to
-   * prevent race conditions. Whenever the lock is set a "done"-event (from a
-   * RadioTx/RadioRx/RadioOff interface) is pending and will "soon" unset the
-   * lock (and then updateState() will called again).  The updateState()
-   * function decides about the next state by checking a list of possible
-   * current states ordered by priority, e.g. it first always checks whether
-   * the CAP is still active. Calling this function more than necessary can do
-   * no harm, but it SHOULD be called whenever an event happened that might
-   * lead to a state change.
-   */ 
-
-  void updateState()
-  {
-    error_t result = SUCCESS;
-    next_state_t next;
-    atomic {
-      // long atomics are bad... but in this block, once the
-      // current state has been determined only one branch will
-      // be taken (no loops, etc.)
-      if (m_lock || !call Token.isOwner())
-        return;
-      m_lock = TRUE; // lock
-
-      // Check 1: for beacon-enabled PANs, has the CAP finished?
-      if (m_isBeaconEnabledPAN 
-          && (COORD_ROLE || call IsTrackingBeacons.getNow()) // FALSE only if device could't find a beacon
-          && (call TimeCalc.hasExpired(call CapStart.getNow(), call CapLen.getNow()-IEEE154_RADIO_GUARD_TIME) ||
-          !call CapEndAlarm.isRunning())){
-        if (call RadioOff.isOff()) {
-          stopAllAlarms();  // may still fire, locked through isOwner()
-          if (DEVICE_ROLE && m_indirectTxPending)
-            signal IndirectTxWaitAlarm.fired();
-          m_broadcastRxPending = FALSE;
-          if (COORD_ROLE && m_bcastFrame){
-            // didn't manage to transmit a broadcast
-            restoreFrameFromBackup();
-            signalTxBroadcastDone(m_bcastFrame, IEEE154_CHANNEL_ACCESS_FAILURE);
-            m_bcastFrame = NULL;
-          }
-          m_lock = FALSE; // unlock
-          call TokenToCfp.transfer();
-          return;
-        } else 
-          next = SWITCH_OFF;
-      }
-
-      // Check 2: should a broadcast frame be received/transmitted immediately
-      // at the start of CAP?
-      else if (DEVICE_ROLE && m_broadcastRxPending){
-        // receive a broadcast from coordinator
-        next = tryReceive(BROADCAST_ALARM);
-      } else if (COORD_ROLE && m_bcastFrame){
-        next = tryTransmit();
-      }
-
-      // Check 3: was an indirect transmission successfully started 
-      // and are we now waiting for a frame from the coordinator?
-      else if (DEVICE_ROLE && m_indirectTxPending) {
-        next = tryReceive(INDIRECT_TX_ALARM);
-      }
-
-      // Check 4: is some other operation (like MLME-SCAN or MLME-RESET) pending? 
-      else if (call IsTokenRequested.getNow()) {
-        if (call RadioOff.isOff()) {
-          stopAllAlarms();  // may still fire, locked through isOwner()
-          call Token.release();
-          next = DO_NOTHING;
-        } else 
-          next = SWITCH_OFF;
-      }
-
-      // Check 5: is battery life extension (BLE) active and 
-      // has the BLE period expired?
-      else if (call IsBLEActive.getNow() &&
-          call TimeCalc.hasExpired(call CapStart.getNow(), call BLELen.getNow()) &&
-          !call IsRxEnableActive.getNow()) {
-        next = trySwitchOff();
-      }
-
-      // Check 6: is there a frame ready to transmit?
-      else if (m_currentFrame != NULL) {
-        next = tryTransmit();
-      }
-
-      // Check 7: should we be in receive mode?
-      else if (COORD_ROLE || call IsRxEnableActive.getNow()) {
-        next = tryReceive(NO_ALARM);
-        if (next == DO_NOTHING && call IsRxEnableActive.getNow()){
-          // this means there is an active MLME_RX_ENABLE.request
-          // and the radio was just switched to Rx mode - signal
-          // a notify event to inform the next higher layer
-          post wasRxEnabledTask();
-        }
-      }
-
-      // Check 8: just make sure the radio is switched off  
-      else {
-        next = trySwitchOff();
-        if (next == DO_NOTHING && (!m_isBeaconEnabledPAN || (DEVICE_ROLE && !call IsTrackingBeacons.getNow()))){
-          // nothing more to do... just release the Token
-          m_lock = FALSE; // unlock
-          call TokenToCfp.transfer();
-          return;
-        }
-      }
-
-      // if there is nothing to do, then we must clear the lock
-      if (next == DO_NOTHING)
-        m_lock = FALSE;
-    } // atomic
-    // put next state in operation (possibly keeping the lock)
-    switch (next)
-    {
-      case SWITCH_OFF: result = call RadioOff.off(); break;
-      case LOAD_TX: result = call RadioTx.load(m_currentFrame); break;
-      case PREPARE_RX: result = call RadioRx.prepare(); break;
-      case WAIT_FOR_TXDONE: break;
-      case DO_NOTHING: break;
-    }
-    if (result != SUCCESS)
-      call Leds.led0On(); // internal error: could not update state !!!
-  }
-  
-  next_state_t tryTransmit()
-  {
-    // tries to transmit m_currentFrame using the configuration stored
-    // in other module variables (m_backoff, etc.)
-    next_state_t next;
-    if (call RadioTx.getLoadedFrame() == m_currentFrame){
-      // the frame is already loaded -> transmit it now
-      if (m_numCCA == 1){
-        // unslotted CSMA-CA
-        call RadioTx.transmit(NULL, m_backoff, m_numCCA, m_currentFrame->header->mhr[MHR_INDEX_FC1] & FC1_ACK_REQUEST ? TRUE : FALSE);
-        next = WAIT_FOR_TXDONE; // this will NOT clear the lock
-      } else {
-        // slotted CSMA-CA
-        uint32_t capLen = call CapLen.getNow(), capStart = call CapStart.getNow();
-        uint32_t elapsed, totalTime;
-        totalTime = IEEE154_RADIO_TX_SEND_DELAY + 
-          m_backoff - m_backoffElapsed + m_transactionTime + IEEE154_RADIO_GUARD_TIME;
-        if (totalTime > capLen)
-          totalTime = capLen; // CAP is too short
-        elapsed = call TimeCalc.timeElapsed(capStart, call CapEndAlarm.getNow());
-        elapsed += (20 - (elapsed % 20)); // round to backoff boundary
-        if (!call TimeCalc.hasExpired(capStart, capLen - totalTime)){
-          call RadioTx.transmit(call CapStartRefTime.getNow(), 
-              elapsed + IEEE154_RADIO_TX_SEND_DELAY + m_backoff - m_backoffElapsed, 
-              m_numCCA, 
-              m_currentFrame->header->mhr[MHR_INDEX_FC1] & FC1_ACK_REQUEST ? TRUE : FALSE);
-          next = WAIT_FOR_TXDONE; // this will NOT clear the lock
-        } else {
-          // frame does not fit in remaing portion of the CAP
-          if (elapsed < call CapLen.getNow()){
-            m_backoffElapsed += call CapLen.getNow() - elapsed;
-            if (m_backoffElapsed > m_backoff)
-              m_backoffElapsed = m_backoff;
-          }
-          next = SWITCH_OFF;
-        }
-      }
-    } else {
-      // the frame to transmit has not yet been loaded -> load it now
-      if (!call RadioOff.isOff())
-        next = SWITCH_OFF;
-      else {
-        if (m_lastFrame){
-          // the done event for the previous frame has not yet been
-          // signalled to the upper layer -> wait
-          next = DO_NOTHING; 
-        } else
-          next = LOAD_TX;
-      }
-    }
-    return next;
-  }
-
-  next_state_t tryReceive(rx_alarm_t alarmType)
-  {
-    next_state_t next;
-    if (call RadioRx.isReceiving()){
-      next = DO_NOTHING;
-    } else if (call RadioRx.isPrepared()){
-      call RadioRx.receive(NULL, 0);
-      switch (alarmType)
-      {
-        case INDIRECT_TX_ALARM: call IndirectTxWaitAlarm.start(m_macMaxFrameTotalWaitTime); break;
-        case BROADCAST_ALARM: call BroadcastAlarm.start(m_macMaxFrameTotalWaitTime); break;
-        case NO_ALARM: break;
-      }
-      next = DO_NOTHING;
-    } else if (call RadioOff.isOff())
-      next = PREPARE_RX;
-    else
-      next = SWITCH_OFF;
-    return next;
-  }
-
-  next_state_t trySwitchOff()
-  {
-    next_state_t next;
-    if (call RadioOff.isOff())
-      next = DO_NOTHING;
-    else
-      next = SWITCH_OFF;
-    return next;
-  }
-
-  async event void RadioTx.loadDone(){ m_lock = FALSE; updateState();}
-  async event void RadioOff.offDone(){ m_lock = FALSE; updateState();}
-  async event void RadioRx.prepareDone(){ m_lock = FALSE; updateState();}
-
-  async event void CapEndAlarm.fired(){ 
-    call Debug.log(LEVEL_IMPORTANT, CapP_CAP_END_FIRED, superframeDirection, 0, 0);
-    updateState();
-  }
-  async event void BLEAlarm.fired(){ updateState();}
-  event void RxEnableStateChange.notify(bool whatever){ updateState();}
-  async event void BroadcastAlarm.fired(){ m_broadcastRxPending = FALSE; updateState();}
-
-  async event void IndirectTxWaitAlarm.fired() 
-  { 
-    atomic {
-      if (m_indirectTxPending){
-        m_indirectTxPending = FALSE; 
-        post signalTxDoneTask(); 
-      }
-    }
-  }
-
-  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, 
-      ieee154_reftime_t *referenceTime, bool ackPendingFlag, error_t error)
-  {
-    bool retry = FALSE;
-    switch (error)
-    {
-      case SUCCESS:
-        m_result = IEEE154_SUCCESS;
-        if (DEVICE_ROLE && frame->payload[0] == CMD_FRAME_DATA_REQUEST &&
-            ((frame->header->mhr[MHR_INDEX_FC1]) & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_CMD){
-          // just transmitted a data request frame
-          m_result = IEEE154_NO_DATA; // pessimistic 
-          if (ackPendingFlag){
-            // the coordinator has data for us; switch to Rx 
-            // to complete the indirect transmission
-            m_indirectTxPending = TRUE;
-            m_lastFrame = m_currentFrame;
-            m_currentFrame = NULL;
-            if (call RadioRx.prepare() != SUCCESS) // SHOULD succeed
-              call RadioOff.off();
-            return;
-          }
-        }
-        break;
-      case EBUSY:
-        // we're following the SDL Spec in IEEE 802.15.4-2003 Annex D
-        m_result = IEEE154_CHANNEL_ACCESS_FAILURE;
-        m_NB += 1;
-        if (m_NB < m_macMaxCSMABackoffs){
-          m_BE += 1;
-          if (m_BE > m_macMaxBE)
-            m_BE = m_macMaxBE;
-          retry = TRUE;
-        }
-        break;
-      case ENOACK:
-        // we're following the SDL Spec in IEEE 802.15.4-2003 Annex D
-        m_result = IEEE154_NO_ACK;
-        m_NB += 1;
-        // shouldn't the next check be (m_NB-1 < m_macMaxFrameRetries)? but
-        // on the other hand, NB is used for CHANNEL_ACCESS_FAILURE and NO_ACK,
-        // i.e. m_NB does not tell us much about past retransmissions anyway...
-        if (m_NB < m_macMaxFrameRetries){
-          m_BE = m_macMinBE;
-          retry = TRUE;
-        }
-        break;
-      default: break;
-    }
-    if (retry){
-      m_backoff = generateRandomBackoff(m_BE) * IEEE154_aUnitBackoffPeriod; // next backoff
-      m_backoffElapsed = 0;
-    } else if (COORD_ROLE && frame == m_bcastFrame){
-      // signal result of broadcast transmissions immediately 
-      restoreFrameFromBackup();
-      signalTxBroadcastDone(m_bcastFrame, m_result);
-      m_bcastFrame = NULL;
-    } else {
-      m_lastFrame = m_currentFrame;
-      m_currentFrame = NULL;
-      post signalTxDoneTask();
-    }    
-    m_lock = FALSE;
-    updateState();
-  }
-
-  task void signalTxDoneTask()
-  {
-    ieee154_txframe_t *lastFrame = m_lastFrame;
-    m_lastFrame = NULL; // only now can a next transmission begin 
-    m_indirectTxPending = FALSE;
-    if (lastFrame)
-      signal CapTx.transmitDone(lastFrame, m_result);
-    updateState();
-  }
-
-  event message_t* RadioRx.received(message_t* frame, ieee154_reftime_t *timestamp)
-  {
-    // received a frame during CAP - find out frame type and
-    // signal it to corresponding client component
-    uint8_t *payload = (uint8_t *) frame->data;
-    uint8_t *mhr = MHR(frame);
-    uint8_t frameType = mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK;
-    if (frameType == FC1_FRAMETYPE_CMD)
-      frameType += payload[0];
-    atomic {
-      if (DEVICE_ROLE && m_indirectTxPending){
-        message_t* frameBuf;
-        call IndirectTxWaitAlarm.stop();
-        // TODO: check!
-        //if (frame->payloadLen)
-          // is this frame from our coordinator? hmm... we cannot say
-          // with certainty, because we might only know either the 
-          // coordinator extended or short address (and the frame could
-          // have been sent with the other addressing mode) ??
-          m_result = IEEE154_SUCCESS;
-        frameBuf = signal FrameExtracted.received[frameType](frame, m_lastFrame);
-        signal IndirectTxWaitAlarm.fired();
-        return frameBuf;
-      } else
-        return signal FrameRx.received[frameType](frame);
-    }
-  }
-
-  void backupCurrentFrame()
-  {
-    ieee154_cap_frame_backup_t backup = {m_currentFrame, m_BE, m_macMaxCSMABackoffs, 
-      m_macMaxBE, m_macMinBE, m_NB, m_backoff, m_backoffElapsed, m_transactionTime};
-    call FrameBackup.setNow(&backup);
-  }
-
-  void restoreFrameFromBackup()
-  {
-    ieee154_cap_frame_backup_t *backup = call FrameRestore.getNow();
-    if (backup != NULL){
-      m_currentFrame = backup->frame;
-      m_BE = backup->BE;
-      m_macMaxCSMABackoffs = backup->allowedBackoffs;
-      m_macMaxBE = backup->macMaxBE; 
-      m_macMinBE = backup->macMinBE; 
-      m_NB = backup->NB; 
-      m_backoff = backup->backoff;
-      m_backoffElapsed = backup->backoffElapsed;
-      m_transactionTime = backup->transactionTime;
-    }
-  }
-
-  async command ieee154_status_t BroadcastTx.transmitNow(ieee154_txframe_t *frame) 
-  {
-    // if this command is called then it is (MUST be) called 
-    // only just before the token is transferred to this component
-    // and it is then be called only once per CAP (max. one broadcast 
-    // is allowed after a beacon transmission)
-    atomic {
-      if (!call Token.isOwner() && m_bcastFrame == NULL){
-        m_bcastFrame = frame;
-        return IEEE154_SUCCESS;
-      } else {
-        call Leds.led0On();
-        return IEEE154_TRANSACTION_OVERFLOW;
-      }
-    }
-  }
-
-  void signalTxBroadcastDone(ieee154_txframe_t *frame, ieee154_status_t error)
-  {
-    signal BroadcastTx.transmitNowDone(frame, error);
-  }
-
-  task void wasRxEnabledTask()
-  {
-    signal WasRxEnabled.notify(TRUE);
-  }
-
-  bool isUnslottedCSMA_CA()
-  {
-    return (m_numCCA == 1);
-  }
-
-  event void Token.granted()
-  {
-    // the current frame should be transmitted using unslotted CSMA-CA
-    updateState();
-  }
-
-  task void tokenRequestedTask()
-  {
-    signal TokenRequested.requested();
-  }
-
-  async event void TokenRequested.requested() 
-  {
-    atomic {
-      if (call Token.isOwner()){
-        if (!m_lock && !(DEVICE_ROLE && m_indirectTxPending) && !(COORD_ROLE && m_bcastFrame))
-          call Token.release();
-        else
-          post tokenRequestedTask();
-      }
-    }
-  }
-
-  async event void TokenRequested.immediateRequested() {}
-
-  default event void CapTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status){}
-  default event message_t* FrameRx.received[uint8_t client](message_t* data){return data;}
-  default async command bool IsRxEnableActive.getNow(){return FALSE;}
-
-  default async command void IndirectTxWaitAlarm.start(uint32_t dt){call Leds.led0On();}
-  default async command void IndirectTxWaitAlarm.stop(){call Leds.led0On();}
-  default async command void IndirectTxWaitAlarm.startAt(uint32_t t0, uint32_t dt){call Leds.led0On();}
-  
-  default async command void BroadcastAlarm.start(uint32_t dt){call Leds.led0On();}
-  default async command void BroadcastAlarm.stop(){call Leds.led0On();}
-  default async command void BroadcastAlarm.startAt(uint32_t t0, uint32_t dt){call Leds.led0On();}
-
-  default async command bool IsRxBroadcastPending.getNow(){ return FALSE;}
-  default async event void BroadcastTx.transmitNowDone(ieee154_txframe_t *frame, ieee154_status_t status){}
-  default event message_t* FrameExtracted.received[uint8_t client](message_t* msg, ieee154_txframe_t *txFrame){return msg;}
-  default async command error_t FrameBackup.setNow(ieee154_cap_frame_backup_t* val ){return FAIL;}
-  default async command ieee154_cap_frame_backup_t* FrameRestore.getNow(){return NULL;}
-
-  command error_t WasRxEnabled.enable(){return FAIL;}
-  command error_t WasRxEnabled.disable(){return FAIL;}
-  command error_t FindBeacon.enable(){return FAIL;}
-  command error_t FindBeacon.disable(){return FAIL;}
-}
diff --git a/tos/lib/mac/tkn154/CapQueueP.nc b/tos/lib/mac/tkn154/CapQueueP.nc
deleted file mode 100644 (file)
index b3104d4..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154_MAC.h"
-generic module CapQueueP() {
-  provides
-  {
-    interface Init as Reset;
-    interface FrameTx[uint8_t client];
-    interface FrameRx as FrameExtracted[uint8_t client];
-    interface Purge;
-  } uses {
-    interface Queue<ieee154_txframe_t*>;
-    interface FrameTx as CapTx;
-    interface FrameRx as SubFrameExtracted;
-  }
-}
-implementation
-{
-  task void tryCapTxTask();
-  bool m_busy;
-  uint8_t m_client;
-
-  command error_t Reset.init()
-  {
-    while (call Queue.size()){
-      ieee154_txframe_t *txFrame = call Queue.dequeue();
-      signal FrameTx.transmitDone[txFrame->client](txFrame, IEEE154_TRANSACTION_OVERFLOW);
-    }
-    m_busy = FALSE;
-    return SUCCESS;
-  }
-
-  command ieee154_status_t FrameTx.transmit[uint8_t client](ieee154_txframe_t *txFrame)
-  {
-    txFrame->client = client;
-    if (call Queue.enqueue(txFrame) != SUCCESS)
-      return IEEE154_TRANSACTION_OVERFLOW;
-    else {
-      post tryCapTxTask();
-      return IEEE154_SUCCESS;
-    }
-  }
-
-  task void tryCapTxTask()
-  {
-    if (!m_busy && call Queue.size()){
-      ieee154_txframe_t *txFrame = call Queue.head();
-      if (txFrame->headerLen == 0){ 
-        // was purged
-        call Queue.dequeue();
-        signal Purge.purgeDone(txFrame, IEEE154_SUCCESS);
-        post tryCapTxTask();
-      }
-      m_client = txFrame->client;
-      if (call CapTx.transmit(txFrame) == IEEE154_SUCCESS){
-        m_busy = TRUE;
-      }
-    }
-  }
-
-  event void CapTx.transmitDone(ieee154_txframe_t *txFrame, ieee154_status_t status)
-  {
-    call Queue.dequeue();
-    m_busy = FALSE;
-    signal FrameTx.transmitDone[txFrame->client](txFrame, status);
-    post tryCapTxTask();
-  }
-
-  event message_t* SubFrameExtracted.received(message_t* frame)
-  {
-    // this event is signalled when a frame has been received
-    // in response to a data request command frame. The transmitDone 
-    // event will be signalled later
-    return signal FrameExtracted.received[m_client](frame);
-  }
-
-  default event void FrameTx.transmitDone[uint8_t client](ieee154_txframe_t *txFrame, ieee154_status_t status){}
-
-  command ieee154_status_t Purge.purge(uint8_t msduHandle)
-  {
-    uint8_t qSize = call Queue.size(), i;
-    if (qSize > 1){
-      for (i=0; i<qSize-1; i++){
-        ieee154_txframe_t *txFrame = call Queue.element(i);
-        if (((txFrame->header->mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_DATA) &&
-          txFrame->handle == msduHandle){
-          txFrame->headerLen = 0; // mark as invalid
-          return IEEE154_SUCCESS;
-        }
-      }
-    }
-    return IEEE154_INVALID_HANDLE;
-  }
-  
-  default event void Purge.purgeDone(ieee154_txframe_t *txFrame, ieee154_status_t status){}
-}
index 8ba9c136e5849a801d9456bcbe930def5d68eadf..e6000157fbaac0a06b045ac5b5a1e1071499f009 100644 (file)
@@ -49,10 +49,8 @@ module CoordBroadcastP
   } uses {
     interface Queue<ieee154_txframe_t*>; 
     interface FrameTxNow as CapTransmitNow;
-    interface ResourceTransfer as TokenToCap;
-    interface ResourceTransferred as TokenTransferred;
-    interface GetNow<bool> as BeaconFramePendingBit;
-    interface Leds;
+    interface TransferableResource as RadioToken;
+    interface SuperframeStructure as OutgoingSF;
   }
 }
 implementation
@@ -90,7 +88,7 @@ implementation
   command ieee154_status_t RealignmentTx.transmit(ieee154_txframe_t *frame)
   {
     atomic {
-      if (!m_realignmentFrame){
+      if (!m_realignmentFrame) {
         m_realignmentFrame = frame;
         return IEEE154_SUCCESS;
       } else
@@ -106,20 +104,18 @@ implementation
       return (m_realignmentFrame != NULL || m_queueHead != NULL);
   }
 
-  event void TokenTransferred.transferred()
+  async event void RadioToken.transferredFrom(uint8_t fromClient)
   {
     // CAP has started - are there any broadcast frames to be transmitted?
-    if (call BeaconFramePendingBit.getNow()){
+    if (call OutgoingSF.isBroadcastPending()) {
       ieee154_txframe_t *broadcastFrame = m_realignmentFrame;
       if (broadcastFrame == NULL)
         broadcastFrame = m_queueHead;
-      if (broadcastFrame){
-        m_lock = TRUE;
-        call CapTransmitNow.transmitNow(broadcastFrame);
-      } else
-        call Leds.led0On(); // internal error!
+      ASSERT(broadcastFrame != NULL);
+      m_lock = TRUE;
+      call CapTransmitNow.transmitNow(broadcastFrame);
     }
-    call TokenToCap.transfer();
+    call RadioToken.transferTo(RADIO_CLIENT_COORDCAP);
   }
 
   async event void CapTransmitNow.transmitNowDone(ieee154_txframe_t *txFrame, ieee154_status_t status)
@@ -133,14 +129,16 @@ implementation
   {
     if (!m_lock)
       return;
-    if (m_transmittedFrame == m_realignmentFrame){
+    if (m_transmittedFrame == m_realignmentFrame) {
       m_realignmentFrame = NULL;
       signal RealignmentTx.transmitDone(m_transmittedFrame, m_status);
-    } else if (m_transmittedFrame == m_queueHead){
+    } else if (m_transmittedFrame == m_queueHead) {
       call Queue.dequeue();
       m_queueHead = call Queue.head();
       signal BroadcastDataFrame.transmitDone(m_transmittedFrame, m_status);
     }
     m_lock = FALSE;
   }
+
+  event void RadioToken.granted(){ ASSERT(0); }
 }
index 70421aa93cb9d4171bdff48e3e5cb7f7c792d2f2..03563636b28fb5152fbdf76a23d61eed42db328e 100644 (file)
@@ -67,6 +67,7 @@ implementation
     ORPHAN_RESPONSE,
     BEACON_REALIGNMENT,
   };
+
   uint8_t m_payload[9];
   bool m_busy = FALSE;
   void destroyRealignmentFrame(ieee154_txframe_t *frame);
@@ -96,8 +97,7 @@ implementation
         call Frame.getSrcAddr(frame, &srcAddress) == SUCCESS)    
       signal MLME_ORPHAN.indication (
                           srcAddress.extendedAddress,
-                          NULL // security
-                        );
+                          NULL);
     return frame;
   }
 
@@ -105,8 +105,7 @@ implementation
                           uint64_t OrphanAddress,
                           uint16_t ShortAddress,
                           bool AssociatedMember,
-                          ieee154_security_t *security
-                        )
+                          ieee154_security_t *security)
   {
     ieee154_txframe_t *txFrame;
     ieee154_status_t txStatus;
@@ -115,7 +114,7 @@ implementation
     dstAddress.extendedAddress = OrphanAddress;
     if (!AssociatedMember)
       txStatus = IEEE154_SUCCESS;
-    else if (m_busy || (txFrame = newRealignmentFrame(ORPHAN_RESPONSE, &dstAddress)) != NULL)
+    else if (m_busy || (txFrame = newRealignmentFrame(ORPHAN_RESPONSE, &dstAddress)) == NULL)
       txStatus = IEEE154_TRANSACTION_OVERFLOW;
     else {
       m_busy = TRUE;
@@ -125,7 +124,7 @@ implementation
       txFrame->payload[5] = call MLME_GET.phyCurrentChannel();
       *((nxle_uint16_t*) &txFrame->payload[6]) = ShortAddress;
       txFrame->payloadLen = 8;
-      if ((txStatus = call CoordRealignmentTx.transmit(txFrame)) != IEEE154_SUCCESS){
+      if ((txStatus = call CoordRealignmentTx.transmit(txFrame)) != IEEE154_SUCCESS) {
         m_busy = FALSE;
         destroyRealignmentFrame(txFrame);
       }
@@ -140,8 +139,8 @@ implementation
     uint8_t dstAddrMode;
     ieee154_address_t srcAddress;
 
-    if ((txFrame = call TxFramePool.get()) != NULL){
-      if ((txControl = call TxControlPool.get()) == NULL){
+    if ((txFrame = call TxFramePool.get()) != NULL) {
+      if ((txControl = call TxControlPool.get()) == NULL) {
         call TxFramePool.put(txFrame);
         txFrame = NULL;
       } else {
@@ -150,7 +149,7 @@ implementation
         txFrame->payload = m_payload;
         txFrame->header->mhr[MHR_INDEX_FC1] = FC1_FRAMETYPE_CMD;
         txFrame->header->mhr[MHR_INDEX_FC2] = FC2_SRC_MODE_EXTENDED;
-        if (type == ORPHAN_RESPONSE){
+        if (type == ORPHAN_RESPONSE) {
           txFrame->header->mhr[MHR_INDEX_FC2] |= FC2_DEST_MODE_EXTENDED;
           dstAddrMode = ADDR_MODE_EXTENDED_ADDRESS;
           txFrame->header->mhr[MHR_INDEX_FC1] |= FC1_ACK_REQUEST;
@@ -185,7 +184,8 @@ implementation
     uint8_t *mhr = MHR(txFrame);
     ieee154_address_t dstAddr;
     ieee154_address_t srcAddr;
-    if (m_busy){
+
+    if (m_busy) {
       call FrameUtility.convertToNative(&dstAddr.extendedAddress, &mhr[MHR_INDEX_ADDRESS+2]);
       call FrameUtility.convertToNative(&srcAddr.extendedAddress, &mhr[MHR_INDEX_ADDRESS+2+8+2]);
       signal MLME_COMM_STATUS.indication (
@@ -195,8 +195,7 @@ implementation
           ADDR_MODE_EXTENDED_ADDRESS, // DstAddrMode
           dstAddr,
           status,
-          NULL  //security
-          );
+          NULL);
       call TxControlPool.put((ieee154_txcontrol_t*) ((uint8_t*) txFrame->header - offsetof(ieee154_txcontrol_t, header)));
       call TxFramePool.put(txFrame);
       m_busy = FALSE;
@@ -210,11 +209,9 @@ implementation
                           uint8_t DstAddrMode,
                           ieee154_address_t DstAddr,
                           ieee154_status_t status,
-                          ieee154_security_t *security
-                        ){}
+                          ieee154_security_t *security) {}
 
   default event void MLME_ORPHAN.indication (
                           uint64_t OrphanAddress,
-                          ieee154_security_t *security
-                        ){}
+                          ieee154_security_t *security) {}
 }
index 4e951b0ea9398495eb46c5481c10ac92c99c9c11..146c3b47fabffd4581670ff853956e64596b2e05 100644 (file)
@@ -42,7 +42,6 @@ module DataP
     interface MCPS_DATA; 
     interface MCPS_PURGE;
   } uses {
-    interface Get<bool> as IsSendingBeacons;
     interface FrameRx as CoordCapRx;
     interface FrameTx as DeviceCapTx;
     interface FrameTx as CoordCapTx;
@@ -80,8 +79,7 @@ implementation
                           message_t *frame,
                           uint8_t payloadLen,
                           uint8_t msduHandle,
-                          uint8_t txOptions
-                        )
+                          uint8_t txOptions)
   {
     uint8_t srcAddrMode = call Frame.getSrcAddrMode(frame);
     uint8_t dstAddrMode = call Frame.getDstAddrMode(frame);
@@ -89,9 +87,10 @@ implementation
     ieee154_status_t txStatus;
     ieee154_txframe_t *txFrame;
     uint8_t sfType=0;
-    uint8_t *mhr;
+    uint8_t *mhr, mhrLen = call Frame.getHeaderLength(frame);
 
-    if (payloadLen > call Packet.maxPayloadLength())
+    if (payloadLen > call Packet.maxPayloadLength() || 
+        mhrLen + payloadLen + 2 > IEEE154_aMaxPHYPacketSize) // extra 2 for MAC footer (CRC)
       txStatus = IEEE154_INVALID_PARAMETER;
     else if ((!srcAddrMode && !dstAddrMode) || 
         (srcAddrMode > ADDR_MODE_EXTENDED_ADDRESS || dstAddrMode > ADDR_MODE_EXTENDED_ADDRESS) ||
@@ -106,7 +105,7 @@ implementation
       txFrame->metadata = &((message_metadata_t*) frame->metadata)->ieee154;
       txFrame->payloadLen = payloadLen;
       mhr = txFrame->header->mhr;
-      txFrame->headerLen = call Frame.getHeaderLength(frame);
+      txFrame->headerLen = mhrLen;
       mhr[MHR_INDEX_FC1] &= ~(FC1_FRAMETYPE_MASK | FC1_FRAME_PENDING | FC1_ACK_REQUEST);
       mhr[MHR_INDEX_FC1] |= FC1_FRAMETYPE_DATA;
       if (txOptions & TX_OPTIONS_ACK)
@@ -123,12 +122,12 @@ implementation
       // coordinator address in the PIB, if they match the frame is
       // sent in the incoming sf otherwise in the outgoing sf
       call Frame.getDstAddr(frame, &dstAddr);
-      if (dstAddrMode == ADDR_MODE_SHORT_ADDRESS){
+      if (dstAddrMode == ADDR_MODE_SHORT_ADDRESS) {
         if (dstAddr.shortAddress == call MLME_GET.macCoordShortAddress())
           sfType = INCOMING_SUPERFRAME;
         else
           sfType = OUTGOING_SUPERFRAME;
-      } else if (dstAddrMode == ADDR_MODE_EXTENDED_ADDRESS){
+      } else if (dstAddrMode == ADDR_MODE_EXTENDED_ADDRESS) {
         if (dstAddr.extendedAddress == call MLME_GET.macCoordExtendedAddress())
           sfType = INCOMING_SUPERFRAME;
         else
@@ -137,7 +136,7 @@ implementation
         sfType = INCOMING_SUPERFRAME;
 
       // GTS?
-      if (txOptions & TX_OPTIONS_GTS){
+      if (txOptions & TX_OPTIONS_GTS) {
         if (sfType == INCOMING_SUPERFRAME)
           txStatus = call DeviceCfpTx.transmit(txFrame);
         else
@@ -145,9 +144,8 @@ implementation
 
       // indirect transmission?
       } else if ((txOptions & TX_OPTIONS_INDIRECT) && 
-          call IsSendingBeacons.get() && 
-          (dstAddrMode >= ADDR_MODE_SHORT_ADDRESS)){
-        if (dstAddrMode == ADDR_MODE_SHORT_ADDRESS && dstAddr.shortAddress == 0xFFFF){
+          (dstAddrMode >= ADDR_MODE_SHORT_ADDRESS)) {
+        if (dstAddrMode == ADDR_MODE_SHORT_ADDRESS && dstAddr.shortAddress == 0xFFFF) {
           mhr[MHR_INDEX_FC1] &= ~FC1_ACK_REQUEST;
           txStatus = call BroadcastTx.transmit(txFrame);
         } else
@@ -160,7 +158,7 @@ implementation
         else
           txStatus = call CoordCapTx.transmit(txFrame);
 
-      if (txStatus != IEEE154_SUCCESS){
+      if (txStatus != IEEE154_SUCCESS) {
         call TxFramePool.put(txFrame);
       }
     }
@@ -168,8 +166,7 @@ implementation
   }
 
   command ieee154_status_t MCPS_PURGE.request  (
-                          uint8_t msduHandle
-                        )
+                          uint8_t msduHandle)
   {
     if (call PurgeDirect.purge(msduHandle) == IEEE154_SUCCESS ||
         call PurgeIndirect.purge(msduHandle) == IEEE154_SUCCESS ||
@@ -222,7 +219,7 @@ implementation
 
   message_t* dataReceived(message_t* frame)
   {
-    return signal MCPS_DATA.indication( frame );
+    return signal MCPS_DATA.indication(frame);
   }
 
   void finishTxTransaction(ieee154_txframe_t *txFrame, ieee154_status_t status)
@@ -230,6 +227,7 @@ implementation
     uint8_t handle = txFrame->handle;
     uint32_t txTime = txFrame->metadata->timestamp;
     message_t *msg = (message_t*) ((uint8_t*) txFrame->header - offsetof(message_t, header));
+
     call TxFramePool.put(txFrame);
     signal MCPS_DATA.confirm(msg, handle, status, txTime);
   }
@@ -269,10 +267,10 @@ implementation
                           message_t *msg,
                           uint8_t msduHandle,
                           ieee154_status_t status,
-                          uint32_t Timestamp
-                        ){}
+                          uint32_t Timestamp) {}
 
-  default event message_t* MCPS_DATA.indication ( message_t* frame ){ return frame; }
-  default command ieee154_status_t DeviceCfpTx.transmit(ieee154_txframe_t *data){return IEEE154_INVALID_GTS;}
-  default command ieee154_status_t CoordCfpTx.transmit(ieee154_txframe_t *data){return IEEE154_INVALID_GTS;}
+  default event message_t* MCPS_DATA.indication(message_t* frame) { return frame; }
+  default command ieee154_status_t DeviceCfpTx.transmit(ieee154_txframe_t *data) {return IEEE154_INVALID_GTS;}
+  default command ieee154_status_t BroadcastTx.transmit(ieee154_txframe_t *data) {return IEEE154_INVALID_PARAMETER;}
+  default command ieee154_status_t CoordCfpTx.transmit(ieee154_txframe_t *data) {return IEEE154_INVALID_GTS;}
 }
diff --git a/tos/lib/mac/tkn154/DebugC.nc b/tos/lib/mac/tkn154/DebugC.nc
new file mode 100644 (file)
index 0000000..6af96f4
--- /dev/null
@@ -0,0 +1,48 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+configuration DebugC {
+}
+implementation {
+  components DebugP, LedsC, MainC;
+  DebugP.Boot -> MainC;
+  DebugP.Leds -> LedsC;
+
+#if defined(PLATFORM_TELOSB)
+  components UserButtonC;
+  DebugP.ButtonPressed -> UserButtonC;
+#endif
+}
+
diff --git a/tos/lib/mac/tkn154/DebugP.nc b/tos/lib/mac/tkn154/DebugP.nc
new file mode 100644 (file)
index 0000000..ebeb61a
--- /dev/null
@@ -0,0 +1,169 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "printf.h"
+#include <stdio.h>
+#ifdef __STDC__
+#include <stdarg.h>
+#else
+#include <varargs.h>
+#endif
+#if defined(PLATFORM_TELOSB)
+#include <UserButton.h>
+#endif
+
+module DebugP {
+  uses {
+    interface Boot;
+    interface Leds;
+#if defined(PLATFORM_TELOSB)
+    interface Notify<button_state_t> as ButtonPressed;
+#endif
+  }
+}
+implementation {
+
+  enum {
+    MAX_LEN_FUNNAME = 50,
+    MAX_LEN_FILENAME = 50,
+    NUM_LIST_ENTRIES = 20,
+  };
+
+  typedef struct {
+    const char *filename;
+    uint16_t line;
+    const char *format;
+    uint32_t param[2];
+  } debug_list_entry_t;
+
+  norace debug_list_entry_t m_list[NUM_LIST_ENTRIES];
+  norace uint8_t m_head;
+  norace uint8_t m_tail;
+  norace bool m_overflow;
+
+
+  uint16_t m_assertCounter;
+  norace uint16_t m_assertLine;
+  norace char m_assertFilename[MAX_LEN_FILENAME];
+  norace char m_assertFunction[MAX_LEN_FUNNAME];
+
+  event void Boot.booted() {
+#if defined(PLATFORM_TELOSB)
+    call ButtonPressed.enable();
+#endif
+  }
+
+#if defined(PLATFORM_TELOSB)
+  event void ButtonPressed.notify( button_state_t val )
+  {
+    dbg_serial_flush();
+  }
+#endif
+
+  task void assertFailTask()
+  {
+    if (m_assertCounter == 0) {
+      printf("Assert failed: File: %s, line: %d, function: %s.\n", m_assertFilename, m_assertLine, m_assertFunction);
+      printfflush();
+    }
+    if (m_assertCounter++ < 3000) {
+      call Leds.led0On(); 
+      call Leds.led1On(); 
+      call Leds.led2On(); 
+    } else {
+      call Leds.led0Off();
+      call Leds.led1Off();
+      call Leds.led2Off(); 
+    }
+    if (m_assertCounter > 6000)
+      m_assertCounter = 0;
+    post assertFailTask();
+  }
+
+  void tkn154_assert(bool val, const char *filename, uint16_t line, const char *func) @C() @spontaneous()
+  {
+    if (!val) {
+      if (m_assertLine == 0) {
+        // only catch the first failure, output it periodically
+        m_assertLine = line;
+        strncpy(m_assertFilename, filename, MAX_LEN_FILENAME);
+        strncpy(m_assertFunction, func, MAX_LEN_FUNNAME);
+        post assertFailTask();
+      }
+    }
+  }
+
+  void tkn154_dbg_serial(const char *filename, uint16_t line, ...) @C() @spontaneous()
+  { 
+    // This function must be fast: we just copy the strings and 
+    // output them later in the flush-function 
+
+    if ((m_head + 1) % NUM_LIST_ENTRIES != m_tail) {
+      va_list argp;
+
+      m_list[m_head].filename = filename;
+      m_list[m_head].line = line;
+      va_start(argp, line);
+      m_list[m_head].format = va_arg(argp, char*);
+      m_list[m_head].param[0] = va_arg(argp, uint32_t);
+      m_list[m_head].param[1] = va_arg(argp, uint32_t);
+      va_end(argp);
+      m_head = (m_head  + 1) % NUM_LIST_ENTRIES;
+    } else
+      m_overflow = TRUE;
+  }
+
+  task void serialFlushTask()
+  {
+    if (m_overflow)
+      printf("SERIAL OVERFLOW!\n");
+    if (m_head != m_tail) {
+      printf("%s:%d:", m_list[m_tail].filename, m_list[m_tail].line);
+      printf(m_list[m_tail].format, m_list[m_tail].param[0], m_list[m_tail].param[1]);
+      atomic {
+        if (++m_tail >= NUM_LIST_ENTRIES)
+          m_tail = 0;
+      }
+    }
+    if (m_head != m_tail)
+      post serialFlushTask();
+    printfflush();
+  }
+
+  void tkn154_dbg_serial_flush() @C() @spontaneous()
+  {
+    post serialFlushTask();
+  }
+}
diff --git a/tos/lib/mac/tkn154/DisassociateP.nc b/tos/lib/mac/tkn154/DisassociateP.nc
new file mode 100644 (file)
index 0000000..ad9404e
--- /dev/null
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+
+#include "TKN154_MAC.h"
+
+module DisassociateP
+{
+  provides
+  {
+    interface Init;
+    interface MLME_DISASSOCIATE;
+  } uses {
+
+    interface FrameTx as DisassociationIndirectTx;
+    interface FrameTx as DisassociationDirectTx;
+    interface FrameTx as DisassociationToCoord;
+
+    interface FrameRx as DisassociationDirectRxFromCoord;
+    interface FrameExtracted as DisassociationExtractedFromCoord;
+    interface FrameRx as DisassociationRxFromDevice;
+
+    interface Pool<ieee154_txframe_t> as TxFramePool;
+    interface Pool<ieee154_txcontrol_t> as TxControlPool;
+    interface MLME_GET;
+    interface MLME_SET;
+    interface FrameUtility;
+    interface IEEE154Frame as Frame;
+    interface Get<uint64_t> as LocalExtendedAddress;
+  }
+}
+implementation
+{
+  enum {
+    S_IDLE = 0xFF,
+  };
+  uint8_t m_payloadDisassocRequest[2];
+  uint8_t m_coordAddrMode;
+  bool m_disAssociationOngoing;
+  void resetPanValuesInPib();
+
+  command error_t Init.init()
+  {
+    m_payloadDisassocRequest[0] = S_IDLE;
+    m_coordAddrMode = 0;
+    m_disAssociationOngoing = FALSE;
+    return SUCCESS;
+  }
+
+  /* ------------------- MLME_DISASSOCIATE (initiating) ------------------- */
+
+  command ieee154_status_t MLME_DISASSOCIATE.request  (
+                          uint8_t DeviceAddrMode,
+                          uint16_t DevicePANID,
+                          ieee154_address_t DeviceAddress,
+                          ieee154_disassociation_reason_t DisassociateReason,
+                          bool TxIndirect,
+                          ieee154_security_t *security)
+  {
+    ieee154_status_t status = IEEE154_SUCCESS;
+    ieee154_txframe_t *txFrame=0;
+    ieee154_txcontrol_t *txControl=0;
+    ieee154_address_t srcAddress;
+
+    if (security && security->SecurityLevel)
+      status = IEEE154_UNSUPPORTED_SECURITY;
+    else if (call MLME_GET.macPANId() != DevicePANID || 
+        (DeviceAddrMode != ADDR_MODE_SHORT_ADDRESS && DeviceAddrMode != ADDR_MODE_EXTENDED_ADDRESS))
+      status = IEEE154_INVALID_PARAMETER;
+    else if (m_disAssociationOngoing || !(txFrame = call TxFramePool.get()))
+      status = IEEE154_TRANSACTION_OVERFLOW;
+    else if (!(txControl = call TxControlPool.get())) {
+      call TxFramePool.put(txFrame);
+      status = IEEE154_TRANSACTION_OVERFLOW;
+    } 
+    if (status == IEEE154_SUCCESS) {
+      txFrame->header = &txControl->header;
+      txFrame->metadata = &txControl->metadata;
+      srcAddress.extendedAddress = call LocalExtendedAddress.get();
+      txFrame->headerLen = call FrameUtility.writeHeader(
+          txFrame->header->mhr,
+          DeviceAddrMode,
+          call MLME_GET.macPANId(),
+          &DeviceAddress,
+          ADDR_MODE_EXTENDED_ADDRESS,
+          call MLME_GET.macPANId(),
+          &srcAddress,
+          TRUE);
+      txFrame->header->mhr[MHR_INDEX_FC1] = FC1_ACK_REQUEST | FC1_FRAMETYPE_CMD | FC1_PAN_ID_COMPRESSION;
+      txFrame->header->mhr[MHR_INDEX_FC2] = FC2_SRC_MODE_EXTENDED |
+        (DeviceAddrMode == ADDR_MODE_SHORT_ADDRESS ? FC2_DEST_MODE_SHORT : FC2_DEST_MODE_EXTENDED);
+      m_payloadDisassocRequest[0] = CMD_FRAME_DISASSOCIATION_NOTIFICATION;
+      m_payloadDisassocRequest[1] = DisassociateReason;
+      txFrame->payload = m_payloadDisassocRequest;
+      txFrame->payloadLen = 2;
+      m_disAssociationOngoing = TRUE;
+      if ((DeviceAddrMode == ADDR_MODE_SHORT_ADDRESS &&
+            DeviceAddress.shortAddress == call MLME_GET.macCoordShortAddress()) ||
+          (DeviceAddrMode == ADDR_MODE_EXTENDED_ADDRESS &&
+           DeviceAddress.extendedAddress == call MLME_GET.macCoordExtendedAddress())) {
+        status = call DisassociationToCoord.transmit(txFrame);
+      } else if (TxIndirect) {
+        status = call DisassociationIndirectTx.transmit(txFrame);
+      } else {
+        status = call DisassociationDirectTx.transmit(txFrame);
+      }
+      if (status != IEEE154_SUCCESS) {
+        m_disAssociationOngoing = FALSE;
+        call TxFramePool.put(txFrame);
+        call TxControlPool.put(txControl);
+      }
+    }
+    dbg_serial("DisassociateP", "MLME_DISASSOCIATE.request -> result: %lu\n", (uint32_t) status);
+    return status;
+  }
+
+  event void DisassociationToCoord.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) 
+  { 
+    // transmitted a disassociation notification to our coordinator
+    uint8_t *mhr = MHR(data), srcAddrOffset = 7;
+    uint8_t DeviceAddrMode = (mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) >> FC2_SRC_MODE_OFFSET;
+    uint16_t DevicePANID = *((nxle_uint16_t*) (&(mhr[MHR_INDEX_ADDRESS])));
+    ieee154_address_t DeviceAddress;
+
+    if ((mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_MASK) == FC2_DEST_MODE_EXTENDED)
+      srcAddrOffset += 6;
+    call FrameUtility.convertToNative(&DeviceAddress.extendedAddress, &mhr[srcAddrOffset]);
+    call TxControlPool.put((ieee154_txcontrol_t*) ((uint8_t*) data->header - offsetof(ieee154_txcontrol_t, header)));
+    call TxFramePool.put(data);
+    dbg_serial("DisassociateP", "transmitDone() -> result: %lu\n", (uint32_t) status);
+    m_disAssociationOngoing = FALSE;
+
+    // "[...] even if the acknowledgment is not received, 
+    // the device should consider itself disassociated."  (Sect. 7.5.3.2)
+    if (status == IEEE154_SUCCESS || status == IEEE154_NO_ACK)
+      resetPanValuesInPib();  
+    signal MLME_DISASSOCIATE.confirm(status, DeviceAddrMode, DevicePANID, DeviceAddress);
+  }
+
+  event void DisassociationIndirectTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) 
+  {
+    signal DisassociationDirectTx.transmitDone(data, status);
+  }
+
+  event void DisassociationDirectTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) 
+  { 
+    // transmitted a disassociation notification to a device
+    uint8_t *mhr = MHR(data), dstAddrOffset = 5;
+    uint8_t DeviceAddrMode = (mhr[1] & FC2_DEST_MODE_MASK) >> FC2_DEST_MODE_OFFSET;
+    uint16_t DevicePANID = *((nxle_uint16_t*) (&(mhr[MHR_INDEX_ADDRESS])));
+    ieee154_address_t DeviceAddress;
+
+    call FrameUtility.convertToNative(&DeviceAddress.extendedAddress, &mhr[dstAddrOffset]);
+    call TxControlPool.put((ieee154_txcontrol_t*) ((uint8_t*) data->header - offsetof(ieee154_txcontrol_t, header)));
+    call TxFramePool.put(data);
+    dbg_serial("DisassociateP", "transmitDone() -> result: %lu\n", (uint32_t) status);
+    m_disAssociationOngoing = FALSE;
+
+    // "[...] even if the acknowledgment is not received, 
+    // the device should consider itself disassociated." (Sect. 7.5.3.2)
+    if (status == IEEE154_SUCCESS || status == IEEE154_NO_ACK)
+      resetPanValuesInPib();      
+    signal MLME_DISASSOCIATE.confirm(status, DeviceAddrMode, DevicePANID, DeviceAddress);
+  }
+
+  /* ------------------- MLME_DISASSOCIATE (receiving) ------------------- */
+
+  event message_t* DisassociationDirectRxFromCoord.received(message_t* frame)
+  {
+    // received a disassociation notification from the coordinator (direct tx)
+    ieee154_address_t address;
+
+    address.extendedAddress = call LocalExtendedAddress.get();
+    signal MLME_DISASSOCIATE.indication(address.extendedAddress, frame->data[1], NULL);
+    return frame;
+  }
+
+  event message_t* DisassociationExtractedFromCoord.received(message_t* frame, ieee154_txframe_t *txFrame)
+  {
+    // received a disassociation notification from the coordinator (indirect transmission)
+    return signal DisassociationDirectRxFromCoord.received(frame);
+  }
+
+  event message_t* DisassociationRxFromDevice.received(message_t* frame)
+  {
+    // received a disassociation notification from the device
+    ieee154_address_t address;
+
+    if (call Frame.getSrcAddrMode(frame) == ADDR_MODE_EXTENDED_ADDRESS && 
+        call Frame.getSrcAddr(frame, &address) == SUCCESS)
+      signal MLME_DISASSOCIATE.indication(address.extendedAddress, frame->data[1], NULL);
+    dbg_serial("DisassociateP", "Received disassociation request from %lx\n", (uint32_t) address.shortAddress);
+    return frame;
+  }
+
+  void resetPanValuesInPib()
+  {
+    // "An associated device shall disassociate itself by removing 
+    // all references to the PAN; the MLME shall set macPANId, 
+    // macShortAddress, macAssociatedPANCoord, macCoordShortAddress 
+    // and macCoordExtended- Address to the default values." (Sect. 7.5.3.2) 
+    call MLME_SET.macPANId(IEEE154_DEFAULT_PANID);
+    call MLME_SET.macShortAddress(IEEE154_DEFAULT_SHORTADDRESS);
+    call MLME_SET.macAssociatedPANCoord(IEEE154_DEFAULT_ASSOCIATEDPANCOORD);
+    call MLME_SET.macCoordShortAddress(IEEE154_DEFAULT_COORDSHORTADDRESS);
+    call MLME_SET.macCoordExtendedAddress(0);
+  }
+
+  /* ------------------- Defaults ------------------- */
+
+  default event void MLME_DISASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_disassociation_reason_t DisassociateReason,
+                          ieee154_security_t *security) {}
+
+  default event void MLME_DISASSOCIATE.confirm    (
+                          ieee154_status_t status,
+                          uint8_t DeviceAddrMode,
+                          uint16_t DevicePANID,
+                          ieee154_address_t DeviceAddress) {}
+
+}
diff --git a/tos/lib/mac/tkn154/DispatchQueueP.nc b/tos/lib/mac/tkn154/DispatchQueueP.nc
new file mode 100644 (file)
index 0000000..18731a8
--- /dev/null
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154_MAC.h"
+generic module DispatchQueueP() {
+  provides
+  {
+    interface Init as Reset;
+    interface FrameTx[uint8_t client];
+    interface FrameRx as FrameExtracted[uint8_t client];
+    interface Purge;
+  } uses {
+    interface Queue<ieee154_txframe_t*>;
+    interface FrameTx as FrameTxCsma;
+    interface FrameRx as SubFrameExtracted;
+  }
+}
+implementation
+{
+  task void txTask();
+  bool m_state;
+  uint8_t m_client;
+
+  enum {
+    TX_DONE_PENDING = 0x01,
+    RESET_PENDING = 0x02,
+  };
+
+  bool isTxDonePending() { return (m_state & TX_DONE_PENDING) ? TRUE : FALSE; }
+  void setTxDonePending() { m_state |= TX_DONE_PENDING; }
+  void resetTxDonePending() { m_state &= ~TX_DONE_PENDING; }
+
+  bool isResetPending() { return (m_state & RESET_PENDING) ? TRUE : FALSE; }
+  void setResetPending() { m_state |= RESET_PENDING; }
+  void resetResetPending() { m_state &= ~RESET_PENDING; }
+
+  command error_t Reset.init()
+  {
+    setResetPending();
+    while (call Queue.size()) {
+      ieee154_txframe_t *txFrame = call Queue.dequeue();
+      signal FrameTx.transmitDone[txFrame->client](txFrame, IEEE154_TRANSACTION_OVERFLOW);
+    }
+    resetResetPending();
+    return SUCCESS;
+  }
+
+  command ieee154_status_t FrameTx.transmit[uint8_t client](ieee154_txframe_t *txFrame)
+  {
+    txFrame->client = client;
+    if (isResetPending() || call Queue.enqueue(txFrame) != SUCCESS)
+      return IEEE154_TRANSACTION_OVERFLOW;
+    else {
+      post txTask();
+      return IEEE154_SUCCESS;
+    }
+  }
+
+  task void txTask()
+  {
+    if (!isTxDonePending() && call Queue.size()) {
+      ieee154_txframe_t *txFrame = call Queue.head();
+      if (txFrame->headerLen == 0) { 
+        // was purged
+        call Queue.dequeue();
+        signal Purge.purgeDone(txFrame, IEEE154_SUCCESS);
+        post txTask();
+      }
+      m_client = txFrame->client;
+      setTxDonePending();
+      if (call FrameTxCsma.transmit(txFrame) != IEEE154_SUCCESS)
+        resetTxDonePending();
+    }
+  }
+
+  event void FrameTxCsma.transmitDone(ieee154_txframe_t *txFrame, ieee154_status_t status)
+  {
+    resetTxDonePending();
+    if (!call Queue.size())
+      return; // all frames were spooled out (reset)
+    call Queue.dequeue();
+    signal FrameTx.transmitDone[txFrame->client](txFrame, status);
+    if (IEEE154_BEACON_ENABLED_PAN && status == IEEE154_NO_BEACON) {
+      // this means that we lost sync -> spool out all queued frames 
+      while (call Queue.size()) {
+        ieee154_txframe_t *frame = call Queue.dequeue();
+        signal FrameTx.transmitDone[frame->client](frame, IEEE154_NO_BEACON);
+      }
+    }
+    post txTask();
+  }
+
+  event message_t* SubFrameExtracted.received(message_t* frame)
+  {
+    // this event is signalled when a frame has been received
+    // in response to a data request command frame. The transmitDone 
+    // event will be signalled later
+    return signal FrameExtracted.received[m_client](frame);
+  }
+
+  default event void FrameTx.transmitDone[uint8_t client](ieee154_txframe_t *txFrame, ieee154_status_t status) {}
+
+  command ieee154_status_t Purge.purge(uint8_t msduHandle)
+  {
+    uint8_t qSize = call Queue.size(), i;
+    if (qSize > 1) {
+      for (i=0; i<qSize-1; i++) {
+        ieee154_txframe_t *txFrame = call Queue.element(i);
+        if (((txFrame->header->mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_DATA) &&
+          txFrame->handle == msduHandle) {
+          txFrame->headerLen = 0; // mark as invalid
+          return IEEE154_SUCCESS;
+        }
+      }
+    }
+    return IEEE154_INVALID_HANDLE;
+  }
+  
+  default event void Purge.purgeDone(ieee154_txframe_t *txFrame, ieee154_status_t status) {}
+}
diff --git a/tos/lib/mac/tkn154/DispatchSlottedCsmaP.nc b/tos/lib/mac/tkn154/DispatchSlottedCsmaP.nc
new file mode 100644 (file)
index 0000000..3a173d6
--- /dev/null
@@ -0,0 +1,764 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154_PHY.h"
+#include "TKN154_MAC.h"
+
+
+/** 
+ * This module is responsible for the transmission/reception of DATA and
+ * COMMAND frames in the CAP of beacon-enabled PANs. Its main tasks are
+ * initialization of the parameters of the slotted CSMA-CA algorithm (NB, BE,
+ * etc.), initiating retransmissions and dealing with broadcast transmissions.
+ * It does not implement the actual CSMA-CA algorithm, because due to its
+ * timing requirements the CSMA-CA algorithm is not part of the MAC
+ * implementation but of the chip-specific radio driver.
+ *
+ * This module does slightly different things depending on whether it is the
+ * CAP for an outgoing superframe (sfDirection = OUTGOING_SUPERFRAME), i.e. the
+ * CAP from the perspective of a coordinator after it has transmitted its own
+ * beacon; or for an incoming superframe (sfDirection = INCOMING_SUPERFRAME),
+ * i.e.  the CAP from the perspective of a device after it has received a
+ * beacon from its coordinator. For example, in the CAP a coordinator will
+ * typically listen for incoming frames from the devices, and a device will
+ * typically switch the radio off unless it has a frame to transmit.
+ */
+
+generic module DispatchSlottedCsmaP(uint8_t sfDirection)
+{
+  provides
+  {
+    interface Init as Reset;
+    interface FrameTx as FrameTx;
+    interface FrameRx as FrameRx[uint8_t frameType];
+    interface FrameExtracted as FrameExtracted[uint8_t frameType];
+    interface FrameTxNow as BroadcastTx;
+    interface Notify<bool> as WasRxEnabled;
+  }
+  uses
+  {
+    interface Alarm<TSymbolIEEE802154,uint32_t> as CapEndAlarm;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as BLEAlarm;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as RxWaitAlarm;
+    interface TransferableResource as RadioToken;
+    interface ResourceRequested as RadioTokenRequested;
+    interface SuperframeStructure; 
+    interface GetNow<token_requested_t> as IsRadioTokenRequested;
+    interface GetNow<bool> as IsRxEnableActive; 
+    interface Get<ieee154_txframe_t*> as GetIndirectTxFrame; 
+    interface Notify<bool> as RxEnableStateChange;
+    interface GetNow<bool> as IsTrackingBeacons;
+    interface Notify<const void*> as PIBUpdateMacRxOnWhenIdle;
+    interface FrameUtility;
+    interface SlottedCsmaCa;
+    interface RadioRx;
+    interface RadioOff;
+    interface MLME_GET;
+    interface MLME_SET;
+    interface TimeCalc;
+    interface Leds;
+    interface SetNow<ieee154_cap_frame_backup_t*> as FrameBackup;
+    interface GetNow<ieee154_cap_frame_backup_t*> as FrameRestore;
+    interface SplitControl as TrackSingleBeacon;
+    interface MLME_SYNC_LOSS;
+  }
+}
+implementation
+{
+  typedef enum {
+    SWITCH_OFF,       
+    WAIT_FOR_RXDONE,  
+    WAIT_FOR_TXDONE,  
+    DO_NOTHING,       
+  } next_state_t; 
+
+  typedef enum {
+    INDIRECT_TX_ALARM,
+    BROADCAST_ALARM,
+    NO_ALARM,
+  } rx_alarm_t;
+
+  enum {
+    COORD_ROLE = (sfDirection == OUTGOING_SUPERFRAME),
+    DEVICE_ROLE = !COORD_ROLE,
+    RADIO_CLIENT_CFP = COORD_ROLE ? RADIO_CLIENT_COORDCFP : RADIO_CLIENT_DEVICECFP,
+  };
+
+  /* state / frame management */
+  norace bool m_lock;
+  norace bool m_resume;
+  norace ieee154_txframe_t *m_currentFrame;
+  norace ieee154_txframe_t *m_bcastFrame;
+  norace ieee154_txframe_t *m_lastFrame;
+  norace uint16_t m_remainingBackoff;
+  ieee154_macRxOnWhenIdle_t macRxOnWhenIdle;
+
+  /* variables for the slotted CSMA-CA */
+  norace ieee154_csma_t m_csma;
+  norace ieee154_macMaxBE_t m_BE;
+  norace ieee154_macMaxCSMABackoffs_t m_macMaxCSMABackoffs;
+  norace ieee154_macMaxBE_t m_macMaxBE;
+  norace ieee154_macMaxFrameRetries_t m_macMaxFrameRetries;
+  norace ieee154_status_t m_txStatus;
+  norace uint32_t m_transactionTime;
+  norace bool m_indirectTxPending = FALSE;
+  norace bool m_broadcastRxPending;
+  norace ieee154_macMaxFrameTotalWaitTime_t m_macMaxFrameTotalWaitTime;
+
+  /* function / task prototypes */
+  void stopAllAlarms();
+  next_state_t tryReceive();
+  next_state_t tryTransmit();
+  next_state_t trySwitchOff();
+  void backupCurrentFrame();
+  void restoreFrameFromBackup();  
+  void updateState();
+  void setCurrentFrame(ieee154_txframe_t *frame);
+  void signalTxBroadcastDone(ieee154_txframe_t *frame, ieee154_status_t error);
+  task void signalTxDoneTask();
+  task void setupTxBroadcastTask();
+  task void wasRxEnabledTask();
+
+#ifdef TKN154_DEBUG
+  enum {
+    HEADER_STR_LEN = 27,
+    DBG_STR_SIZE = 250,
+  };
+  norace uint16_t m_dbgNumEntries;
+  norace char m_dbgStr[HEADER_STR_LEN + DBG_STR_SIZE] = "updateState() transitions: ";
+  void dbg_push_state(uint8_t state) {
+    if (m_dbgNumEntries < DBG_STR_SIZE-3)
+      m_dbgStr[HEADER_STR_LEN + m_dbgNumEntries++] = '0' + state; 
+  }
+  void dbg_flush_state() {
+    m_dbgStr[HEADER_STR_LEN + m_dbgNumEntries++] = '\n'; 
+    m_dbgStr[HEADER_STR_LEN + m_dbgNumEntries++] = 0; 
+    dbg_serial("DispatchSlottedCsmaP",m_dbgStr);
+    m_dbgNumEntries = 0;
+  }
+#else 
+#define dbg_push_state(X)
+#define dbg_flush_state()
+#endif
+
+  error_t reset(error_t error)
+  {
+    if (call RadioToken.isOwner()) // internal error! this must not happen!
+      return FAIL;
+    if (m_currentFrame)
+      signal FrameTx.transmitDone(m_currentFrame, error);
+    if (m_lastFrame)
+      signal FrameTx.transmitDone(m_lastFrame, error);
+    if (m_bcastFrame)
+      signalTxBroadcastDone(m_bcastFrame, error);
+    m_currentFrame = m_lastFrame = m_bcastFrame = NULL;
+    m_macMaxFrameTotalWaitTime = call MLME_GET.macMaxFrameTotalWaitTime();
+    stopAllAlarms();
+    return SUCCESS;
+  }
+
+  command error_t Reset.init()
+  {
+    return reset(IEEE154_TRANSACTION_OVERFLOW);
+  }
+
+  event void MLME_SYNC_LOSS.indication (
+                          ieee154_status_t lossReason,
+                          uint16_t PANId,
+                          uint8_t LogicalChannel,
+                          uint8_t ChannelPage,
+                          ieee154_security_t *security
+                        )
+  {
+    // we lost sync to the coordinator -> spool out current packet
+    reset(IEEE154_NO_BEACON);
+  }
+
+  async event void RadioToken.transferredFrom(uint8_t fromClient)
+  {
+    // we got the token, i.e. CAP has just started
+    uint32_t capDuration = (uint32_t) call SuperframeStructure.numCapSlots() * 
+      (uint32_t) call SuperframeStructure.sfSlotDuration();
+    uint16_t guardTime = call SuperframeStructure.guardTime();
+
+    dbg_serial("DispatchSlottedCsmaP", "Got token, remaining CAP time: %lu\n", 
+        call SuperframeStructure.sfStartTime() + capDuration - guardTime - call CapEndAlarm.getNow());
+
+    if (capDuration < guardTime) {
+      // CAP is too short to do anything useful
+      dbg_serial("DispatchSlottedCsmaP", "CAP too short!\n");
+      call RadioToken.transferTo(RADIO_CLIENT_CFP);
+      return;
+    } else {
+      capDuration -= guardTime;
+      if (DEVICE_ROLE)
+        m_broadcastRxPending = call SuperframeStructure.isBroadcastPending();
+      else { 
+        // COORD_ROLE
+        if (m_bcastFrame != NULL) {
+          // we have to transmit a broadcast frame immediately; this
+          // may require to a backup of the previously active frame 
+          // and a reinitializing the CSMA parameters -> will do it 
+          // in task context and then continue
+          m_lock = TRUE;
+          post setupTxBroadcastTask(); 
+          dbg_serial("DispatchSlottedCsmaP", "Preparing broadcast...\n");
+        }
+      }
+      call CapEndAlarm.startAt(call SuperframeStructure.sfStartTime(), capDuration);
+      if (call SuperframeStructure.battLifeExtDuration() > 0)
+        call BLEAlarm.startAt(call SuperframeStructure.sfStartTime(), call SuperframeStructure.battLifeExtDuration());
+    }
+    updateState();
+  }
+
+  command ieee154_status_t FrameTx.transmit(ieee154_txframe_t *frame)
+  {
+    if (m_currentFrame != NULL) {
+      // we've not finished transmitting the current frame yet
+      dbg_serial("DispatchSlottedCsmaP", "Overflow\n");
+      return IEEE154_TRANSACTION_OVERFLOW;
+    } else {
+      setCurrentFrame(frame);
+      dbg("DispatchSlottedCsmaP", "New frame to transmit, DSN: %lu\n", (uint32_t) MHR(frame)[MHR_INDEX_SEQNO]);
+      // a beacon must be found before transmitting in a beacon-enabled PAN
+      if (DEVICE_ROLE && !call IsTrackingBeacons.getNow()) {
+        call TrackSingleBeacon.start();
+        dbg_serial("DispatchSlottedCsmaP", "Tracking single beacon now\n");
+        // we'll get the Token after a beacon was found or a SYNC_LOSS event
+        // if none was found during the next aBaseSuperframeDuration*(2n+1) symbols  
+      }
+      updateState();
+      return IEEE154_SUCCESS;
+    }
+  }
+
+  event void TrackSingleBeacon.startDone(error_t error)
+  {
+    if (error != SUCCESS) // beacon could not be tracked
+      reset(IEEE154_NO_BEACON);
+    // else: we'll get the RadioToken and continue as usual ...
+  }
+
+  task void setupTxBroadcastTask()
+  {
+    ieee154_macDSN_t tmp;
+    ieee154_txframe_t *oldFrame = m_currentFrame;
+    if (COORD_ROLE) {
+      if (m_bcastFrame != NULL) {
+        // broadcasts should be transmitted *immediately* after the beacon,  
+        // which may interrupt a pending transmit operation from the previous
+        // CAP; back up the last active frame configuration (may be none)    
+        // and restore it after the broadcast frame has been transmitted;    
+        // do this through interfaces and don't wire them for DEVICE_ROLE,   
+        // so we don't waste the RAM of devices
+        backupCurrentFrame();
+        setCurrentFrame(m_bcastFrame);
+        if (oldFrame) {
+          // now the sequence number are out of order... swap them back
+          tmp = m_bcastFrame->header->mhr[MHR_INDEX_SEQNO];
+          m_bcastFrame->header->mhr[MHR_INDEX_SEQNO] = 
+            oldFrame->header->mhr[MHR_INDEX_SEQNO];
+          oldFrame->header->mhr[MHR_INDEX_SEQNO] = tmp;
+        }
+      }
+    }
+    m_lock = FALSE;
+    updateState(); 
+  }
+
+  void setCurrentFrame(ieee154_txframe_t *frame)
+  {
+    ieee154_macDSN_t dsn = call MLME_GET.macDSN();
+    frame->header->mhr[MHR_INDEX_SEQNO] = dsn++;
+    call MLME_SET.macDSN(dsn);
+    m_csma.NB = 0;
+    m_csma.macMaxCsmaBackoffs = m_macMaxCSMABackoffs = call MLME_GET.macMaxCSMABackoffs();
+    m_csma.macMaxBE = m_macMaxBE = call MLME_GET.macMaxBE();
+    m_csma.BE = call MLME_GET.macMinBE();
+    if (call MLME_GET.macBattLifeExt() && m_csma.BE > 2)
+      m_csma.BE = 2;
+    m_BE = m_csma.BE;
+    if (COORD_ROLE && call GetIndirectTxFrame.get() == frame)
+      m_macMaxFrameRetries =  0; // this is an indirect transmissions (never retransmit)
+    else
+      m_macMaxFrameRetries =  call MLME_GET.macMaxFrameRetries();
+    m_transactionTime = IEEE154_SHR_DURATION + 
+      (frame->headerLen + frame->payloadLen + 2) * IEEE154_SYMBOLS_PER_OCTET; // extra 2 for CRC
+    if (frame->header->mhr[MHR_INDEX_FC1] & FC1_ACK_REQUEST)
+      m_transactionTime += (IEEE154_aTurnaroundTime + IEEE154_aUnitBackoffPeriod + 
+          11 * IEEE154_SYMBOLS_PER_OCTET); // 11 byte for the ACK PPDU
+    // if (frame->headerLen + frame->payloadLen > IEEE154_aMaxSIFSFrameSize) 
+    //  m_transactionTime += call MLME_GET.macMinLIFSPeriod(); 
+    // else 
+    //  m_transactionTime += call MLME_GET.macMinSIFSPeriod(); 
+    m_macMaxFrameTotalWaitTime = call MLME_GET.macMaxFrameTotalWaitTime();
+    m_currentFrame = frame;
+  }
+  void stopAllAlarms()
+  {
+    call CapEndAlarm.stop();
+    if (DEVICE_ROLE)
+      call RxWaitAlarm.stop();
+    call BLEAlarm.stop();
+  }
+
+  /** 
+   * The updateState() function is called whenever something happened that
+   * might require a state transition; it implements a lock mechanism (m_lock)
+   * to prevent race conditions. Whenever the lock is set a "done"-event (from
+   * the SlottedCsmaCa/RadioRx/RadioOff interface) is pending and will "soon"
+   * unset the lock (and then updateState() will called again).  The
+   * updateState() function decides about the next state by checking a list of
+   * possible current states ordered by priority, e.g. it first always checks
+   * whether the CAP is still active. Calling this function more than necessary
+   * can do no harm.
+   */ 
+
+  void updateState()
+  {
+    uint32_t capDuration; 
+    next_state_t next;
+    atomic {
+      // long atomics are bad... but in this block, once the/ current state has
+      // been determined only one branch will/ be taken (there are no loops)
+      if (m_lock || !call RadioToken.isOwner())
+        return;
+      m_lock = TRUE; // lock
+      capDuration = (uint32_t) call SuperframeStructure.numCapSlots() * 
+               (uint32_t) call SuperframeStructure.sfSlotDuration();
+
+      // Check 1: has the CAP finished?
+      if ((call TimeCalc.hasExpired(call SuperframeStructure.sfStartTime(), 
+                capDuration - call SuperframeStructure.guardTime()) ||
+          !call CapEndAlarm.isRunning())) {
+        dbg_push_state(1);
+        if (call RadioOff.isOff()) {
+          stopAllAlarms();  // may still fire, but is locked through isOwner()
+          if (DEVICE_ROLE && m_indirectTxPending)
+            signal RxWaitAlarm.fired();
+          m_broadcastRxPending = FALSE;
+          if (COORD_ROLE && m_bcastFrame) {
+            // didn't manage to transmit a broadcast
+            restoreFrameFromBackup();
+            signalTxBroadcastDone(m_bcastFrame, IEEE154_CHANNEL_ACCESS_FAILURE);
+            m_bcastFrame = NULL;
+          }
+          m_lock = FALSE; // unlock
+          dbg_flush_state();
+          dbg_serial("DispatchSlottedCsmaP", "Handing over to CFP.\n");
+          call RadioToken.transferTo(RADIO_CLIENT_CFP);
+          return;
+        } else 
+          next = SWITCH_OFF;
+      }
+
+      // Check 2: should a broadcast frame be received/transmitted
+      // immediately at the start of CAP?
+      else if (DEVICE_ROLE && m_broadcastRxPending) {
+        // receive a broadcast from coordinator
+        dbg_push_state(2);
+        next = tryReceive();
+      } else if (COORD_ROLE && m_bcastFrame) {
+        dbg_push_state(2);
+        next = tryTransmit();
+      }
+
+      // Check 3: was an indirect transmission successfully started 
+      // and are we now waiting for a frame from the coordinator?
+      else if (DEVICE_ROLE && m_indirectTxPending) {
+        dbg_push_state(3);
+        next = tryReceive();
+      }
+
+      // Check 4: is some other operation (like MLME-SCAN or MLME-RESET) pending? 
+      else if (call IsRadioTokenRequested.getNow()) {
+        dbg_push_state(4);
+        if (call RadioOff.isOff()) {
+          stopAllAlarms();  // may still fire, but is locked through isOwner()
+          // nothing more to do... just release the Token
+          m_lock = FALSE; // unlock
+          dbg_serial("DispatchSlottedCsmaP", "Token requested: Handing over to CFP.\n");
+          call RadioToken.release();
+          return;
+        } else 
+          next = SWITCH_OFF;
+      }
+
+      // Check 5: is battery life extension (BLE) active and 
+      // has the BLE period expired?
+      else if (call SuperframeStructure.battLifeExtDuration() > 0 &&
+          call TimeCalc.hasExpired(call SuperframeStructure.sfStartTime(), 
+            call SuperframeStructure.battLifeExtDuration()) &&
+          !call IsRxEnableActive.getNow() && !macRxOnWhenIdle) {
+        dbg_push_state(5);
+        next = trySwitchOff();
+      }
+
+      // Check 6: is there a frame ready to transmit?
+      else if (m_currentFrame != NULL) {
+        dbg_push_state(6);
+        next = tryTransmit();
+      }
+
+      // Check 7: should we be in receive mode?
+      else if (COORD_ROLE || call IsRxEnableActive.getNow() || macRxOnWhenIdle) {
+        dbg_push_state(7);
+        next = tryReceive();
+        if (next == DO_NOTHING) {
+          // if there was an active MLME_RX_ENABLE.request then we'll
+          // inform the next higher layer that radio is now in Rx mode
+          post wasRxEnabledTask();
+        }
+      }
+
+      // Check 8: just make sure the radio is switched off  
+      else {
+        dbg_push_state(8);
+        next = trySwitchOff();
+      }
+
+      // if there is nothing to do, then we must clear the lock
+      if (next == DO_NOTHING)
+        m_lock = FALSE;
+    } // atomic
+
+    // put next state in operation (possibly keeping the lock)
+    switch (next)
+    {
+      case SWITCH_OFF: ASSERT(call RadioOff.off() == SUCCESS); break;
+      case WAIT_FOR_RXDONE: break;
+      case WAIT_FOR_TXDONE: break;
+      case DO_NOTHING: break;
+    }
+  }
+  
+  next_state_t tryTransmit()
+  {
+    // tries to transmit m_currentFrame
+    uint32_t capDuration = (uint32_t) call SuperframeStructure.numCapSlots() * 
+      (uint32_t) call SuperframeStructure.sfSlotDuration();
+    next_state_t next;
+
+    if (!call RadioOff.isOff())
+      next = SWITCH_OFF;
+    else {
+      uint32_t dtMax = capDuration - call SuperframeStructure.guardTime() - m_transactionTime;
+      // round to backoff boundary
+      dtMax = dtMax + (IEEE154_aUnitBackoffPeriod - (dtMax % IEEE154_aUnitBackoffPeriod));
+      if (dtMax > capDuration)
+        dtMax = 0;
+      if (call SuperframeStructure.battLifeExtDuration() > 0) {
+        // battery life extension
+        uint16_t bleLen = call SuperframeStructure.battLifeExtDuration();
+        if (bleLen < dtMax)
+          dtMax = bleLen;
+      }
+      if (call TimeCalc.hasExpired(call SuperframeStructure.sfStartTime(), dtMax))
+        next = DO_NOTHING; // frame doesn't fit in the remaining CAP
+      else {
+        error_t res;
+        res = call SlottedCsmaCa.transmit(m_currentFrame, &m_csma, 
+                   call SuperframeStructure.sfStartTimeRef(), dtMax, m_resume, m_remainingBackoff);
+        dbg("DispatchSlottedCsmaP", "SlottedCsmaCa.transmit() -> %lu\n", (uint32_t) res);
+        next = WAIT_FOR_TXDONE; // this will NOT clear the lock
+      }
+    }
+    return next;
+  }
+
+  next_state_t tryReceive()
+  {
+    next_state_t next;
+    if (call RadioRx.isReceiving())
+      next = DO_NOTHING;
+    else if (!call RadioOff.isOff())
+      next = SWITCH_OFF;
+    else {
+      call RadioRx.enableRx(0, 0);
+      next = WAIT_FOR_RXDONE;
+    }
+    return next;
+  }
+
+  next_state_t trySwitchOff()
+  {
+    next_state_t next;
+    if (call RadioOff.isOff())
+      next = DO_NOTHING;
+    else
+      next = SWITCH_OFF;
+    return next;
+  }
+
+  async event void RadioOff.offDone() 
+  { 
+    m_lock = FALSE; 
+    updateState();
+  }
+
+  async event void RadioRx.enableRxDone() 
+  { 
+    if (DEVICE_ROLE && (m_indirectTxPending || m_broadcastRxPending))
+      call RxWaitAlarm.start(m_macMaxFrameTotalWaitTime);
+    m_lock = FALSE; 
+    updateState();
+  }
+
+  async event void CapEndAlarm.fired() { 
+    dbg_serial("DispatchSlottedCsmaP", "CapEndAlarm.fired()\n");
+    updateState();
+  }
+  async event void BLEAlarm.fired() { updateState();}
+  event void RxEnableStateChange.notify(bool whatever) { updateState();}
+  event void PIBUpdateMacRxOnWhenIdle.notify( const void* val ) {
+    atomic macRxOnWhenIdle = *((ieee154_macRxOnWhenIdle_t*) val);
+    updateState();
+  }
+
+  async event void RxWaitAlarm.fired() 
+  { 
+    if (DEVICE_ROLE && (m_indirectTxPending || m_broadcastRxPending))
+      atomic {
+        if (m_indirectTxPending) {
+          m_indirectTxPending = FALSE; 
+          post signalTxDoneTask(); 
+        } else if (m_broadcastRxPending) {
+          m_broadcastRxPending = FALSE;
+          updateState();
+        }
+      }
+  }
+
+  async event void SlottedCsmaCa.transmitDone(ieee154_txframe_t *frame, ieee154_csma_t *csma, 
+      bool ackPendingFlag,  uint16_t remainingBackoff, error_t result)
+  {
+    bool done = TRUE;
+    dbg("DispatchSlottedCsmaP", "SlottedCsmaCa.transmitDone() -> %lu\n", (uint32_t) result);
+    m_resume = FALSE;
+
+    switch (result)
+    {
+      case SUCCESS:
+        // frame was successfully transmitted, if ACK was requested
+        // then a matching ACK was successfully received as well   
+        m_txStatus = IEEE154_SUCCESS;
+        if (DEVICE_ROLE && frame->payload[0] == CMD_FRAME_DATA_REQUEST &&
+            ((frame->header->mhr[MHR_INDEX_FC1]) & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_CMD) {
+          // this was a data request frame
+          m_txStatus = IEEE154_NO_DATA; // pessimistic 
+          if (ackPendingFlag) {
+            // the coordinator has data for us; switch to Rx 
+            // to complete the indirect transmission         
+            m_indirectTxPending = TRUE;
+            m_lastFrame = m_currentFrame;
+            m_currentFrame = NULL;
+            ASSERT(call RadioRx.enableRx(0, 0) == SUCCESS);
+            return;
+          }
+        }
+        break;
+      case FAIL:
+        // The CSMA-CA algorithm failed: the frame was not transmitted,
+        // because channel was never idle                              
+        m_txStatus = IEEE154_CHANNEL_ACCESS_FAILURE;
+        break;
+      case ENOACK:
+        // frame was transmitted, but we didn't receive an ACK (although
+        // we requested an one). note: coordinator never retransmits an 
+        // indirect transmission (see above) 
+        if (m_macMaxFrameRetries > 0) {
+          // retransmit: reinitialize CSMA-CA parameters
+          done = FALSE;
+          m_csma.NB = 0;
+          m_csma.macMaxCsmaBackoffs = m_macMaxCSMABackoffs;
+          m_csma.macMaxBE = m_macMaxBE;
+          m_csma.BE = m_BE;
+          m_macMaxFrameRetries -= 1;
+        } else
+          m_txStatus = IEEE154_NO_ACK;
+        break;
+      case EINVAL: // DEBUG!!!
+        dbg_serial("DispatchSlottedCsmaP", "EINVAL returned by transmitDone()!\n");
+        // fall through
+      case ERETRY:
+        // frame was not transmitted, because the transaction does not
+        // fit in the remaining CAP (in beacon-enabled PANs only)
+        dbg_serial("DispatchSlottedCsmaP", "Transaction didn't fit, current BE: %lu\n", (uint32_t) csma->BE);
+        m_resume = TRUE;
+        m_remainingBackoff = remainingBackoff;
+        done = FALSE;
+        m_lock = FALSE; // debug! problem: if CAP endalarm has fired it's a deadlock!
+        if (!call CapEndAlarm.isRunning())
+          updateState();
+        return;
+        break;
+      default: 
+        ASSERT(0);
+        break;
+    }
+
+    if (COORD_ROLE && frame == m_bcastFrame) {
+      // always signal result of broadcast transmissions immediately 
+      restoreFrameFromBackup();
+      signalTxBroadcastDone(m_bcastFrame, (!done) ? IEEE154_CHANNEL_ACCESS_FAILURE : m_txStatus);
+      m_bcastFrame = NULL;
+    } else if (done) {
+      m_lastFrame = m_currentFrame;
+      m_currentFrame = NULL;
+      post signalTxDoneTask();
+    }  
+
+    m_lock = FALSE;
+    updateState();
+  }
+
+  task void signalTxDoneTask()
+  {
+    ieee154_txframe_t *lastFrame = m_lastFrame;
+    ieee154_status_t status = m_txStatus;
+    m_indirectTxPending = FALSE;
+    m_lastFrame = NULL; // only now can the next transmission can begin 
+    if (lastFrame) {
+      dbg("DispatchSlottedCsmaP", "Transmit done, DSN: %lu, result: 0x%lx\n", 
+          (uint32_t) MHR(lastFrame)[MHR_INDEX_SEQNO], (uint32_t) status);
+      signal FrameTx.transmitDone(lastFrame, status);
+    }
+    updateState();
+  }
+
+  event message_t* RadioRx.received(message_t* frame, const ieee154_timestamp_t *timestamp)
+  {
+    // received a frame -> find out frame type and
+    // signal it to responsible client component
+    uint8_t *payload = (uint8_t *) frame->data;
+    uint8_t *mhr = MHR(frame);
+    uint8_t frameType = mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK;
+
+    if (frameType == FC1_FRAMETYPE_CMD)
+      frameType += payload[0];
+    dbg("DispatchSlottedCsmaP", "Received frame, DSN: %lu, type: 0x%lu\n", 
+        (uint32_t) mhr[MHR_INDEX_SEQNO], (uint32_t) frameType);
+    atomic {
+      if (DEVICE_ROLE && (m_indirectTxPending || m_broadcastRxPending)) {
+        message_t* frameBuf;
+        call RxWaitAlarm.stop();
+        // TODO: check the following: 
+        // is this frame from our coordinator? hmm... we cannot say/ with
+        // certainty, because we might only know either the  coordinator
+        // extended or short address (and the frame could/ have been sent
+        // with the other addressing mode) ??
+        m_txStatus = IEEE154_SUCCESS;
+        if (m_indirectTxPending)
+          frameBuf = signal FrameExtracted.received[frameType](frame, m_lastFrame); // indirect tx from coord
+        else
+          frameBuf = signal FrameRx.received[frameType](frame); // broadcast from coordinator
+        signal RxWaitAlarm.fired();
+        return frameBuf;
+      } else
+        return signal FrameRx.received[frameType](frame);
+    }
+  }
+
+  void backupCurrentFrame()
+  {
+    ieee154_cap_frame_backup_t backup = {m_currentFrame, m_csma, m_transactionTime};
+    call FrameBackup.setNow(&backup);
+  }
+
+  void restoreFrameFromBackup()
+  {
+    ieee154_cap_frame_backup_t *backup = call FrameRestore.getNow();
+    if (backup != NULL) {
+      m_currentFrame = backup->frame;
+      memcpy(&m_csma, &backup->csma, sizeof(ieee154_csma_t));
+      m_transactionTime = backup->transactionTime;
+    }
+  }
+
+  async command ieee154_status_t BroadcastTx.transmitNow(ieee154_txframe_t *frame) 
+  {
+    // if this command is called then it is (MUST be) called only just before
+    // the token is transferred to this component and it is then called
+    // only once per CAP (max. one broadcast is allowed after a beacon
+    // transmission)
+    atomic {
+      if (!call RadioToken.isOwner() && m_bcastFrame == NULL) {
+        m_bcastFrame = frame;
+        return IEEE154_SUCCESS;
+      } else {
+        ASSERT(0);
+        return IEEE154_TRANSACTION_OVERFLOW;
+      }
+    }
+  }
+
+  void signalTxBroadcastDone(ieee154_txframe_t *frame, ieee154_status_t error)
+  {
+    signal BroadcastTx.transmitNowDone(frame, error);
+  }
+
+  task void wasRxEnabledTask()
+  {
+    signal WasRxEnabled.notify(TRUE);
+  }
+
+  event void RadioToken.granted()
+  {
+    ASSERT(0); // should never happen
+  }
+
+  default event void FrameTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) {}
+  default event message_t* FrameRx.received[uint8_t client](message_t* data) {return data;}
+  default async command bool IsRxEnableActive.getNow() {return FALSE;}
+
+  default async command void RxWaitAlarm.start(uint32_t dt) {ASSERT(0);}
+  default async command void RxWaitAlarm.stop() {ASSERT(0);}
+  default async command void RxWaitAlarm.startAt(uint32_t t0, uint32_t dt) {ASSERT(0);}
+  
+  default async command bool SuperframeStructure.isBroadcastPending() { return FALSE;}
+  default async event void BroadcastTx.transmitNowDone(ieee154_txframe_t *frame, ieee154_status_t status) {}
+  default event message_t* FrameExtracted.received[uint8_t client](message_t* msg, ieee154_txframe_t *txFrame) {return msg;}
+  default async command error_t FrameBackup.setNow(ieee154_cap_frame_backup_t* val) {return FAIL;}
+  default async command ieee154_cap_frame_backup_t* FrameRestore.getNow() {return NULL;}
+  event void TrackSingleBeacon.stopDone(error_t error){}
+  default command error_t TrackSingleBeacon.start() {if (DEVICE_ROLE) ASSERT(0); return SUCCESS;}
+
+  command error_t WasRxEnabled.enable() {return FAIL;}
+  command error_t WasRxEnabled.disable() {return FAIL;}
+  async event void RadioTokenRequested.requested(){ updateState(); }
+  async event void RadioTokenRequested.immediateRequested(){ updateState(); }
+}
diff --git a/tos/lib/mac/tkn154/DispatchUnslottedCsmaP.nc b/tos/lib/mac/tkn154/DispatchUnslottedCsmaP.nc
new file mode 100644 (file)
index 0000000..adde079
--- /dev/null
@@ -0,0 +1,533 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154_PHY.h"
+#include "TKN154_MAC.h"
+
+/** 
+ * This module is responsible for the transmission/reception of DATA and
+ * COMMAND frames in a nonbeacon-enabled PAN. Its main tasks are initialization
+ * of the parameters of the unslotted CSMA-CA algorithm (NB, BE, etc.),
+ * initiating retransmissions and managing requests for enabling the receiver
+ * for a finite period of time. It does not implement the actual CSMA-CA
+ * algorithm, because due to its timing requirements the CSMA-CA algorithm is
+ * not part of the MAC implementation but of the chip-specific radio driver.
+ */
+
+module DispatchUnslottedCsmaP
+{
+  provides
+  {
+    interface Init as Reset;
+    interface MLME_START;
+    interface FrameTx as FrameTx;
+    interface FrameRx as FrameRx[uint8_t frameType];
+    interface FrameExtracted as FrameExtracted[uint8_t frameType];
+    interface Notify<bool> as WasRxEnabled;
+  }
+  uses
+  {
+    interface Timer<TSymbolIEEE802154> as IndirectTxWaitTimer;
+    interface TransferableResource as RadioToken;
+    interface ResourceRequested as RadioTokenRequested;
+    interface GetNow<token_requested_t> as IsRadioTokenRequested;
+    interface GetNow<bool> as IsRxEnableActive; 
+    interface Set<ieee154_macSuperframeOrder_t> as SetMacSuperframeOrder;
+    interface Set<ieee154_macPanCoordinator_t> as SetMacPanCoordinator;     
+    interface Get<ieee154_txframe_t*> as GetIndirectTxFrame; 
+    interface Notify<bool> as RxEnableStateChange;
+    interface Notify<const void*> as PIBUpdateMacRxOnWhenIdle;
+    interface FrameUtility;
+    interface UnslottedCsmaCa;
+    interface RadioRx;
+    interface RadioOff;
+    interface MLME_GET;
+    interface MLME_SET;
+    interface TimeCalc;
+    interface Leds;
+  }
+}
+implementation
+{
+  typedef enum {
+    SWITCH_OFF,       
+    WAIT_FOR_RXDONE,  
+    WAIT_FOR_TXDONE,  
+    DO_NOTHING,       
+  } next_state_t; 
+
+  typedef enum {
+    INDIRECT_TX_ALARM,
+    NO_ALARM,
+  } rx_alarm_t;
+
+  /* state / frame management */
+  norace bool m_lock;
+  norace bool m_resume;
+  norace ieee154_txframe_t *m_currentFrame;
+  norace ieee154_txframe_t *m_lastFrame;
+  norace ieee154_macRxOnWhenIdle_t m_macRxOnWhenIdle;
+
+  /* variables for the unslotted CSMA-CA */
+  norace ieee154_csma_t m_csma;
+  norace ieee154_macMaxBE_t m_BE;
+  norace ieee154_macMaxCSMABackoffs_t m_macMaxCSMABackoffs;
+  norace ieee154_macMaxBE_t m_macMaxBE;
+  norace ieee154_macMaxFrameRetries_t m_macMaxFrameRetries;
+  norace ieee154_status_t m_txStatus;
+  norace uint32_t m_transactionTime;
+  norace bool m_indirectTxPending = FALSE;
+
+  /* function / task prototypes */
+  next_state_t tryReceive();
+  next_state_t tryTransmit();
+  next_state_t trySwitchOff();
+  void backupCurrentFrame();
+  void restoreFrameFromBackup();  
+  void updateState();
+  void setCurrentFrame(ieee154_txframe_t *frame);
+  void signalTxBroadcastDone(ieee154_txframe_t *frame, ieee154_status_t error);
+  task void signalTxDoneTask();
+  task void wasRxEnabledTask();
+  task void startIndirectTxTimerTask();
+  task void signalStartConfirmTask();
+
+  command error_t Reset.init()
+  {
+    if (m_currentFrame)
+      signal FrameTx.transmitDone(m_currentFrame, IEEE154_TRANSACTION_OVERFLOW);
+    if (m_lastFrame)
+      signal FrameTx.transmitDone(m_lastFrame, IEEE154_TRANSACTION_OVERFLOW);
+    m_currentFrame = m_lastFrame = NULL;
+    call IndirectTxWaitTimer.stop();
+    return SUCCESS;
+  }
+
+  command ieee154_status_t MLME_START.request  (
+                          uint16_t panID,
+                          uint8_t logicalChannel,
+                          uint8_t channelPage,
+                          uint32_t startTime,
+                          uint8_t beaconOrder,
+                          uint8_t superframeOrder,
+                          bool panCoordinator,
+                          bool batteryLifeExtension,
+                          bool coordRealignment,
+                          ieee154_security_t *coordRealignSecurity,
+                          ieee154_security_t *beaconSecurity)
+  {
+    ieee154_status_t status;
+    ieee154_macShortAddress_t shortAddress = call MLME_GET.macShortAddress();
+
+    // check parameters
+    if ((coordRealignSecurity && coordRealignSecurity->SecurityLevel) ||
+        (beaconSecurity && beaconSecurity->SecurityLevel))
+      status = IEEE154_UNSUPPORTED_SECURITY;
+    else if (shortAddress == 0xFFFF) 
+      status = IEEE154_NO_SHORT_ADDRESS;
+    else if (logicalChannel > 26 ||
+        (channelPage != IEEE154_SUPPORTED_CHANNELPAGE) ||
+        !(IEEE154_SUPPORTED_CHANNELS & ((uint32_t) 1 << logicalChannel)))
+      status =  IEEE154_INVALID_PARAMETER;
+    else if (beaconOrder != 15) 
+      status = IEEE154_INVALID_PARAMETER;
+    else {
+      call MLME_SET.macPANId(panID);
+      call MLME_SET.phyCurrentChannel(logicalChannel);
+      call MLME_SET.macBeaconOrder(beaconOrder);
+      call SetMacPanCoordinator.set(panCoordinator);
+      //TODO: check realignment
+      post signalStartConfirmTask();
+      status = IEEE154_SUCCESS;
+    }      
+    dbg_serial("DispatchUnslottedCsmaP", "MLME_START.request -> result: %lu\n", (uint32_t) status);
+    return status;
+  }
+
+  task void signalStartConfirmTask()
+  {
+    signal MLME_START.confirm(IEEE154_SUCCESS);
+  }
+
+  command ieee154_status_t FrameTx.transmit(ieee154_txframe_t *frame)
+  {
+    if (m_currentFrame != NULL) {
+      // we've not finished transmitting the current frame yet
+      dbg_serial("DispatchUnslottedCsmaP", "Overflow\n");
+      return IEEE154_TRANSACTION_OVERFLOW;
+    } else {
+      setCurrentFrame(frame);
+      if (call RadioToken.isOwner())
+        updateState();
+      else
+        call RadioToken.request();      
+      return IEEE154_SUCCESS;
+    }
+  }
+
+  event void RadioToken.granted()
+  {
+    updateState();
+  }
+
+  void setCurrentFrame(ieee154_txframe_t *frame)
+  {
+    if (frame->header->mhr[MHR_INDEX_FC1] != FC1_FRAMETYPE_BEACON) { 
+      // set the sequence number for command/data frame
+      ieee154_macDSN_t dsn = call MLME_GET.macDSN();
+      frame->header->mhr[MHR_INDEX_SEQNO] = dsn++;
+      call MLME_SET.macDSN(dsn);
+    } else {
+      // set the sequence number for beacon frame
+      ieee154_macBSN_t bsn = call MLME_GET.macBSN(); 
+      frame->header->mhr[MHR_INDEX_SEQNO] = bsn++;
+      call MLME_SET.macBSN(bsn);
+    }    
+    m_csma.NB = 0;
+    m_csma.macMaxCsmaBackoffs = m_macMaxCSMABackoffs = call MLME_GET.macMaxCSMABackoffs();
+    m_csma.macMaxBE = m_macMaxBE = call MLME_GET.macMaxBE();
+    m_csma.BE = call MLME_GET.macMinBE();
+    if (call MLME_GET.macBattLifeExt() && m_csma.BE > 2)
+      m_csma.BE = 2;
+    m_BE = m_csma.BE;
+    if (call GetIndirectTxFrame.get() == frame)
+      m_macMaxFrameRetries =  0; // this is an indirect transmissions (never retransmit)
+    else
+      m_macMaxFrameRetries =  call MLME_GET.macMaxFrameRetries();
+    m_transactionTime = IEEE154_SHR_DURATION + 
+      (frame->headerLen + frame->payloadLen + 2) * IEEE154_SYMBOLS_PER_OCTET; // extra 2 for CRC
+    if (frame->header->mhr[MHR_INDEX_FC1] & FC1_ACK_REQUEST)
+      m_transactionTime += (IEEE154_aTurnaroundTime + IEEE154_aUnitBackoffPeriod + 
+          11 * IEEE154_SYMBOLS_PER_OCTET); // 11 byte for the ACK PPDU
+    // if (frame->headerLen + frame->payloadLen > IEEE154_aMaxSIFSFrameSize) 
+    //  m_transactionTime += call MLME_GET.macMinLIFSPeriod(); 
+    // else 
+    //  m_transactionTime += call MLME_GET.macMinSIFSPeriod(); 
+    m_currentFrame = frame;
+  }
+
+  /** 
+   * The updateState() function is called whenever some event happened that
+   * might require a state transition; it implements a lock mechanism (m_lock)
+   * to prevent race conditions. Whenever the lock is set a "done"-event (from
+   * a RadioTx/RadioRx/RadioOff interface) is pending and will "soon" unset the
+   * lock (and then updateState() will called again).  The updateState()
+   * function decides about the next state by checking a list of possible
+   * current states ordered by priority. Calling this function more than
+   * necessary can do no harm.
+   */ 
+
+  void updateState()
+  {
+    next_state_t next;
+    atomic {
+      // long atomics are bad... but in this block, once the
+      // current state has been determined only one branch will
+      // be taken (there are no loops)
+      if (m_lock || !call RadioToken.isOwner())
+        return;
+      m_lock = TRUE; // lock
+
+      // Check 1: was an indirect transmission successfully started 
+      // and are we now waiting for a frame from the coordinator?
+      if (m_indirectTxPending) {
+        next = tryReceive();
+      }
+
+      // Check 2: is some other operation (like MLME-SCAN or MLME-RESET) pending? 
+      else if (call IsRadioTokenRequested.getNow()) {
+        if (call RadioOff.isOff()) {
+          // nothing more to do... just release the Token
+          dbg_serial("DispatchUnslottedCsmaP", "Token requested: releasing it.\n");
+          call RadioToken.request(); // we want it back afterwards ...
+          m_lock = FALSE; // unlock
+          call RadioToken.release();
+          return;
+        } else 
+          next = SWITCH_OFF;
+      }
+
+      // Check 3: is there a frame ready to transmit?
+      else if (m_currentFrame != NULL) {
+        next = tryTransmit();
+      }
+
+      // Check 4: should we be in receive mode?
+      else if (call IsRxEnableActive.getNow() || m_macRxOnWhenIdle) {
+        next = tryReceive();
+        if (next == DO_NOTHING) {
+          // if there was an active MLME_RX_ENABLE.request then we'll
+          // inform the next higher layer that radio is now in Rx mode
+          post wasRxEnabledTask();
+        }
+      }
+
+      // Check 5: just make sure the radio is switched off  
+      else {
+        next = trySwitchOff();
+        if (next == DO_NOTHING) {
+          // nothing more to do... just release the Token
+          m_lock = FALSE; // unlock
+          dbg_serial("DispatchUnslottedCsmaP", "Releasing token\n");
+          call RadioToken.release();
+          return;
+        }
+      }
+
+      // if there is nothing to do, then we must clear the lock
+      if (next == DO_NOTHING)
+        m_lock = FALSE;
+    } // atomic
+
+    // put next state in operation (possibly keeping the lock)
+    switch (next)
+    {
+      case SWITCH_OFF: ASSERT(call RadioOff.off() == SUCCESS); break;
+      case WAIT_FOR_RXDONE: break;
+      case WAIT_FOR_TXDONE: break;
+      case DO_NOTHING: break;
+    }
+  }
+  
+  next_state_t tryTransmit()
+  {
+    // tries to transmit m_currentFrame
+    next_state_t next;
+
+    if (!call RadioOff.isOff())
+      next = SWITCH_OFF;
+    else {
+      error_t res;
+      res = call UnslottedCsmaCa.transmit(m_currentFrame, &m_csma);
+      dbg("DispatchUnslottedCsmaP", "UnslottedCsmaCa.transmit() -> %lu\n", (uint32_t) res);
+      next = WAIT_FOR_TXDONE; // this will NOT clear the lock
+    }
+    return next;
+  }
+
+  next_state_t tryReceive()
+  {
+    next_state_t next;
+    if (call RadioRx.isReceiving())
+      next = DO_NOTHING;
+    else if (!call RadioOff.isOff())
+      next = SWITCH_OFF;
+    else {
+      call RadioRx.enableRx(0, 0);
+      next = WAIT_FOR_RXDONE;
+    }
+    return next;
+  }
+
+  next_state_t trySwitchOff()
+  {
+    next_state_t next;
+    if (call RadioOff.isOff())
+      next = DO_NOTHING;
+    else
+      next = SWITCH_OFF;
+    return next;
+  }
+
+  async event void RadioOff.offDone() 
+  { 
+    m_lock = FALSE; 
+    updateState();
+  }
+
+  async event void RadioRx.enableRxDone() 
+  { 
+    if (m_indirectTxPending) // indirect transmission, now waiting for data
+      post startIndirectTxTimerTask();
+    m_lock = FALSE; 
+    updateState();
+  }
+
+  event void RxEnableStateChange.notify(bool whatever) 
+  { 
+    if (!call RadioToken.isOwner())
+      call RadioToken.request();
+    else
+      updateState();
+  }
+
+  event void PIBUpdateMacRxOnWhenIdle.notify( const void* val ) 
+  {
+    atomic m_macRxOnWhenIdle = *((ieee154_macRxOnWhenIdle_t*) val);
+    signal RxEnableStateChange.notify(TRUE);
+  }
+
+  event void IndirectTxWaitTimer.fired() 
+  { 
+    atomic {
+      if (m_indirectTxPending) {
+        m_indirectTxPending = FALSE; 
+        post signalTxDoneTask(); 
+      }
+    }
+  }
+
+  task void startIndirectTxTimerTask()
+  {
+    call IndirectTxWaitTimer.startOneShot(call MLME_GET.macMaxFrameTotalWaitTime()); 
+  }
+
+  async event void UnslottedCsmaCa.transmitDone(ieee154_txframe_t *frame, 
+      ieee154_csma_t *csma, bool ackPendingFlag, error_t result)
+  {
+    bool done = TRUE;
+    dbg("DispatchUnslottedCsmaP", "UnslottedCsmaCa.transmitDone() -> %lu\n", (uint32_t) result);
+    m_resume = FALSE;
+
+    switch (result)
+    {
+      case SUCCESS:
+        // frame was successfully transmitted, if ACK was requested
+        // then a matching ACK was successfully received as well   
+        m_txStatus = IEEE154_SUCCESS;
+        if (frame->payload[0] == CMD_FRAME_DATA_REQUEST &&
+            ((frame->header->mhr[MHR_INDEX_FC1]) & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_CMD) {
+          // this was a data request frame
+          m_txStatus = IEEE154_NO_DATA; // pessimistic 
+          if (ackPendingFlag) {
+            // the coordinator has data for us; switch to Rx 
+            // to complete the indirect transmission         
+            m_indirectTxPending = TRUE;
+            m_lastFrame = m_currentFrame;
+            m_currentFrame = NULL;
+            ASSERT(call RadioRx.enableRx(0, 0) == SUCCESS);
+            return;
+          }
+        }
+        break;
+      case FAIL:
+        // The CSMA-CA algorithm failed: the frame was not transmitted,
+        // because channel was never idle                              
+        m_txStatus = IEEE154_CHANNEL_ACCESS_FAILURE;
+        break;
+      case ENOACK:
+        // frame was transmitted, but we didn't receive an ACK (although
+        // we requested an one). note: coordinator never retransmits an 
+        // indirect transmission (see above) 
+        if (m_macMaxFrameRetries > 0) {
+          // retransmit: reinitialize CSMA-CA parameters
+          done = FALSE;
+          m_csma.NB = 0;
+          m_csma.macMaxCsmaBackoffs = m_macMaxCSMABackoffs;
+          m_csma.macMaxBE = m_macMaxBE;
+          m_csma.BE = m_BE;
+          m_macMaxFrameRetries -= 1;
+        } else
+          m_txStatus = IEEE154_NO_ACK;
+        break;
+      default: 
+        ASSERT(0);
+        break;
+    }
+
+    if (done) {
+      m_lastFrame = m_currentFrame;
+      m_currentFrame = NULL;
+      post signalTxDoneTask();
+    }  
+
+    m_lock = FALSE;
+    updateState();
+  }
+
+  task void signalTxDoneTask()
+  {
+    ieee154_txframe_t *lastFrame = m_lastFrame;
+    ieee154_status_t status = m_txStatus;
+    m_indirectTxPending = FALSE;
+    m_lastFrame = NULL; // only now the next transmission can begin 
+    if (lastFrame) {
+      dbg("DispatchUnslottedCsmaP", "Transmit done, DSN: %lu, result: 0x%lx\n", 
+          (uint32_t) MHR(lastFrame)[MHR_INDEX_SEQNO], (uint32_t) status);
+      signal FrameTx.transmitDone(lastFrame, status);
+    }
+    updateState();
+  }
+
+  event message_t* RadioRx.received(message_t* frame, const ieee154_timestamp_t *timestamp)
+  {
+    // received a frame -> find out frame type and
+    // signal it to responsible client component
+    uint8_t *payload = (uint8_t *) frame->data;
+    uint8_t *mhr = MHR(frame);
+    uint8_t frameType = mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK;
+
+    if (frameType == FC1_FRAMETYPE_CMD)
+      frameType += payload[0];
+    dbg("DispatchUnslottedCsmaP", "Received frame, DSN: %lu, type: 0x%lu\n", 
+        (uint32_t) mhr[MHR_INDEX_SEQNO], (uint32_t) frameType);
+    atomic {
+      if (m_indirectTxPending) {
+        message_t* frameBuf;
+        call IndirectTxWaitTimer.stop();
+        // TODO: check!
+        //if (frame->payloadLen)
+          // is this frame from our coordinator? hmm... we cannot say
+          // with certainty, because we might only know either the 
+          // coordinator extended or short address (and the frame could
+          // have been sent with the other addressing mode) ??
+          m_txStatus = IEEE154_SUCCESS;
+        frameBuf = signal FrameExtracted.received[frameType](frame, m_lastFrame);
+        signal IndirectTxWaitTimer.fired();
+        return frameBuf;
+      } else
+        return signal FrameRx.received[frameType](frame);
+    }
+  }
+
+  task void wasRxEnabledTask()
+  {
+    signal WasRxEnabled.notify(TRUE);
+  }
+
+
+  default event void FrameTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) {}
+  default event message_t* FrameRx.received[uint8_t client](message_t* data) {return data;}
+  default async command bool IsRxEnableActive.getNow() {return FALSE;}
+
+  default event message_t* FrameExtracted.received[uint8_t client](message_t* msg, ieee154_txframe_t *txFrame) {return msg;}
+
+  command error_t WasRxEnabled.enable() {return FAIL;}
+  command error_t WasRxEnabled.disable() {return FAIL;}
+  default event void MLME_START.confirm(ieee154_status_t status) {}
+  async event void RadioToken.transferredFrom(uint8_t fromClientID) {ASSERT(0);}
+  async event void RadioTokenRequested.requested(){ updateState(); }
+  async event void RadioTokenRequested.immediateRequested(){ updateState(); }
+}
diff --git a/tos/lib/mac/tkn154/FrameDispatchImplP.nc b/tos/lib/mac/tkn154/FrameDispatchImplP.nc
deleted file mode 100644 (file)
index c952713..0000000
+++ /dev/null
@@ -1,213 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154_MAC.h"
-#include "TKN154_DEBUG.h"
-module FrameDispatchImplP 
-{
-  provides
-  {
-    interface RadioRx as MacRx[uint8_t client];
-    interface RadioTx as MacTx[uint8_t client];
-    interface RadioOff as MacRadioOff[uint8_t client];
-  } uses {
-    interface ArbiterInfo;
-    interface RadioRx as PhyRx;
-    interface RadioTx as PhyTx;
-    interface RadioOff as PhyRadioOff;
-    interface Get<bool> as RadioPromiscuousMode;
-    interface Leds;
-    interface Ieee802154Debug as Debug;
-  }
-}
-implementation
-{
-
-/* ----------------------- RadioRx ----------------------- */
-
-  async command error_t MacRx.prepare[uint8_t client]()
-  {
-    if (client == call ArbiterInfo.userId())
-      return call PhyRx.prepare();
-    else {
-      call Leds.led0On();
-      return FAIL;
-    } 
-  }
-    
-  async event void PhyRx.prepareDone()
-  {
-    signal MacRx.prepareDone[call ArbiterInfo.userId()]();
-  }
-
-  async command bool MacRx.isPrepared[uint8_t client]()
-  {
-    if (client == call ArbiterInfo.userId())
-      return call PhyRx.isPrepared();
-    else {
-      call Leds.led0On();
-      return FAIL;
-    } 
-  }
-
-  async command error_t MacRx.receive[uint8_t client](ieee154_reftime_t *t0, uint32_t dt)
-  {
-    if (client == call ArbiterInfo.userId()) 
-      return call PhyRx.receive(t0, dt);
-    else {
-      call Leds.led0On();
-      return IEEE154_TRANSACTION_OVERFLOW;
-    }
-  }
-
-  event message_t* PhyRx.received(message_t *msg, ieee154_reftime_t *timestamp)
-  {
-    uint8_t *mhr = MHR(msg);
-    if (((mhr[1] & FC2_FRAME_VERSION_MASK) > FC2_FRAME_VERSION_1)
-        && (!call RadioPromiscuousMode.get()))
-      return msg;
-#ifndef IEEE154_SECURITY_ENABLED
-    if ((mhr[0] & FC1_SECURITY_ENABLED)
-        && (!call RadioPromiscuousMode.get()))
-      return msg;
-#endif
-    return signal MacRx.received[call ArbiterInfo.userId()](msg, timestamp);
-  }
-
-  async command bool MacRx.isReceiving[uint8_t client]()
-  {
-    if (client == call ArbiterInfo.userId())
-      return call PhyRx.isReceiving();
-    else {
-      call Leds.led0On();
-      return FAIL;
-    } 
-  }
-
-/* ----------------------- RadioTx ----------------------- */
-
-  async command error_t MacTx.load[uint8_t client](ieee154_txframe_t *frame)
-  {
-    if (client == call ArbiterInfo.userId())
-      return call PhyTx.load(frame);
-    else {
-      call Leds.led0On();
-      return IEEE154_TRANSACTION_OVERFLOW;
-    }
-  }
-    
-  async event void PhyTx.loadDone()
-  {
-    signal MacTx.loadDone[call ArbiterInfo.userId()]();
-  }
-
-  async command ieee154_txframe_t* MacTx.getLoadedFrame[uint8_t client]()
-  {
-    if (client == call ArbiterInfo.userId())
-      return call PhyTx.getLoadedFrame();
-    else {
-      call Leds.led0On();
-      return NULL;
-    }
-  }
-
-
-  async command error_t MacTx.transmit[uint8_t client](ieee154_reftime_t *referenceTime, 
-      uint32_t timeOffset, uint8_t numCCA, bool ackRequest)
-  {
-    if (client == call ArbiterInfo.userId()) 
-      return call PhyTx.transmit(referenceTime, timeOffset, numCCA, ackRequest);
-    else {
-      call Leds.led0On();
-      return IEEE154_TRANSACTION_OVERFLOW;
-    }
-  }
-
-  async event void PhyTx.transmitDone(ieee154_txframe_t *frame, 
-      ieee154_reftime_t *referenceTime, bool ackPendingFlag, error_t error)   
-  {
-    signal MacTx.transmitDone[call ArbiterInfo.userId()](frame, referenceTime, ackPendingFlag, error);
-  }
-
-/* ----------------------- RadioOff ----------------------- */
-
-  async command error_t MacRadioOff.off[uint8_t client]()
-  {
-    if (client == call ArbiterInfo.userId())
-      return call PhyRadioOff.off();
-    else {
-      call Leds.led0On();
-      return EBUSY;
-    }
-  }
-
-  async event void PhyRadioOff.offDone()
-  {
-    signal MacRadioOff.offDone[call ArbiterInfo.userId()]();
-  }
-
-  
-  async command bool MacRadioOff.isOff[uint8_t client]()
-  {
-    if (client == call ArbiterInfo.userId())
-      return call PhyRadioOff.isOff();
-    else
-      return EBUSY;
-  }
-
-/* ----------------------- Defaults ----------------------- */
-
-  default async event void MacTx.loadDone[uint8_t client]()
-  {
-    call Debug.log(LEVEL_CRITICAL, RadioRxTxP_DEFAULT_PREPARE_TX_DONE, 0, 0, 0);
-  }
-  default async event void MacTx.transmitDone[uint8_t client](ieee154_txframe_t *frame, 
-      ieee154_reftime_t *referenceTime, bool ackPendingFlag, error_t error) 
-  {
-    call Debug.log(LEVEL_CRITICAL, RadioRxTxP_DEFAULT_TX_DONE, 0, 0, 0);
-  }
-  default async event void MacRx.prepareDone[uint8_t client]()
-  {
-    call Debug.log(LEVEL_CRITICAL, RadioRxTxP_DEFAULT_PREPARE_RX_DONE, 0, 0, 0);
-  }
-  default event message_t* MacRx.received[uint8_t client](message_t *frame, ieee154_reftime_t *timestamp)
-  {
-    call Debug.log(LEVEL_INFO, RadioRxTxP_DEFAULT_RECEIVED, client, call ArbiterInfo.userId(), 0xff);
-    return frame;
-  }
-  default async event void MacRadioOff.offDone[uint8_t client]()
-  {
-    call Debug.log(LEVEL_CRITICAL, RadioRxTxP_DEFAULT_OFFDONE, 0, 0, 0);
-  }
-}
diff --git a/tos/lib/mac/tkn154/FrameDispatchP.nc b/tos/lib/mac/tkn154/FrameDispatchP.nc
deleted file mode 100644 (file)
index 7f69f9e..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154_MAC.h"
-configuration FrameDispatchP  
-{
-  provides
-  {
-    interface RadioRx as RadioRx[uint8_t client];
-    interface RadioTx as RadioTx[uint8_t client];
-    interface RadioOff as RadioOff[uint8_t client];
-    interface Resource as Token[uint8_t client];
-    interface ResourceRequested as TokenRequested[uint8_t client];
-    interface ResourceTransferControl as TokenTransferControl;
-    interface GetNow<bool> as IsResourceRequested;
-    interface Leds as LedsRadioClient;
-  } uses {
-    interface RadioRx as PhyRx;
-    interface RadioTx as PhyTx;
-    interface RadioOff as PhyRadioOff;
-    interface Get<bool> as RadioPromiscuousMode;
-    interface Leds;
-    interface Ieee802154Debug as Debug;
-  }
-}
-implementation
-{
-  components FrameDispatchImplP;
-  RadioRx = FrameDispatchImplP.MacRx;
-  RadioTx = FrameDispatchImplP.MacTx;
-  RadioOff = FrameDispatchImplP.MacRadioOff;
-  PhyRx = FrameDispatchImplP.PhyRx;
-  PhyTx = FrameDispatchImplP.PhyTx;
-  PhyRadioOff = FrameDispatchImplP.PhyRadioOff;
-  RadioPromiscuousMode = FrameDispatchImplP;
-  Leds = FrameDispatchImplP;
-  Debug = FrameDispatchImplP;
-  LedsRadioClient = Leds;
-
-  components new SimpleRoundRobinTransferArbiterC(IEEE802154_RADIO_RESOURCE) as Arbiter;
-  Token = Arbiter;  
-  TokenRequested = Arbiter;
-  TokenTransferControl = Arbiter;
-  IsResourceRequested = Arbiter;
-  FrameDispatchImplP.ArbiterInfo -> Arbiter;
-}
index cf654ce6763a6f6ce4f0df2933550a720e0fee92..c404bcec7932ae8182749e0e9137eb72843f84b9 100644 (file)
@@ -30,6 +30,7 @@
  * $Revision$
  * $Date$
  * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * @author: Jasper Buesch <buesch@tkn.tu-berlin.de>
  * ========================================================================
  */
 
@@ -41,6 +42,7 @@ module IndirectTxP
     interface FrameTx[uint8_t client];
     interface WriteBeaconField as PendingAddrWrite;
     interface Notify<bool> as PendingAddrSpecUpdated;
+    interface Get<ieee154_txframe_t*> as GetIndirectTxFrame; 
     interface Purge;
   }
   uses
@@ -48,11 +50,10 @@ module IndirectTxP
     interface FrameTx as CoordCapTx;
     interface FrameRx as DataRequestRx;
     interface MLME_GET;
-    interface FrameUtility;
+    interface IEEE154Frame;
     interface Timer<TSymbolIEEE802154> as IndirectTxTimeout;
     interface TimeCalc;
     interface Leds;
-    interface Ieee802154Debug as Debug;
   }
 }
 implementation
@@ -68,8 +69,13 @@ implementation
   uint8_t m_numTableEntries;
   uint8_t m_numShortPending;
   uint8_t m_numExtPending;
+  ieee154_txframe_t m_emptyDataFrame;
+  ieee154_metadata_t m_emptyDataFrameMetadata;
+  ieee154_header_t m_emptyDataFrameHeader;
+
   task void tryCoordCapTxTask();
   void tryCoordCapTx();
+  void transmitEmptyDataFrame(message_t* dataRequestFrame);
 
   command error_t Reset.init()
   {
@@ -86,26 +92,49 @@ implementation
     m_numTableEntries = 0;
     m_numShortPending = 0;
     m_numExtPending = 0;
+
+    m_emptyDataFrame.header = &m_emptyDataFrameHeader;
+    m_emptyDataFrame.metadata = &m_emptyDataFrameMetadata;
+    m_emptyDataFrame.payload = &m_numExtPending; // dummy (payloadLen is always 0)
+    m_emptyDataFrame.payloadLen = 0;
+    m_emptyDataFrame.client = 0; // unlock
     return SUCCESS;
   }
 
-  uint32_t getPersistenceTime()
+  uint32_t getPersistenceTimeSymbols()
   {
-    uint32_t persistenceTime;
-    persistenceTime = call MLME_GET.macTransactionPersistenceTime();
-    persistenceTime *= IEEE154_aBaseSuperframeDuration;
-    persistenceTime *= ((uint16_t) 1) << call MLME_GET.macBeaconOrder();
-    return persistenceTime;
+    // transform macTransactionPersistenceTime PIB attribute
+    // from "unit periods" to symbols (cf. page 166) 
+    uint32_t unitPeriod;
+    ieee154_macBeaconOrder_t BO = call MLME_GET.macBeaconOrder();
+
+    if (BO <= 14) {
+      unitPeriod = IEEE154_aBaseSuperframeDuration;
+      unitPeriod *= ((uint16_t) 1) << BO;
+    } else
+      unitPeriod = IEEE154_aBaseSuperframeDuration;
+    return unitPeriod * call MLME_GET.macTransactionPersistenceTime();
   }
 
   command ieee154_status_t Purge.purge(uint8_t msduHandle)
   {
-    return IEEE154_INVALID_HANDLE; // TODO
+    uint8_t i = 0;
+    for (i=0; i<NUM_MAX_PENDING; i++) {
+      if ((m_txFrameTable[i]->handle == msduHandle) && (m_client != m_txFrameTable[i]->client) ){
+        ieee154_txframe_t *purgedFrame;
+        purgedFrame = m_txFrameTable[i];
+        m_txFrameTable[i] = NULL;
+        m_numTableEntries -= 1;
+        signal Purge.purgeDone(purgedFrame, IEEE154_PURGED);
+        return IEEE154_SUCCESS;
+      }
+    }
+    return IEEE154_INVALID_HANDLE;
   }
 
   command uint8_t PendingAddrWrite.write(uint8_t *pendingAddrField, uint8_t maxlen)
   {
-    // write the pending addr field (inside the beacon frame)
+    // writes the pending addr field (inside the beacon frame)
     uint8_t i, j, k=0;
     uint8_t *longAdrPtr[NUM_MAX_PENDING];
     nxle_uint16_t *adrPtr;
@@ -116,11 +145,11 @@ implementation
       return 0;
     pendingAddrField[0] = 0;
     adrPtr = (nxle_uint16_t *) &pendingAddrField[1];
-    for (i=0; i<NUM_MAX_PENDING; i++){
+    for (i=0; i<NUM_MAX_PENDING; i++) {
       if (!m_txFrameTable[i])
         continue;
       txFrame = m_txFrameTable[i];
-      if ((txFrame->header->mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_MASK) == FC2_DEST_MODE_SHORT){
+      if ((txFrame->header->mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_MASK) == FC2_DEST_MODE_SHORT) {
         *adrPtr++ = *((nxle_uint16_t*) &txFrame->header->mhr[MHR_INDEX_ADDRESS + sizeof(ieee154_macPANId_t)]);
       } else if ((txFrame->header->mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_MASK) == FC2_DEST_MODE_EXTENDED)
         longAdrPtr[k++] = &(txFrame->header->mhr[MHR_INDEX_ADDRESS + sizeof(ieee154_macPANId_t)]);
@@ -129,7 +158,6 @@ implementation
       for (j=0; j<8; j++)
         pendingAddrField[1 + 2*m_numShortPending + i*8 + j] = longAdrPtr[i][j];
     pendingAddrField[0] = m_numShortPending | (m_numExtPending << 4);
-    call Debug.log(LEVEL_INFO, IndirectTxP_BEACON_ASSEMBLY, len,0,0);
     return len;
   }
 
@@ -140,10 +168,10 @@ implementation
 
   command ieee154_status_t FrameTx.transmit[uint8_t client](ieee154_txframe_t *txFrame)
   {
-    // send a frame through indirect transmission
+    // sends a frame using indirect transmission
     uint8_t i;
-    if (m_numTableEntries >= NUM_MAX_PENDING){
-      call Debug.log(LEVEL_IMPORTANT, IndirectTxP_OVERFLOW, 0,0,0);
+    if (m_numTableEntries >= NUM_MAX_PENDING) {
+      dbg_serial("IndirectTxP", "Overflow\n");
       return IEEE154_TRANSACTION_OVERFLOW;
     }
     txFrame->client = client;
@@ -158,8 +186,8 @@ implementation
     else if ((txFrame->header->mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_MASK) == FC2_DEST_MODE_EXTENDED)
       m_numExtPending++;
     if (!call IndirectTxTimeout.isRunning())
-      call IndirectTxTimeout.startOneShot(getPersistenceTime());
-    call Debug.log(LEVEL_INFO, IndirectTxP_NOTIFIED, 0,0,0);
+      call IndirectTxTimeout.startOneShot(getPersistenceTimeSymbols());
+    dbg_serial("IndirectTxP", "Preparing a transmission.\n");
     signal PendingAddrSpecUpdated.notify(TRUE);
     return IEEE154_SUCCESS;
   }
@@ -168,13 +196,12 @@ implementation
   {
     uint8_t i, j, srcAddressMode, dstAddressMode, *src;
     uint8_t *mhr = MHR(frame);
-    uint8_t destMode = (mhr[1] & FC2_DEST_MODE_MASK);
+    uint8_t destMode = (mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_MASK);
+    ieee154_txframe_t *dataResponseFrame = NULL;
 
     // received a data request frame from a device
     // have we got some pending data for it ?
-    if (!m_numTableEntries)
-      return frame;
-    srcAddressMode = (mhr[1] & FC2_SRC_MODE_MASK);
+    srcAddressMode = (mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK);
     if (!(srcAddressMode & FC2_SRC_MODE_SHORT))
       return frame;  // no source address
     src = mhr + MHR_INDEX_ADDRESS;
@@ -182,13 +209,13 @@ implementation
       src += 4;
     else if (destMode == FC2_DEST_MODE_EXTENDED)
       src += 10;
-    if (!((mhr[0] & FC1_PAN_ID_COMPRESSION) && (mhr[1] & FC2_DEST_MODE_SHORT)))
+    if (!((mhr[MHR_INDEX_FC1] & FC1_PAN_ID_COMPRESSION) && (mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_SHORT)))
       src += 2;
-    for (i=0; i<NUM_MAX_PENDING; i++){
-      if (!m_txFrameTable[i])
+    for (i=0; i<NUM_MAX_PENDING; i++) {
+      if (m_txFrameTable[i] == NULL)
         continue;
       else {
-        dstAddressMode = (m_txFrameTable[i]->header->mhr[1] & FC2_DEST_MODE_MASK);
+        dstAddressMode = (m_txFrameTable[i]->header->mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_MASK);
         if ((dstAddressMode << 4) != srcAddressMode)
           continue;
         else {
@@ -196,39 +223,70 @@ implementation
           uint8_t *dst = &(m_txFrameTable[i]->header->mhr[MHR_INDEX_ADDRESS]) + 2;
           uint8_t len = ((srcAddressMode == FC2_SRC_MODE_SHORT) ? 2 : 8);
           for (j=0; j<len; j++)
-            if (*dst != *src)
-              break;
-          if (j==len)
-            break; // match! break from outer loop
+            if (dst[j] != src[j])
+              break;  // no match!
+          if (j==len) { // match!
+            if (dataResponseFrame == NULL)
+              dataResponseFrame = m_txFrameTable[i];
+            else // got even more than one frame for this device: set pending flag
+              dataResponseFrame->header->mhr[MHR_INDEX_FC1] |= FC1_FRAME_PENDING;
+          }
         }
       }
     }
-    call Debug.log(LEVEL_INFO, IndirectTxP_REQUESTED, NUM_MAX_PENDING-i,i,*src);
-    if (i != NUM_MAX_PENDING){
+    if (dataResponseFrame != NULL) {
       // found a matching frame, mark it for transmission
-      m_txFrameTable[i]->client |= SEND_THIS_FRAME;
+      dbg_serial("IndirectTxP", "We have data for this device, trying to transmit...\n");
+      dataResponseFrame->client |= SEND_THIS_FRAME;
       post tryCoordCapTxTask();
     } else {
-      // TODO: send an empty data frame to the device
+      dbg_serial("IndirectTxP", "We don't have data for this device, sending an empty frame...\n");
+      transmitEmptyDataFrame(frame);
     }
     return frame;
   }
 
+  void transmitEmptyDataFrame(message_t* dataRequestFrame)
+  {
+    // the cast in the next line is dangerous -> this is only a temporary workaround!
+    // (until the new T2 message buffer abstraction is available)
+    message_t *emptyDataMsg = (message_t *) m_emptyDataFrame.header;
+    ieee154_address_t dstAddr;
+    uint16_t dstPanID;
+
+    if (m_emptyDataFrame.client != 0)
+      return; // locked (already transmitting an empty data frame)
+    if (call IEEE154Frame.getSrcAddr(dataRequestFrame, &dstAddr) != IEEE154_SUCCESS ||
+        call IEEE154Frame.getSrcPANId(dataRequestFrame, &dstPanID) != IEEE154_SUCCESS)
+      return;
+    call IEEE154Frame.setAddressingFields(emptyDataMsg,
+        call IEEE154Frame.getDstAddrMode(dataRequestFrame), // will become srcAddrMode
+        call IEEE154Frame.getSrcAddrMode(dataRequestFrame), // will become dstAddrMode
+        dstPanID,
+        &dstAddr,
+        NULL //security
+        );
+    MHR(&m_emptyDataFrame)[MHR_INDEX_FC1] |= FC1_FRAMETYPE_DATA;
+    m_emptyDataFrame.headerLen = call IEEE154Frame.getHeaderLength(emptyDataMsg);
+    m_emptyDataFrame.client = 1; // lock
+    if (call CoordCapTx.transmit(&m_emptyDataFrame) != IEEE154_SUCCESS)
+      m_emptyDataFrame.client = 0; // unlock
+  }
+
   void tryCoordCapTx()
   {
     // iterate over the queued frames and transmit them in the CAP 
     // (if they are marked for transmission)
     uint8_t i;
-    if (!m_pendingTxFrame && m_numTableEntries){
+    if (m_pendingTxFrame == NULL && m_numTableEntries) {
       for (i=0; i<NUM_MAX_PENDING; i++)
-        if (m_txFrameTable[i] && (m_txFrameTable[i]->client & SEND_THIS_FRAME)){
-          // TODO: set frame pending bit, if there's more data for this destination
+        if (m_txFrameTable[i] && (m_txFrameTable[i]->client & SEND_THIS_FRAME)) {
           m_pendingTxFrame = m_txFrameTable[i];
           m_client = m_txFrameTable[i]->client;
-          if (call CoordCapTx.transmit(m_txFrameTable[i]) == IEEE154_SUCCESS){
-            call Debug.log(LEVEL_INFO, IndirectTxP_SEND_NOW, 0,0,0);
+          if (call CoordCapTx.transmit(m_txFrameTable[i]) == IEEE154_SUCCESS) {
+            dbg_serial("IndirectTxP", "Started a transmission.\n");
           } else {
-            m_pendingTxFrame = 0;
+            m_pendingTxFrame = NULL;
             post tryCoordCapTxTask();
           }
           return; // done - wait for txDone
@@ -245,12 +303,12 @@ implementation
   {
     // a transaction has expired 
     uint32_t now = call IndirectTxTimeout.getNow(), dt=0;
-    uint32_t persistenceTime = getPersistenceTime();
+    uint32_t persistenceTime = getPersistenceTimeSymbols();
     uint8_t i;
 
     for (i=0; i<NUM_MAX_PENDING; i++)
-      if (m_txFrameTable[i] && m_txFrameTable[i] != m_pendingTxFrame){
-        if (call TimeCalc.hasExpired(m_txFrameTable[i]->metadata->timestamp, persistenceTime)){ 
+      if (m_txFrameTable[i] && m_txFrameTable[i] != m_pendingTxFrame) {
+        if (call TimeCalc.hasExpired(m_txFrameTable[i]->metadata->timestamp, persistenceTime)) 
           ieee154_txframe_t *txFrame = m_txFrameTable[i];
           txFrame->client &= ~SEND_THIS_FRAME;
           m_txFrameTable[i] = NULL;
@@ -261,11 +319,11 @@ implementation
             m_numExtPending--;
           signal FrameTx.transmitDone[txFrame->client](txFrame, IEEE154_TRANSACTION_EXPIRED);
           signal PendingAddrSpecUpdated.notify(TRUE);
-        } else if (call TimeCalc.timeElapsed(m_txFrameTable[i]->metadata->timestamp, now) > dt){
+        } else if (call TimeCalc.timeElapsed(m_txFrameTable[i]->metadata->timestamp, now) > dt) {
           dt = call TimeCalc.timeElapsed(m_txFrameTable[i]->metadata->timestamp, now);
         }
       }
-    if (dt != 0){
+    if (dt != 0) {
       if (dt > persistenceTime)
         dt = persistenceTime;
       call IndirectTxTimeout.startOneShot(persistenceTime - dt);
@@ -275,9 +333,15 @@ implementation
   event void CoordCapTx.transmitDone(ieee154_txframe_t *txFrame, ieee154_status_t status)
   {
     uint8_t i;
-    // TODO: if CSMA-CA algorithm failed, then frame shall remain in transaction queue
+    // TODO: if CSMA-CA algorithm failed, then frame shall still remain in transaction queue
+    dbg_serial("IndirectTxP", "transmitDone(), status: %lu\n", (uint32_t) status);
+
+    if (txFrame == &m_emptyDataFrame) {
+      m_emptyDataFrame.client = 0; // unlock
+      return;
+    }
     for (i=0; i<NUM_MAX_PENDING; i++)
-      if (m_txFrameTable[i] == txFrame){
+      if (m_txFrameTable[i] == txFrame) {
         m_txFrameTable[i] = NULL; // slot is now empty
         break;
       }
@@ -292,10 +356,11 @@ implementation
       m_numExtPending--;    
     signal FrameTx.transmitDone[txFrame->client](txFrame, status);
     post tryCoordCapTxTask();
-    call Debug.log(LEVEL_INFO, IndirectTxP_SEND_DONE, status,m_numTableEntries,0);
   }
 
-  command error_t PendingAddrSpecUpdated.enable(){return FAIL;}
-  command error_t PendingAddrSpecUpdated.disable(){return FAIL;}
-  default event void FrameTx.transmitDone[uint8_t client](ieee154_txframe_t *txFrame, ieee154_status_t status){}
+  command ieee154_txframe_t* GetIndirectTxFrame.get() { return m_pendingTxFrame;}
+  command error_t PendingAddrSpecUpdated.enable() {return FAIL;}
+  command error_t PendingAddrSpecUpdated.disable() {return FAIL;}
+  default event void PendingAddrSpecUpdated.notify( bool val ) {return;}
+  default event void FrameTx.transmitDone[uint8_t client](ieee154_txframe_t *txFrame, ieee154_status_t status) {}
 }
index e1c6219e35967171bf94d937bfec45ec94d5a71d..51c41c9061d2de55c7a6e08505083cd7f4be254f 100644 (file)
  * ========================================================================
  */
 
-/* This component maintains the PIB (PAN Information Base) attributes and
- * provides interfaces for accessing fields in a MAC frame. */
+/** 
+ * This component maintains the PIB (PAN Information Base) attributes and
+ * provides interfaces for accessing fields in a MAC frame. 
+ */
 
 #include "TKN154.h"
 #include "TKN154_PIB.h"
@@ -49,12 +51,11 @@ module PibP {
     interface Set<ieee154_macSuperframeOrder_t> as SetMacSuperframeOrder;
     interface Set<ieee154_macBeaconTxTime_t> as SetMacBeaconTxTime;
     interface Set<ieee154_macPanCoordinator_t> as SetMacPanCoordinator;
-    interface Get<ieee154_macPanCoordinator_t> as IsMacPanCoordinator;
-    interface Get<bool> as IsBeaconEnabledPAN;
     interface FrameUtility;
     interface IEEE154Frame as Frame;
     interface IEEE154BeaconFrame as BeaconFrame;
     interface Get<uint64_t> as GetLocalExtendedAddress;
+    interface GetNow<token_requested_t> as IsRadioTokenRequested;
     interface Notify<const void*> as PIBUpdate[uint8_t PIBAttributeID];
     interface Packet;
     interface TimeCalc;
@@ -62,12 +63,12 @@ module PibP {
   uses
   {
     interface Get<bool> as PromiscuousModeGet;
-    interface Init as CapReset;
-    interface Init as CapQueueReset;
+    interface Init as DispatchReset;
+    interface Init as DispatchQueueReset;
     interface Init as MacReset;
     interface SplitControl as RadioControl;
     interface Random;
-    interface Resource as Token;
+    interface TransferableResource as RadioToken;
     interface RadioOff;
     interface LocalTime<TSymbolIEEE802154>;
   }
@@ -77,8 +78,7 @@ implementation
   ieee154_PIB_t m_pib;
   uint8_t m_numResetClientPending;
   bool m_setDefaultPIB;
-  uint8_t m_panType;
-  uint8_t m_resetSpin;
+  norace uint8_t m_resetSpin;
 
 #ifdef IEEE154_EXTENDED_ADDRESS
   const uint64_t m_aExtendedAddressLE = IEEE154_EXTENDED_ADDRESS;
@@ -96,9 +96,7 @@ implementation
   command error_t LocalInit.init()
   {
 #ifndef IEEE154_EXTENDED_ADDRESS
-    uint32_t *p = (uint32_t*) &m_aExtendedAddressLE;
-    *p++ = call Random.rand32();
-    *p = call Random.rand32();
+    m_aExtendedAddressLE = (((uint64_t) call Random.rand32() ) << 32 ) | call Random.rand32(); 
 #endif
     resetAttributesToDefault();
     return SUCCESS;
@@ -114,6 +112,7 @@ implementation
     m_pib.macAssociationPermit = IEEE154_DEFAULT_ASSOCIATIONPERMIT;
     m_pib.macAutoRequest = IEEE154_DEFAULT_AUTOREQUEST;
     m_pib.macBattLifeExt = IEEE154_DEFAULT_BATTLIFEEXT;
+    m_pib.macBattLifeExtPeriods = IEEE154_DEFAULT_BATTLIFEEXTPERIODS;
     m_pib.macBeaconPayloadLength = IEEE154_DEFAULT_BEACONPAYLOADLENGTH;
     m_pib.macBeaconOrder = IEEE154_DEFAULT_BEACONORDER;
     m_pib.macBeaconTxTime = IEEE154_DEFAULT_BEACONTXTIME;
@@ -151,17 +150,17 @@ implementation
     waitTime = (((uint16_t) 1 << macMaxBE) - 1) * (macMaxCSMABackoffs - m);
     if (m) {
       k = 0;
-      while (k != m){
-        waitTime += ((uint16_t) 1 << (macMaxBE+k));
+      while (k != m) {
+        waitTime += ((uint16_t) 1 << (macMinBE+k));
         k += 1;
       }
     }
     waitTime *= IEEE154_aUnitBackoffPeriod;
-    waitTime += IEEE154_SHR_DURATION;
+    waitTime += call MLME_GET.phyMaxFrameDuration();
     m_pib.macMaxFrameTotalWaitTime = waitTime;
   }
 
-  command ieee154_status_t MLME_RESET.request(bool SetDefaultPIB, uint8_t PANType
+  command ieee154_status_t MLME_RESET.request(bool SetDefaultPIB) 
   {
     // resetting the complete stack is not so easy...
     // first we acquire the Token (get exclusive radio access), then we switch off 
@@ -171,21 +170,22 @@ implementation
     // Alarms!), but there can still be pending Timers/tasks -> we stop all Timers
     // through MacReset.init() and then spin a few tasks in between to get 
     // everything "flushed out"
-    if (PANType != BEACON_ENABLED_PAN && PANType != NONBEACON_ENABLED_PAN)
-      return IEEE154_INVALID_PARAMETER;
+    ieee154_status_t status = IEEE154_SUCCESS;
     if (call PromiscuousModeGet.get())
-      return IEEE154_TRANSACTION_OVERFLOW; // must first cancel promiscuous mode!
-    m_setDefaultPIB = SetDefaultPIB;
-    m_panType = PANType; 
-    if (!call Token.isOwner())
-      call Token.request();
-    return IEEE154_SUCCESS;
+      status = IEEE154_TRANSACTION_OVERFLOW; // must first cancel promiscuous mode!
+    else {
+      m_setDefaultPIB = SetDefaultPIB;
+      m_resetSpin = 5;
+      call RadioToken.request();
+    }   
+    dbg_serial("PibP", "MLME_RESET.request(%lu) -> result: %lu\n", 
+        (uint32_t) SetDefaultPIB, (uint32_t) status);
+    return status;
   }
 
-  event void Token.granted()
+  event void RadioToken.granted()
   {
-    error_t error = call RadioOff.off();
-    if (error != SUCCESS) // either it is already off or driver has not been started
+    if (call RadioOff.off() != SUCCESS)
       signal RadioOff.offDone();
   }
 
@@ -196,35 +196,34 @@ implementation
 
   task void radioControlStopTask()
   {
-    if (call RadioControl.stop() == EALREADY)
+    error_t result = call RadioControl.stop();
+    if (result == EALREADY)
       signal RadioControl.stopDone(SUCCESS);
+    else
+      ASSERT(result == SUCCESS);
   }
 
-  event void RadioControl.stopDone(error_t error)
+  event void RadioControl.stopDone(error_t result)
   {
-    call CapReset.init();       // resets the CAP component(s)
-    call CapQueueReset.init();  // resets the CAP queue component(s)
-    call MacReset.init();       // resets the remaining components
-    m_resetSpin = 5;
+    ASSERT(result == SUCCESS);
+    call DispatchReset.init();       // resets the dispatch component(s), spools out frames
+    call DispatchQueueReset.init();  // resets the dispatch queue component(s), spools out frames
+    call MacReset.init();            // resets the remaining components
     post resetSpinTask();
   }
 
   task void resetSpinTask()
   {
-    if (m_resetSpin == 2){
-      // just to be safe...
-      call CapReset.init();       
-      call CapQueueReset.init();  
-      call MacReset.init();       
-    }
-    if (m_resetSpin--){
+    m_resetSpin -= 1;
+    if (m_resetSpin != 0) {
       post resetSpinTask();
       return;
     }
-    if (call RadioControl.start() == EALREADY)
-      signal RadioControl.startDone(SUCCESS);
+    ASSERT(call RadioControl.start() == SUCCESS);
   }
 
+  async command token_requested_t IsRadioTokenRequested.getNow(){ return m_resetSpin != 0; }
+
   event void RadioControl.startDone(error_t error)
   {
     if (m_setDefaultPIB)
@@ -239,94 +238,96 @@ implementation
       signal PIBUpdate.notify[IEEE154_macShortAddress](&m_pib.macShortAddress);
       signal PIBUpdate.notify[IEEE154_macPanCoordinator](&m_pib.macPanCoordinator);
     }
-    call Token.release();
+    call RadioToken.release();
     signal MLME_RESET.confirm(IEEE154_SUCCESS);
   }
   
-/* ----------------------- MLME-GET ----------------------- */
+  /* ----------------------- MLME-GET ----------------------- */
+
+  command ieee154_phyCurrentChannel_t MLME_GET.phyCurrentChannel() { return m_pib.phyCurrentChannel;}
 
-  command ieee154_phyCurrentChannel_t MLME_GET.phyCurrentChannel(){ return m_pib.phyCurrentChannel;}
+  command ieee154_phyChannelsSupported_t MLME_GET.phyChannelsSupported() { return IEEE154_SUPPORTED_CHANNELS;}
 
-  command ieee154_phyChannelsSupported_t MLME_GET.phyChannelsSupported(){ return IEEE154_SUPPORTED_CHANNELS;}
+  command ieee154_phyTransmitPower_t MLME_GET.phyTransmitPower() { return m_pib.phyTransmitPower;}
 
-  command ieee154_phyTransmitPower_t MLME_GET.phyTransmitPower(){ return m_pib.phyTransmitPower;}
+  command ieee154_phyCCAMode_t MLME_GET.phyCCAMode() { return m_pib.phyCCAMode;}
 
-  command ieee154_phyCCAMode_t MLME_GET.phyCCAMode(){ return m_pib.phyCCAMode;}
+  command ieee154_phyCurrentPage_t MLME_GET.phyCurrentPage() { return m_pib.phyCurrentPage;}
 
-  command ieee154_phyCurrentPage_t MLME_GET.phyCurrentPage(){ return m_pib.phyCurrentPage;}
+  command ieee154_phyMaxFrameDuration_t MLME_GET.phyMaxFrameDuration() { return IEEE154_MAX_FRAME_DURATION;}
 
-  command ieee154_phyMaxFrameDuration_t MLME_GET.phyMaxFrameDuration(){ return IEEE154_MAX_FRAME_DURATION;}
+  command ieee154_phySHRDuration_t MLME_GET.phySHRDuration() { return IEEE154_SHR_DURATION;}
 
-  command ieee154_phySHRDuration_t MLME_GET.phySHRDuration(){ return IEEE154_SHR_DURATION;}
+  command ieee154_phySymbolsPerOctet_t MLME_GET.phySymbolsPerOctet() { return IEEE154_SYMBOLS_PER_OCTET;}
 
-  command ieee154_phySymbolsPerOctet_t MLME_GET.phySymbolsPerOctet(){ return IEEE154_SYMBOLS_PER_OCTET;}
+  command ieee154_macAckWaitDuration_t MLME_GET.macAckWaitDuration() { return IEEE154_ACK_WAIT_DURATION;}
 
-  command ieee154_macAckWaitDuration_t MLME_GET.macAckWaitDuration(){ return IEEE154_ACK_WAIT_DURATION;}
+  command ieee154_macAssociationPermit_t MLME_GET.macAssociationPermit() { return m_pib.macAssociationPermit;}
 
-  command ieee154_macAssociationPermit_t MLME_GET.macAssociationPermit(){ return m_pib.macAssociationPermit;}
+  command ieee154_macAutoRequest_t MLME_GET.macAutoRequest() { return m_pib.macAutoRequest;}
 
-  command ieee154_macAutoRequest_t MLME_GET.macAutoRequest(){ return m_pib.macAutoRequest;}
+  command ieee154_macBattLifeExt_t MLME_GET.macBattLifeExt() { return m_pib.macBattLifeExt;}
 
-  command ieee154_macBattLifeExt_t MLME_GET.macBattLifeExt(){ return m_pib.macBattLifeExt;}
+  command ieee154_macBattLifeExtPeriods_t MLME_GET.macBattLifeExtPeriods() { return m_pib.macBattLifeExtPeriods;}
 
-  command ieee154_macBattLifeExtPeriods_t MLME_GET.macBattLifeExtPeriods(){ return IEEE154_BATT_LIFE_EXT_PERIODS;}
+  command ieee154_macBeaconOrder_t MLME_GET.macBeaconOrder() { return m_pib.macBeaconOrder;}
 
-  command ieee154_macBeaconOrder_t MLME_GET.macBeaconOrder(){ return m_pib.macBeaconOrder;}
+  command ieee154_macBeaconTxTime_t MLME_GET.macBeaconTxTime() { return m_pib.macBeaconTxTime;}
 
-  command ieee154_macBeaconTxTime_t MLME_GET.macBeaconTxTime(){ return m_pib.macBeaconTxTime;}
+  command ieee154_macBSN_t MLME_GET.macBSN() { return m_pib.macBSN;}
 
-  command ieee154_macBSN_t MLME_GET.macBSN(){ return m_pib.macBSN;}
+  command ieee154_macCoordExtendedAddress_t MLME_GET.macCoordExtendedAddress() { return m_pib.macCoordExtendedAddress;}
 
-  command ieee154_macCoordExtendedAddress_t MLME_GET.macCoordExtendedAddress(){ return m_pib.macCoordExtendedAddress;}
+  command ieee154_macCoordShortAddress_t MLME_GET.macCoordShortAddress() { return m_pib.macCoordShortAddress;}
 
-  command ieee154_macCoordShortAddress_t MLME_GET.macCoordShortAddress(){ return m_pib.macCoordShortAddress;}
+  command ieee154_macDSN_t MLME_GET.macDSN() { return m_pib.macDSN;}
 
-  command ieee154_macDSN_t MLME_GET.macDSN(){ return m_pib.macDSN;}
+  command ieee154_macGTSPermit_t MLME_GET.macGTSPermit() { return m_pib.macGTSPermit;}
 
-  command ieee154_macGTSPermit_t MLME_GET.macGTSPermit(){ return m_pib.macGTSPermit;}
+  command ieee154_macMaxCSMABackoffs_t MLME_GET.macMaxCSMABackoffs() { return m_pib.macMaxCSMABackoffs;}
 
-  command ieee154_macMaxCSMABackoffs_t MLME_GET.macMaxCSMABackoffs(){ return m_pib.macMaxCSMABackoffs;}
+  command ieee154_macMinBE_t MLME_GET.macMinBE() { return m_pib.macMinBE;}
 
-  command ieee154_macMinBE_t MLME_GET.macMinBE(){ return m_pib.macMinBE;}
+  command ieee154_macPANId_t MLME_GET.macPANId() { return m_pib.macPANId;}
 
-  command ieee154_macPANId_t MLME_GET.macPANId(){ return m_pib.macPANId;}
+  command ieee154_macPromiscuousMode_t MLME_GET.macPromiscuousMode() { return call PromiscuousModeGet.get();}
 
-  command ieee154_macPromiscuousMode_t MLME_GET.macPromiscuousMode(){ return call PromiscuousModeGet.get();}
+  command ieee154_macRxOnWhenIdle_t MLME_GET.macRxOnWhenIdle() { return m_pib.macRxOnWhenIdle;}
 
-  command ieee154_macRxOnWhenIdle_t MLME_GET.macRxOnWhenIdle(){ return m_pib.macRxOnWhenIdle;}
+  command ieee154_macShortAddress_t MLME_GET.macShortAddress() { return m_pib.macShortAddress;}
 
-  command ieee154_macShortAddress_t MLME_GET.macShortAddress(){ return m_pib.macShortAddress;}
+  command ieee154_macSuperframeOrder_t MLME_GET.macSuperframeOrder() { return m_pib.macSuperframeOrder;}
 
-  command ieee154_macSuperframeOrder_t MLME_GET.macSuperframeOrder(){ return m_pib.macSuperframeOrder;}
+  command ieee154_macTransactionPersistenceTime_t MLME_GET.macTransactionPersistenceTime() { return m_pib.macTransactionPersistenceTime;}
 
-  command ieee154_macTransactionPersistenceTime_t MLME_GET.macTransactionPersistenceTime(){ return m_pib.macTransactionPersistenceTime;}
+  command ieee154_macAssociatedPANCoord_t MLME_GET.macAssociatedPANCoord() { return m_pib.macAssociatedPANCoord;}
 
-  command ieee154_macAssociatedPANCoord_t MLME_GET.macAssociatedPANCoord(){ return m_pib.macAssociatedPANCoord;}
+  command ieee154_macMaxBE_t MLME_GET.macMaxBE() { return m_pib.macMaxBE;}
 
-  command ieee154_macMaxBE_t MLME_GET.macMaxBE(){ return m_pib.macMaxBE;}
+  command ieee154_macMaxFrameTotalWaitTime_t MLME_GET.macMaxFrameTotalWaitTime() { return m_pib.macMaxFrameTotalWaitTime;}
 
-  command ieee154_macMaxFrameTotalWaitTime_t MLME_GET.macMaxFrameTotalWaitTime(){ return m_pib.macMaxFrameTotalWaitTime;}
+  command ieee154_macMaxFrameRetries_t MLME_GET.macMaxFrameRetries() { return m_pib.macMaxFrameRetries;}
 
-  command ieee154_macMaxFrameRetries_t MLME_GET.macMaxFrameRetries(){ return m_pib.macMaxFrameRetries;}
+  command ieee154_macResponseWaitTime_t MLME_GET.macResponseWaitTime() { return m_pib.macResponseWaitTime;}
 
-  command ieee154_macResponseWaitTime_t MLME_GET.macResponseWaitTime(){ return m_pib.macResponseWaitTime;}
+  command ieee154_macSyncSymbolOffset_t MLME_GET.macSyncSymbolOffset() { return IEEE154_SYNC_SYMBOL_OFFSET;}
 
-  command ieee154_macSyncSymbolOffset_t MLME_GET.macSyncSymbolOffset(){ return IEEE154_SYNC_SYMBOL_OFFSET;}
+  command ieee154_macTimestampSupported_t MLME_GET.macTimestampSupported() { return IEEE154_TIMESTAMP_SUPPORTED;}
 
-  command ieee154_macTimestampSupported_t MLME_GET.macTimestampSupported(){ return IEEE154_TIMESTAMP_SUPPORTED;}
+  command ieee154_macSecurityEnabled_t MLME_GET.macSecurityEnabled() { return m_pib.macSecurityEnabled;}
 
-  command ieee154_macSecurityEnabled_t MLME_GET.macSecurityEnabled(){ return m_pib.macSecurityEnabled;}
+  command ieee154_macMinLIFSPeriod_t MLME_GET.macMinLIFSPeriod() { return IEEE154_MIN_LIFS_PERIOD;}
 
-  command ieee154_macMinLIFSPeriod_t MLME_GET.macMinLIFSPeriod(){ return IEEE154_MIN_LIFS_PERIOD;}
+  command ieee154_macMinSIFSPeriod_t MLME_GET.macMinSIFSPeriod() { return IEEE154_MIN_SIFS_PERIOD;}
 
-  command ieee154_macMinSIFSPeriod_t MLME_GET.macMinSIFSPeriod(){ return IEEE154_MIN_SIFS_PERIOD;}
+  command ieee154_macPanCoordinator_t MLME_GET.macPanCoordinator() { return m_pib.macPanCoordinator;}
 
-/* ----------------------- MLME-SET ----------------------- */
+  /* ----------------------- MLME-SET ----------------------- */
 
-  command ieee154_status_t MLME_SET.phyCurrentChannel(ieee154_phyCurrentChannel_t value){
+  command ieee154_status_t MLME_SET.phyCurrentChannel(ieee154_phyCurrentChannel_t value) {
     uint32_t i = 1;
     uint8_t k = value;
-    while (i && k){
+    while (i && k) {
       i <<= 1;
       k -= 1;
     }
@@ -337,13 +338,13 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.phyTransmitPower(ieee154_phyTransmitPower_t value){
+  command ieee154_status_t MLME_SET.phyTransmitPower(ieee154_phyTransmitPower_t value) {
     m_pib.phyTransmitPower = (value & 0x3F);
     signal PIBUpdate.notify[IEEE154_phyTransmitPower](&m_pib.phyTransmitPower);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.phyCCAMode(ieee154_phyCCAMode_t value){
+  command ieee154_status_t MLME_SET.phyCCAMode(ieee154_phyCCAMode_t value) {
     if (value < 1 || value > 3)
       return IEEE154_INVALID_PARAMETER;
     m_pib.phyCCAMode = value;
@@ -351,7 +352,7 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.phyCurrentPage(ieee154_phyCurrentPage_t value){
+  command ieee154_status_t MLME_SET.phyCurrentPage(ieee154_phyCurrentPage_t value) {
     if (value > 31)
       return IEEE154_INVALID_PARAMETER;
     m_pib.phyCurrentPage = value;
@@ -359,25 +360,25 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macAssociationPermit(ieee154_macAssociationPermit_t value){
+  command ieee154_status_t MLME_SET.macAssociationPermit(ieee154_macAssociationPermit_t value) {
     m_pib.macAssociationPermit = value;
     signal PIBUpdate.notify[IEEE154_macAssociationPermit](&m_pib.macAssociationPermit);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macAutoRequest(ieee154_macAutoRequest_t value){
+  command ieee154_status_t MLME_SET.macAutoRequest(ieee154_macAutoRequest_t value) {
     m_pib.macAutoRequest = value;
     signal PIBUpdate.notify[IEEE154_macAutoRequest](&m_pib.macAutoRequest);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macBattLifeExt(ieee154_macBattLifeExt_t value){
+  command ieee154_status_t MLME_SET.macBattLifeExt(ieee154_macBattLifeExt_t value) {
     m_pib.macBattLifeExt = value;
     signal PIBUpdate.notify[IEEE154_macBattLifeExt](&m_pib.macBattLifeExt);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macBattLifeExtPeriods(ieee154_macBattLifeExtPeriods_t value){
+  command ieee154_status_t MLME_SET.macBattLifeExtPeriods(ieee154_macBattLifeExtPeriods_t value) {
     if (value < 6 || value > 41)
       return IEEE154_INVALID_PARAMETER;
     m_pib.macBattLifeExtPeriods = value;
@@ -385,7 +386,7 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macBeaconOrder(ieee154_macBeaconOrder_t value){
+  command ieee154_status_t MLME_SET.macBeaconOrder(ieee154_macBeaconOrder_t value) {
     if (value > 15)
       return IEEE154_INVALID_PARAMETER;
     m_pib.macBeaconOrder = value;
@@ -393,37 +394,37 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macBSN(ieee154_macBSN_t value){
+  command ieee154_status_t MLME_SET.macBSN(ieee154_macBSN_t value) {
     m_pib.macBSN = value;
     signal PIBUpdate.notify[IEEE154_macBSN](&m_pib.macBSN);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macCoordExtendedAddress(ieee154_macCoordExtendedAddress_t value){
+  command ieee154_status_t MLME_SET.macCoordExtendedAddress(ieee154_macCoordExtendedAddress_t value) {
     m_pib.macCoordExtendedAddress = value;
     signal PIBUpdate.notify[IEEE154_macCoordExtendedAddress](&m_pib.macCoordExtendedAddress);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macCoordShortAddress(ieee154_macCoordShortAddress_t value){
+  command ieee154_status_t MLME_SET.macCoordShortAddress(ieee154_macCoordShortAddress_t value) {
     m_pib.macCoordShortAddress = value;
     signal PIBUpdate.notify[IEEE154_macCoordShortAddress](&m_pib.macCoordShortAddress);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macDSN(ieee154_macDSN_t value){
+  command ieee154_status_t MLME_SET.macDSN(ieee154_macDSN_t value) {
     m_pib.macDSN = value;
     signal PIBUpdate.notify[IEEE154_macDSN](&m_pib.macDSN);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macGTSPermit(ieee154_macGTSPermit_t value){
+  command ieee154_status_t MLME_SET.macGTSPermit(ieee154_macGTSPermit_t value) {
     m_pib.macGTSPermit = value;
     signal PIBUpdate.notify[IEEE154_macGTSPermit](&m_pib.macGTSPermit);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macMaxCSMABackoffs(ieee154_macMaxCSMABackoffs_t value){
+  command ieee154_status_t MLME_SET.macMaxCSMABackoffs(ieee154_macMaxCSMABackoffs_t value) {
     if (value > 5)
       return IEEE154_INVALID_PARAMETER;
     m_pib.macMaxCSMABackoffs = value;
@@ -432,7 +433,7 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macMinBE(ieee154_macMinBE_t value){
+  command ieee154_status_t MLME_SET.macMinBE(ieee154_macMinBE_t value) {
     if (value > m_pib.macMaxBE)
       return IEEE154_INVALID_PARAMETER;
     m_pib.macMinBE = value;
@@ -441,37 +442,37 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macPANId(ieee154_macPANId_t value){
+  command ieee154_status_t MLME_SET.macPANId(ieee154_macPANId_t value) {
     m_pib.macPANId = value;
     signal PIBUpdate.notify[IEEE154_macPANId](&m_pib.macPANId);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macRxOnWhenIdle(ieee154_macRxOnWhenIdle_t value){
+  command ieee154_status_t MLME_SET.macRxOnWhenIdle(ieee154_macRxOnWhenIdle_t value) {
     m_pib.macRxOnWhenIdle = value;
     signal PIBUpdate.notify[IEEE154_macRxOnWhenIdle](&m_pib.macRxOnWhenIdle);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macShortAddress(ieee154_macShortAddress_t value){
+  command ieee154_status_t MLME_SET.macShortAddress(ieee154_macShortAddress_t value) {
     m_pib.macShortAddress = value;
     signal PIBUpdate.notify[IEEE154_macShortAddress](&m_pib.macShortAddress);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macTransactionPersistenceTime(ieee154_macTransactionPersistenceTime_t value){
+  command ieee154_status_t MLME_SET.macTransactionPersistenceTime(ieee154_macTransactionPersistenceTime_t value) {
     m_pib.macTransactionPersistenceTime = value;
     signal PIBUpdate.notify[IEEE154_macTransactionPersistenceTime](&m_pib.macTransactionPersistenceTime);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macAssociatedPANCoord(ieee154_macAssociatedPANCoord_t value){
+  command ieee154_status_t MLME_SET.macAssociatedPANCoord(ieee154_macAssociatedPANCoord_t value) {
     m_pib.macAssociatedPANCoord = value;
     signal PIBUpdate.notify[IEEE154_macAssociatedPANCoord](&m_pib.macAssociatedPANCoord);
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macMaxBE(ieee154_macMaxBE_t value){
+  command ieee154_status_t MLME_SET.macMaxBE(ieee154_macMaxBE_t value) {
     if (value < 3 || value > 8)
       return IEEE154_INVALID_PARAMETER;
     m_pib.macMaxBE = value;
@@ -480,7 +481,7 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macMaxFrameTotalWaitTime(ieee154_macMaxFrameTotalWaitTime_t value){
+  command ieee154_status_t MLME_SET.macMaxFrameTotalWaitTime(ieee154_macMaxFrameTotalWaitTime_t value) {
     // equation 14 on page 160 defines how macMaxFrameTotalWaitTime is calculated;
     // its value depends only on other PIB attributes and constants - why does the standard 
     // allow setting it by the next higher layer ??
@@ -489,7 +490,7 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macMaxFrameRetries(ieee154_macMaxFrameRetries_t value){
+  command ieee154_status_t MLME_SET.macMaxFrameRetries(ieee154_macMaxFrameRetries_t value) {
     if (value > 7)
       return IEEE154_INVALID_PARAMETER;
     m_pib.macMaxFrameRetries = value;
@@ -497,7 +498,7 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macResponseWaitTime(ieee154_macResponseWaitTime_t value){
+  command ieee154_status_t MLME_SET.macResponseWaitTime(ieee154_macResponseWaitTime_t value) {
     if (value < 2 || value > 64)
       return IEEE154_INVALID_PARAMETER;
     m_pib.macResponseWaitTime = value;
@@ -505,31 +506,27 @@ implementation
     return IEEE154_SUCCESS;
   }
 
-  command ieee154_status_t MLME_SET.macSecurityEnabled(ieee154_macSecurityEnabled_t value){
+  command ieee154_status_t MLME_SET.macSecurityEnabled(ieee154_macSecurityEnabled_t value) {
     return IEEE154_UNSUPPORTED_ATTRIBUTE;
   }
   
   // Read-only attributes (writable only by MAC components)
-  command void SetMacSuperframeOrder.set( ieee154_macSuperframeOrder_t value ){
+  command void SetMacSuperframeOrder.set( ieee154_macSuperframeOrder_t value{
     m_pib.macSuperframeOrder = value;
     signal PIBUpdate.notify[IEEE154_macSuperframeOrder](&m_pib.macSuperframeOrder);
   }
 
-  command void SetMacBeaconTxTime.set( ieee154_macBeaconTxTime_t value ){
+  command void SetMacBeaconTxTime.set( ieee154_macBeaconTxTime_t value{
     m_pib.macBeaconTxTime = value;
     signal PIBUpdate.notify[IEEE154_macBeaconTxTime](&m_pib.macBeaconTxTime);
   }
 
-  command void SetMacPanCoordinator.set( ieee154_macPanCoordinator_t value ){
+  command void SetMacPanCoordinator.set( ieee154_macPanCoordinator_t value{
     m_pib.macPanCoordinator = value;
     signal PIBUpdate.notify[IEEE154_macPanCoordinator](&m_pib.macPanCoordinator);
   }
 
-  command ieee154_macPanCoordinator_t IsMacPanCoordinator.get(){
-    return m_pib.macPanCoordinator;
-  }
-
-/* ----------------------- TimeCalc ----------------------- */
+  /* ----------------------- TimeCalc ----------------------- */
 
   async command uint32_t TimeCalc.timeElapsed(uint32_t t0, uint32_t t1)
   {
@@ -551,11 +548,10 @@ implementation
     return (elapsed >= dt);
   }
 
-/* ----------------------- Frame Access ----------------------- */
+  /* ----------------------- Frame Access ----------------------- */
 
   command void Packet.clear(message_t* msg)
   {
-    uint8_t i;
     memset(msg->header, 0, sizeof(message_header_t));
     memset(msg->metadata, 0, sizeof(message_metadata_t));
   }
@@ -572,7 +568,7 @@ implementation
 
   command uint8_t Packet.maxPayloadLength()
   {
-#if TOSH_DATA_LENGTH < 118
+#if TOSH_DATA_LENGTH < IEEE154_aMaxMACPayloadSize
 #warning Payload portion in message_t is smaller than required (TOSH_DATA_LENGTH < IEEE154_aMaxMACPayloadSize). This means that larger packets cannot be sent/received.
 #endif
     return TOSH_DATA_LENGTH;
@@ -594,10 +590,10 @@ implementation
       bool PANIDCompression)      
   {
     uint8_t offset = MHR_INDEX_ADDRESS;
-    if (DstAddrMode == ADDR_MODE_SHORT_ADDRESS || DstAddrMode == ADDR_MODE_EXTENDED_ADDRESS){
+    if (DstAddrMode == ADDR_MODE_SHORT_ADDRESS || DstAddrMode == ADDR_MODE_EXTENDED_ADDRESS) {
       *((nxle_uint16_t*) &mhr[offset]) = DstPANId;
       offset += 2;
-      if (DstAddrMode == ADDR_MODE_SHORT_ADDRESS){
+      if (DstAddrMode == ADDR_MODE_SHORT_ADDRESS) {
         *((nxle_uint16_t*) &mhr[offset]) = DstAddr->shortAddress;
         offset += 2;
       } else {
@@ -605,12 +601,12 @@ implementation
         offset += 8; 
       }
     }
-    if (SrcAddrMode == ADDR_MODE_SHORT_ADDRESS || SrcAddrMode == ADDR_MODE_EXTENDED_ADDRESS){
-      if (DstPANId != SrcPANId || !PANIDCompression){
+    if (SrcAddrMode == ADDR_MODE_SHORT_ADDRESS || SrcAddrMode == ADDR_MODE_EXTENDED_ADDRESS) {
+      if (DstPANId != SrcPANId || !PANIDCompression) {
         *((nxle_uint16_t*) &mhr[offset]) = SrcPANId;
         offset += 2;
       }
-      if (SrcAddrMode == ADDR_MODE_SHORT_ADDRESS){
+      if (SrcAddrMode == ADDR_MODE_SHORT_ADDRESS) {
         *((nxle_uint16_t*) &mhr[offset]) = SrcAddr->shortAddress;
         offset += 2;
       } else {
@@ -635,10 +631,10 @@ implementation
     if ((*(nxle_uint16_t*) (&mhr[offset])) != m_pib.macPANId)
       return FALSE; // wrong PAN ID
     offset += 2;         
-    if ((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) == FC2_SRC_MODE_SHORT){
+    if ((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) == FC2_SRC_MODE_SHORT) {
       if ((*(nxle_uint16_t*) (&mhr[offset])) != m_pib.macCoordShortAddress)
         return FALSE;
-    } else if ((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) == FC2_SRC_MODE_EXTENDED){
+    } else if ((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) == FC2_SRC_MODE_EXTENDED) {
       if (!isCoordExtendedAddress(mhr + offset))
         return FALSE;
     }
@@ -653,12 +649,12 @@ implementation
     if (fcf1 & FC1_SECURITY_ENABLED)
       return FAIL; // not supported 
     idCompression = (fcf1 & FC1_PAN_ID_COMPRESSION);
-    if (fcf2 & 0x08){ // short or ext. address
+    if (fcf2 & 0x08) { // short or ext. address
       offset += 4; // pan id + short address
       if (fcf2 & 0x04) // ext. address
         offset += 6; // diff to short address
     }
-    if (fcf2 & 0x80){ // short or ext. address
+    if (fcf2 & 0x80) { // short or ext. address
       offset += 2;
       if (!idCompression)
         offset += 2;
@@ -789,7 +785,7 @@ implementation
     if ((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) == FC2_SRC_MODE_SHORT)
       address->shortAddress = *((nxle_uint16_t*) (&(mhr[offset])));
     else
-      call FrameUtility.convertToNative(&address->extendedAddress, (&(mhr[offset]) ));
+      call FrameUtility.convertToNative(&address->extendedAddress, (&(mhr[offset])));
     return SUCCESS;
   }
 
@@ -848,20 +844,19 @@ implementation
   command bool Frame.hasStandardCompliantHeader(message_t* frame)
   {
     uint8_t *mhr = MHR(frame);
-    if ( ((mhr[0] & FC1_FRAMETYPE_MASK) > 0x03) ||
+    if (((mhr[0] & FC1_FRAMETYPE_MASK) > 0x03) ||
          ((mhr[MHR_INDEX_FC2] & FC2_DEST_MODE_MASK) == 0x04) || 
          ((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) == 0x40) || 
 #ifndef IEEE154_SECURITY_ENABLED
          ((mhr[0] & FC1_SECURITY_ENABLED)) || 
 #endif
-         (mhr[MHR_INDEX_FC2] & FC2_FRAME_VERSION_2)
-        )
+         (mhr[MHR_INDEX_FC2] & FC2_FRAME_VERSION_2))
       return FALSE;
     else
       return TRUE;
   }
 
-/* ----------------------- Beacon Frame Access ----------------------- */
+  /* ----------------------- Beacon Frame Access ----------------------- */
 
   uint8_t getPendAddrSpecOffset(uint8_t *macPayloadField)
   {
@@ -891,11 +886,11 @@ implementation
     uint8_t pendAddrSpec = payload[pendAddrSpecOffset], i;
     if (((mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK) != FC1_FRAMETYPE_BEACON))
       return FAIL;
-    if (addrMode == ADDR_MODE_SHORT_ADDRESS){
+    if (addrMode == ADDR_MODE_SHORT_ADDRESS) {
       for (i=0; i<(pendAddrSpec & PENDING_ADDRESS_SHORT_MASK) && i<bufferSize; i++)
         buffer[i].shortAddress = *((nxle_uint16_t*) (payload + pendAddrSpecOffset + 1 + 2*i));
       return SUCCESS;
-    } else if (addrMode == ADDR_MODE_EXTENDED_ADDRESS){
+    } else if (addrMode == ADDR_MODE_EXTENDED_ADDRESS) {
       for (i=0; i<((pendAddrSpec & PENDING_ADDRESS_EXT_MASK) >> 4) && i<bufferSize; i++)
         call FrameUtility.convertToNative(&(buffer[i].extendedAddress),
             ((payload + pendAddrSpecOffset +
@@ -928,7 +923,7 @@ implementation
   {
     uint8_t *mhr = MHR(frame);
     uint8_t *payload = (uint8_t *) frame->data;
-    if ((mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_BEACON){
+    if ((mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_BEACON) {
       uint8_t pendAddrSpecOffset = getPendAddrSpecOffset(payload);
       uint8_t pendAddrSpec = payload[pendAddrSpecOffset];
       payload += (pendAddrSpecOffset + 1);
@@ -944,8 +939,8 @@ implementation
   {
     uint8_t *mhr = MHR(frame);
     uint8_t len = ((ieee154_header_t*) frame->header)->length & FRAMECTL_LENGTH_MASK;
-    if ((mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_BEACON){
-      uint8_t *payload = call Frame.getPayload(frame);
+    if ((mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_BEACON) {
+      uint8_t *payload = call BeaconFrame.getBeaconPayload(frame);
       len = len - (payload - (uint8_t *) frame->data);
     } 
     return len;
@@ -960,45 +955,47 @@ implementation
       message_t *frame,
       uint8_t LogicalChannel,
       uint8_t ChannelPage,
-      ieee154_PANDescriptor_t *PANDescriptor
-      )
+      ieee154_PANDescriptor_t *pdescriptor)
   {
     uint8_t *mhr = MHR(frame);
     uint8_t offset;
     ieee154_metadata_t *metadata = (ieee154_metadata_t*) frame->metadata;
 
-    if ( (mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK) != FC1_FRAMETYPE_BEACON ||
+    if ((mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK) != FC1_FRAMETYPE_BEACON ||
          (((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) != FC2_SRC_MODE_SHORT) && 
-          ((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) != FC2_SRC_MODE_EXTENDED)) )
+          ((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) != FC2_SRC_MODE_EXTENDED)))
       return FAIL;
-    PANDescriptor->CoordAddrMode = (mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) >> FC2_SRC_MODE_OFFSET;
+
+    pdescriptor->CoordAddrMode = (mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) >> FC2_SRC_MODE_OFFSET;
     offset = MHR_INDEX_ADDRESS;
-    PANDescriptor->CoordPANId = *((nxle_uint16_t*) &mhr[offset]);
+    pdescriptor->CoordPANId = *((nxle_uint16_t*) &mhr[offset]);
     offset += sizeof(ieee154_macPANId_t);
+
     if ((mhr[MHR_INDEX_FC2] & FC2_SRC_MODE_MASK) == FC2_SRC_MODE_SHORT)
-      PANDescriptor->CoordAddress.shortAddress = *((nxle_uint16_t*) &mhr[offset]);
+      pdescriptor->CoordAddress.shortAddress = *((nxle_uint16_t*) &mhr[offset]);
     else
-      call FrameUtility.convertToNative(&PANDescriptor->CoordAddress.extendedAddress, &mhr[offset]);
-    PANDescriptor->LogicalChannel = LogicalChannel;
-    PANDescriptor->ChannelPage = ChannelPage;
-    ((uint8_t*) &PANDescriptor->SuperframeSpec)[0] = frame->data[BEACON_INDEX_SF_SPEC1]; // little endian
-    ((uint8_t*) &PANDescriptor->SuperframeSpec)[1] = frame->data[BEACON_INDEX_SF_SPEC2];
-    PANDescriptor->GTSPermit = (frame->data[BEACON_INDEX_GTS_SPEC] & GTS_SPEC_PERMIT) ? 1 : 0;
-    PANDescriptor->LinkQuality = metadata->linkQuality;
-    PANDescriptor->TimeStamp = metadata->timestamp;
+      call FrameUtility.convertToNative(&pdescriptor->CoordAddress.extendedAddress, &mhr[offset]);
+
+    pdescriptor->LogicalChannel = LogicalChannel;
+    pdescriptor->ChannelPage = ChannelPage;
+    ((uint8_t*) &pdescriptor->SuperframeSpec)[0] = frame->data[BEACON_INDEX_SF_SPEC1]; // little endian
+    ((uint8_t*) &pdescriptor->SuperframeSpec)[1] = frame->data[BEACON_INDEX_SF_SPEC2];
+    pdescriptor->GTSPermit = (frame->data[BEACON_INDEX_GTS_SPEC] & GTS_SPEC_PERMIT) ? 1 : 0;
+    pdescriptor->LinkQuality = metadata->linkQuality;
+    pdescriptor->TimeStamp = metadata->timestamp;
 #ifndef IEEE154_SECURITY_ENABLED
-    PANDescriptor->SecurityFailure = IEEE154_SUCCESS;
-    PANDescriptor->SecurityLevel = 0;
-    PANDescriptor->KeyIdMode = 0;
-    PANDescriptor->KeySource = 0;
-    PANDescriptor->KeyIndex = 0;    
+    pdescriptor->SecurityFailure = IEEE154_SUCCESS;
+    pdescriptor->SecurityLevel = 0;
+    pdescriptor->KeyIdMode = 0;
+    pdescriptor->KeySource = 0;
+    pdescriptor->KeyIndex = 0;    
 #else
-#error Implementation of BeaconFrame.parsePANDescriptor() needs adaptation !
+#error Implementation of BeaconFrame.parsePANDescriptor() needs to be adapted!
 #endif
     return SUCCESS;   
   }
 
-/* ----------------------- FrameUtility, etc. ----------------------- */
+  /* ----------------------- FrameUtility, etc. ----------------------- */
 
   command uint64_t GetLocalExtendedAddress.get()
   {
@@ -1009,7 +1006,7 @@ implementation
   {
     uint8_t i;
     uint64_t srcCopy = *src;
-    for (i=0; i<8; i++){
+    for (i=0; i<8; i++) {
       destLE[i] = srcCopy;
       srcCopy >>= 8;
     }
@@ -1048,12 +1045,8 @@ implementation
     return dest == m_pib.macCoordExtendedAddress;
   }
 
-  command bool IsBeaconEnabledPAN.get()
-  {
-    return (m_panType == BEACON_ENABLED_PAN);
-  }
-
-  default event void PIBUpdate.notify[uint8_t PIBAttributeID](const void* PIBAttributeValue){}
-  command error_t PIBUpdate.enable[uint8_t PIBAttributeID](){return FAIL;}
-  command error_t PIBUpdate.disable[uint8_t PIBAttributeID](){return FAIL;}
+  default event void PIBUpdate.notify[uint8_t PIBAttributeID](const void* PIBAttributeValue) {}
+  command error_t PIBUpdate.enable[uint8_t PIBAttributeID]() {return FAIL;}
+  command error_t PIBUpdate.disable[uint8_t PIBAttributeID]() {return FAIL;}
+  async event void RadioToken.transferredFrom(uint8_t fromClient){ASSERT(0);}
 }
index df20b2a8e12768c2efc2824d118eaaa9e0a6077c..3b5c83aa0f3b3037e99d83b4ea53607f2d6cc23f 100644 (file)
@@ -52,7 +52,6 @@ module PollP
     interface FrameUtility;
     interface Pool<ieee154_txframe_t> as TxFramePool;
     interface Pool<ieee154_txcontrol_t> as TxControlPool;
-    interface Ieee802154Debug as Debug;
     interface MLME_GET;
     interface Get<uint64_t> as LocalExtendedAddress;
   }
@@ -65,7 +64,7 @@ implementation
   };
   int m_numPending;
   uint8_t m_dataRequestCmdID = CMD_FRAME_DATA_REQUEST;
-  void buildDataRequestFrame( uint8_t destAddrMode, uint16_t destPANId,
+  void assembleDataRequestFrame( uint8_t destAddrMode, uint16_t destPANId,
       uint8_t* DstAddr, uint8_t srcAddrMode, ieee154_txframe_t *txFrame);
 
   command error_t Init.init()
@@ -78,25 +77,24 @@ implementation
                           uint8_t coordAddrMode,
                           uint16_t coordPANID,
                           ieee154_address_t coordAddress,
-                          ieee154_security_t *security      
-                        )
+                          ieee154_security_t *security)
   {
     ieee154_txframe_t *txFrame;
     ieee154_txcontrol_t *txControl;
     uint8_t srcAddrMode = 2;
-    ieee154_status_t txStatus = IEEE154_SUCCESS;
+    ieee154_status_t status = IEEE154_SUCCESS;
     uint8_t coordAddressLE[8]; // little endian is what we want
 
     if (security && security->SecurityLevel)
-      txStatus = IEEE154_UNSUPPORTED_SECURITY;
+      status = IEEE154_UNSUPPORTED_SECURITY;
     else if (coordAddrMode < 2 || coordAddrMode > 3 || coordPANID == 0xFFFF)
-      txStatus = IEEE154_INVALID_PARAMETER; 
+      status = IEEE154_INVALID_PARAMETER; 
     else if (!(txFrame = call TxFramePool.get()))
       // none of the predefined return value really fits
-      txStatus = IEEE154_TRANSACTION_OVERFLOW; 
-    else if (!(txControl = call TxControlPool.get())){
+      status = IEEE154_TRANSACTION_OVERFLOW; 
+    else if (!(txControl = call TxControlPool.get())) {
       call TxFramePool.put(txFrame);
-      txStatus = IEEE154_TRANSACTION_OVERFLOW;
+      status = IEEE154_TRANSACTION_OVERFLOW;
     } else {
       txFrame->header = &txControl->header;
       txFrame->metadata = &txControl->metadata;
@@ -107,15 +105,17 @@ implementation
       txFrame->handle = HANDLE_MLME_POLL_REQUEST;
       if (call MLME_GET.macShortAddress() >= 0xFFFE)
         srcAddrMode = 3;
-      buildDataRequestFrame(coordAddrMode, coordPANID, coordAddressLE, srcAddrMode, txFrame);
-      if ((txStatus = call PollTx.transmit(txFrame)) != IEEE154_SUCCESS){
+      assembleDataRequestFrame(coordAddrMode, coordPANID, coordAddressLE, srcAddrMode, txFrame);
+      if ((status = call PollTx.transmit(txFrame)) != IEEE154_SUCCESS) {
         call TxFramePool.put(txFrame);
         call TxControlPool.put(txControl);
-        call Debug.log(LEVEL_IMPORTANT, PollP_ALLOC_FAIL1, 0, 0, 0);
+        status = IEEE154_TRANSACTION_OVERFLOW;
       } else 
         m_numPending++;
     }
-    return txStatus;
+
+    dbg_serial("PollP", "MLME_POLL.request -> result: %lu\n", (uint32_t) status);
+    return status;
   }
 
   command ieee154_status_t DataRequest.poll[uint8_t client](uint8_t CoordAddrMode, 
@@ -124,34 +124,36 @@ implementation
     ieee154_txframe_t *txFrame;
     ieee154_txcontrol_t *txControl;
     ieee154_status_t status = IEEE154_TRANSACTION_OVERFLOW;
-    call Debug.log(LEVEL_INFO, PollP_INTERNAL_POLL, CoordAddrMode, client, m_numPending);
-    if (client == SYNC_CLIENT && m_numPending != 0){
+
+    dbg_serial("PollP", "Internal Poll\n");
+    if (client == SYNC_POLL_CLIENT && m_numPending != 0) {
       // no point in auto-requesting if user request is pending
       signal DataRequest.pollDone[client]();
       return IEEE154_SUCCESS;
-    } else if ((txFrame = call TxFramePool.get())){
-      if (!(txControl = call TxControlPool.get()))
-        call TxFramePool.put(txFrame);
-      else {
+    } else if ((txFrame = call TxFramePool.get()) != NULL) {
+      if ((txControl = call TxControlPool.get()) != NULL) {
         txFrame->header = &txControl->header;
         txFrame->metadata = &txControl->metadata;
         txFrame->handle = client;
-        buildDataRequestFrame(CoordAddrMode, CoordPANId, 
+        assembleDataRequestFrame(CoordAddrMode, CoordPANId, 
             CoordAddressLE, srcAddrMode, txFrame);
-        if ((status = call PollTx.transmit(txFrame)) != IEEE154_SUCCESS){
+        if ((status = call PollTx.transmit(txFrame)) != IEEE154_SUCCESS) {
           call TxControlPool.put(txControl);
           call TxFramePool.put(txFrame);
-          call Debug.log(LEVEL_IMPORTANT, PollP_ALLOC_FAIL2, 0, 0, 0);
+          dbg_serial("PollP", "Tx Overflow\n");
         } else 
           m_numPending++;
-      }
+      } else {
+        call TxFramePool.put(txFrame);
+      } 
     }
+    dbg_serial("PollP", "Status %lu, numPending: %lu\n", (uint32_t) status, (uint32_t) m_numPending);
     if (status != IEEE154_SUCCESS)
       signal DataRequest.pollDone[client]();
     return status;
   }
 
-  void buildDataRequestFrame(uint8_t destAddrMode, uint16_t destPANId,
+  void assembleDataRequestFrame(uint8_t destAddrMode, uint16_t destPANId,
       uint8_t* destAddrPtrLE, uint8_t srcAddrMode, ieee154_txframe_t *txFrame)
   {
     // destAddrPtrLE points to an address in little-endian format !
@@ -187,26 +189,25 @@ implementation
 
   event message_t* DataExtracted.received(message_t* frame, ieee154_txframe_t *txFrame)
   {
-    if (!txFrame){
-      call Debug.log(LEVEL_CRITICAL, PollP_INTERNAL_ERROR, 0, 0, 0);
+    if (!txFrame) {
+      dbg_serial("PollP", "Internal error\n");
       return frame;
     } else
-      call Debug.log(LEVEL_INFO, PollP_SUCCESS, 0, 0, 0);
+      dbg_serial("PollP", "Extracted data successfully\n");
     if (txFrame->handle == HANDLE_MLME_POLL_REQUEST)
       signal MLME_POLL.confirm(IEEE154_SUCCESS);
     else
       signal DataRequest.pollDone[txFrame->handle]();
     txFrame->handle = HANDLE_MLME_POLL_SUCCESS; // mark as processed
     // TODO: check if pending bit is set (then initiate another POLL)
-    call Debug.log(LEVEL_IMPORTANT, PollP_RX, txFrame->handle, 0, 0);
     return signal DataRx.received(frame);
   }
 
   event void PollTx.transmitDone(ieee154_txframe_t *txFrame, ieee154_status_t status)
   {
-    call Debug.log(LEVEL_IMPORTANT, PollP_TXDONE, status, txFrame->handle, 0);
+    dbg_serial("PollP", "transmitDone()\n");
     m_numPending--;
-    if (txFrame->handle != HANDLE_MLME_POLL_SUCCESS){
+    if (txFrame->handle != HANDLE_MLME_POLL_SUCCESS) {
       // didn't receive a DATA frame from the coordinator
       if (status == IEEE154_SUCCESS) // TODO: can this happen if a frame other than DATA was extracted?
         status = IEEE154_NO_DATA;
@@ -218,6 +219,6 @@ implementation
     call TxControlPool.put((ieee154_txcontrol_t*) ((uint8_t*) txFrame->header - offsetof(ieee154_txcontrol_t, header)));
     call TxFramePool.put(txFrame);
   }
-  default event void MLME_POLL.confirm(ieee154_status_t status){}
-  default event void DataRequest.pollDone[uint8_t client](){}
+  default event void MLME_POLL.confirm(ieee154_status_t status) {}
+  default event void DataRequest.pollDone[uint8_t client]() {}
 }
diff --git a/tos/lib/mac/tkn154/PromiscuousModeP.nc b/tos/lib/mac/tkn154/PromiscuousModeP.nc
new file mode 100644 (file)
index 0000000..2997f89
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154_PHY.h"
+#include "TKN154_MAC.h"
+module PromiscuousModeP 
+{
+  provides {
+    interface Init;
+    interface SplitControl as PromiscuousMode;
+    interface Get<bool> as PromiscuousModeGet;
+    interface FrameRx;
+    interface GetNow<token_requested_t> as IsRadioTokenRequested;
+  } uses {
+    interface TransferableResource as RadioToken;
+    interface RadioRx as PromiscuousRx;
+    interface RadioOff;
+    interface Set<bool> as RadioPromiscuousMode;
+  }
+}
+implementation
+{
+  norace enum promiscuous_state {
+    S_STOPPING,
+    S_STOPPED,
+    S_STARTING,
+    S_STARTED,
+  } m_state;
+
+  command error_t Init.init()
+  {
+    m_state = S_STOPPED;
+    return SUCCESS;
+  }
+
+  /* ----------------------- Promiscuous Mode ----------------------- */
+
+  command bool PromiscuousModeGet.get()
+  {
+    return (m_state == S_STARTED);
+  }
+
+  command error_t PromiscuousMode.start()
+  {
+    error_t result = FAIL;
+    if (m_state == S_STOPPED) {
+      m_state = S_STARTING;
+      call RadioToken.request();
+      result = SUCCESS;
+    }
+    dbg_serial("PromiscuousModeP", "PromiscuousMode.start -> result: %lu\n", (uint32_t) result);
+    return result;
+  }
+
+  event void RadioToken.granted()
+  {
+    call RadioPromiscuousMode.set(TRUE);
+    if (call RadioOff.isOff())
+      signal RadioOff.offDone();
+    else
+      call RadioOff.off();
+  }
+
+  task void signalStartDoneTask()
+  {
+    m_state = S_STARTED;
+    dbg_serial("PromiscuousModeP", "Promiscuous mode enabled.\n");
+    signal PromiscuousMode.startDone(SUCCESS);
+  }
+
+  async event void PromiscuousRx.enableRxDone()
+  {
+    post signalStartDoneTask();
+  }
+
+  event message_t* PromiscuousRx.received(message_t *frame, const ieee154_timestamp_t *timestamp)
+  {
+    if (m_state == S_STARTED) {
+      ((ieee154_header_t*) frame->header)->length |= FRAMECTL_PROMISCUOUS;
+      return signal FrameRx.received(frame);
+    } else
+      return frame;
+  }
+
+  command error_t PromiscuousMode.stop()
+  {
+    error_t result = FAIL;
+    if (m_state == S_STARTED) {
+      m_state = S_STOPPING;
+      call RadioOff.off();
+      result = SUCCESS;
+    }
+    dbg_serial("PromiscuousModeP", "PromiscuousMode.stop -> result: %lu\n", (uint32_t) result);
+    return result;
+  }
+
+  task void continueStopTask()
+  {
+    call RadioPromiscuousMode.set(FALSE);
+    m_state = S_STOPPED;
+    call RadioToken.release();
+    dbg_serial("PromiscuousModeP", "Promiscuous mode disabled.\n");
+    signal PromiscuousMode.stopDone(SUCCESS);
+  }
+
+  async event void RadioOff.offDone()
+  {
+    if (m_state == S_STARTING) {
+      call PromiscuousRx.enableRx(0, 0);
+    } else
+      post continueStopTask();
+  }
+
+  async command token_requested_t IsRadioTokenRequested.getNow(){ return m_state == S_STARTING; }
+  default event void PromiscuousMode.startDone(error_t error) {}
+  default event void PromiscuousMode.stopDone(error_t error) {}
+  async event void RadioToken.transferredFrom(uint8_t clientFrom){ASSERT(0);}
+}
index e9b4bd3eada666177d43854da421047b5f87d882..6a081b619d09f9b85623496013fca7a2c53257f6 100644 (file)
@@ -1,25 +1,34 @@
 This directory contains "TKN15.4", a platform-independent IEEE 802.15.4-2006
-MAC implementation. The code is in alpha state, under active development, but
-most of the functionality described in the standard is implemented (and
-cursorily tested). The MAC itself is platform-independent, but it requires
-(1) a suitable radio driver, (2) Alarms/Timers with symbol precision and (3)
-some "platform glue" code (defining guard times, etc.). Currently the only
-supported platform is TelosB (however: without additional hardware support on
-TelosB the timing in beacon-enabled mode is not standard compliant).
+MAC implementation. The code is under active development and most of the
+functionality described in the standard is implemented and tested.  The MAC
+itself is platform-independent, but it requires (1) a suitable radio driver,
+(2) Alarms/Timers with symbol precision and (3) some "platform glue" code
+(defining guard times, etc.). Currently the only supported platforms are TelosB
+and micaZ (note: because they do not have a clock that satisfies the
+precision/accuracy requirements of the IEEE 802.15.4 standard -- 62.500 Hz,
++-40 ppm in the 2.4 GHz band -- the timing in beacon-enabled mode is not
+standard compliant).
 
-Status 6/16/08
---------------
+Status (last updated 9/14/09)
+-----------------------------
 
-missing functionality:
-- security (not planned)
-- GTS (not planned)
-- PAN ID conflict resolution
-- multiple indirect transmissions to the same destination
+Missing functionality:
+- GTS
+- security services
+- PAN ID conflict notification/resolution
+- indirect transmissions: frames are not kept in transaction queue 
+  in case CSMA-CA algorithm fails
 
-missing documentation:
-- overview on the architecture of TKN15.4
-- guidance on porting TKN15.4 to a new platform
-- ...
+Known Issues:
+- resetting the MAC during operation (via MLME_RESET) has not been tested
+- if initial beacon Tx timestamp is invalid, the coordinator will hang 
+- frame pending flags are (need to be) always set in the ACK headers
+- transmitting coordinator realignment frames has not been tested
+- using an incoming and outgoing superframe at the same time has not been tested
+- during an ongoing CSMA-CA transmission incoming frames are ignored
+- on a beacon-enabled PAN: if the device cannot find the beacon the DATA frame 
+  is not transmitted (but it should be transmitted using unslotted CSMA-CA, see 
+  Sect. 7.5.6.1 "Transmission")
 
 Implementation 
 --------------
@@ -28,6 +37,7 @@ MAC implementation: tinyos-2.x/tos/lib/mac/tkn154
 MAC interfaces: tinyos-2.x/tos/lib/mac/tkn154/interfaces
 CC2420 driver: tinyos-2.x/tos/chips/cc2420_tkn154
 TelosB "platform glue" code: tinyos-2.x/tos/platforms/telosb/mac/tkn154
+micaZ "platform glue" code: tinyos-2.x/tos/platforms/micaz/mac/tkn154
 Example applications: tinyos-2.x/apps/tests/tkn154
 
 Note: TEP3 recommends that interface names "should be mixed case, starting
@@ -35,16 +45,26 @@ upper case". To match the syntax used in the IEEE 802.15.4 standard the
 interfaces provided by the MAC to the next higher layer deviate from this
 convention (they are all caps, e.g. MLME_START).
 
+Documentation
+-------------
+
+A technical report on TKN15.4 is available here:
+http://www.tkn.tu-berlin.de/publications/papers/TKN154.pdf
+
+TKN15.4 is the basis for the implementation of the TinyOS 15.4 WG:
+http://tinyos.stanford.edu:8000/15.4_WG
+
 Copyright
 ---------
 
-This work was supported by the the European Commision within the 6th Framework
-Project 2005-IST-5-033406-STP (ANGEL project)
+This work was supported by the European Commision within the 6th Framework
+Programme ICT Project ANGEL (Reference: 033506) and within the 7th Framework
+Programme ICT Project CONET (Reference: 224053).
 
 Author: Jan-Hinrich Hauer <hauer@tkn.tu-berlin.de>
 
 /*
- * Copyright (c) 2008, Technische Universitaet Berlin
+ * Copyright (c) 2009, Technische Universitaet Berlin
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without 
index 53b6e9b78f4ad834e01eecc0c936a48c967cb338..a9fd02cf81f144a4fe16d94eba9a9d00dd1303c1 100644 (file)
  * @author Jan Hauer <hauer@tkn.tu-berlin.de>
  * ========================================================================
  */
+
 #include "TKN154_MAC.h"
-generic configuration RadioClientC() 
+generic configuration RadioClientC(uint8_t clientID
 {
   provides
   {
+    interface RadioOff;
     interface RadioRx;
     interface RadioTx;
-    interface RadioOff;
-    interface Resource as Token;
-    interface ResourceRequested as TokenRequested;
-    interface ResourceTransfer;
-    interface ResourceTransferred;
-    interface ResourceTransferConnector as TransferFrom;
-    interface GetNow<bool> as IsResourceRequested;
-  } uses {
-    interface ResourceTransferConnector as TransferTo;
+    interface SlottedCsmaCa;
+    interface UnslottedCsmaCa;
+    interface TransferableResource as RadioToken;
+    interface ResourceRequested as RadioTokenRequested;
   }
 }
 implementation
 {
-  enum {
-    CLIENT = unique(IEEE802154_RADIO_RESOURCE),
-  };
-
-  components FrameDispatchP;
-  RadioRx = FrameDispatchP.RadioRx[CLIENT];
-  RadioTx = FrameDispatchP.RadioTx[CLIENT];
-  RadioOff = FrameDispatchP.RadioOff[CLIENT];
-  Token = FrameDispatchP.Token[CLIENT];
-  IsResourceRequested = FrameDispatchP.IsResourceRequested;
-  TokenRequested = FrameDispatchP.TokenRequested[CLIENT];
-
-  components new TransferClientP(CLIENT);
-  ResourceTransfer = TransferClientP;
-  ResourceTransferred = TransferClientP;
-  TransferTo = TransferClientP;
-  TransferFrom = TransferClientP;
-  TransferClientP.ResourceTransferControl -> FrameDispatchP;
-  TransferClientP.Leds -> FrameDispatchP;
+  components RadioControlP;
+  RadioRx = RadioControlP.RadioRx[clientID];
+  RadioTx = RadioControlP.RadioTx[clientID];
+  RadioOff = RadioControlP.RadioOff[clientID];
+  SlottedCsmaCa = RadioControlP.SlottedCsmaCa[clientID];
+  UnslottedCsmaCa = RadioControlP.UnslottedCsmaCa[clientID];
+  RadioToken = RadioControlP.TransferableResource[clientID];
+  RadioTokenRequested = RadioControlP.ResourceRequested[clientID];
 }
 
diff --git a/tos/lib/mac/tkn154/RadioControlImplP.nc b/tos/lib/mac/tkn154/RadioControlImplP.nc
new file mode 100644 (file)
index 0000000..afafb8c
--- /dev/null
@@ -0,0 +1,221 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154_MAC.h"
+
+module RadioControlImplP 
+{
+  provides
+  {
+    interface RadioRx as MacRx[uint8_t client];
+    interface RadioTx as MacTx[uint8_t client];
+    interface SlottedCsmaCa as SlottedCsmaCa[uint8_t client];
+    interface UnslottedCsmaCa as UnslottedCsmaCa[uint8_t client];
+    interface RadioOff as MacRadioOff[uint8_t client];
+  } uses {
+    interface ArbiterInfo;
+    interface RadioRx as PhyRx;
+    interface RadioTx as PhyTx;
+    interface SlottedCsmaCa as PhySlottedCsmaCa;
+    interface UnslottedCsmaCa as PhyUnslottedCsmaCa;
+    interface RadioOff as PhyRadioOff;
+    interface Get<bool> as RadioPromiscuousMode;
+    interface Leds;
+  }
+}
+implementation
+{
+
+  /* ----------------------- RadioRx ----------------------- */
+
+  async command error_t MacRx.enableRx[uint8_t client](uint32_t t0, uint32_t dt)
+  {
+    if (client == call ArbiterInfo.userId()) 
+      return call PhyRx.enableRx(t0, dt);
+    else {
+      ASSERT(0);
+      return IEEE154_TRANSACTION_OVERFLOW;
+    }
+  }
+
+  async event void PhyRx.enableRxDone()
+  {
+    signal MacRx.enableRxDone[call ArbiterInfo.userId()]();
+  }
+
+  event message_t* PhyRx.received(message_t *msg, const ieee154_timestamp_t *timestamp)
+  {
+    uint8_t *mhr = MHR(msg);
+
+    dbg("RadioControlImplP", "Received frame, DSN: %lu, type: 0x%lu\n", 
+        (uint32_t) mhr[MHR_INDEX_SEQNO], (uint32_t) mhr[MHR_INDEX_FC1] & FC1_FRAMETYPE_MASK);
+
+    if (((mhr[1] & FC2_FRAME_VERSION_MASK) > FC2_FRAME_VERSION_1)
+        && (!call RadioPromiscuousMode.get()))
+      return msg;
+
+#ifndef IEEE154_SECURITY_ENABLED
+    if ((mhr[0] & FC1_SECURITY_ENABLED)
+        && (!call RadioPromiscuousMode.get()))
+      return msg;
+#endif
+    return signal MacRx.received[call ArbiterInfo.userId()](msg, timestamp);
+  }
+
+  async command bool MacRx.isReceiving[uint8_t client]()
+  {
+    if (client == call ArbiterInfo.userId())
+      return call PhyRx.isReceiving();
+    else {
+      ASSERT(0);
+      return FAIL;
+    } 
+  }
+
+  default async event void MacRx.enableRxDone[uint8_t client]() { ASSERT(0); }
+
+  default event message_t* MacRx.received[uint8_t client](message_t *frame, const ieee154_timestamp_t *timestamp)
+  {
+    ASSERT(0);
+    return frame;
+  }
+
+  /* ----------------------- RadioTx ----------------------- */
+
+  async command error_t MacTx.transmit[uint8_t client](ieee154_txframe_t *frame, 
+      const ieee154_timestamp_t *t0, uint32_t dt)
+  {
+    if (client == call ArbiterInfo.userId())
+      return call PhyTx.transmit(frame, t0, dt);
+    else {
+      ASSERT(0);
+      return IEEE154_TRANSACTION_OVERFLOW;
+    }
+  }
+  
+  async event void PhyTx.transmitDone(ieee154_txframe_t *frame, 
+      const ieee154_timestamp_t *timestamp, error_t result)
+  {
+    signal MacTx.transmitDone[call ArbiterInfo.userId()](frame, timestamp, result);
+  }
+
+  default async event void MacTx.transmitDone[uint8_t client](ieee154_txframe_t *frame, 
+      const ieee154_timestamp_t *timestamp, error_t result) 
+  {
+    ASSERT(0);
+  }
+
+  /* ----------------------- Unslotted CSMA ----------------------- */
+
+  async command error_t UnslottedCsmaCa.transmit[uint8_t client](ieee154_txframe_t *frame, ieee154_csma_t *csma)
+  {
+    if (client == call ArbiterInfo.userId()) 
+      return call PhyUnslottedCsmaCa.transmit(frame, csma);
+    else {
+      ASSERT(0);
+      return IEEE154_TRANSACTION_OVERFLOW;
+    }
+  }
+
+  async event void PhyUnslottedCsmaCa.transmitDone(ieee154_txframe_t *frame, ieee154_csma_t *csma, bool ackPendingFlag, error_t result)
+  {
+    signal UnslottedCsmaCa.transmitDone[call ArbiterInfo.userId()](
+        frame, csma, ackPendingFlag, result);
+  }
+
+  default async event void UnslottedCsmaCa.transmitDone[uint8_t client](
+      ieee154_txframe_t *frame, ieee154_csma_t *csma, bool ackPendingFlag, error_t result)
+  {
+    ASSERT(0);
+  }
+
+  /* ----------------------- Slotted CSMA ----------------------- */
+
+  async command error_t SlottedCsmaCa.transmit[uint8_t client](ieee154_txframe_t *frame, ieee154_csma_t *csma,
+      const ieee154_timestamp_t *slot0Time, uint32_t dtMax, bool resume, uint16_t remainingBackoff)
+  {
+    if (client == call ArbiterInfo.userId()) 
+      return call PhySlottedCsmaCa.transmit(frame, csma, slot0Time, dtMax, resume, remainingBackoff);
+    else {
+      ASSERT(0);
+      return IEEE154_TRANSACTION_OVERFLOW;
+    }
+  }
+
+  async event void PhySlottedCsmaCa.transmitDone(ieee154_txframe_t *frame, ieee154_csma_t *csma, 
+      bool ackPendingFlag,  uint16_t remainingBackoff, error_t result)
+  {
+    signal SlottedCsmaCa.transmitDone[call ArbiterInfo.userId()](
+        frame, csma, ackPendingFlag, remainingBackoff, result);
+  }
+
+  default async event void SlottedCsmaCa.transmitDone[uint8_t client](
+      ieee154_txframe_t *frame, ieee154_csma_t *csma, 
+      bool ackPendingFlag,  uint16_t remainingBackoff, error_t result)
+  {
+    ASSERT(0);
+  }
+
+  /* ----------------------- RadioOff ----------------------- */
+
+  async command error_t MacRadioOff.off[uint8_t client]()
+  {
+    if (client == call ArbiterInfo.userId())
+      return call PhyRadioOff.off();
+    else {
+      ASSERT(0);
+      return EBUSY;
+    }
+  }
+
+  async event void PhyRadioOff.offDone()
+  {
+    signal MacRadioOff.offDone[call ArbiterInfo.userId()]();
+  }
+
+  
+  async command bool MacRadioOff.isOff[uint8_t client]()
+  {
+    if (client == call ArbiterInfo.userId())
+      return call PhyRadioOff.isOff();
+    else
+      return EBUSY;
+  }
+
+  default async event void MacRadioOff.offDone[uint8_t client]()
+  {
+    ASSERT(0);
+  }
+}
diff --git a/tos/lib/mac/tkn154/RadioControlP.nc b/tos/lib/mac/tkn154/RadioControlP.nc
new file mode 100644 (file)
index 0000000..a9e9a2e
--- /dev/null
@@ -0,0 +1,86 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154_MAC.h"
+configuration RadioControlP  
+{
+  provides
+  {
+    interface RadioRx as RadioRx[uint8_t client];
+    interface RadioTx as RadioTx[uint8_t client];
+    interface SlottedCsmaCa as SlottedCsmaCa[uint8_t client];
+    interface UnslottedCsmaCa as UnslottedCsmaCa[uint8_t client];
+    interface RadioOff as RadioOff[uint8_t client];
+    interface TransferableResource[uint8_t id];
+    interface ResourceRequested[uint8_t id];
+  } uses {
+    interface RadioRx as PhyRx;
+    interface RadioTx as PhyTx;
+    interface SlottedCsmaCa as PhySlottedCsmaCa;
+    interface UnslottedCsmaCa as PhyUnslottedCsmaCa;
+    interface RadioOff as PhyRadioOff;
+    interface Get<bool> as RadioPromiscuousMode;
+    interface ResourceConfigure[uint8_t id];
+    interface Leds;
+  }
+}
+implementation
+{
+  components RadioControlImplP;
+  RadioRx = RadioControlImplP.MacRx;
+  RadioTx = RadioControlImplP.MacTx;
+  SlottedCsmaCa = RadioControlImplP.SlottedCsmaCa;
+  UnslottedCsmaCa = RadioControlImplP.UnslottedCsmaCa;
+  RadioOff = RadioControlImplP.MacRadioOff;
+  PhyRx = RadioControlImplP.PhyRx;
+  PhyTx = RadioControlImplP.PhyTx;
+  PhySlottedCsmaCa = RadioControlImplP.PhySlottedCsmaCa;
+  PhyUnslottedCsmaCa = RadioControlImplP.PhyUnslottedCsmaCa;
+  PhyRadioOff = RadioControlImplP.PhyRadioOff;
+  RadioPromiscuousMode = RadioControlImplP;
+  Leds = RadioControlImplP;
+
+  components MainC;
+  components new RoundRobinResourceQueueC(uniqueCount(IEEE802154_RADIO_RESOURCE)) as Queue;
+  components new SimpleTransferArbiterP() as Arbiter;
+
+  MainC.SoftwareInit -> Queue;
+
+  TransferableResource = Arbiter;
+  ResourceRequested = Arbiter;
+  RadioControlImplP.ArbiterInfo -> Arbiter;
+  ResourceConfigure = Arbiter;
+
+  Arbiter.Queue -> Queue;
+}
index 6835bed8ae845b454253e3b6717c2967f086edde..5e260174532fba151ba5371707b1cd4b09f63266 100644 (file)
@@ -39,56 +39,36 @@ module RxEnableP
 {
   provides
   {
-    interface Init;
+    interface Init as Reset;
     interface MLME_RX_ENABLE;
-    interface SplitControl as PromiscuousMode;
-    interface FrameRx;
-    interface Get<bool> as PromiscuousModeGet;
     interface GetNow<bool> as IsRxEnableActive; 
     interface Notify<bool> as RxEnableStateChange;
   }
   uses
   {
-    interface Resource as Token;
-    interface RadioRx as PromiscuousRx;
-    interface RadioOff;
-    interface Set<bool> as RadioPromiscuousMode;
-    interface Ieee802154Debug as Debug;
     interface Timer<TSymbolIEEE802154> as RxEnableTimer;
-    interface Get<bool> as IsBeaconEnabledPAN;
     interface Get<ieee154_macPanCoordinator_t> as IsMacPanCoordinator;
+    interface SuperframeStructure as IncomingSuperframeStructure;
+    interface SuperframeStructure as OutgoingSuperframeStructure;
     interface GetNow<bool> as IsTrackingBeacons;
-    interface GetNow<uint32_t> as IncomingSfStart; 
-    interface GetNow<uint32_t> as IncomingBeaconInterval; 
-    interface Get<bool> as IsSendingBeacons;
-    interface GetNow<uint32_t> as OutgoingSfStart; 
-    interface GetNow<uint32_t> as OutgoingBeaconInterval; 
+    interface GetNow<bool> as IsSendingBeacons;
     interface Notify<bool> as WasRxEnabled;
     interface TimeCalc;
   }
 }
 implementation
 {
-  enum promiscuous_state {
-    S_IDLE,
-    S_STARTING,
-    S_STARTED,
-    S_STOPPING,
-  } m_promiscuousState;
 
   uint32_t m_rxOnDuration;
   uint32_t m_rxOnOffset;
   uint32_t m_rxOnAnchor;
   norace bool m_isRxEnabled;
-  bool m_isRxEnableConfirmPending;
+  bool m_confirmPending;
 
-  task void prepareDoneTask();
-  task void radioOffDoneTask();
-
-  command error_t Init.init()
+  command error_t Reset.init()
   {
-    if (m_isRxEnableConfirmPending){
-      m_isRxEnableConfirmPending = FALSE;
+    if (m_confirmPending) {
+      m_confirmPending = FALSE;
       signal MLME_RX_ENABLE.confirm(IEEE154_SUCCESS);
     }
     m_isRxEnabled = FALSE;
@@ -96,70 +76,79 @@ implementation
     return SUCCESS;
   }
 
-/* ----------------------- MLME-RX-ENABLE ----------------------- */
+  /* ----------------------- MLME-RX-ENABLE ----------------------- */
 
   command ieee154_status_t MLME_RX_ENABLE.request  ( 
                           bool DeferPermit,
                           uint32_t RxOnTime,
-                          uint32_t RxOnDuration
-                        )
+                          uint32_t RxOnDuration)
   {
+    ieee154_status_t status = IEEE154_SUCCESS;
     uint32_t lastBeaconTime=0;
     uint32_t beaconInterval=0;
 
-    if (m_isRxEnableConfirmPending)
-      return IEEE154_TRANSACTION_OVERFLOW;
-    if (RxOnTime > 0xFFFFFF || RxOnDuration > 0xFFFFFF)
-      return IEEE154_INVALID_PARAMETER;
-    if (call IsBeaconEnabledPAN.get()){
-      if (call IsSendingBeacons.get() && call IsMacPanCoordinator.get()){
+    if (m_confirmPending)
+      status = IEEE154_TRANSACTION_OVERFLOW;
+    else if (IEEE154_BEACON_ENABLED_PAN && RxOnTime > 0xFFFFFF)
+      status = IEEE154_INVALID_PARAMETER;
+    else if (RxOnDuration > 0xFFFFFF)
+      status = IEEE154_INVALID_PARAMETER;
+    else if (IEEE154_BEACON_ENABLED_PAN) {
+      if (call IsSendingBeacons.getNow() && call IsMacPanCoordinator.get()) {
         // for OUTGOING SUPERFRAME
-        lastBeaconTime = call OutgoingSfStart.getNow();
-        beaconInterval = call OutgoingBeaconInterval.getNow();
-      } else if (call IsTrackingBeacons.getNow()){
+        lastBeaconTime = call OutgoingSuperframeStructure.sfStartTime();
+        beaconInterval = call OutgoingSuperframeStructure.sfSlotDuration() * 16;
+      } else if (call IsTrackingBeacons.getNow()) {
         // for INCOMING SUPERFRAME 
-        lastBeaconTime = call IncomingSfStart.getNow();
-        beaconInterval = call IncomingBeaconInterval.getNow();
+        lastBeaconTime = call IncomingSuperframeStructure.sfStartTime();
+        beaconInterval = call IncomingSuperframeStructure.sfSlotDuration() * 16;
       }
       if (beaconInterval == 0)
-        return IEEE154_PAST_TIME; // we're not even sending/receiving beacons
-      if (RxOnTime+RxOnDuration >= beaconInterval)
-        return IEEE154_ON_TIME_TOO_LONG;
-      if (call TimeCalc.hasExpired(lastBeaconTime, RxOnTime - IEEE154_aTurnaroundTime)){
+        status = IEEE154_PAST_TIME; // we're not even sending/receiving beacons
+      else if (RxOnTime+RxOnDuration >= beaconInterval)
+        status = IEEE154_ON_TIME_TOO_LONG;
+      else if (call TimeCalc.hasExpired(lastBeaconTime, RxOnTime - IEEE154_aTurnaroundTime)) {
         if (!DeferPermit)
-          return IEEE154_PAST_TIME;
+          status = IEEE154_PAST_TIME;
         else {
           // defer to next beacon
           RxOnTime += beaconInterval;
         }
       }
-      m_rxOnAnchor = lastBeaconTime;
-      m_rxOnOffset = RxOnTime;
+      if (status == IEEE154_SUCCESS) {
+        m_rxOnAnchor = lastBeaconTime;
+        m_rxOnOffset = RxOnTime;
+      }
     } else {
+      // this is a nonbeacon-enabled PAN
       m_rxOnAnchor = call RxEnableTimer.getNow();
       m_rxOnOffset = 0;
     }
-    m_rxOnDuration = RxOnDuration;      
-    m_isRxEnabled = FALSE;
-    m_isRxEnableConfirmPending = TRUE;
-    call RxEnableTimer.startOneShotAt(m_rxOnAnchor, m_rxOnOffset);
-    signal RxEnableStateChange.notify(TRUE);
-    return IEEE154_SUCCESS;
+
+    if (status == IEEE154_SUCCESS) {
+      m_rxOnDuration = RxOnDuration;      
+      m_isRxEnabled = FALSE;
+      m_confirmPending = TRUE;
+      call RxEnableTimer.startOneShotAt(m_rxOnAnchor, m_rxOnOffset);
+      signal RxEnableStateChange.notify(TRUE);
+    }
+    dbg_serial("RxEnableP", "MLME_RX_ENABLE.request -> result: %lu\n", (uint32_t) status);
+    return status;
   }
 
   event void RxEnableTimer.fired()
   {
-    if (!m_isRxEnabled){
+    if (!m_isRxEnabled) {
       m_isRxEnabled = TRUE;
       call RxEnableTimer.startOneShotAt(m_rxOnAnchor, m_rxOnOffset + m_rxOnDuration);
     } else {
       m_isRxEnabled = FALSE;
-      if (m_isRxEnableConfirmPending){
-        // this means we tried to enable rx, but never
-        // succeeded, because there were  "other 
-        // responsibilities" - but is SUCCESS really
+      if (m_confirmPending) {
+        // this means we tried to enable rx, but never succeeded, because
+        // there were  "other responsibilities" - but is SUCCESS really
         // an appropriate error code in this case?
-        m_isRxEnableConfirmPending = FALSE;
+        m_confirmPending = FALSE;
+        dbg_serial("RxEnableP", "never actually managed to switch to Rx mode\n");
         signal MLME_RX_ENABLE.confirm(IEEE154_SUCCESS);
       }
     }
@@ -171,104 +160,23 @@ implementation
     return m_isRxEnabled;
   }
 
-  event void WasRxEnabled.notify( bool val )
+  event void WasRxEnabled.notify(bool val)
   {
-    if (m_isRxEnabled && m_isRxEnableConfirmPending){
-      m_isRxEnableConfirmPending = FALSE;
+    if (m_isRxEnabled && m_confirmPending) {
+      m_confirmPending = FALSE;
+      dbg_serial("RxEnableP", "MLME_RX_ENABLE.confirm, radio is now in Rx mode\n");
       signal MLME_RX_ENABLE.confirm(IEEE154_SUCCESS);
     }
   }
 
-  command error_t RxEnableStateChange.enable(){return FAIL;}
-  command error_t RxEnableStateChange.disable(){return FAIL;}
-
-/* ----------------------- Promiscuous Mode ----------------------- */
-
-  command bool PromiscuousModeGet.get()
-  {
-    return (m_promiscuousState == S_STARTED);
-  }
-
-  command error_t PromiscuousMode.start()
-  {
-    if (m_promiscuousState != S_IDLE)
-      return FAIL;
-    m_promiscuousState = S_STARTING;
-    call Token.request();
-    call Debug.log(LEVEL_INFO, EnableRxP_PROMISCUOUS_REQUEST, m_promiscuousState, 0, 0);
-    call Debug.flush();
-    return SUCCESS;
-  }
-
-  event void Token.granted()
-  {
-    if (m_promiscuousState != S_STARTING){
-      call Token.release();
-      return;
-    }
-    call RadioPromiscuousMode.set(TRUE);
-    if (call PromiscuousRx.prepare() != IEEE154_SUCCESS){
-      m_promiscuousState = S_IDLE;
-      call Token.release();
-      call Debug.log(LEVEL_IMPORTANT, EnableRxP_RADIORX_ERROR, 0, 0, 0);
-      signal PromiscuousMode.startDone(FAIL);
-    }
-  }
-
-  async event void PromiscuousRx.prepareDone()
-  {
-    post prepareDoneTask();
-  }
-
-  task void prepareDoneTask()
-  {
-    if (m_promiscuousState != S_STARTING){
-      call Token.release();
-      return;
-    }    
-    m_promiscuousState = S_STARTED;
-    call PromiscuousRx.receive(NULL, 0);
-    signal PromiscuousMode.startDone(SUCCESS);
-    call Debug.log(LEVEL_INFO, EnableRxP_PROMISCUOUS_ON, m_promiscuousState, 0, 0);
-  }
-
-  event message_t* PromiscuousRx.received(message_t *frame, ieee154_reftime_t *timestamp)
-  {
-    if (m_promiscuousState == S_STARTED){
-      ((ieee154_header_t*) frame->header)->length |= FRAMECTL_PROMISCUOUS;
-      return signal FrameRx.received(frame);
-    } else
-      return frame;
-  }
-
-  command error_t PromiscuousMode.stop()
-  {
-    if (m_promiscuousState != S_STARTED)
-      return FAIL;
-    m_promiscuousState = S_STOPPING;
-    call RadioOff.off();
-    return SUCCESS;
-  }
-
-  async event void RadioOff.offDone()
-  {
-    post radioOffDoneTask();
-  }
-
-  task void radioOffDoneTask()
-  {
-    if (m_promiscuousState != S_STOPPING){
-      call Token.release();
-      return;
-    }
-    m_promiscuousState = S_IDLE;
-    call RadioPromiscuousMode.set(FALSE);
-    call Token.release();
-    signal PromiscuousMode.stopDone(SUCCESS);
-    call Debug.log(LEVEL_INFO, EnableRxP_PROMISCUOUS_OFF, m_promiscuousState, 0, 0);
-  }
-
-  default event void PromiscuousMode.startDone(error_t error){}
-  default event void PromiscuousMode.stopDone(error_t error){}
-  default event void MLME_RX_ENABLE.confirm(ieee154_status_t status){}
+  command error_t RxEnableStateChange.enable() {return FAIL;}
+  command error_t RxEnableStateChange.disable() {return FAIL;}
+  default event void MLME_RX_ENABLE.confirm(ieee154_status_t status) {}
+  default async command uint32_t IncomingSuperframeStructure.sfStartTime() {return 0;}
+  default async command uint16_t IncomingSuperframeStructure.sfSlotDuration() {return 0;}
+  default async command uint32_t OutgoingSuperframeStructure.sfStartTime() {return 0;}
+  default async command uint16_t OutgoingSuperframeStructure.sfSlotDuration() {return 0;}
+  default async command bool IsTrackingBeacons.getNow() { return FALSE;}
+  default async command bool IsSendingBeacons.getNow() { return FALSE;}
+  default command ieee154_macPanCoordinator_t IsMacPanCoordinator.get() { return FALSE;}
 }
index d5cd2355d1c801a3aa111c6c8bc07bfb72567ec5..f8f44f77925727cc6df711cffad2cba2139c2f51 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * This module is responsible for channel scanning.
+ */
+
 #include "TKN154_MAC.h"
 module ScanP
 {
@@ -41,6 +45,7 @@ module ScanP
     interface Init;
     interface MLME_SCAN;
     interface MLME_BEACON_NOTIFY;
+    interface GetNow<token_requested_t> as IsRadioTokenRequested;
   }
   uses
   {
@@ -55,7 +60,7 @@ module ScanP
     interface Timer<TSymbolIEEE802154> as ScanTimer;
     interface Pool<ieee154_txframe_t> as TxFramePool;
     interface Pool<ieee154_txcontrol_t> as TxControlPool;
-    interface Resource as Token;
+    interface TransferableResource as RadioToken;
     interface FrameUtility;
     interface Leds;
   }
@@ -64,47 +69,48 @@ implementation
 {
   enum {
     MAX_PAYLOAD_SIZE = 1,
+    LAST_CHANNEL = 26,
   };
+#define INVALID_CHANNEL_BITMASK 0xFC000000L
 
   ieee154_txframe_t *m_txFrame = NULL;
   uint8_t m_payload[MAX_PAYLOAD_SIZE];  
   uint8_t m_scanType;
   uint32_t m_scanChannels;
-  uint32_t m_unscannedChannels;
-  ieee154_macAutoRequest_t m_macAutoRequest;
-  norace uint32_t m_currentChannelBit;
   norace uint8_t m_currentChannelNum;
+  bool m_terminateScan;
   void* m_resultList;
   uint8_t m_resultListNumEntries;
   uint8_t m_resultIndex;
   ieee154_macPANId_t m_PANID;
   norace uint32_t m_scanDuration;
-  bool m_busy = FALSE;
+  norace bool m_busy = FALSE;
 
   void nextIteration();
+  void continueScanRequest();
   task void startTimerTask();
   task void nextIterationTask();
 
   command error_t Init.init()
   {
-    // triggered by MLME_RESET; remember: Init will not be called
-    // while this component owns the Token, so the worst case is 
-    // that a MLME_SCAN was accepted (returned IEEE154_SUCCESS)
-    // but the Token.granted() has not been signalled 
-    if (m_busy){
-      m_currentChannelNum = 27;
+    // triggered by MLME_RESET; Note: Init will not be called
+    // while this component owns the RadioToken, so the worst case is 
+    // that a MLME_SCAN was accepted (returned IEEE154_SUCCESS)  
+    // but the RadioToken.granted() has not been signalled            
+    if (m_busy) {
+      m_terminateScan = TRUE;
       nextIteration(); // signals confirm and resets state
     }
     return SUCCESS;
   }
 
-/* ----------------------- MLME-SCAN ----------------------- */
-/* "The MLME-SCAN.request primitive is used to initiate a channel scan over a
- * given list of channels. A device can use a channel scan to measure the
- * energy on the channel, search for the coordinator with which it associated,
- * or search for all coordinators transmitting beacon frames within the POS of
- * the scanning device." (IEEE 802.15.4-2006 Sect. 7.1.11.1) 
- **/
+  /* ----------------------- MLME-SCAN ----------------------- */
+  /* "The MLME-SCAN.request primitive is used to initiate a channel scan over a
  * given list of channels. A device can use a channel scan to measure the
  * energy on the channel, search for the coordinator with which it associated,
  * or search for all coordinators transmitting beacon frames within the POS of
  * the scanning device." (IEEE 802.15.4-2006 Sect. 7.1.11.1) 
  **/
 
   command ieee154_status_t MLME_SCAN.request  (
                           uint8_t ScanType,
@@ -115,48 +121,48 @@ implementation
                           int8_t* EnergyDetectList,
                           uint8_t PANDescriptorListNumEntries,
                           ieee154_PANDescriptor_t* PANDescriptorList,
-                          ieee154_security_t *security
-                        )
+                          ieee154_security_t *security)
   {
     ieee154_status_t status = IEEE154_SUCCESS;
     ieee154_phyChannelsSupported_t supportedChannels = call MLME_GET.phyChannelsSupported();
     ieee154_txcontrol_t *txControl = NULL;
 
-    if (m_busy){
+    if (m_busy) {
       status = IEEE154_SCAN_IN_PROGRESS;
-    } else if (security && security->SecurityLevel){
+    } else if (security && security->SecurityLevel) {
       status = IEEE154_UNSUPPORTED_SECURITY;
-    } if ( (ScanType > 3) || (ScanType < 3 && ScanDuration > 14) || 
-            (ChannelPage != IEEE154_SUPPORTED_CHANNELPAGE) ||
-            !(supportedChannels & ScanChannels) ||
-            (EnergyDetectListNumEntries && PANDescriptorListNumEntries) ||
-            (EnergyDetectList != NULL && PANDescriptorList != NULL) ||
-            (EnergyDetectListNumEntries && EnergyDetectList == NULL) ||
-            (PANDescriptorListNumEntries && PANDescriptorList == NULL)) {
+    } if ((ScanType > 3) || (ScanType < 3 && ScanDuration > 14) || 
+        (ChannelPage != IEEE154_SUPPORTED_CHANNELPAGE) ||
+        !(supportedChannels & ScanChannels) ||
+        ((ScanType != ORPHAN_SCAN) &&
+         ((EnergyDetectListNumEntries && PANDescriptorListNumEntries) ||
+          (EnergyDetectList != NULL && PANDescriptorList != NULL) ||
+          (EnergyDetectListNumEntries && EnergyDetectList == NULL) ||
+          (PANDescriptorListNumEntries && PANDescriptorList == NULL)))) {
       status = IEEE154_INVALID_PARAMETER;
-    } else if (ScanType != ENERGY_DETECTION_SCAN &&
-        !(m_txFrame = call TxFramePool.get())) { 
+    } else if ((ScanType == ACTIVE_SCAN || ScanType == ORPHAN_SCAN) &&
+        ((m_txFrame = call TxFramePool.get()) == NULL)) {
       status = IEEE154_TRANSACTION_OVERFLOW;
-    } else if (ScanType != ENERGY_DETECTION_SCAN &&
-        !(txControl = call TxControlPool.get())) { 
+    } else if ((ScanType == ACTIVE_SCAN || ScanType == ORPHAN_SCAN) &&
+        ((txControl = call TxControlPool.get()) == NULL)) { 
       call TxFramePool.put(m_txFrame);
       m_txFrame = NULL;
       status = IEEE154_TRANSACTION_OVERFLOW;
     } else {
-      m_txFrame->header = &txControl->header;
-      m_txFrame->payload = m_payload;
-      m_txFrame->metadata = &txControl->metadata;
+      if (m_txFrame != NULL){
+        m_txFrame->header = &txControl->header;
+        m_txFrame->payload = m_payload;
+        m_txFrame->metadata = &txControl->metadata;
+      }
       m_busy = TRUE;
       m_scanType = ScanType;
       m_scanChannels = ScanChannels;
       m_scanDuration = (((uint32_t) 1 << ScanDuration) + 1) * IEEE154_aBaseSuperframeDuration;
-      m_macAutoRequest = call MLME_GET.macAutoRequest();
       m_PANID = call MLME_GET.macPANId();
-      m_unscannedChannels = 0;
-      m_currentChannelBit = 1;
       m_currentChannelNum = 0;
+      m_terminateScan = FALSE;
       m_resultIndex = 0;
-      if (ScanType == ENERGY_DETECTION_SCAN){
+      if (ScanType == ENERGY_DETECTION_SCAN) {
         m_resultList = EnergyDetectList;
         m_resultListNumEntries = EnergyDetectListNumEntries;
       } else {
@@ -165,22 +171,37 @@ implementation
       }
       if (m_resultList == NULL)
         m_resultListNumEntries = 0;
-      call Token.request();
+      call RadioToken.request();
     }
+    dbg_serial("ScanP", "MLME_SCAN.request -> result: %lu\n", (uint32_t) status);
     return status;
   }
 
-  event void Token.granted()
+  event void RadioToken.granted()
+  {
+    if (call RadioOff.isOff())
+      continueScanRequest();
+    else 
+      ASSERT(call RadioOff.off() == SUCCESS);
+    // will continue in continueScanRequest()
+  }
+
+  task void continueScanRequestTask() 
+  { 
+    continueScanRequest(); 
+  }
+
+  void continueScanRequest()
   {
     uint8_t i;
     ieee154_macPANId_t bcastPANID = 0xFFFF;
     ieee154_macDSN_t dsn = call MLME_GET.macDSN();
 
-    if (!m_busy){
-      call Token.release();
+    if (!m_busy) {
+      call RadioToken.release();
       return;
     }
-    switch (m_scanType){
+    switch (m_scanType) {
       case ACTIVE_SCAN:
         // beacon request frame
         m_txFrame->header->mhr[MHR_INDEX_FC1] = FC1_FRAMETYPE_CMD;
@@ -198,14 +219,14 @@ implementation
         break;
       case ORPHAN_SCAN:
         // orphan notification frame
-        m_scanDuration = call MLME_GET.macResponseWaitTime();
+        m_scanDuration = call MLME_GET.macResponseWaitTime() * IEEE154_aBaseSuperframeDuration;
         m_txFrame->header->mhr[MHR_INDEX_FC1] = FC1_FRAMETYPE_CMD | FC1_PAN_ID_COMPRESSION;
         m_txFrame->header->mhr[MHR_INDEX_FC2] = FC2_SRC_MODE_EXTENDED | FC2_DEST_MODE_SHORT;
         m_txFrame->header->mhr[MHR_INDEX_SEQNO] = dsn;
         call MLME_SET.macDSN(dsn+1);
         for (i=0; i<4; i++) // broadcast dest PAN ID + broadcast dest addr
           m_txFrame->header->mhr[MHR_INDEX_ADDRESS + i] = 0xFF;
-        call FrameUtility.copyLocalExtendedAddressLE((uint8_t*) &(m_txFrame->header[MHR_INDEX_ADDRESS + i]));
+        call FrameUtility.copyLocalExtendedAddressLE((uint8_t*) &(m_txFrame->header->mhr[MHR_INDEX_ADDRESS + i]));
         m_txFrame->headerLen = 15;
         m_payload[0] = CMD_FRAME_ORPHAN_NOTIFICATION;
         m_txFrame->payloadLen = 1;
@@ -216,155 +237,179 @@ implementation
 
   void nextIteration()
   {
+    ieee154_phyChannelsSupported_t supportedChannels = call MLME_GET.phyChannelsSupported();
+    uint32_t currentChannelBit = (uint32_t) 1 << m_currentChannelNum;
     error_t radioStatus = SUCCESS;
-    uint32_t supportedChannels = IEEE154_SUPPORTED_CHANNELS;
-    atomic {
-      while (!(m_scanChannels & m_currentChannelBit & supportedChannels) && m_currentChannelNum < 27){
-        m_unscannedChannels |= m_currentChannelBit;
-        m_currentChannelBit <<= 1;
+
+    if (!m_terminateScan){
+      while (m_currentChannelNum <= LAST_CHANNEL &&  
+          !(m_scanChannels & currentChannelBit & supportedChannels)){
         m_currentChannelNum++;
+        currentChannelBit <<= 1;
       }
     }
-    if (m_currentChannelNum < 27) {
+
+    if (m_currentChannelNum <= LAST_CHANNEL && !m_terminateScan) {
+      // scan the next channel
       call MLME_SET.phyCurrentChannel(m_currentChannelNum);
-      switch (m_scanType){
+      dbg_serial("ScanP", "Scanning channel %lu...\n", (uint32_t) m_currentChannelNum);
+      switch (m_scanType) {
         case PASSIVE_SCAN:
-          radioStatus = call RadioRx.prepare();
+          radioStatus = call RadioRx.enableRx(0, 0);
           break;
-        case ACTIVE_SCAN:
+        case ACTIVE_SCAN: // fall through
         case ORPHAN_SCAN:
-          radioStatus = call RadioTx.load(m_txFrame);
+          radioStatus = call RadioTx.transmit(m_txFrame, NULL, 0);
           break;
         case ENERGY_DETECTION_SCAN:
           radioStatus = call EnergyDetection.start(m_scanDuration);
           break;
       }
-      if (radioStatus != SUCCESS){
-        call Leds.led0On();
-      }
+      ASSERT(radioStatus == SUCCESS);
     } else {
-      ieee154_status_t result = IEEE154_SUCCESS;
       // we're done
-      m_currentChannelBit <<= 1; 
-      while (m_currentChannelBit){
-        m_unscannedChannels |= m_currentChannelBit;
-        m_currentChannelBit <<= 1;
-      }
-      m_unscannedChannels &= m_scanChannels; // only channels that were requested
-      if (m_scanType != ENERGY_DETECTION_SCAN && !m_resultIndex)
+      ieee154_status_t result = IEEE154_SUCCESS;
+      uint32_t unscannedChannels = 0;
+
+      if (m_terminateScan){
+        // Scan operation terminated because the max. 
+        // number of PAN descriptors/ED samples was reached.
+        // Check if there are channels that were unscanned.
+        // In active/passive scan we consider a channel 
+        // unscanned if it was not completely scanned.
+        if (m_scanType == PASSIVE_SCAN || m_scanType == ACTIVE_SCAN) 
+          currentChannelBit >>= 1; // last (partially) scanned channel
+        while (!(currentChannelBit & INVALID_CHANNEL_BITMASK) &&
+               (m_scanChannels & currentChannelBit)){
+          unscannedChannels |= currentChannelBit;
+          currentChannelBit <<= 1;
+        }
+        if (unscannedChannels) // some channels were not (completely) scanned
+          result = IEEE154_LIMIT_REACHED;
+      } else if (m_scanType != ENERGY_DETECTION_SCAN && !m_resultIndex)
         result = IEEE154_NO_BEACON;
+
       if (m_scanType == PASSIVE_SCAN || m_scanType == ACTIVE_SCAN) 
         call MLME_SET.macPANId(m_PANID);
-      if (m_txFrame != NULL){
+      if (m_txFrame != NULL) {
         call TxControlPool.put((ieee154_txcontrol_t*) ((uint8_t*) m_txFrame->header - offsetof(ieee154_txcontrol_t, header)));
         call TxFramePool.put(m_txFrame);
       }
       m_txFrame = NULL;
-      if (call Token.isOwner())
-        call Token.release();
+      if (call RadioToken.isOwner())
+        call RadioToken.release();
       m_busy = FALSE;
+      dbg_serial("ScanP", "MLME_SCAN.confirm()\n");
       signal MLME_SCAN.confirm (
           result,
           m_scanType,
           IEEE154_SUPPORTED_CHANNELPAGE,
-          m_unscannedChannels,
+          unscannedChannels,
           (m_scanType == ENERGY_DETECTION_SCAN) ? m_resultIndex : 0,
-          (m_scanType == ENERGY_DETECTION_SCAN) ? (uint8_t*) m_resultList : NULL,
+          (m_scanType == ENERGY_DETECTION_SCAN) ? (int8_t*) m_resultList : NULL,
           ((m_scanType == ACTIVE_SCAN ||
-           m_scanType == PASSIVE_SCAN) && m_macAutoRequest) ? m_resultIndex : 0,
+           m_scanType == PASSIVE_SCAN) && call MLME_GET.macAutoRequest()) ? m_resultIndex : 0,
           ((m_scanType == ACTIVE_SCAN ||
-           m_scanType == PASSIVE_SCAN) && m_macAutoRequest) ? (ieee154_PANDescriptor_t*) m_resultList : NULL
-          );
+           m_scanType == PASSIVE_SCAN) && call MLME_GET.macAutoRequest()) ? (ieee154_PANDescriptor_t*) m_resultList : NULL);
     }
+    dbg_serial_flush();
+  }
+  
+  async event void RadioRx.enableRxDone()
+  {
+    post startTimerTask();
   }
 
-/* ----------------------- EnergyDetection ----------------------- */
+  /* ----------------------- EnergyDetection ----------------------- */
 
   event void EnergyDetection.done(error_t status, int8_t EnergyLevel)
   {
     if (status == SUCCESS && m_resultListNumEntries)
       ((uint8_t*) m_resultList)[m_resultIndex++] = EnergyLevel;
-    else 
-      m_unscannedChannels |= m_currentChannelBit;
     if (m_resultIndex == m_resultListNumEntries)
-      m_currentChannelNum = 27; // done
-    else
-      m_currentChannelNum++;
-    call RadioOff.off();
+      m_terminateScan = TRUE; // done
+    if (call RadioOff.off() == EALREADY)
+      signal RadioOff.offDone();
   }
 
-/* ----------------------- Active/Orphan scan ----------------------- */
-
-  async event void RadioTx.loadDone()
-  {
-    call RadioTx.transmit(0, 0, 0, FALSE);
-  }
+  /* ----------------------- Active/Orphan scan ----------------------- */
   
-  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, 
-      ieee154_reftime_t *referenceTime, bool ackPendingFlag, error_t error)
+  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, const ieee154_timestamp_t *timestamp, error_t result)
   {
-    if (call RadioRx.prepare() != SUCCESS) // must succeed
-      call Leds.led0On();
+    ASSERT(call RadioRx.enableRx(0, 0) == SUCCESS);
   }
 
-/* -------- Receive events (for  Active/Passive/Orphan scan) -------- */
+  /* -------- Receive events (for  Active/Passive/Orphan scan) -------- */
 
-  async event void RadioRx.prepareDone()
+  event message_t* RadioRx.received(message_t *frame, const ieee154_timestamp_t *timestamp)
   {
-    call RadioRx.receive(NULL, 0);
-    post startTimerTask();
-  }
+    if (!m_busy)
+      return frame;
 
-  event message_t* RadioRx.received(message_t *frame, ieee154_reftime_t *timestamp)
-  {
-    atomic {
-      if (!m_busy)
-        return frame;
-      if (m_scanType == ORPHAN_SCAN){
-        if (!m_resultIndex)
-          if ((MHR(frame)[0] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_CMD &&
-              ((uint8_t*)call Frame.getPayload(frame))[0] == CMD_FRAME_COORDINATOR_REALIGNMENT){
-            m_resultIndex++; 
-            m_currentChannelNum = 27; // terminate scan
-            call RadioOff.off();
-          }
-      } else if ((((ieee154_header_t*) frame->header)->mhr[0] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_BEACON) {
-        //  PASSIVE_SCAN / ACTIVE_SCAN
-        if (!m_macAutoRequest)
-          return signal MLME_BEACON_NOTIFY.indication (frame);
-        else if (m_resultListNumEntries && m_resultIndex < m_resultListNumEntries &&
-            call BeaconFrame.parsePANDescriptor(
-              frame, 
-              m_currentChannelNum, 
-              IEEE154_SUPPORTED_CHANNELPAGE,
-              &((ieee154_PANDescriptor_t*) m_resultList)[m_resultIndex]) == SUCCESS){
-          // check uniqueness: both PAN ID and source address must not be in a previously received beacon
-          uint8_t i;
-          if (m_resultIndex)
-            for (i=0; i<m_resultIndex; i++)
-              if ( ((ieee154_PANDescriptor_t*) m_resultList)[i].CoordPANId == 
-                   ((ieee154_PANDescriptor_t*) m_resultList)[m_resultIndex].CoordPANId &&
-                   ((ieee154_PANDescriptor_t*) m_resultList)[i].CoordAddrMode == 
-                   ((ieee154_PANDescriptor_t*) m_resultList)[m_resultIndex].CoordAddrMode)
-                if ( (((ieee154_PANDescriptor_t*) m_resultList)[i].CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
-                      ((ieee154_PANDescriptor_t*) m_resultList)[i].CoordAddress.shortAddress ==
-                      ((ieee154_PANDescriptor_t*) m_resultList)[m_resultIndex].CoordAddress.shortAddress) ||
-                     (((ieee154_PANDescriptor_t*) m_resultList)[i].CoordAddrMode == ADDR_MODE_EXTENDED_ADDRESS &&
-                      ((ieee154_PANDescriptor_t*) m_resultList)[i].CoordAddress.extendedAddress ==
-                      ((ieee154_PANDescriptor_t*) m_resultList)[m_resultIndex].CoordAddress.extendedAddress) )
-                  return frame; // not unique
-          m_resultIndex++;
-          if (m_resultIndex == m_resultListNumEntries){
-            m_currentChannelNum = 27; // terminate scan
-            call RadioOff.off();
-          }
+    if (m_scanType == ORPHAN_SCAN) {
+      uint8_t *payload = call Frame.getPayload(frame);
+      if (!m_resultIndex)
+        if ((MHR(frame)[0] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_CMD &&
+            payload[0] == CMD_FRAME_COORDINATOR_REALIGNMENT) {
+
+          // Sect. 7.5.4.3: "the device shall update its MAC PIB with the PAN  
+          // information contained in the coordinator realignment command"
+           
+          call MLME_SET.macPANId( *((nxle_uint16_t*) &payload[1]) );
+          call MLME_SET.macCoordShortAddress( *((nxle_uint16_t*) &payload[3]) );
+          call MLME_SET.phyCurrentChannel( *((nxle_uint16_t*) &payload[5]) );
+          call MLME_SET.macShortAddress( *((nxle_uint16_t*) &payload[6]) );
+          m_resultIndex++; 
+          dbg_serial("ScanP", "Received coordinator realignment frame.\n");
+          m_terminateScan = TRUE;
+          call RadioOff.off();
         }
+    } else if ((((ieee154_header_t*) frame->header)->mhr[0] & FC1_FRAMETYPE_MASK) == FC1_FRAMETYPE_BEACON) {
+
+      // PASSIVE_SCAN / ACTIVE_SCAN:
+      // A beacon frame containing a non-empty payload is always signalled
+      // to the next higher layer (regardless of the value of macAutoRequest);
+      // when macAutoRequest is set to TRUE, then the beacon is always 
+      // stored in the PAN Descriptor list (see 7.1.11.2.1 - Table 68)
+
+      if (!call MLME_GET.macAutoRequest())
+        return signal MLME_BEACON_NOTIFY.indication (frame);
+      else if (m_resultIndex >= m_resultListNumEntries) {
+        m_terminateScan = TRUE;
+        call RadioOff.off();
+      } else if (call BeaconFrame.parsePANDescriptor(
+            frame, 
+            m_currentChannelNum, 
+            IEEE154_SUPPORTED_CHANNELPAGE,
+            &((ieee154_PANDescriptor_t*) m_resultList)[m_resultIndex]) == SUCCESS) {
+
+        // check uniqueness: PAN ID and source address must 
+        // not be found in a previously received beacon
+        uint8_t i;
+        ieee154_PANDescriptor_t* descriptor = (ieee154_PANDescriptor_t*) m_resultList;
+
+        dbg_serial("ScanP", "Received beacon, source: 0x%lx, channel: %lu.\n", 
+            (uint32_t) descriptor[m_resultIndex].CoordAddress.shortAddress, (uint32_t) m_currentChannelNum);
+        for (i=0; i<m_resultIndex; i++)
+          if (descriptor[i].CoordPANId == descriptor[m_resultIndex].CoordPANId &&
+              descriptor[i].CoordAddrMode == descriptor[m_resultIndex].CoordAddrMode)
+            if ((descriptor[i].CoordAddrMode == ADDR_MODE_SHORT_ADDRESS &&
+                  descriptor[i].CoordAddress.shortAddress ==
+                  descriptor[m_resultIndex].CoordAddress.shortAddress) ||
+                (descriptor[i].CoordAddrMode == ADDR_MODE_EXTENDED_ADDRESS &&
+                 descriptor[i].CoordAddress.extendedAddress ==
+                 descriptor[m_resultIndex].CoordAddress.extendedAddress))
+              break; // not unique
+        if (i == m_resultIndex)
+          m_resultIndex++; // was unique
       }
-    }
+      if (call BeaconFrame.getBeaconPayloadLength(frame) > 0)
+        return signal MLME_BEACON_NOTIFY.indication (frame);
+    } //  PASSIVE_SCAN / ACTIVE_SCAN
     return frame;
   }
 
-/* ----------------------- Common ----------------------- */
+  /* ----------------------- Common ----------------------- */
 
   task void startTimerTask() 
   { 
@@ -378,9 +423,12 @@ implementation
 
   async event void RadioOff.offDone()
   {
-    m_currentChannelBit <<= 1;
-    m_currentChannelNum++;    
-    post nextIterationTask();
+    if (m_currentChannelNum == 0)
+      post continueScanRequestTask();
+    else {
+      m_currentChannelNum++;    
+      post nextIterationTask();
+    }
   }
 
   task void nextIterationTask()
@@ -388,7 +436,9 @@ implementation
     nextIteration();
   }
 
-  default event message_t* MLME_BEACON_NOTIFY.indication ( message_t *beaconFrame ){return beaconFrame;}
+  async command token_requested_t IsRadioTokenRequested.getNow(){ return m_busy;}
+  async event void RadioToken.transferredFrom(uint8_t id){ ASSERT(0);}
+  default event message_t* MLME_BEACON_NOTIFY.indication (message_t *beaconFrame) {return beaconFrame;}
   default event void MLME_SCAN.confirm    (
                           ieee154_status_t status,
                           uint8_t ScanType,
@@ -397,6 +447,5 @@ implementation
                           uint8_t EnergyDetectListNumEntries,
                           int8_t* EnergyDetectList,
                           uint8_t PANDescriptorListNumEntries,
-                          ieee154_PANDescriptor_t* PANDescriptorList
-                        ){}
+                          ieee154_PANDescriptor_t* PANDescriptorList) {}
 }
diff --git a/tos/lib/mac/tkn154/SimpleRoundRobinTransferArbiterC.nc b/tos/lib/mac/tkn154/SimpleRoundRobinTransferArbiterC.nc
deleted file mode 100644 (file)
index fa43524..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * "Copyright (c) 2005 Washington University in St. Louis.
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- *
- * IN NO EVENT SHALL WASHINGTON UNIVERSITY IN ST. LOUIS BE LIABLE TO ANY PARTY 
- * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING 
- * OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF WASHINGTON 
- * UNIVERSITY IN ST. LOUIS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * WASHINGTON UNIVERSITY IN ST. LOUIS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND WASHINGTON UNIVERSITY IN ST. LOUIS HAS NO 
- * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
- * MODIFICATIONS."
- */
-/*
- * Copyright (c) 2004, Technische Universitat Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitat Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-/**
- * Please refer to TEP 108 for more information about this component and its
- * intended use.<br><br>
- *
- * This component provides the Resource, ArbiterInfo, and Resource
- * Controller interfaces and uses the ResourceConfigure interface as
- * described in TEP 108.  It provides arbitration to a shared resource in
- * an FCFS fashion.  An array is used to keep track of which users have put
- * in requests for the resource.  Upon the release of the resource by one
- * of these users, the array is checked and the next user (in FCFS order)
- * that has a pending request will ge granted control of the resource.  If
- * there are no pending requests, then the resource becomes idle and any
- * user can put in a request and immediately receive access to the
- * Resource.
- *
- * @param <b>resourceName</b> -- The name of the Resource being shared
- * 
- * @author Kevin Klues (klues@tkn.tu-berlin.de)
- * @author Philip Levis
- */
-generic configuration SimpleRoundRobinTransferArbiterC(char resourceName[]) {
-  provides {
-    interface Resource[uint8_t id];
-    interface ResourceRequested[uint8_t id];
-    interface ResourceTransferControl;
-    interface ArbiterInfo;
-    interface GetNow<bool> as IsResourceRequested;
-  }
-  uses interface ResourceConfigure[uint8_t id];
-}
-implementation {
-  components MainC;
-  components new RoundRobinResourceQueueC(uniqueCount(resourceName)) as Queue;
-  components new SimpleTransferArbiterP() as Arbiter;
-
-  MainC.SoftwareInit -> Queue;
-
-  Resource = Arbiter;
-  ResourceRequested = Arbiter;
-  ArbiterInfo = Arbiter;
-  ResourceConfigure = Arbiter;
-  ResourceTransferControl = Arbiter;
-  IsResourceRequested = Arbiter;
-
-  Arbiter.Queue -> Queue;
-}
index 76ae05b4294bae3e70e44bd1d7c0784a50fbf22e..1262c5a2ff47b3cc8a1d5a8db4fd66cbe48207fc 100644 (file)
  * 
  * @author Kevin Klues (klues@tkn.tu-berlin.de)
  * @author Philip Levis
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de> (added resource transfer)
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de> (added TransferableResource interface)
  */
  
 generic module SimpleTransferArbiterP() {
   provides {
-    interface Resource[uint8_t id];
+    interface TransferableResource as Resource[uint8_t id];
     interface ResourceRequested[uint8_t id];
-    interface ResourceTransferControl;
     interface ArbiterInfo;
-    interface GetNow<bool> as IsResourceRequested;
   }
   uses {
     interface ResourceConfigure[uint8_t id];
@@ -68,17 +66,12 @@ implementation {
   uint8_t state = RES_IDLE;
   norace uint8_t resId = NO_RES;
   norace uint8_t reqResId;
-  norace uint8_t numTransfers;
-  norace bool reqWhileTransferred;
   
   task void grantedTask();
-  task void checkResourceRequestedTask();
   
   async command error_t Resource.request[uint8_t id]() {
     signal ResourceRequested.requested[resId]();
     atomic {
-      if (numTransfers > 0)
-        reqWhileTransferred = TRUE;
       if(state == RES_IDLE) {
         state = RES_GRANTING;
         reqResId = id;
@@ -106,8 +99,6 @@ implementation {
     bool released = FALSE;
     atomic {
       if(state == RES_BUSY && resId == id) {
-        numTransfers = 0;
-        reqWhileTransferred = FALSE;
         if(call Queue.isEmpty() == FALSE) {
           reqResId = call Queue.dequeue();
           state = RES_GRANTING;
@@ -127,36 +118,19 @@ implementation {
     return FAIL;
   }
 
-  async command bool IsResourceRequested.getNow()
-  {
-    return reqWhileTransferred;
-  }
-
-  task void checkResourceRequestedTask()
-  {
-    if (numTransfers && reqWhileTransferred)
-      signal ResourceRequested.requested[resId]();
-  }
-
-  async command error_t ResourceTransferControl.transfer(uint8_t fromClient, uint8_t toClient)
+  async command error_t Resource.transferTo[uint8_t fromID](uint8_t toID)
   {
     atomic {
-      if (call ArbiterInfo.userId() == fromClient){
-        numTransfers += 1;
-        call ResourceConfigure.unconfigure[fromClient]();
+      if (call ArbiterInfo.userId() == fromID) {
+        call ResourceConfigure.unconfigure[fromID]();
         call ResourceConfigure.configure[resId]();
-        resId = toClient;
-        post checkResourceRequestedTask();
+        resId = toID;
+        signal Resource.transferredFrom[toID](fromID); // consider moving this outside the atomic
         return SUCCESS;
       }
-    } 
+    }
     return FAIL;
   }
-
-  async command error_t ResourceTransferControl.release(uint8_t client)
-  {
-    return call Resource.release[client]();
-  }
     
   /**
     Check if the Resource is currently in use
@@ -212,4 +186,6 @@ implementation {
   }
   default async command void ResourceConfigure.unconfigure[uint8_t id]() {
   }
+  default async event void Resource.transferredFrom[uint8_t id](uint8_t c) {
+  }
 }
index 9889b7eb97a9ba3882ffe6fecfd164dcc4ecdc04..baca7c03dd11b8c2922b730438a4cd1f368a94a0 100644 (file)
@@ -36,7 +36,6 @@
 #ifndef __TKN154_H
 #define __TKN154_H
 
-
 /****************************************************
  * IEEE 802.15.4 Enumerations
  */
@@ -79,6 +78,7 @@ typedef enum ieee154_status
   IEEE154_UNSUPPORTED_ATTRIBUTE   = 0xF4,
   IEEE154_UNSUPPORTED_LEGACY      = 0xDE,
   IEEE154_UNSUPPORTED_SECURITY    = 0xDF,
+  IEEE154_PURGED                  = 0xDA, // custom attribute
 } ieee154_status_t;
 
 typedef enum ieee154_association_status 
@@ -230,6 +230,37 @@ typedef bool                ieee154_macPanCoordinator_t;
 // When security is implemented the following line should be commented out
 #define IEEE154_SECURITY_DISABLED
 
+/**************************************************** 
+ * Flags for disabling MAC functionality (to save program memory)
+ */
+
+// Disable scanning (MLME_SCAN will not work):
+// #define IEEE154_SCAN_DISABLED
+//
+// Disable beacon tracking (MLME_SYNC will not work):
+// #define IEEE154_BEACON_SYNC_DISABLED
+//
+// Disable beacon transmission (MLME_START will not work):
+// #define IEEE154_BEACON_TX_DISABLED
+//
+// Disable promiscuous mode (PromiscuousMode.start() will not work):
+// #define IEEE154_PROMISCUOUS_MODE_DISABLED
+//
+// Disallow next higher layer to switch to receive mode (MLME_RX_ENABLE will not work):
+// #define IEEE154_RXENABLE_DISABLED
+//
+// Disable association (MLME_ASSOCIATE will not work):
+// #define IEEE154_ASSOCIATION_DISABLED
+//
+// Disable association (MLME_DISASSOCIATE will not work):
+// #define IEEE154_DISASSOCIATION_DISABLED
+//
+// Disable coordinator realignment (MLME_ORPHAN will not work):
+// #define IEEE154_COORD_REALIGNMENT_DISABLED
+//
+// Disable transmission of broadcasts from coordinator to devices:
+// #define IEEE154_COORD_BROADCAST_DISABLED
+
 /**************************************************** 
  * Static memory allocation for Queue/Pool
  */
diff --git a/tos/lib/mac/tkn154/TKN154BeaconEnabledP.nc b/tos/lib/mac/tkn154/TKN154BeaconEnabledP.nc
new file mode 100644 (file)
index 0000000..87f7f6b
--- /dev/null
@@ -0,0 +1,527 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154_PHY.h"
+#include "TKN154_MAC.h"
+#include "TKN154_PIB.h"
+
+#define IEEE154_BEACON_ENABLED_PAN TRUE
+
+configuration TKN154BeaconEnabledP
+{
+  provides
+  {
+    /* MCPS-SAP */
+    interface MCPS_DATA;
+    interface MCPS_PURGE;
+    interface Packet;
+
+    /* MLME-SAP */
+    interface MLME_ASSOCIATE;
+    interface MLME_BEACON_NOTIFY;
+    interface MLME_COMM_STATUS;
+    interface MLME_DISASSOCIATE;
+    interface MLME_GET;
+/*    interface MLME_GTS;*/
+    interface MLME_ORPHAN;
+    interface MLME_POLL;
+    interface MLME_RESET;
+    interface MLME_RX_ENABLE;
+    interface MLME_SCAN;
+    interface MLME_SET;
+    interface MLME_START;
+    interface MLME_SYNC;
+    interface MLME_SYNC_LOSS;
+
+    interface Notify<const void*> as PIBUpdate[uint8_t attributeID];
+    interface IEEE154Frame;
+    interface IEEE154BeaconFrame;
+    interface IEEE154TxBeaconPayload;
+    interface SplitControl as PromiscuousMode;
+    interface Get<uint64_t> as GetLocalExtendedAddress;
+    interface TimeCalc;
+    interface FrameUtility;
+
+  } uses {
+
+    interface RadioRx;
+    interface RadioTx;
+    interface RadioOff;
+    interface SlottedCsmaCa;
+    interface EnergyDetection;
+    interface SplitControl as PhySplitControl;
+    interface Set<bool> as RadioPromiscuousMode;
+
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm1;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm2;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm3;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm4;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm5;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm6;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm7;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm8;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm9;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm10;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm11;
+
+    interface Timer<TSymbolIEEE802154> as Timer1;
+    interface Timer<TSymbolIEEE802154> as Timer2;
+    interface Timer<TSymbolIEEE802154> as Timer3;
+    interface Timer<TSymbolIEEE802154> as Timer4;
+    interface Timer<TSymbolIEEE802154> as Timer5;
+
+    interface LocalTime<TSymbolIEEE802154>;
+    interface Random;
+    interface Leds;
+  }
+}
+implementation
+{
+  components DataP,
+             PibP,
+             RadioControlP,
+             IndirectTxP,
+             PollP,
+
+#ifndef IEEE154_SCAN_DISABLED
+             ScanP,
+#else
+             NoScanP as ScanP,
+#endif
+
+#ifndef IEEE154_ASSOCIATION_DISABLED
+             AssociateP,
+#else
+             NoAssociateP as AssociateP,
+#endif
+
+#ifndef IEEE154_DISASSOCIATION_DISABLED
+             DisassociateP,
+#else
+             NoDisassociateP as DisassociateP,
+#endif
+
+#ifndef IEEE154_BEACON_SYNC_DISABLED
+             BeaconSynchronizeP,
+             new DispatchQueueP() as DeviceCapQueue,
+             new DispatchSlottedCsmaP(INCOMING_SUPERFRAME) as DeviceCap,
+#else
+             NoBeaconSynchronizeP as BeaconSynchronizeP,
+             new NoDispatchQueueP() as DeviceCapQueue,
+             new NoDispatchSlottedCsmaP(INCOMING_SUPERFRAME) as DeviceCap,
+#endif
+             NoDeviceCfpP as DeviceCfp,
+
+#ifndef IEEE154_BEACON_TX_DISABLED
+             BeaconTransmitP,
+             new DispatchQueueP() as CoordCapQueue,
+             new DispatchSlottedCsmaP(OUTGOING_SUPERFRAME) as CoordCap,
+#else
+             NoBeaconTransmitP as BeaconTransmitP,
+             new NoDispatchQueueP() as CoordCapQueue,
+             new NoDispatchSlottedCsmaP(OUTGOING_SUPERFRAME) as CoordCap,
+#endif
+             NoCoordCfpP as CoordCfp,
+
+#ifndef IEEE154_RXENABLE_DISABLED
+             RxEnableP,
+#else
+             NoRxEnableP as RxEnableP,
+#endif
+
+
+#ifndef IEEE154_PROMISCUOUS_MODE_DISABLED
+             PromiscuousModeP,
+#else
+             NoPromiscuousModeP as PromiscuousModeP,
+#endif
+
+#ifndef IEEE154_COORD_REALIGNMENT_DISABLED
+             CoordRealignmentP,
+#else
+             NoCoordRealignmentP as CoordRealignmentP,
+#endif
+
+#ifndef IEEE154_COORD_BROADCAST_DISABLED
+             CoordBroadcastP,
+#else
+             NoCoordBroadcastP as CoordBroadcastP,
+#endif
+
+             new PoolC(ieee154_txframe_t, TXFRAME_POOL_SIZE) as TxFramePoolP,
+             new PoolC(ieee154_txcontrol_t, TXCONTROL_POOL_SIZE) as TxControlPoolP,
+             new QueueC(ieee154_txframe_t*, CAP_TX_QUEUE_SIZE) as DeviceCapQueueC,
+             new QueueC(ieee154_txframe_t*, CAP_TX_QUEUE_SIZE) as CoordCapQueueC,
+             new QueueC(ieee154_txframe_t*, CAP_TX_QUEUE_SIZE) as BroadcastQueueC;
+
+  components MainC;
+
+  /* MCPS */
+  MCPS_DATA = DataP; 
+  MCPS_PURGE = DataP; 
+
+  /* MLME */
+  MLME_START = BeaconTransmitP;
+  MLME_ASSOCIATE = AssociateP;
+  MLME_DISASSOCIATE = DisassociateP;
+  MLME_BEACON_NOTIFY = BeaconSynchronizeP;
+  MLME_BEACON_NOTIFY = ScanP;
+  MLME_COMM_STATUS = AssociateP;
+  MLME_COMM_STATUS = CoordRealignmentP;
+  MLME_GET = PibP;
+  MLME_ORPHAN = CoordRealignmentP;
+  /* MLME_GTS = CfpTransmitP;*/
+  MLME_POLL = PollP;
+  MLME_RESET = PibP;
+  MLME_RX_ENABLE = RxEnableP;
+  MLME_SCAN = ScanP;
+  MLME_SET = PibP;
+  MLME_SYNC = BeaconSynchronizeP;
+  MLME_SYNC_LOSS = BeaconSynchronizeP;
+  IEEE154Frame = PibP;
+  IEEE154BeaconFrame = PibP;
+  PromiscuousMode = PromiscuousModeP;
+  GetLocalExtendedAddress = PibP.GetLocalExtendedAddress;
+  IEEE154TxBeaconPayload = BeaconTransmitP;
+  Packet = PibP; 
+  TimeCalc = PibP;
+  FrameUtility = PibP;
+  
+  /* ----------------------- Scanning (MLME-SCAN) ----------------------- */
+
+  components new RadioClientC(RADIO_CLIENT_SCAN) as ScanRadioClient;
+  PibP.MacReset -> ScanP;
+  ScanP.MLME_GET -> PibP;
+  ScanP.MLME_SET -> PibP.MLME_SET;
+  ScanP.EnergyDetection = EnergyDetection;
+  ScanP.RadioRx -> ScanRadioClient;
+  ScanP.RadioTx -> ScanRadioClient;
+  ScanP.Frame -> PibP;
+  ScanP.BeaconFrame -> PibP;
+  ScanP.RadioOff -> ScanRadioClient;
+  ScanP.ScanTimer = Timer1;
+  ScanP.TxFramePool -> TxFramePoolP;
+  ScanP.TxControlPool -> TxControlPoolP;
+  ScanP.RadioToken -> ScanRadioClient;
+  ScanP.Leds = Leds;
+  ScanP.FrameUtility -> PibP;
+
+  /* ----------------- Beacon Transmission (MLME-START) ----------------- */
+  
+  components new RadioClientC(RADIO_CLIENT_BEACONTRANSMIT) as BeaconTxRadioClient;
+  PibP.MacReset -> BeaconTransmitP;
+  BeaconTransmitP.PIBUpdate[IEEE154_macAssociationPermit] -> PibP.PIBUpdate[IEEE154_macAssociationPermit];
+  BeaconTransmitP.PIBUpdate[IEEE154_macGTSPermit] -> PibP.PIBUpdate[IEEE154_macGTSPermit];
+  BeaconTransmitP.BeaconSendAlarm = Alarm1;
+  BeaconTransmitP.BeaconPayloadUpdateTimer = Timer2;
+  BeaconTransmitP.RadioOff -> BeaconTxRadioClient;
+  BeaconTransmitP.BeaconTx -> BeaconTxRadioClient;
+  BeaconTransmitP.MLME_SET -> PibP.MLME_SET;
+  BeaconTransmitP.MLME_GET -> PibP;
+  BeaconTransmitP.SetMacSuperframeOrder -> PibP.SetMacSuperframeOrder;
+  BeaconTransmitP.SetMacBeaconTxTime -> PibP.SetMacBeaconTxTime;
+  BeaconTransmitP.SetMacPanCoordinator -> PibP.SetMacPanCoordinator;
+  BeaconTransmitP.RadioToken -> BeaconTxRadioClient;
+  BeaconTransmitP.RealignmentBeaconEnabledTx -> CoordBroadcastP.RealignmentTx;
+  BeaconTransmitP.RealignmentNonBeaconEnabledTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
+  BeaconTransmitP.BeaconRequestRx -> CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_BEACON_REQUEST];
+  BeaconTransmitP.GtsInfoWrite -> CoordCfp.GtsInfoWrite;
+  BeaconTransmitP.PendingAddrSpecUpdated -> IndirectTxP.PendingAddrSpecUpdated;
+  BeaconTransmitP.PendingAddrWrite -> IndirectTxP.PendingAddrWrite;
+  BeaconTransmitP.FrameUtility -> PibP.FrameUtility;
+  BeaconTransmitP.IsTrackingBeacons -> BeaconSynchronizeP.IsTrackingBeacons;
+  BeaconTransmitP.IncomingSF -> BeaconSynchronizeP.IncomingSF;
+  BeaconTransmitP.GetSetRealignmentFrame -> CoordRealignmentP;
+  BeaconTransmitP.IsBroadcastReady -> CoordBroadcastP.IsBroadcastReady;
+  BeaconTransmitP.TimeCalc -> PibP;
+  BeaconTransmitP.Random = Random;
+  BeaconTransmitP.Leds = Leds;
+
+  /* ------------------ Beacon Tracking (MLME-SYNC) ------------------ */
+
+  components new RadioClientC(RADIO_CLIENT_BEACONSYNCHRONIZE) as SyncRadioClient;
+  PibP.MacReset -> BeaconSynchronizeP;
+  BeaconSynchronizeP.MLME_SET -> PibP.MLME_SET;
+  BeaconSynchronizeP.MLME_GET -> PibP;
+  BeaconSynchronizeP.TrackAlarm = Alarm2;
+  BeaconSynchronizeP.FrameUtility -> PibP;
+  BeaconSynchronizeP.Frame -> PibP;
+  BeaconSynchronizeP.BeaconFrame -> PibP;
+  BeaconSynchronizeP.BeaconRx -> SyncRadioClient;
+  BeaconSynchronizeP.RadioOff -> SyncRadioClient;
+  BeaconSynchronizeP.DataRequest -> PollP.DataRequest[SYNC_POLL_CLIENT];
+  BeaconSynchronizeP.RadioToken -> SyncRadioClient;
+  BeaconSynchronizeP.TimeCalc -> PibP;
+  BeaconSynchronizeP.CoordRealignmentRx -> DeviceCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_COORDINATOR_REALIGNMENT];
+  BeaconSynchronizeP.Leds = Leds;
+
+  /* -------------------- Association (MLME-ASSOCIATE) -------------------- */
+
+  PibP.MacReset -> AssociateP;
+  AssociateP.AssociationRequestRx -> CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_ASSOCIATION_REQUEST];
+  AssociateP.AssociationRequestTx -> DeviceCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
+  AssociateP.AssociationResponseExtracted -> DeviceCap.FrameExtracted[FC1_FRAMETYPE_CMD + CMD_FRAME_ASSOCIATION_RESPONSE];
+  AssociateP.AssociationResponseTx -> IndirectTxP.FrameTx[unique(INDIRECT_TX_CLIENT)];
+  AssociateP.DataRequest -> PollP.DataRequest[ASSOCIATE_POLL_CLIENT];
+  AssociateP.ResponseTimeout = Timer3;
+  AssociateP.TxFramePool -> TxFramePoolP;
+  AssociateP.TxControlPool -> TxControlPoolP;
+  AssociateP.MLME_GET -> PibP;
+  AssociateP.MLME_SET -> PibP.MLME_SET;
+  AssociateP.FrameUtility -> PibP;
+  AssociateP.Frame -> PibP;
+  AssociateP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
+
+  /* --------------- Disassociation (MLME-DISASSOCIATE) --------------- */
+
+  PibP.MacReset -> DisassociateP;
+  DisassociateP.DisassociationIndirectTx -> IndirectTxP.FrameTx[unique(INDIRECT_TX_CLIENT)];
+  DisassociateP.DisassociationDirectTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
+  DisassociateP.DisassociationToCoord -> DeviceCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
+  DisassociateP.DisassociationDirectRxFromCoord -> 
+    DeviceCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_DISASSOCIATION_NOTIFICATION];
+  DisassociateP.DisassociationExtractedFromCoord -> 
+    DeviceCap.FrameExtracted[FC1_FRAMETYPE_CMD + CMD_FRAME_DISASSOCIATION_NOTIFICATION];
+  DisassociateP.DisassociationRxFromDevice -> 
+    CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_DISASSOCIATION_NOTIFICATION];
+  DisassociateP.TxFramePool -> TxFramePoolP;
+  DisassociateP.TxControlPool -> TxControlPoolP;
+  DisassociateP.MLME_GET -> PibP;
+  DisassociateP.MLME_SET -> PibP;
+  DisassociateP.FrameUtility -> PibP;
+  DisassociateP.Frame -> PibP;
+  DisassociateP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
+
+  /* ------------------ Data Transmission (MCPS-DATA) ------------------- */
+
+  DataP.CoordCapRx -> CoordCap.FrameRx[FC1_FRAMETYPE_DATA]; 
+  DataP.DeviceCapTx -> DeviceCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
+  DataP.CoordCapTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
+  DataP.DeviceCapRx -> PollP.DataRx;                          
+  DataP.DeviceCapRx -> PromiscuousModeP.FrameRx;              
+  DataP.DeviceCapRx -> DeviceCap.FrameRx[FC1_FRAMETYPE_DATA]; 
+  DataP.TxFramePool -> TxFramePoolP;
+  DataP.BroadcastTx -> CoordBroadcastP.BroadcastDataFrame;
+  DataP.DeviceCfpTx -> DeviceCfp.CfpTx;
+  DataP.IndirectTx -> IndirectTxP.FrameTx[unique(INDIRECT_TX_CLIENT)];
+  DataP.FrameUtility -> PibP;
+  DataP.Frame -> PibP;
+  DataP.PurgeDirect -> DeviceCapQueue;
+  DataP.PurgeIndirect -> IndirectTxP;
+  DataP.PurgeGtsDevice -> DeviceCfp;
+  DataP.PurgeGtsCoord -> CoordCfp;
+  DataP.MLME_GET -> PibP;
+  DataP.Packet -> PibP;
+  DataP.Leds = Leds;
+
+  /* ------------------------ Polling (MLME-POLL) ----------------------- */
+
+  PibP.MacReset -> PollP;
+  PollP.PollTx -> DeviceCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
+  PollP.DataExtracted -> DeviceCap.FrameExtracted[FC1_FRAMETYPE_DATA];
+  PollP.FrameUtility -> PibP;
+  PollP.TxFramePool -> TxFramePoolP;
+  PollP.TxControlPool -> TxControlPoolP;
+  PollP.MLME_GET -> PibP;
+  PollP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
+
+  /* ---------------------- Indirect transmission ----------------------- */
+
+  PibP.MacReset -> IndirectTxP;
+  IndirectTxP.CoordCapTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
+  IndirectTxP.DataRequestRx -> CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_DATA_REQUEST];
+  IndirectTxP.MLME_GET -> PibP;
+  IndirectTxP.IEEE154Frame -> PibP;
+  IndirectTxP.IndirectTxTimeout = Timer4;
+  IndirectTxP.TimeCalc -> PibP;
+  IndirectTxP.Leds = Leds;
+
+  /* ---------------------------- Realignment --------------------------- */
+
+  PibP.MacReset -> CoordRealignmentP;
+  CoordRealignmentP.CoordRealignmentTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
+  CoordRealignmentP.OrphanNotificationRx -> CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_ORPHAN_NOTIFICATION];
+  CoordRealignmentP.FrameUtility -> PibP;
+  CoordRealignmentP.Frame -> PibP;
+  CoordRealignmentP.TxFramePool -> TxFramePoolP;
+  CoordRealignmentP.TxControlPool -> TxControlPoolP;
+  CoordRealignmentP.MLME_GET -> PibP;
+  CoordRealignmentP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
+
+  /* ---------------------------- Broadcasts ---------------------------- */
+
+  components new RadioClientC(RADIO_CLIENT_COORDBROADCAST) as CoordBroadcastRadioClient;
+  PibP.MacReset -> CoordBroadcastP;
+  CoordBroadcastP.RadioToken -> CoordBroadcastRadioClient;
+  CoordBroadcastP.OutgoingSF -> BeaconTransmitP.OutgoingSF;
+  CoordBroadcastP.CapTransmitNow -> CoordCap.BroadcastTx;
+  CoordBroadcastP.Queue -> BroadcastQueueC;
+
+  /* --------------------- CAP (incoming superframe) -------------------- */
+
+  PibP.DispatchQueueReset -> DeviceCapQueue;
+  DeviceCapQueue.Queue -> DeviceCapQueueC;
+  DeviceCapQueue.FrameTxCsma -> DeviceCap;
+
+  PibP.DispatchQueueReset -> CoordCapQueue;
+  CoordCapQueue.Queue -> CoordCapQueueC;
+  CoordCapQueue.FrameTxCsma -> CoordCap;
+  
+  components new RadioClientC(RADIO_CLIENT_DEVICECAP) as DeviceCapRadioClient;
+  PibP.DispatchReset -> DeviceCap;
+  DeviceCap.CapEndAlarm = Alarm3;
+  DeviceCap.BLEAlarm = Alarm4;
+  DeviceCap.RxWaitAlarm = Alarm5;
+  DeviceCap.RadioToken -> DeviceCapRadioClient;
+  DeviceCap.RadioTokenRequested -> DeviceCapRadioClient;
+  DeviceCap.SuperframeStructure -> BeaconSynchronizeP.IncomingSF;
+  DeviceCap.IsRxEnableActive -> RxEnableP.IsRxEnableActive;
+  DeviceCap.IsRadioTokenRequested -> PibP.IsRadioTokenRequested; // fan out...
+  DeviceCap.IsRadioTokenRequested -> PromiscuousModeP.IsRadioTokenRequested;
+  DeviceCap.IsRadioTokenRequested -> ScanP.IsRadioTokenRequested;
+  DeviceCap.GetIndirectTxFrame -> IndirectTxP;
+  DeviceCap.RxEnableStateChange -> RxEnableP.RxEnableStateChange;  
+  DeviceCap.IsTrackingBeacons -> BeaconSynchronizeP.IsTrackingBeacons;  
+  DeviceCap.PIBUpdateMacRxOnWhenIdle -> PibP.PIBUpdate[IEEE154_macRxOnWhenIdle];
+  DeviceCap.FrameUtility -> PibP;
+  DeviceCap.SlottedCsmaCa -> DeviceCapRadioClient;
+  DeviceCap.RadioRx -> DeviceCapRadioClient;
+  DeviceCap.RadioOff -> DeviceCapRadioClient;
+  DeviceCap.MLME_GET -> PibP;
+  DeviceCap.MLME_SET -> PibP.MLME_SET;
+  DeviceCap.TimeCalc -> PibP;
+  DeviceCap.Leds = Leds;
+  DeviceCap.TrackSingleBeacon -> BeaconSynchronizeP.TrackSingleBeacon;
+  DeviceCap.MLME_SYNC_LOSS -> BeaconSynchronizeP;
+
+  /* ---------------------- CAP (outgoing superframe) ------------------- */
+
+  components new RadioClientC(RADIO_CLIENT_COORDCAP) as CoordCapRadioClient, 
+             new BackupP(ieee154_cap_frame_backup_t);
+  PibP.DispatchReset -> CoordCap;
+  CoordCap.CapEndAlarm = Alarm6;
+  CoordCap.BLEAlarm = Alarm7;
+  CoordCap.RadioToken -> CoordCapRadioClient;
+  CoordCap.RadioTokenRequested -> CoordCapRadioClient;
+  CoordCap.SuperframeStructure -> BeaconTransmitP.OutgoingSF;
+  CoordCap.IsRxEnableActive -> RxEnableP.IsRxEnableActive;
+  CoordCap.IsRadioTokenRequested -> PibP.IsRadioTokenRequested; // fan out...
+  CoordCap.IsRadioTokenRequested -> PromiscuousModeP.IsRadioTokenRequested;
+  CoordCap.IsRadioTokenRequested -> ScanP.IsRadioTokenRequested;
+  CoordCap.GetIndirectTxFrame -> IndirectTxP;
+  CoordCap.RxEnableStateChange -> RxEnableP.RxEnableStateChange;  
+  CoordCap.IsTrackingBeacons -> BeaconSynchronizeP.IsTrackingBeacons;  
+  CoordCap.PIBUpdateMacRxOnWhenIdle -> PibP.PIBUpdate[IEEE154_macRxOnWhenIdle];
+  CoordCap.FrameUtility -> PibP;
+  CoordCap.SlottedCsmaCa -> CoordCapRadioClient;
+  CoordCap.RadioRx -> CoordCapRadioClient;
+  CoordCap.RadioOff -> CoordCapRadioClient;
+  CoordCap.MLME_GET -> PibP;
+  CoordCap.MLME_SET -> PibP.MLME_SET;
+  CoordCap.TimeCalc -> PibP;
+  CoordCap.Leds = Leds;
+  CoordCap.FrameBackup -> BackupP;
+  CoordCap.FrameRestore -> BackupP;
+
+  /* -------------------- GTS (incoming superframe) --------------------- */
+
+  components new RadioClientC(RADIO_CLIENT_DEVICECFP) as DeviceCfpRadioClient;
+  PibP.MacReset -> DeviceCfp;
+  DeviceCfp.RadioToken -> DeviceCfpRadioClient;
+  DeviceCfp.IncomingSF -> BeaconSynchronizeP.IncomingSF; 
+  DeviceCfp.CfpSlotAlarm = Alarm8;
+  DeviceCfp.CfpEndAlarm = Alarm9;
+  DeviceCfp.RadioTx -> DeviceCfpRadioClient;
+  DeviceCfp.RadioRx -> DeviceCfpRadioClient;
+  DeviceCfp.RadioOff -> DeviceCfpRadioClient;
+  DeviceCfp.MLME_GET -> PibP;
+  DeviceCfp.MLME_SET -> PibP.MLME_SET; 
+
+  /* -------------------- GTS (outgoing superframe) --------------------- */
+
+  components new RadioClientC(RADIO_CLIENT_COORDCFP) as CoordCfpRadioClient;
+  PibP.MacReset -> CoordCfp;
+  CoordCfp.RadioToken -> CoordCfpRadioClient;
+  CoordCfp.OutgoingSF -> BeaconTransmitP.OutgoingSF; 
+  CoordCfp.CfpSlotAlarm = Alarm10;
+  CoordCfp.CfpEndAlarm = Alarm11;
+  CoordCfp.RadioTx -> CoordCfpRadioClient;
+  CoordCfp.RadioRx -> CoordCfpRadioClient;
+  CoordCfp.RadioOff -> CoordCfpRadioClient;
+  CoordCfp.MLME_GET -> PibP;
+  CoordCfp.MLME_SET -> PibP.MLME_SET;
+
+  /* -------------------------- promiscuous mode ------------------------ */
+
+  components new RadioClientC(RADIO_CLIENT_PROMISCUOUSMODE) as PromiscuousModeRadioClient;
+  PibP.MacReset -> PromiscuousModeP;
+  PromiscuousModeP.RadioToken -> PromiscuousModeRadioClient;
+  PromiscuousModeP.PromiscuousRx -> PromiscuousModeRadioClient;
+  PromiscuousModeP.RadioOff -> PromiscuousModeRadioClient;
+  PromiscuousModeP.RadioPromiscuousMode = RadioPromiscuousMode;
+
+  /* --------------------------- MLME-RX-ENABLE  ------------------------ */
+
+  PibP.MacReset -> RxEnableP;
+  RxEnableP.IncomingSuperframeStructure -> BeaconSynchronizeP;
+  RxEnableP.OutgoingSuperframeStructure -> BeaconTransmitP;
+  RxEnableP.IsTrackingBeacons -> BeaconSynchronizeP.IsTrackingBeacons;
+  RxEnableP.IsSendingBeacons-> BeaconTransmitP.IsSendingBeacons;
+  RxEnableP.TimeCalc -> PibP.TimeCalc;
+  RxEnableP.WasRxEnabled -> DeviceCap.WasRxEnabled;
+  RxEnableP.WasRxEnabled -> CoordCap.WasRxEnabled;
+  RxEnableP.RxEnableTimer = Timer5;
+
+  /* ------------------------------- PIB -------------------------------- */
+
+  components new RadioClientC(RADIO_CLIENT_PIB) as PibRadioClient;
+  PIBUpdate = PibP;
+  MainC.SoftwareInit -> PibP.LocalInit;
+  PibP.RadioControl = PhySplitControl;
+  PibP.Random = Random; 
+  PibP.PromiscuousModeGet -> PromiscuousModeP; 
+  PibP.LocalTime = LocalTime;
+  PibP.RadioToken -> PibRadioClient;
+  PibP.RadioOff -> PibRadioClient;
+
+  /* ------------------------- Radio Control ---------------------------- */
+
+  RadioControlP.PhyTx = RadioTx;
+  RadioControlP.PhySlottedCsmaCa = SlottedCsmaCa;
+  RadioControlP.PhyRx = RadioRx;
+  RadioControlP.PhyRadioOff = RadioOff;
+  RadioControlP.RadioPromiscuousMode -> PromiscuousModeP;
+  RadioControlP.Leds = Leds;
+}
diff --git a/tos/lib/mac/tkn154/TKN154NonBeaconEnabledP.nc b/tos/lib/mac/tkn154/TKN154NonBeaconEnabledP.nc
new file mode 100644 (file)
index 0000000..dea2bdc
--- /dev/null
@@ -0,0 +1,357 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#include "TKN154_PHY.h"
+#include "TKN154_MAC.h"
+#include "TKN154_PIB.h"
+
+#define IEEE154_BEACON_ENABLED_PAN FALSE
+
+configuration TKN154NonBeaconEnabledP
+{
+  provides
+  {
+    /* MCPS-SAP */
+    interface MCPS_DATA;
+    interface MCPS_PURGE;
+    interface Packet;
+
+    /* MLME-SAP */
+    interface MLME_ASSOCIATE;
+    interface MLME_BEACON_NOTIFY;
+    interface MLME_COMM_STATUS;
+    interface MLME_DISASSOCIATE;
+    interface MLME_GET;
+    interface MLME_ORPHAN;
+    interface MLME_POLL;
+    interface MLME_RESET;
+    interface MLME_RX_ENABLE;
+    interface MLME_SCAN;
+    interface MLME_SET;
+    interface MLME_START;
+
+    interface Notify<const void*> as PIBUpdate[uint8_t attributeID];
+    interface IEEE154Frame;
+    interface IEEE154BeaconFrame;
+    interface IEEE154TxBeaconPayload;
+    interface SplitControl as PromiscuousMode;
+    interface Get<uint64_t> as GetLocalExtendedAddress;
+    interface TimeCalc;
+    interface FrameUtility;
+
+  } uses {
+
+    interface RadioRx;
+    interface RadioTx;
+    interface RadioOff;
+    interface UnslottedCsmaCa;
+    interface EnergyDetection;
+    interface SplitControl as PhySplitControl;
+    interface Set<bool> as RadioPromiscuousMode;
+
+    interface Timer<TSymbolIEEE802154> as Timer1;
+    interface Timer<TSymbolIEEE802154> as Timer2;
+    interface Timer<TSymbolIEEE802154> as Timer3;
+    interface Timer<TSymbolIEEE802154> as Timer4;
+    interface Timer<TSymbolIEEE802154> as Timer5;
+
+    interface LocalTime<TSymbolIEEE802154>;
+    interface Random;
+    interface Leds;
+  }
+}
+implementation
+{
+  components DataP,
+             PibP,
+             RadioControlP,
+             IndirectTxP,
+             PollP,
+             BeaconRequestRxP,
+
+#ifndef IEEE154_SCAN_DISABLED
+             ScanP,
+#else
+             NoScanP as ScanP,
+#endif
+
+#ifndef IEEE154_ASSOCIATION_DISABLED
+             AssociateP,
+#else
+             NoAssociateP as AssociateP,
+#endif
+
+#ifndef IEEE154_DISASSOCIATION_DISABLED
+             DisassociateP,
+#else
+             NoDisassociateP as DisassociateP,
+#endif
+             new DispatchQueueP() as DispatchQueueP,
+             DispatchUnslottedCsmaP as DispatchP,
+
+#ifndef IEEE154_RXENABLE_DISABLED
+             RxEnableP,
+#else
+             NoRxEnableP as RxEnableP,
+#endif
+
+
+#ifndef IEEE154_PROMISCUOUS_MODE_DISABLED
+             PromiscuousModeP,
+#else
+             NoPromiscuousModeP as PromiscuousModeP,
+#endif
+
+#ifndef IEEE154_COORD_REALIGNMENT_DISABLED
+             CoordRealignmentP,
+#else
+             NoCoordRealignmentP as CoordRealignmentP,
+#endif
+
+             new PoolC(ieee154_txframe_t, TXFRAME_POOL_SIZE) as TxFramePoolP,
+             new PoolC(ieee154_txcontrol_t, TXCONTROL_POOL_SIZE) as TxControlPoolP,
+             new QueueC(ieee154_txframe_t*, CAP_TX_QUEUE_SIZE) as DispatchQueueC;
+
+  components MainC;
+
+  /* MCPS */
+  MCPS_DATA = DataP; 
+  MCPS_PURGE = DataP; 
+
+  /* MLME */
+  MLME_START = DispatchP;
+  MLME_ASSOCIATE = AssociateP;
+  MLME_DISASSOCIATE = DisassociateP;
+  MLME_BEACON_NOTIFY = ScanP;
+  MLME_COMM_STATUS = AssociateP;
+  MLME_COMM_STATUS = CoordRealignmentP;
+  MLME_GET = PibP;
+  MLME_ORPHAN = CoordRealignmentP;
+  MLME_POLL = PollP;
+  MLME_RESET = PibP;
+  MLME_RX_ENABLE = RxEnableP;
+  MLME_SCAN = ScanP;
+  MLME_SET = PibP;
+  IEEE154Frame = PibP;
+  IEEE154BeaconFrame = PibP;
+  IEEE154TxBeaconPayload = BeaconRequestRxP;
+  PromiscuousMode = PromiscuousModeP;
+  GetLocalExtendedAddress = PibP.GetLocalExtendedAddress;
+  Packet = PibP; 
+  TimeCalc = PibP;
+  FrameUtility = PibP;
+
+  /* ----------------------- Scanning (MLME-SCAN) ----------------------- */
+
+  components new RadioClientC(RADIO_CLIENT_SCAN) as ScanRadioClient;
+  PibP.MacReset -> ScanP;
+  ScanP.MLME_GET -> PibP;
+  ScanP.MLME_SET -> PibP.MLME_SET;
+  ScanP.EnergyDetection = EnergyDetection;
+  ScanP.RadioRx -> ScanRadioClient;
+  ScanP.RadioTx -> ScanRadioClient;
+  ScanP.Frame -> PibP;
+  ScanP.BeaconFrame -> PibP;
+  ScanP.RadioOff -> ScanRadioClient;
+  ScanP.ScanTimer = Timer1;
+  ScanP.TxFramePool -> TxFramePoolP;
+  ScanP.TxControlPool -> TxControlPoolP;
+  ScanP.RadioToken -> ScanRadioClient;
+  ScanP.Leds = Leds;
+  ScanP.FrameUtility -> PibP;
+
+  /* -------------------- Responding to Active Scans  --------------------- */
+
+  PibP.MacReset -> BeaconRequestRxP;
+  BeaconRequestRxP.BeaconRequestRx -> DispatchP.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_BEACON_REQUEST];
+  BeaconRequestRxP.BeaconRequestResponseTx -> DispatchQueueP.FrameTx[unique(CAP_TX_CLIENT)];
+  BeaconRequestRxP.MLME_GET -> PibP;
+  BeaconRequestRxP.FrameUtility -> PibP;
+  BeaconRequestRxP.Frame -> PibP;
+
+  /* -------------------- Association (MLME-ASSOCIATE) -------------------- */
+
+  PibP.MacReset -> AssociateP;
+  AssociateP.AssociationRequestRx -> DispatchP.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_ASSOCIATION_REQUEST];
+  AssociateP.AssociationRequestTx -> DispatchQueueP.FrameTx[unique(CAP_TX_CLIENT)];
+  AssociateP.AssociationResponseExtracted -> DispatchP.FrameExtracted[FC1_FRAMETYPE_CMD + CMD_FRAME_ASSOCIATION_RESPONSE];
+  AssociateP.AssociationResponseTx -> IndirectTxP.FrameTx[unique(INDIRECT_TX_CLIENT)];
+  AssociateP.DataRequest -> PollP.DataRequest[ASSOCIATE_POLL_CLIENT];
+  AssociateP.ResponseTimeout = Timer2;
+  AssociateP.TxFramePool -> TxFramePoolP;
+  AssociateP.TxControlPool -> TxControlPoolP;
+  AssociateP.MLME_GET -> PibP;
+  AssociateP.MLME_SET -> PibP.MLME_SET;
+  AssociateP.FrameUtility -> PibP;
+  AssociateP.Frame -> PibP;
+  AssociateP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
+
+  /* --------------- Disassociation (MLME-DISASSOCIATE) --------------- */
+
+  PibP.MacReset -> DisassociateP;
+  DisassociateP.DisassociationIndirectTx -> IndirectTxP.FrameTx[unique(INDIRECT_TX_CLIENT)];
+  DisassociateP.DisassociationDirectTx -> DispatchQueueP.FrameTx[unique(CAP_TX_CLIENT)];
+  DisassociateP.DisassociationToCoord -> DispatchQueueP.FrameTx[unique(CAP_TX_CLIENT)];
+  DisassociateP.DisassociationExtractedFromCoord -> 
+    DispatchP.FrameExtracted[FC1_FRAMETYPE_CMD + CMD_FRAME_DISASSOCIATION_NOTIFICATION];
+  DisassociateP.DisassociationRxFromDevice -> 
+    DispatchP.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_DISASSOCIATION_NOTIFICATION];
+  DisassociateP.TxFramePool -> TxFramePoolP;
+  DisassociateP.TxControlPool -> TxControlPoolP;
+  DisassociateP.MLME_GET -> PibP;
+  DisassociateP.MLME_SET -> PibP;
+  DisassociateP.FrameUtility -> PibP;
+  DisassociateP.Frame -> PibP;
+  DisassociateP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
+
+  /* ------------------ Data Transmission (MCPS-DATA) ------------------- */
+
+  DataP.DeviceCapTx -> DispatchQueueP.FrameTx[unique(CAP_TX_CLIENT)];
+  DataP.CoordCapTx -> DispatchQueueP.FrameTx[unique(CAP_TX_CLIENT)];
+  DataP.DeviceCapRx -> PollP.DataRx;                          
+  DataP.DeviceCapRx -> PromiscuousModeP.FrameRx;              
+  DataP.DeviceCapRx -> DispatchP.FrameRx[FC1_FRAMETYPE_DATA]; 
+  DataP.TxFramePool -> TxFramePoolP;
+  DataP.IndirectTx -> IndirectTxP.FrameTx[unique(INDIRECT_TX_CLIENT)];
+  DataP.FrameUtility -> PibP;
+  DataP.Frame -> PibP;
+  DataP.PurgeDirect -> DispatchQueueP;
+  DataP.PurgeIndirect -> IndirectTxP;
+  DataP.MLME_GET -> PibP;
+  DataP.Packet -> PibP;
+  DataP.Leds = Leds;
+
+  /* ------------------------ Polling (MLME-POLL) ----------------------- */
+
+  PibP.MacReset -> PollP;
+  PollP.PollTx -> DispatchQueueP.FrameTx[unique(CAP_TX_CLIENT)];
+  PollP.DataExtracted -> DispatchP.FrameExtracted[FC1_FRAMETYPE_DATA];
+  PollP.FrameUtility -> PibP;
+  PollP.TxFramePool -> TxFramePoolP;
+  PollP.TxControlPool -> TxControlPoolP;
+  PollP.MLME_GET -> PibP;
+  PollP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
+
+  /* ---------------------- Indirect transmission ----------------------- */
+
+  PibP.MacReset -> IndirectTxP;
+  IndirectTxP.CoordCapTx -> DispatchQueueP.FrameTx[unique(CAP_TX_CLIENT)];
+  IndirectTxP.DataRequestRx -> DispatchP.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_DATA_REQUEST];
+  IndirectTxP.MLME_GET -> PibP;
+  IndirectTxP.IEEE154Frame -> PibP;
+  IndirectTxP.IndirectTxTimeout = Timer3;
+  IndirectTxP.TimeCalc -> PibP;
+  IndirectTxP.Leds = Leds;
+
+  /* ---------------------------- Realignment --------------------------- */
+
+  PibP.MacReset -> CoordRealignmentP;
+  CoordRealignmentP.CoordRealignmentTx -> DispatchQueueP.FrameTx[unique(CAP_TX_CLIENT)];
+  CoordRealignmentP.OrphanNotificationRx -> DispatchP.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_ORPHAN_NOTIFICATION];
+  CoordRealignmentP.FrameUtility -> PibP;
+  CoordRealignmentP.Frame -> PibP;
+  CoordRealignmentP.TxFramePool -> TxFramePoolP;
+  CoordRealignmentP.TxControlPool -> TxControlPoolP;
+  CoordRealignmentP.MLME_GET -> PibP;
+  CoordRealignmentP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
+
+  /* --------------------- DispatchP -------------------- */
+
+  PibP.DispatchReset -> DispatchP;
+  PibP.DispatchQueueReset -> DispatchQueueP;
+  DispatchQueueP.Queue -> DispatchQueueC;
+  DispatchQueueP.FrameTxCsma -> DispatchP;
+  
+  components new RadioClientC(unique(IEEE802154_RADIO_RESOURCE)) as DispatchRadioClient;
+  PibP.DispatchReset -> DispatchP;
+  DispatchP.IndirectTxWaitTimer = Timer4;
+  DispatchP.RadioToken -> DispatchRadioClient;
+  DispatchP.SetMacSuperframeOrder -> PibP.SetMacSuperframeOrder;
+  DispatchP.SetMacPanCoordinator -> PibP.SetMacPanCoordinator;
+  DispatchP.IsRxEnableActive -> RxEnableP.IsRxEnableActive;
+  DispatchP.RadioTokenRequested -> DispatchRadioClient;
+  DispatchP.IsRadioTokenRequested -> PibP.IsRadioTokenRequested; // fan out...
+  DispatchP.IsRadioTokenRequested -> PromiscuousModeP.IsRadioTokenRequested;
+  DispatchP.IsRadioTokenRequested -> ScanP.IsRadioTokenRequested;
+  DispatchP.GetIndirectTxFrame -> IndirectTxP;
+  DispatchP.RxEnableStateChange -> RxEnableP.RxEnableStateChange;  
+  DispatchP.PIBUpdateMacRxOnWhenIdle -> PibP.PIBUpdate[IEEE154_macRxOnWhenIdle];
+  DispatchP.FrameUtility -> PibP;
+  DispatchP.UnslottedCsmaCa -> DispatchRadioClient;
+  DispatchP.RadioRx -> DispatchRadioClient;
+  DispatchP.RadioOff -> DispatchRadioClient;
+  DispatchP.MLME_GET -> PibP;
+  DispatchP.MLME_SET -> PibP.MLME_SET;
+  DispatchP.TimeCalc -> PibP;
+  DispatchP.Leds = Leds;
+
+  /* -------------------------- promiscuous mode ------------------------ */
+
+  components new RadioClientC(RADIO_CLIENT_PROMISCUOUSMODE) as PromiscuousModeRadioClient;
+  PibP.MacReset -> PromiscuousModeP;
+  PromiscuousModeP.RadioToken -> PromiscuousModeRadioClient;
+  PromiscuousModeP.PromiscuousRx -> PromiscuousModeRadioClient;
+  PromiscuousModeP.RadioOff -> PromiscuousModeRadioClient;
+  PromiscuousModeP.RadioPromiscuousMode = RadioPromiscuousMode;
+
+  /* --------------------------- MLME-RX-ENABLE  ------------------------ */
+
+  PibP.MacReset -> RxEnableP;
+  RxEnableP.TimeCalc -> PibP.TimeCalc;
+  RxEnableP.WasRxEnabled -> DispatchP.WasRxEnabled;
+  RxEnableP.WasRxEnabled -> DispatchP.WasRxEnabled;
+  RxEnableP.RxEnableTimer = Timer5;
+
+  /* ------------------------------- PIB -------------------------------- */
+
+  components new RadioClientC(RADIO_CLIENT_PIB) as PibRadioClient;
+  PIBUpdate = PibP;
+  MainC.SoftwareInit -> PibP.LocalInit;
+  PibP.RadioControl = PhySplitControl;
+  PibP.Random = Random; 
+  PibP.PromiscuousModeGet -> PromiscuousModeP; 
+  PibP.LocalTime = LocalTime;
+  PibP.RadioToken -> PibRadioClient;
+  PibP.RadioOff -> PibRadioClient;
+
+  /* ------------------------- Radio Control ---------------------------- */
+
+  RadioControlP.PhyTx = RadioTx;
+  RadioControlP.PhyUnslottedCsmaCa = UnslottedCsmaCa;
+  RadioControlP.PhyRx = RadioRx;
+  RadioControlP.PhyRadioOff = RadioOff;
+  RadioControlP.RadioPromiscuousMode -> PromiscuousModeP;
+  RadioControlP.Leds = Leds;
+}
diff --git a/tos/lib/mac/tkn154/TKN154P.nc b/tos/lib/mac/tkn154/TKN154P.nc
deleted file mode 100644 (file)
index 622c6f6..0000000
+++ /dev/null
@@ -1,527 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#include "TKN154_PHY.h"
-#include "TKN154_MAC.h"
-#include "TKN154_PIB.h"
-#include "TKN154_DEBUG.h"
-
-configuration TKN154P
-{
-  provides
-  {
-    // MCPS-SAP
-    interface MCPS_DATA;
-    interface MCPS_PURGE;
-    interface Packet;
-
-    // MLME-SAP
-    interface MLME_ASSOCIATE;
-    interface MLME_BEACON_NOTIFY;
-    interface MLME_COMM_STATUS;
-    interface MLME_DISASSOCIATE;
-    interface MLME_GET;
-/*    interface MLME_GTS;*/
-    interface MLME_ORPHAN;
-    interface MLME_POLL;
-    interface MLME_RESET;
-    interface MLME_RX_ENABLE;
-    interface MLME_SCAN;
-    interface MLME_SET;
-    interface MLME_START;
-    interface MLME_SYNC;
-    interface MLME_SYNC_LOSS;
-
-    interface Notify<const void*> as PIBUpdate[uint8_t attributeID];
-    interface IEEE154Frame;
-    interface IEEE154BeaconFrame;
-    interface IEEE154TxBeaconPayload;
-    interface SplitControl as PromiscuousMode;
-    interface Get<uint64_t> as GetLocalExtendedAddress;
-    interface TimeCalc;
-    interface FrameUtility;
-
-  } uses {
-
-    interface RadioRx;
-    interface RadioTx;
-    interface RadioOff;
-    interface EnergyDetection;
-    interface SplitControl as PhySplitControl;
-    interface Set<bool> as RadioPromiscuousMode;
-
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm1;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm2;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm3;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm4;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm5;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm6;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm7;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm8;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm9;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm10;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm11;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as Alarm12;
-
-    interface Timer<TSymbolIEEE802154> as Timer1;
-    interface Timer<TSymbolIEEE802154> as Timer2;
-    interface Timer<TSymbolIEEE802154> as Timer3;
-    interface Timer<TSymbolIEEE802154> as Timer4;
-    interface Timer<TSymbolIEEE802154> as Timer5;
-
-    interface Ieee802154Debug[uint8_t client];
-    interface LocalTime<TSymbolIEEE802154>;
-    interface Random;
-    interface Leds;
-  }
-}
-implementation
-{
-  components
-#ifndef IEEE154_SCAN_DISABLED
-             ScanP,
-#else
-             NoScanP as ScanP,
-#endif
-             DataP,
-             AssociateP,
-             PollP,
-             RxEnableP,
-             IndirectTxP,
-             PibP,
-             FrameDispatchP,
-
-#ifndef IEEE154_BEACON_SYNC_DISABLED
-             BeaconSynchronizeP,
-             new CapQueueP() as DeviceCapQueue,
-             new CapP(INCOMING_SUPERFRAME) as DeviceCap,
-#else
-             NoBeaconSynchronizeP as BeaconSynchronizeP,
-             new NoCapQueueP() as DeviceCapQueue,
-             new NoCapP() as DeviceCap,
-#endif
-             NoDeviceCfpP as DeviceCfp,
-
-#ifndef IEEE154_BEACON_TX_DISABLED
-             BeaconTransmitP,
-             new CapQueueP() as CoordCapQueue,
-             new CapP(OUTGOING_SUPERFRAME) as CoordCap,
-#else
-             NoBeaconTransmitP as BeaconTransmitP,
-             new NoCapQueueP() as CoordCapQueue,
-             new NoCapP() as CoordCap,
-#endif
-             NoCoordCfpP as CoordCfp,
-
-             CoordRealignmentP,
-             CoordBroadcastP,
-             new PoolC(ieee154_txframe_t, TXFRAME_POOL_SIZE) as TxFramePoolP,
-             new PoolC(ieee154_txcontrol_t, TXCONTROL_POOL_SIZE) as TxControlPoolP,
-             new QueueC(ieee154_txframe_t*, CAP_TX_QUEUE_SIZE) as DeviceCapQueueC,
-             new QueueC(ieee154_txframe_t*, CAP_TX_QUEUE_SIZE) as CoordCapQueueC,
-             new QueueC(ieee154_txframe_t*, CAP_TX_QUEUE_SIZE) as BroadcastQueueC;
-
-  components MainC;
-
-  // MCPS
-  MCPS_DATA = DataP; 
-  MCPS_PURGE = DataP; 
-
-  //MLME
-  MLME_START = BeaconTransmitP;
-  MLME_ASSOCIATE = AssociateP;
-  MLME_BEACON_NOTIFY = BeaconSynchronizeP;
-  MLME_BEACON_NOTIFY = ScanP;
-  MLME_COMM_STATUS = AssociateP;
-  MLME_COMM_STATUS = CoordRealignmentP;
-  MLME_DISASSOCIATE = AssociateP;
-  MLME_GET = PibP;
-  MLME_ORPHAN = CoordRealignmentP;
-/*  MLME_GTS = CfpTransmitP;*/
-  MLME_POLL = PollP;
-  MLME_RESET = PibP;
-  MLME_RX_ENABLE = RxEnableP;
-  MLME_SCAN = ScanP;
-  MLME_SET = PibP;
-  MLME_SYNC = BeaconSynchronizeP;
-  MLME_SYNC_LOSS = BeaconSynchronizeP;
-  IEEE154Frame = PibP;
-  IEEE154BeaconFrame = PibP;
-  PromiscuousMode = RxEnableP;
-  GetLocalExtendedAddress = PibP.GetLocalExtendedAddress;
-  IEEE154TxBeaconPayload = BeaconTransmitP;
-  Packet = PibP; 
-  TimeCalc = PibP;
-  FrameUtility = PibP;
-  
-/* ----------------------- Scanning (MLME-SCAN) ----------------------- */
-
-  components new RadioClientC() as ScanRadioClient;
-  PibP.MacReset -> ScanP;
-  ScanP.MLME_GET -> PibP;
-  ScanP.MLME_SET -> PibP.MLME_SET;
-  ScanP.EnergyDetection = EnergyDetection;
-  ScanP.RadioRx -> ScanRadioClient;
-  ScanP.RadioTx -> ScanRadioClient;
-  ScanP.Frame -> PibP;
-  ScanP.BeaconFrame -> PibP;
-  ScanP.RadioOff -> ScanRadioClient;
-  ScanP.ScanTimer = Timer1;
-  ScanP.TxFramePool -> TxFramePoolP;
-  ScanP.TxControlPool -> TxControlPoolP;
-  ScanP.Token -> ScanRadioClient;
-  ScanP.FrameUtility -> PibP;
-  ScanP.Leds = Leds;
-
-/* ----------------- Beacon Transmission (MLME-START) ----------------- */
-  
-  components new RadioClientC() as StartRadioClient;
-  PibP.MacReset -> BeaconTransmitP;
-  BeaconTransmitP.PIBUpdate[IEEE154_macAssociationPermit] -> PibP.PIBUpdate[IEEE154_macAssociationPermit];
-  BeaconTransmitP.PIBUpdate[IEEE154_macGTSPermit] -> PibP.PIBUpdate[IEEE154_macGTSPermit];
-  BeaconTransmitP.BeaconTxAlarm = Alarm1;
-  BeaconTransmitP.BeaconPayloadUpdateTimer = Timer2;
-  BeaconTransmitP.RadioOff -> StartRadioClient;
-  BeaconTransmitP.IsBeaconEnabledPAN -> PibP.IsBeaconEnabledPAN;
-  BeaconTransmitP.BeaconTx -> StartRadioClient;
-  BeaconTransmitP.MLME_SET -> PibP.MLME_SET;
-  BeaconTransmitP.MLME_GET -> PibP;
-  BeaconTransmitP.SetMacSuperframeOrder -> PibP.SetMacSuperframeOrder;
-  BeaconTransmitP.SetMacBeaconTxTime -> PibP.SetMacBeaconTxTime;
-  BeaconTransmitP.SetMacPanCoordinator -> PibP.SetMacPanCoordinator;
-  BeaconTransmitP.Token -> StartRadioClient;
-  BeaconTransmitP.TokenToBroadcast -> StartRadioClient;
-  BeaconTransmitP.RealignmentBeaconEnabledTx -> CoordBroadcastP.RealignmentTx;
-  BeaconTransmitP.RealignmentNonBeaconEnabledTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
-  BeaconTransmitP.BeaconRequestRx -> CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_BEACON_REQUEST];
-  BeaconTransmitP.GtsInfoWrite -> CoordCfp.GtsInfoWrite;
-  BeaconTransmitP.PendingAddrSpecUpdated -> IndirectTxP.PendingAddrSpecUpdated;
-  BeaconTransmitP.PendingAddrWrite -> IndirectTxP.PendingAddrWrite;
-  BeaconTransmitP.FrameUtility -> PibP.FrameUtility;
-  BeaconTransmitP.IsTrackingBeacons -> BeaconSynchronizeP.IsTrackingBeacons;
-  BeaconTransmitP.LastBeaconRxRefTime -> BeaconSynchronizeP.CapStartRefTime;
-  BeaconTransmitP.LastBeaconRxTime -> BeaconSynchronizeP.CapStart;
-  BeaconTransmitP.GetSetRealignmentFrame -> CoordRealignmentP;
-  BeaconTransmitP.IsBroadcastReady -> CoordBroadcastP.IsBroadcastReady;
-  BeaconTransmitP.TimeCalc -> PibP;
-  BeaconTransmitP.Leds = Leds;
-  BeaconTransmitP.Debug = Ieee802154Debug[START_CLIENT];
-  StartRadioClient.TransferTo -> CoordBroadcastRadioClient.TransferFrom;
-
-/* ---------------- Beacon Synchronization (MLME-SYNC) ---------------- */
-
-  components new RadioClientC() as SyncRadioClient;
-  PibP.MacReset -> BeaconSynchronizeP;
-  BeaconSynchronizeP.MLME_SET -> PibP.MLME_SET;
-  BeaconSynchronizeP.MLME_GET -> PibP;
-  BeaconSynchronizeP.TrackAlarm = Alarm2;
-  BeaconSynchronizeP.FrameUtility -> PibP;
-  BeaconSynchronizeP.FindBeacon -> DeviceCap.FindBeacon;
-  BeaconSynchronizeP.FindBeacon -> CoordCap.FindBeacon;
-  BeaconSynchronizeP.Frame -> PibP;
-  BeaconSynchronizeP.BeaconFrame -> PibP;
-  BeaconSynchronizeP.BeaconRx -> SyncRadioClient;
-  BeaconSynchronizeP.RadioOff -> SyncRadioClient;
-  BeaconSynchronizeP.IsBeaconEnabledPAN -> PibP.IsBeaconEnabledPAN;
-  BeaconSynchronizeP.DataRequest -> PollP.DataRequest[SYNC_CLIENT];
-  BeaconSynchronizeP.Token -> SyncRadioClient;
-  BeaconSynchronizeP.TokenToCap -> SyncRadioClient;
-  BeaconSynchronizeP.TimeCalc -> PibP;
-  BeaconSynchronizeP.CoordRealignmentRx -> DeviceCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_COORDINATOR_REALIGNMENT];
-  BeaconSynchronizeP.Leds = Leds;
-  BeaconSynchronizeP.Debug = Ieee802154Debug[SYNC_CLIENT];
-  SyncRadioClient.TransferTo -> DeviceCapRadioClient.TransferFrom;
-
-/* --------------- Dis/Association (MLME-DIS/ASSOCIATE) --------------- */
-
-  PibP.MacReset -> AssociateP;
-  AssociateP.AssociationRequestRx -> CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_ASSOCIATION_REQUEST];
-  AssociateP.AssociationRequestTx -> DeviceCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
-  AssociateP.AssociationResponseExtracted -> DeviceCap.FrameExtracted[FC1_FRAMETYPE_CMD + CMD_FRAME_ASSOCIATION_RESPONSE];
-  AssociateP.AssociationResponseTx -> IndirectTxP.FrameTx[unique(INDIRECT_TX_CLIENT)];
-  AssociateP.DisassociationIndirectTx -> IndirectTxP.FrameTx[unique(INDIRECT_TX_CLIENT)];
-  AssociateP.DisassociationDirectTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
-  AssociateP.DisassociationToCoord -> DeviceCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
-  AssociateP.DisassociationDirectRxFromCoord -> 
-    DeviceCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_DISASSOCIATION_NOTIFICATION];
-  AssociateP.DisassociationExtractedFromCoord -> 
-    DeviceCap.FrameExtracted[FC1_FRAMETYPE_CMD + CMD_FRAME_DISASSOCIATION_NOTIFICATION];
-  AssociateP.DisassociationRxFromDevice -> 
-    CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_DISASSOCIATION_NOTIFICATION];
-  AssociateP.DataRequest -> PollP.DataRequest[ASSOCIATE_CLIENT];
-  AssociateP.ResponseTimeout = Timer3;
-  AssociateP.TxFramePool -> TxFramePoolP;
-  AssociateP.TxControlPool -> TxControlPoolP;
-  AssociateP.MLME_GET -> PibP;
-  AssociateP.MLME_SET -> PibP.MLME_SET;
-  AssociateP.FrameUtility -> PibP;
-  AssociateP.Frame -> PibP;
-  AssociateP.Leds = Leds;
-  AssociateP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
-  AssociateP.Debug = Ieee802154Debug[ASSOCIATE_CLIENT];
-
-/* ------------------ Data Transmission (MCPS-DATA) ------------------- */
-
-  PibP.MacReset -> DataP;
-  DataP.IsSendingBeacons -> BeaconTransmitP.IsSendingBeacons;
-  DataP.CoordCapRx -> CoordCap.FrameRx[FC1_FRAMETYPE_DATA]; 
-  DataP.DeviceCapTx -> DeviceCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
-  DataP.CoordCapTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
-  DataP.DeviceCapRx -> PollP.DataRx;        // indirect
-  DataP.DeviceCapRx -> RxEnableP.FrameRx;   // promiscuous
-  DataP.DeviceCapRx -> DeviceCap.FrameRx[FC1_FRAMETYPE_DATA]; // broadcast
-  DataP.TxFramePool -> TxFramePoolP;
-  DataP.BroadcastTx -> CoordBroadcastP.BroadcastDataFrame;
-  DataP.DeviceCfpTx -> DeviceCfp.CfpTx;
-  DataP.IndirectTx -> IndirectTxP.FrameTx[unique(INDIRECT_TX_CLIENT)];
-  DataP.FrameUtility -> PibP;
-  DataP.Frame -> PibP;
-  DataP.PurgeDirect -> DeviceCapQueue;
-  DataP.PurgeIndirect -> IndirectTxP;
-  DataP.PurgeGtsDevice -> DeviceCfp;
-  DataP.PurgeGtsCoord -> CoordCfp;
-  DataP.MLME_GET -> PibP;
-  DataP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
-  DataP.Packet -> PibP;
-  DataP.Leds = Leds;
-
-/* ------------------------ Polling (MLME-POLL) ----------------------- */
-
-  PibP.MacReset -> PollP;
-  PollP.PollTx -> DeviceCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
-  PollP.DataExtracted -> DeviceCap.FrameExtracted[FC1_FRAMETYPE_DATA];
-  PollP.FrameUtility -> PibP;
-  PollP.TxFramePool -> TxFramePoolP;
-  PollP.TxControlPool -> TxControlPoolP;
-  PollP.Debug = Ieee802154Debug[POLL_CLIENT];
-  PollP.MLME_GET -> PibP;
-  PollP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
-
-/* ---------------------- Indirect transmission ----------------------- */
-
-  PibP.MacReset -> IndirectTxP;
-  IndirectTxP.CoordCapTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
-  IndirectTxP.DataRequestRx -> CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_DATA_REQUEST];
-  IndirectTxP.MLME_GET -> PibP;
-  IndirectTxP.FrameUtility -> PibP;
-  IndirectTxP.IndirectTxTimeout = Timer4;
-  IndirectTxP.TimeCalc -> PibP;
-  IndirectTxP.Leds = Leds;
-  IndirectTxP.Debug = Ieee802154Debug[INDIRECTTX_DEBUG_CLIENT];
-
-/* ---------------------------- Realignment --------------------------- */
-
-  PibP.MacReset -> CoordRealignmentP;
-  CoordRealignmentP.CoordRealignmentTx -> CoordCapQueue.FrameTx[unique(CAP_TX_CLIENT)];
-  CoordRealignmentP.OrphanNotificationRx -> CoordCap.FrameRx[FC1_FRAMETYPE_CMD + CMD_FRAME_ORPHAN_NOTIFICATION];
-  CoordRealignmentP.FrameUtility -> PibP;
-  CoordRealignmentP.Frame -> PibP;
-  CoordRealignmentP.TxFramePool -> TxFramePoolP;
-  CoordRealignmentP.TxControlPool -> TxControlPoolP;
-  CoordRealignmentP.MLME_GET -> PibP;
-  CoordRealignmentP.LocalExtendedAddress -> PibP.GetLocalExtendedAddress;
-
-/* ---------------------------- Broadcasts ---------------------------- */
-
-  components new RadioClientC() as CoordBroadcastRadioClient;
-  PibP.MacReset -> CoordBroadcastP;
-  CoordBroadcastP.TokenTransferred -> CoordBroadcastRadioClient;
-  CoordBroadcastP.TokenToCap -> CoordBroadcastRadioClient;
-  CoordBroadcastRadioClient.TransferTo -> CoordCapRadioClient.TransferFrom;
-  CoordBroadcastP.BeaconFramePendingBit -> BeaconTransmitP.BeaconFramePendingBit;
-  CoordBroadcastP.CapTransmitNow -> CoordCap.BroadcastTx;
-  CoordBroadcastP.Queue -> BroadcastQueueC;
-  CoordBroadcastP.Leds = Leds;
-
-/* --------------------- CAP (incoming superframe) -------------------- */
-
-  PibP.CapQueueReset -> DeviceCapQueue;
-  DeviceCapQueue.Queue -> DeviceCapQueueC;
-  DeviceCapQueue.CapTx -> DeviceCap;
-
-  PibP.CapQueueReset -> CoordCapQueue;
-  CoordCapQueue.Queue -> CoordCapQueueC;
-  CoordCapQueue.CapTx -> CoordCap;
-  
-  components new RadioClientC() as DeviceCapRadioClient;
-  PibP.CapReset -> DeviceCap;
-  DeviceCap.Random = Random;
-  DeviceCap.CapEndAlarm = Alarm3;
-  DeviceCap.BLEAlarm = Alarm4;
-  DeviceCap.IndirectTxWaitAlarm = Alarm5;
-  DeviceCap.BroadcastAlarm = Alarm6;
-  DeviceCap.Token -> DeviceCapRadioClient;
-  DeviceCap.TokenToCfp -> DeviceCapRadioClient;
-  DeviceCap.TokenTransferred -> DeviceCapRadioClient;
-  DeviceCap.TokenRequested -> DeviceCapRadioClient;
-  DeviceCap.IsTokenRequested -> DeviceCapRadioClient;
-  DeviceCap.CapStart -> BeaconSynchronizeP.CapStart;
-  DeviceCap.CapStartRefTime -> BeaconSynchronizeP.CapStartRefTime;
-  DeviceCap.CapLen -> BeaconSynchronizeP.CapLen;
-  DeviceCap.IsBLEActive -> BeaconSynchronizeP.IsBLEActive;
-  DeviceCap.BLELen -> BeaconSynchronizeP.BLELen;
-  DeviceCap.IsRxBroadcastPending -> BeaconSynchronizeP.IsRxBroadcastPending;
-  DeviceCap.IsRxEnableActive -> RxEnableP.IsRxEnableActive;
-  DeviceCap.RxEnableStateChange -> RxEnableP.RxEnableStateChange;  
-  DeviceCap.IsTrackingBeacons -> BeaconSynchronizeP.IsTrackingBeacons;  
-  DeviceCap.FrameUtility -> PibP;
-  DeviceCap.RadioTx -> DeviceCapRadioClient;
-  DeviceCap.RadioRx -> DeviceCapRadioClient;
-  DeviceCap.RadioOff -> DeviceCapRadioClient;
-  DeviceCap.IsBeaconEnabledPAN -> PibP.IsBeaconEnabledPAN;
-  DeviceCap.MLME_GET -> PibP;
-  DeviceCap.MLME_SET -> PibP.MLME_SET;
-  DeviceCap.Debug = Ieee802154Debug[DEVICE_CAP_CLIENT];
-  DeviceCap.TimeCalc -> PibP;
-  DeviceCap.Leds = Leds;
-  DeviceCapRadioClient.TransferTo -> DeviceCfpRadioClient.TransferFrom;
-
-/* ---------------------- CAP (outgoing superframe) ------------------- */
-
-  components new RadioClientC() as CoordCapRadioClient, 
-             new BackupP(ieee154_cap_frame_backup_t);
-  PibP.CapReset -> CoordCap;
-  CoordCap.Random = Random;
-  CoordCap.CapEndAlarm = Alarm7;
-  CoordCap.BLEAlarm = Alarm8;
-  CoordCap.Token -> CoordCapRadioClient;
-  CoordCap.TokenToCfp -> CoordCapRadioClient;
-  CoordCap.TokenTransferred -> CoordCapRadioClient;
-  CoordCap.TokenRequested -> CoordCapRadioClient;
-  CoordCap.IsTokenRequested -> CoordCapRadioClient;
-  CoordCap.CapStart -> BeaconTransmitP.CapStart;
-  CoordCap.CapStartRefTime -> BeaconTransmitP.CapStartRefTime;
-  CoordCap.CapLen -> BeaconTransmitP.CapLen;
-  CoordCap.IsBLEActive -> BeaconTransmitP.IsBLEActive;
-  CoordCap.BLELen -> BeaconTransmitP.BLELen;
-  CoordCap.IsRxEnableActive -> RxEnableP.IsRxEnableActive;
-  CoordCap.RxEnableStateChange -> RxEnableP.RxEnableStateChange;  
-  CoordCap.IsTrackingBeacons -> BeaconSynchronizeP.IsTrackingBeacons;  
-  CoordCap.FrameUtility -> PibP;
-  CoordCap.RadioTx -> CoordCapRadioClient;
-  CoordCap.RadioRx -> CoordCapRadioClient;
-  CoordCap.RadioOff -> CoordCapRadioClient;
-  CoordCap.IsBeaconEnabledPAN -> PibP.IsBeaconEnabledPAN;
-  CoordCap.MLME_GET -> PibP;
-  CoordCap.MLME_SET -> PibP.MLME_SET;
-  CoordCap.Debug = Ieee802154Debug[COORD_CAP_CLIENT];
-  CoordCap.TimeCalc -> PibP;
-  CoordCap.Leds = Leds;
-  CoordCapRadioClient.TransferTo -> CoordCfpRadioClient.TransferFrom;
-  CoordCap.FrameBackup -> BackupP;
-  CoordCap.FrameRestore -> BackupP;
-
-/* -------------------- GTS (incoming superframe) --------------------- */
-
-  components new RadioClientC() as DeviceCfpRadioClient;
-  PibP.MacReset -> DeviceCfp;
-  DeviceCfp.Token -> DeviceCfpRadioClient;
-  DeviceCfp.TokenTransferred -> DeviceCfpRadioClient;
-  DeviceCfp.TokenRequested -> DeviceCfpRadioClient;
-  DeviceCfp.CapStartRefTime -> BeaconSynchronizeP.CapStartRefTime; 
-  DeviceCfp.CfpEnd -> BeaconSynchronizeP.CfpEnd; 
-  DeviceCfp.GtsField -> BeaconSynchronizeP.GtsField; 
-  DeviceCfp.SfSlotDuration -> BeaconSynchronizeP.SfSlotDuration; 
-  DeviceCfp.FinalCapSlot -> BeaconSynchronizeP.FinalCapSlot; 
-  DeviceCfp.CfpSlotAlarm = Alarm9;
-  DeviceCfp.CfpEndAlarm = Alarm10;
-  DeviceCfp.RadioTx -> DeviceCfpRadioClient;
-  DeviceCfp.RadioRx -> DeviceCfpRadioClient;
-  DeviceCfp.RadioOff -> DeviceCfpRadioClient;
-  DeviceCfp.MLME_GET -> PibP;
-  DeviceCfp.MLME_SET -> PibP.MLME_SET; 
-
-/* -------------------- GTS (outgoing superframe) --------------------- */
-
-  components new RadioClientC() as CoordCfpRadioClient;
-  PibP.MacReset -> CoordCfp;
-  CoordCfp.Token -> CoordCfpRadioClient;
-  CoordCfp.TokenTransferred -> CoordCfpRadioClient;
-  CoordCfp.TokenRequested -> CoordCfpRadioClient;
-  CoordCfp.CfpEnd -> BeaconTransmitP.CfpEnd; 
-  CoordCfp.GtsField -> BeaconTransmitP.GtsField; 
-  CoordCfp.SfSlotDuration -> BeaconTransmitP.SfSlotDuration; 
-  CoordCfp.FinalCapSlot -> BeaconTransmitP.FinalCapSlot; 
-  CoordCfp.CfpSlotAlarm = Alarm11;
-  CoordCfp.CfpEndAlarm = Alarm12;
-  CoordCfp.RadioTx -> CoordCfpRadioClient;
-  CoordCfp.RadioRx -> CoordCfpRadioClient;
-  CoordCfp.RadioOff -> CoordCfpRadioClient;
-  CoordCfp.MLME_GET -> PibP;
-  CoordCfp.MLME_SET -> PibP.MLME_SET;
-
-/* ------------------ MLME-RX-ENABLE / promiscuous mode --------------- */
-
-  components new RadioClientC() as RxEnableRadioClient;
-  PibP.MacReset -> RxEnableP;
-  RxEnableP.Token -> RxEnableRadioClient;
-  RxEnableP.PromiscuousRx -> RxEnableRadioClient;
-  RxEnableP.IncomingSfStart -> BeaconSynchronizeP.CapStart;
-  RxEnableP.OutgoingSfStart -> BeaconTransmitP.CapStart;
-  RxEnableP.IncomingBeaconInterval -> BeaconSynchronizeP.BeaconInterval;
-  RxEnableP.OutgoingBeaconInterval -> BeaconTransmitP.BeaconInterval;
-  RxEnableP.IsTrackingBeacons -> BeaconSynchronizeP.IsTrackingBeacons;
-  RxEnableP.IsSendingBeacons-> BeaconTransmitP.IsSendingBeacons;
-  RxEnableP.IsMacPanCoordinator -> PibP.IsMacPanCoordinator;
-  RxEnableP.IsBeaconEnabledPAN -> PibP.IsBeaconEnabledPAN;
-  RxEnableP.TimeCalc -> PibP.TimeCalc;
-  RxEnableP.RadioOff -> RxEnableRadioClient;
-  RxEnableP.RadioPromiscuousMode = RadioPromiscuousMode;
-  RxEnableP.WasRxEnabled -> DeviceCap.WasRxEnabled;
-  RxEnableP.WasRxEnabled -> CoordCap.WasRxEnabled;
-  RxEnableP.RxEnableTimer = Timer5;
-  RxEnableP.Debug = Ieee802154Debug[RXENABLE_CLIENT];
-
-/* ------------------------------- PIB -------------------------------- */
-
-  components new RadioClientC() as PibRadioClient;
-  PIBUpdate = PibP;
-  MainC.SoftwareInit -> PibP.LocalInit;
-  PibP.RadioControl = PhySplitControl;
-  PibP.Random = Random; 
-  PibP.PromiscuousModeGet -> RxEnableP; 
-  PibP.LocalTime = LocalTime;
-  PibP.Token -> PibRadioClient;
-  PibP.RadioOff -> PibRadioClient;
-
-/* ---------------------------- Dispatcher ---------------------------- */
-
-  FrameDispatchP.PhyTx = RadioTx;
-  FrameDispatchP.PhyRx = RadioRx;
-  FrameDispatchP.PhyRadioOff = RadioOff;
-  FrameDispatchP.RadioPromiscuousMode -> RxEnableP;
-  FrameDispatchP.Leds = Leds;
-  FrameDispatchP.Debug = Ieee802154Debug[RADIORXTX_CLIENT];
-}
diff --git a/tos/lib/mac/tkn154/TKN154_DEBUG.h b/tos/lib/mac/tkn154/TKN154_DEBUG.h
deleted file mode 100644 (file)
index 9ca3d90..0000000
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#ifndef __TKN154_DEBUG_H
-#define __TKN154_DEBUG_H
-
-#define LEVEL_INFO 0
-#define LEVEL_IMPORTANT 50
-#define LEVEL_CRITICAL 100
-
-#define RadioRxTxP_ACQUIRED         0
-#define RadioRxTxP_NOT_ACQUIRED     1
-#define RadioRxTxP_TRANSFERRED      2
-#define RadioRxTxP_NOT_TRANSFERRED  3
-#define RadioRxTxP_RELEASED         4
-#define RadioRxTxP_NOT_RELEASED     5
-#define RadioRxTxP_TRANSFER_REQUEST 6
-#define RadioRxTxP_DEFAULT_PREPARE_TX_DONE 7
-#define RadioRxTxP_DEFAULT_TX_DONE         8
-#define RadioRxTxP_DEFAULT_PREPARE_RX_DONE 9
-#define RadioRxTxP_DEFAULT_RECEIVED        10
-#define RadioRxTxP_DEFAULT_OFFDONE         11
-#define RadioRxTxP_DEFAULT_TRANSFERRED     12 
-#define RadioRxTxP_DEFAULT_TRANSFERREQUEST 13
-#define RadioRxTxP_ASK_ISOWNER             14
-#define RadioRxTxP_RX_NOOWNER              15
-#define RadioRxTxP_DEFAULT_CANCEL_TX_DONE  16
-#define RadioRxTxP_DEFAULT_CANCEL_RX_DONE  17
-
-#define SyncP_BEACON_MISSED_1 0
-#define SyncP_BEACON_MISSED_2 1
-#define SyncP_BEACON_MISSED_3 2
-#define SyncP_TRACK_ALARM     3
-#define SyncP_INVALID_PARAM   4
-#define SyncP_RX_ON           5
-#define SyncP_INTERNAL_ERROR  6
-#define SyncP_BEACON_RX       7
-#define SyncP_RADIO_BUSY      8
-#define SyncP_LOST_SYNC       9
-#define SyncP_RX_PACKET       10
-#define SyncP_NEXT_RX_TIME    11
-#define SyncP_SWITCHOFF       12
-#define SyncP_RX_GARBAGE      13
-#define SyncP_GOT_RESOURCE    14
-#define SyncP_RELEASE_RESOURCE 15
-#define SyncP_RESOURCE_REQUEST  16
-#define SyncP_TRANSFER_RESOURCE 17
-#define SyncP_PREPARE_RX      18
-#define SyncP_REQUEST  19
-#define SyncP_UPDATING  20
-#define SyncP_PREPARE_RX_DONE     21
-#define SyncP_INVALID_TIMESTAMP     22
-#define SyncP_RX_BEACON       SyncP_RX_PACKET
-
-#define StartP_BEACON_TRANSMITTED 0
-#define StartP_UPDATE_STATE   1
-#define StartP_REQUEST        2
-#define StartP_OWNER_TOO_FAST 3
-#define StartP_BEACON_UPDATE  4
-#define StartP_BEACON_UPDATE_2 5
-#define StartP_PREPARE_TX     6
-#define StartP_PREPARE_TXDONE 7
-#define StartP_SKIPPED_BEACON    8
-#define StartP_GOT_RESOURCE    9
-#define StartP_TRANSMIT    10
-
-#define PollP_ALLOC_FAIL1     0
-#define PollP_ALLOC_FAIL2     1
-#define PollP_INTERNAL_POLL   2
-#define PollP_SUCCESS         3
-#define PollP_TXDONE          4
-#define PollP_WRONG_FORMAT    5
-#define PollP_INTERNAL_ERROR  6
-#define PollP_RX              7
-
-#define IndirectTxP_OVERFLOW      0
-#define IndirectTxP_NOTIFIED      1
-#define IndirectTxP_REQUESTED     2
-#define IndirectTxP_BUSY          3
-#define IndirectTxP_DATA_REQUEST  4
-#define IndirectTxP_SEND_NOW      5
-#define IndirectTxP_SEND_NOW_FAIL 6
-#define IndirectTxP_SEND_DONE     7
-#define IndirectTxP_BEACON_ASSEMBLY 8
-
-#define EnableRxP_RADIORX_ERROR       0
-#define EnableRxP_PROMISCUOUS_REQUEST 1
-#define EnableRxP_PROMISCUOUS_ON      2
-#define EnableRxP_PROMISCUOUS_OFF     3
-
-#define AssociateP_REQUEST        0
-#define AssociateP_TXDONE         1
-#define AssociateP_TIMEOUT        2
-#define AssociateP_RX             3
-#define AssociateP_SETTIMER       4
-#define AssociateP_POLL_DONE      5
-
-#define DISSASSOCIATE_REQUEST        50
-#define DISSASSOCIATE_TXDONE         51
-#define DISSASSOCIATE_RX             52
-
-#define CapP_TOO_SHORT           0
-#define CapP_SET_CAP_END         1
-#define CapP_CAP_END_FIRED       2
-
-#define DeviceCapTransmitP_CONTINUE           0
-#define DeviceCapTransmitP_TOVERFLOW          1
-#define DeviceCapTransmitP_RADIO_RESERVE      2
-#define DeviceCapTransmitP_CCA_FAIL           3
-#define DeviceCapTransmitP_NO_ACK             4
-#define DeviceCapTransmitP_TX_DONE            5
-#define DeviceCapTransmitP_TX_PREPARE         6
-#define DeviceCapTransmitP_TX_NOW             7
-#define DeviceCapTransmitP_TX_CANCEL          8
-#define DeviceCapTransmitP_TX_PREPARE_DONE    9
-#define DeviceCapTransmitP_CAP_END_ALARM     10
-#define DeviceCapTransmitP_RADIO_OFF         11
-#define DeviceCapTransmitP_RADIO_RX          12
-#define DeviceCapTransmitP_TX_CANCEL_DONE    13
-#define DeviceCapTransmitP_TX_DONE_UNKNOWN   14
-#define DeviceCapTransmitP_RESOURCE_REQ      15
-#define DeviceCapTransmitP_GOT_RESOURCE      16
-
-#define CoordCapTransmitP_RADIO_RESERVE      0
-#define CoordCapTransmitP_TX_CANCEL          1
-#define CoordCapTransmitP_CCA_FAIL           2
-#define CoordCapTransmitP_CAP_END_ALARM      3
-#define CoordCapTransmitP_OFF_DONE           4
-#define CoordCapTransmitP_FINISH_TX          5
-#define CoordCapTransmitP_RADIO_RX           6
-
-#define Phy_RX_CANCEL      0
-#define Phy_RX_NOW         1
-#define Phy_LOAD_TX_FIFO   2
-#define Phy_LOAD_TX_FIFO_DONE 3
-#define Phy_LOAD_TX_CANCEL 4
-#define Phy_LOAD_TX_NOW 5
-#define Phy_LOAD_TX_RX_NOW 6
-#define Phy_SEND_DONE 7
-#define Phy_SPI_GRANTED 8
-#define Phy_RADIO_OFF 9
-#define Phy_RADIO_OFF_DONE 10
-#define Phy_RADIO_PREPARE_RX 11
-#define Phy_RADIO_PREPARE_TX 12
-#define Phy_RADIO_TX_DONE 13
-#define Phy_RADIO_RECEIVED 14
-
-#define PhyRx_START 0
-#define PhyRx_STOP 1
-#define PhyRx_FIFOP    2
-#define PhyRx_RXON 3
-
-enum {
-  // IDs assigned for debugging
-  START_CLIENT = 0,
-  COORD_CAP_CLIENT = 1,
-  COORD_CFP_CLIENT = 2,
-
-  SYNC_CLIENT = 3,
-  DEVICE_CAP_CLIENT = 4,
-  DEVICE_CFP_CLIENT = 5,
-
-  SCAN_CLIENT = 6,
-
-  RADIORXTX_CLIENT = 7,
-  PIBDATABASE_CLIENT = 8,
-  ASSOCIATE_CLIENT = 9,
-  DEVICECAPQUEUE_CLIENT = 10,
-  INDIRECTTX_DEBUG_CLIENT = 11,
-  DATA_CLIENT = 12,
-  POLL_CLIENT = 13,
-  DISASSOCIATE_CLIENT = 14,
-  RXENABLE_CLIENT = 15,
-
-  PHY_CLIENT = 16,
-  PHY_TXCLIENT = 17,
-  PHY_RXCLIENT = 18,
-};
-
-typedef nx_struct serial_debug_msg {
-  nx_uint8_t client; 
-  nx_uint8_t eventID;
-  nx_uint8_t seqno;
-  nx_uint8_t priority;
-  nx_uint32_t timestamp;
-  nx_uint32_t param1; 
-  nx_uint32_t param2; 
-  nx_uint32_t param3;
-} serial_debug_msg_t;
-
-#ifndef SERIAL_DBG_MSGBUF_SIZE
-#define SERIAL_DBG_MSGBUF_SIZE 25
-#endif
-
-enum {
-  AM_SERIAL_DEBUG_MSG = 222,
-};
-
-#endif // __TKN154_DEBUG_H
index 8edccc00a2a163541aadc1eafaa3e26d020eb88e..f1e301ed75bf685195215603987764f5d175e93e 100644 (file)
@@ -37,6 +37,7 @@
 
 #include "TKN154.h"
 #include "TKN154_PHY.h"
+#include "TKN154_platform.h"
 
 /****************************************************
  * IEEE 802.15.4 PAN information base identifiers
@@ -74,9 +75,7 @@ enum {
   IEEE154_macMaxFrameTotalWaitTime   = 0x58,
   IEEE154_macMaxFrameRetries         = 0x59,
   IEEE154_macMinBE                   = 0x4F,
-// no identifier defined in standard
   IEEE154_macMinLIFSPeriod           = 0xA0,
-// no identifier defined in standard
   IEEE154_macMinSIFSPeriod           = 0xA1,
   IEEE154_macPANId                   = 0x50,
   IEEE154_macPromiscuousMode         = 0x51,
@@ -89,7 +88,7 @@ enum {
   IEEE154_macTimestampSupported      = 0x5C,
   IEEE154_macTransactionPersistenceTime = 0x55,
 
-// attributes not present in the standard PIB:
+  // custom attributes (not present in the standard PIB)
   IEEE154_macPanCoordinator = 0xF0,
 };
 
@@ -128,15 +127,57 @@ enum {
   FC2_FRAME_VERSION_MASK      = 0x30,
 };
 
+/** some unique strings */
+#define SYNC_POLL_CLIENT unique("PollP.client")
+#define ASSOCIATE_POLL_CLIENT unique("PollP.client")
 #define CAP_TX_CLIENT "CapQueueP.FrameTx.client"
 #define INDIRECT_TX_CLIENT "IndirectTx.client"
 #define IEEE802154_RADIO_RESOURCE "RadioRxTxP.resource"
 
 enum {
+  // The following identfiers map to components that access the radio
+  // via RadioClientC(). They are used as parameters for RadioClientC(),
+  // the TransferableResource.transferTo() command and in
+  // the TransferableResource.transferredFrom() event
+
+  RADIO_CLIENT_SCAN = unique(IEEE802154_RADIO_RESOURCE),
+  RADIO_CLIENT_PIB = unique(IEEE802154_RADIO_RESOURCE),
+  RADIO_CLIENT_PROMISCUOUSMODE = unique(IEEE802154_RADIO_RESOURCE),
+
+  RADIO_CLIENT_BEACONTRANSMIT = unique(IEEE802154_RADIO_RESOURCE),
+  RADIO_CLIENT_COORDBROADCAST = unique(IEEE802154_RADIO_RESOURCE),
+  RADIO_CLIENT_COORDCAP = unique(IEEE802154_RADIO_RESOURCE),
+  RADIO_CLIENT_COORDCFP = unique(IEEE802154_RADIO_RESOURCE),
+
+  RADIO_CLIENT_BEACONSYNCHRONIZE = unique(IEEE802154_RADIO_RESOURCE),
+  RADIO_CLIENT_DEVICECAP = unique(IEEE802154_RADIO_RESOURCE),
+  RADIO_CLIENT_DEVICECFP = unique(IEEE802154_RADIO_RESOURCE),
+};
+
+enum {
+  // parameter for the generic DispatchSlottedCsmaP
   OUTGOING_SUPERFRAME,
   INCOMING_SUPERFRAME,
 };
 
+/****************************************************
+ * Default time-related constants for beacon-enabled PANs,
+ * these may be overridden by platform-specific constants.
+ * */   
+
+#ifndef IEEE154_MAX_BEACON_JITTER
+  // will start to listen for a beacon MAX_BEACON_JITTER_TIME(BO) symbols  
+  // before its expected arrival, where BO is the current beacon order 
+  // (here --by default-- BO is ignored)
+  #define IEEE154_MAX_BEACON_JITTER(BO) 20
+#endif
+
+#ifndef IEEE154_MAX_BEACON_LISTEN_TIME
+  // maximum time to listen for a beacon after its expected arrival,
+  // before it is declared as missed
+  #define IEEE154_MAX_BEACON_LISTEN_TIME(BO) (128 * IEEE154_SYMBOLS_PER_OCTET + IEEE154_MAX_BEACON_JITTER(BO))
+#endif
+
 typedef struct {
   uint8_t length;   // top bit denotes -> promiscuous mode
   uint8_t mhr[MHR_MAX_LEN];  
@@ -165,15 +206,16 @@ typedef struct
   ieee154_metadata_t metadata;
 } ieee154_txcontrol_t;
 
+typedef struct ieee154_csma {
+  uint8_t BE;                 // initial backoff exponent
+  uint8_t macMaxBE;           // maximum backoff exponent
+  uint8_t macMaxCsmaBackoffs; // maximum number of allowed backoffs
+  uint8_t NB;                 // number of backoff during current transmission
+} ieee154_csma_t;
+
 typedef struct {
   ieee154_txframe_t *frame;
-  ieee154_macMaxBE_t BE;
-  ieee154_macMaxCSMABackoffs_t allowedBackoffs;
-  ieee154_macMaxBE_t macMaxBE;
-  ieee154_macMinBE_t macMinBE;
-  uint8_t NB;
-  uint16_t backoff;
-  uint16_t backoffElapsed;
+  ieee154_csma_t csma;
   uint32_t transactionTime;
 } ieee154_cap_frame_backup_t;
 
@@ -198,10 +240,19 @@ enum {
   BEACON_INDEX_SF_SPEC2 = 1,
   BEACON_INDEX_GTS_SPEC = 2,
 
+  SF_SPEC1_BO_MASK = 0x0F,
+  SF_SPEC1_BO_OFFSET = 0,
+  SF_SPEC1_SO_MASK = 0xF0,
+  SF_SPEC1_SO_OFFSET = 4,
+
+  SF_SPEC2_FINAL_CAPSLOT_MASK = 0x0F,
+  SF_SPEC2_FINAL_CAPSLOT_OFFSET = 0,
+  SF_SPEC2_BATT_LIFE_EXT = 0x10,
   SF_SPEC2_PAN_COORD = 0x40,
   SF_SPEC2_ASSOCIATION_PERMIT = 0x80,
 
   GTS_DESCRIPTOR_COUNT_MASK = 0x07,
+  GTS_DESCRIPTOR_COUNT_OFFSET = 0,
   GTS_LENGTH_MASK = 0xF0,
   GTS_LENGTH_OFFSET = 4,
   GTS_SPEC_PERMIT = 0x80,
@@ -214,8 +265,8 @@ enum {
   // PHY sublayer constants
   IEEE154_aTurnaroundTime              = 12,
 
-  FRAMECTL_LENGTH_MASK                 = 0x7F, // "length" member in ieee154_frame_t
-  FRAMECTL_PROMISCUOUS                 = 0x80, // "length" member in ieee154_frame_t
+  FRAMECTL_LENGTH_MASK                 = 0x7F, // "length" member in ieee154_header_t
+  FRAMECTL_PROMISCUOUS                 = 0x80, // "length" member in ieee154_header_t
 };
 #define IEEE154_SUPPORTED_CHANNELPAGE  (IEEE154_SUPPORTED_CHANNELS >> 27)
 
@@ -237,5 +288,61 @@ enum {
   IEEE154_aUnitBackoffPeriod           = 20,
 };
 
+// combine function for IsRadioTokenRequested (GetNow) interface
+typedef bool token_requested_t __attribute__((combine(rcombine)));
+token_requested_t rcombine(token_requested_t r1, token_requested_t r2)
+{
+  return r1 || r2;
+}
+
+#ifdef TKN154_DEBUG
+
+  /****************************************************************** 
+   * ATTENTION! Debugging over serial is a lot of overhead. To
+   * keep it simple, here are the rules you have to follow when
+   * using the dbg_serial() macro:
+   *
+   * - dbg_serial() is used like dbg(), i.e. you pass it at least
+   *   two strings, the first one describing the component/file,
+   *   the second is a format string (like in printf())
+   * - following the second string, there may be zero up to 
+   *   two parameters -- these must be (cast to) uint32_t and
+   *   the format specifier must be "%lu", e.g.
+   *   dbg_serial("MyComponentP", "Value: %lu\n", (uint32_t) val);
+   * - both strings must be constants (pointers always valid)
+   * - no data is sent over serial, unless dbg_serial_flush() is
+   *   called; try to call it when the system is idle or at least
+   *   when no time-critical operations are pending; on TelosB
+   *   you can also press the user button to trigger a flush
+   * - on the PC use the printf java client to display the debug
+   *   output (see tinyos-2.x/apps/tests/TestPrintf/README.txt);
+   *   the output format is component:line-in-source-code:text
+   *
+   * The ASSERT(X) macro is used to test for errors. If X evaluates 
+   * to zero, then 3 leds start blinking simulataneously (about 2Hz)
+   * and the node *continuously* outputs over serial the filename/line
+   * where the (first) ASSERT has failed. This means, even if your
+   * TelosB was not attached to your PC while the ASSERT failed you
+   * can typically still pull the information out later.
+   *
+   * When TKN154_DEBUG is not defined (which is the default), then
+   * dbg_serial() maps to dbg(), i.e. is completely removed unless 
+   * the platform is TOSSIM, and in the ASSERT(X) statement X is 
+   * evaluated/executed, but the result is ignored.
+   **/
+
+  /* -> functions are defined in DebugP.nc */
+  void tkn154_assert(bool val, const char *filename, uint16_t line, const char *func);
+  void tkn154_dbg_serial(const char *filename, uint16_t line, ...);
+  void tkn154_dbg_serial_flush();
+  #define ASSERT(X) tkn154_assert(X, __FILE__,__LINE__,__FUNCTION__)
+  #define dbg_serial(m, ...) tkn154_dbg_serial(m, __LINE__,__VA_ARGS__)
+  #define dbg_serial_flush() tkn154_dbg_serial_flush()
+#else
+  // Note: in an ASSERT(X) the X must always be evaluated/executed!
+  #define ASSERT(X) while(!(X)){ break;}
+  #define dbg_serial(m, ...) dbg(m, __VA_ARGS__)
+  #define dbg_serial_flush()
+#endif
 
 #endif // __TKN154_MAC_H
index 224815396d37e92085c143d06e2b8105397d690e..896ef9df26b2fe7393a63a183314859933886285 100644 (file)
@@ -28,7 +28,8 @@
  *
  * - Revision -------------------------------------------------------------
  * $Date$
- * @author Torsten Halbhuebner <hhuebner.tu-berlin.de>
+ * @author Torsten Halbhuebner <hhuebner@tkn.tu-berlin.de>
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
  * ========================================================================
  */
 
  */
 
 
-typedef struct ieee154_PIB_t {
+typedef struct ieee154_PIB {
 
-  /**************/
-  /* bool types */
-  /**************/
+  /** bool types */
    
   // 0x41
   ieee154_macAssociationPermit_t macAssociationPermit;
@@ -62,11 +61,10 @@ typedef struct ieee154_PIB_t {
   ieee154_macAssociatedPANCoord_t macAssociatedPANCoord;
   // 0x5D
   ieee154_macSecurityEnabled_t macSecurityEnabled;
-  // no standard attribute
+  // custom attribute
   ieee154_macPanCoordinator_t macPanCoordinator;
-  /*****************/
-  /* uint8_t types */
-  /*****************/
+
+  /** uint8_t types */
 
   // 0x00
   ieee154_phyCurrentChannel_t phyCurrentChannel;
@@ -99,9 +97,7 @@ typedef struct ieee154_PIB_t {
   // 0x5a
   ieee154_macResponseWaitTime_t macResponseWaitTime;
 
-  /*****************************/
-  /* larger than uint8_t types */
-  /*****************************/
+  /** larger than uint8_t types */
 
   // 0x4B
   ieee154_macCoordShortAddress_t macCoordShortAddress;
@@ -122,45 +118,114 @@ typedef struct ieee154_PIB_t {
 } ieee154_PIB_t;
 
 // PHY PIB default attributes
-
-#define IEEE154_DEFAULT_CURRENTCHANNEL          26
-#define IEEE154_DEFAULT_CHANNELSSUPPORTED_PAGE0 0x07FFF800
-#define IEEE154_DEFAULT_CHANNELSSUPPORTED_PAGE1 0
-#define IEEE154_DEFAULT_CHANNELSSUPPORTED_PAGE2 0
-#define IEEE154_DEFAULT_CCAMODE                 3
-#define IEEE154_DEFAULT_CURRENTPAGE             0
-#define IEEE154_DEFAULT_TRANSMITPOWER_dBm       0
+#ifndef IEEE154_DEFAULT_CURRENTCHANNEL          
+  #define IEEE154_DEFAULT_CURRENTCHANNEL          26
+#endif
+#ifndef IEEE154_DEFAULT_CHANNELSSUPPORTED_PAGE0 
+  #define IEEE154_DEFAULT_CHANNELSSUPPORTED_PAGE0 0x07FFF800
+#endif
+#ifndef IEEE154_DEFAULT_CHANNELSSUPPORTED_PAGE1 
+  #define IEEE154_DEFAULT_CHANNELSSUPPORTED_PAGE1 0
+#endif
+#ifndef IEEE154_DEFAULT_CHANNELSSUPPORTED_PAGE2 
+  #define IEEE154_DEFAULT_CHANNELSSUPPORTED_PAGE2 0
+#endif
+#ifndef IEEE154_DEFAULT_CCAMODE                 
+  #define IEEE154_DEFAULT_CCAMODE                 3
+#endif
+#ifndef IEEE154_DEFAULT_CURRENTPAGE             
+  #define IEEE154_DEFAULT_CURRENTPAGE             0
+#endif
+#ifndef IEEE154_DEFAULT_TRANSMITPOWER_dBm       
+  #define IEEE154_DEFAULT_TRANSMITPOWER_dBm       0
+#endif
 
 // MAC PIB default attributes
-#define IEEE154_DEFAULT_ASSOCIATEDPANCOORD      FALSE
-#define IEEE154_DEFAULT_ASSOCIATIONPERMIT       FALSE
-#define IEEE154_DEFAULT_AUTOREQUEST             TRUE
-#define IEEE154_DEFAULT_BATTLIFEEXT             FALSE
-#define IEEE154_DEFAULT_BATTLIFEEXTPERIODS      6
-#define IEEE154_DEFAULT_BEACONPAYLOAD           NULL
-#define IEEE154_DEFAULT_BEACONPAYLOADLENGTH     0
-#define IEEE154_DEFAULT_BEACONORDER             15
-#define IEEE154_DEFAULT_BEACONTXTIME            0
-#define IEEE154_DEFAULT_COORDSHORTADDRESS       0xFFFF
-#define IEEE154_DEFAULT_GTSPERMIT               TRUE
-#define IEEE154_DEFAULT_MAXBE                   5
-#define IEEE154_DEFAULT_MAXCSMABACKOFFS         4
-#define IEEE154_DEFAULT_MAXFRAMETOTALWAITTIME   2626
-#define IEEE154_DEFAULT_MAXFRAMERETRIES         3
-#define IEEE154_DEFAULT_MINBE                   3
-#define IEEE154_DEFAULT_MINLIFSPERIOD           40
-#define IEEE154_DEFAULT_MINSIFSPERIOD           12
-#define IEEE154_DEFAULT_PANID                   0xFFFF
-#define IEEE154_DEFAULT_PROMISCUOUSMODE         FALSE
-#define IEEE154_DEFAULT_RESPONSEWAITTIME        32
-#define IEEE154_DEFAULT_RXONWHENIDLE            FALSE
-#define IEEE154_DEFAULT_SECURITYENABLED         FALSE
-#define IEEE154_DEFAULT_SHORTADDRESS            0xFFFF
-
-#define IEEE154_DEFAULT_SUPERFRAMEORDER         15
-#define IEEE154_DEFAULT_SYNCSYMBOLOFFSET        0
-#define IEEE154_DEFAULT_TIMESTAMPSUPPORTED      TRUE
-#define IEEE154_DEFAULT_TRANSACTIONPERSISTENCETIME  0x01F4
+#ifndef IEEE154_DEFAULT_ASSOCIATEDPANCOORD      
+  #define IEEE154_DEFAULT_ASSOCIATEDPANCOORD      FALSE
+#endif
+#ifndef IEEE154_DEFAULT_ASSOCIATIONPERMIT       
+  #define IEEE154_DEFAULT_ASSOCIATIONPERMIT       FALSE
+#endif
+#ifndef IEEE154_DEFAULT_AUTOREQUEST             
+  #define IEEE154_DEFAULT_AUTOREQUEST             TRUE
+#endif
+#ifndef IEEE154_DEFAULT_BATTLIFEEXT             
+  #define IEEE154_DEFAULT_BATTLIFEEXT             FALSE
+#endif
+#ifndef IEEE154_DEFAULT_BATTLIFEEXTPERIODS      
+  #define IEEE154_DEFAULT_BATTLIFEEXTPERIODS      6
+#endif
+#ifndef IEEE154_DEFAULT_BEACONPAYLOAD           
+  #define IEEE154_DEFAULT_BEACONPAYLOAD           NULL
+#endif
+#ifndef IEEE154_DEFAULT_BEACONPAYLOADLENGTH     
+  #define IEEE154_DEFAULT_BEACONPAYLOADLENGTH     0
+#endif
+#ifndef IEEE154_DEFAULT_BEACONORDER             
+  #define IEEE154_DEFAULT_BEACONORDER             15
+#endif
+#ifndef IEEE154_DEFAULT_BEACONTXTIME            
+  #define IEEE154_DEFAULT_BEACONTXTIME            0
+#endif
+#ifndef IEEE154_DEFAULT_COORDSHORTADDRESS       
+  #define IEEE154_DEFAULT_COORDSHORTADDRESS       0xFFFF
+#endif
+#ifndef IEEE154_DEFAULT_GTSPERMIT               
+  #define IEEE154_DEFAULT_GTSPERMIT               TRUE
+#endif
+#ifndef IEEE154_DEFAULT_MAXBE                   
+  #define IEEE154_DEFAULT_MAXBE                   5
+#endif
+#ifndef IEEE154_DEFAULT_MAXCSMABACKOFFS         
+  #define IEEE154_DEFAULT_MAXCSMABACKOFFS         4
+#endif
+#ifndef IEEE154_DEFAULT_MAXFRAMETOTALWAITTIME   
+  #define IEEE154_DEFAULT_MAXFRAMETOTALWAITTIME   2626
+#endif
+#ifndef IEEE154_DEFAULT_MAXFRAMERETRIES         
+  #define IEEE154_DEFAULT_MAXFRAMERETRIES         3
+#endif
+#ifndef IEEE154_DEFAULT_MINBE                   
+  #define IEEE154_DEFAULT_MINBE                   3
+#endif
+#ifndef IEEE154_DEFAULT_MINLIFSPERIOD           
+  #define IEEE154_DEFAULT_MINLIFSPERIOD           40
+#endif
+#ifndef IEEE154_DEFAULT_MINSIFSPERIOD           
+  #define IEEE154_DEFAULT_MINSIFSPERIOD           12
+#endif
+#ifndef IEEE154_DEFAULT_PANID                   
+  #define IEEE154_DEFAULT_PANID                   0xFFFF
+#endif
+#ifndef IEEE154_DEFAULT_PROMISCUOUSMODE         
+  #define IEEE154_DEFAULT_PROMISCUOUSMODE         FALSE
+#endif
+#ifndef IEEE154_DEFAULT_RESPONSEWAITTIME        
+  #define IEEE154_DEFAULT_RESPONSEWAITTIME        32
+#endif
+#ifndef IEEE154_DEFAULT_RXONWHENIDLE            
+  #define IEEE154_DEFAULT_RXONWHENIDLE            FALSE
+#endif
+#ifndef IEEE154_DEFAULT_SECURITYENABLED         
+  #define IEEE154_DEFAULT_SECURITYENABLED         FALSE
+#endif
+#ifndef IEEE154_DEFAULT_SHORTADDRESS            
+  #define IEEE154_DEFAULT_SHORTADDRESS            0xFFFF
+#endif
+
+#ifndef IEEE154_DEFAULT_SUPERFRAMEORDER         
+  #define IEEE154_DEFAULT_SUPERFRAMEORDER         15
+#endif
+#ifndef IEEE154_DEFAULT_SYNCSYMBOLOFFSET        
+  #define IEEE154_DEFAULT_SYNCSYMBOLOFFSET        0
+#endif
+#ifndef IEEE154_DEFAULT_TIMESTAMPSUPPORTED      
+  #define IEEE154_DEFAULT_TIMESTAMPSUPPORTED      TRUE
+#endif
+#ifndef IEEE154_DEFAULT_TRANSACTIONPERSISTENCETIME  
+  #define IEEE154_DEFAULT_TRANSACTIONPERSISTENCETIME  0x01F4
+#endif
 
 #define IEEE154_INVALID_TIMESTAMP (0xffffffff)
 
diff --git a/tos/lib/mac/tkn154/TransferClientP.nc b/tos/lib/mac/tkn154/TransferClientP.nc
deleted file mode 100644 (file)
index 8a780c0..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-generic module TransferClientP(uint8_t myUserId)
-{
-  provides
-  {
-    interface ResourceTransfer;
-    interface ResourceTransferred;
-    interface ResourceTransferConnector as TransferredFrom;
-  } uses {
-    interface ResourceTransferConnector as TransferTo;
-    interface ResourceTransferControl;
-    interface Leds;
-  }
-}
-implementation
-{
-  async command error_t ResourceTransfer.transfer()
-  {
-    error_t result;
-    uint8_t toClient = call TransferTo.getUserId();
-    atomic {
-      result = call ResourceTransferControl.transfer(myUserId, toClient);
-      if (result == SUCCESS)
-        call TransferTo.transfer();
-    }
-    return result;
-  }
-
-  async command uint8_t TransferredFrom.getUserId(){ return myUserId;}
-
-  task void TransferredTask()
-  {
-    signal ResourceTransferred.transferred();
-  }
-
-  async command void TransferredFrom.transfer()
-  {
-    post TransferredTask();
-  }
-  default async command uint8_t TransferTo.getUserId(){ call Leds.led0On(); return 0xFF;}
-  default async command void TransferTo.transfer(){ call Leds.led0On(); }
-  default event void ResourceTransferred.transferred(){}
-}
diff --git a/tos/lib/mac/tkn154/dummies/NoAssociateP.nc b/tos/lib/mac/tkn154/dummies/NoAssociateP.nc
new file mode 100644 (file)
index 0000000..3e469f5
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+ /** Empty placeholder component for AssociateP. */
+
+#include "TKN154_MAC.h"
+
+module NoAssociateP
+{
+  provides
+  {
+    interface Init;
+    interface MLME_ASSOCIATE;
+    interface MLME_COMM_STATUS;
+  }
+  uses
+  {
+    interface FrameRx as AssociationRequestRx;
+    interface FrameTx as AssociationRequestTx;
+    interface FrameExtracted as AssociationResponseExtracted;
+    interface FrameTx as AssociationResponseTx;
+
+    interface DataRequest;
+    interface Timer<TSymbolIEEE802154> as ResponseTimeout;
+    interface Pool<ieee154_txframe_t> as TxFramePool;
+    interface Pool<ieee154_txcontrol_t> as TxControlPool;
+    interface MLME_GET;
+    interface MLME_SET;
+    interface FrameUtility;
+    interface IEEE154Frame as Frame;
+    interface Get<uint64_t> as LocalExtendedAddress;
+  }
+}
+implementation
+{
+
+  command error_t Init.init() { return SUCCESS; }
+
+  /* ------------------- MLME_ASSOCIATE Request ------------------- */
+
+  command ieee154_status_t MLME_ASSOCIATE.request  (
+                          uint8_t LogicalChannel,
+                          uint8_t ChannelPage,
+                          uint8_t CoordAddrMode,
+                          uint16_t CoordPANID,
+                          ieee154_address_t CoordAddress,
+                          ieee154_CapabilityInformation_t CapabilityInformation,
+                          ieee154_security_t *security
+                        )
+  {
+    return IEEE154_TRANSACTION_OVERFLOW;
+  }
+
+  event void AssociationRequestTx.transmitDone(ieee154_txframe_t *txFrame, ieee154_status_t status) { }
+  
+  event void ResponseTimeout.fired() { }
+
+  event message_t* AssociationResponseExtracted.received(message_t* frame, ieee154_txframe_t *txFrame) { return frame; }
+
+  event void DataRequest.pollDone() { }
+
+  /* ------------------- MLME_ASSOCIATE Response ------------------- */
+
+  event message_t* AssociationRequestRx.received(message_t* frame) { return frame; }
+
+  command ieee154_status_t MLME_ASSOCIATE.response (
+                          uint64_t deviceAddress,
+                          uint16_t assocShortAddress,
+                          ieee154_association_status_t status,
+                          ieee154_security_t *security
+                        )
+  {
+    return IEEE154_TRANSACTION_OVERFLOW;
+  }
+
+  event void AssociationResponseTx.transmitDone(ieee154_txframe_t *txFrame, ieee154_status_t status) { }
+
+  /* ------------------- Defaults ------------------- */
+
+  default event void MLME_ASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_CapabilityInformation_t CapabilityInformation,
+                          ieee154_security_t *security
+                        ){}
+  default event void MLME_ASSOCIATE.confirm    (
+                          uint16_t AssocShortAddress,
+                          uint8_t status,
+                          ieee154_security_t *security
+                        ){}
+  default event void MLME_COMM_STATUS.indication (
+                          uint16_t PANId,
+                          uint8_t SrcAddrMode,
+                          ieee154_address_t SrcAddr,
+                          uint8_t DstAddrMode,
+                          ieee154_address_t DstAddr,
+                          ieee154_status_t status,
+                          ieee154_security_t *security
+                        ){}
+}
index 92e8bb4819eefcc1b73cfe5232964911bf306a77..30fa2ff7ccc53eb42e8934c715c2e9708b08b0e5 100644 (file)
@@ -33,6 +33,7 @@
  * ========================================================================
  */
 
+ /** Empty placeholder component for BeaconSynchronizeP. */
 
 #include "TKN154_MAC.h"
 
@@ -40,94 +41,84 @@ module NoBeaconSynchronizeP
 {
   provides
   {
-    interface Init;
+    interface Init as Reset;
     interface MLME_SYNC;
     interface MLME_BEACON_NOTIFY;
     interface MLME_SYNC_LOSS;
+    interface SuperframeStructure as IncomingSF;
     interface GetNow<bool> as IsTrackingBeacons;
-    interface Get<uint32_t> as GetLastBeaconRxTime;
-    interface GetNow<uint32_t> as CapStart;
-    interface GetNow<ieee154_reftime_t*> as CapStartRefTime; 
-    interface GetNow<uint32_t> as CapLen;
-    interface GetNow<uint32_t> as CapEnd; 
-    interface GetNow<uint32_t> as CfpEnd; 
-    interface GetNow<uint32_t> as CfpLen;
-    interface GetNow<uint32_t> as BeaconInterval; 
-    interface GetNow<bool> as IsBLEActive; 
-    interface GetNow<uint16_t> as BLELen; 
-    interface GetNow<uint8_t*> as GtsField; 
-    interface GetNow<uint32_t> as SfSlotDuration; 
-    interface GetNow<uint8_t> as FinalCapSlot; 
-    interface GetNow<uint8_t> as NumGtsSlots;
-    interface GetNow<bool> as IsRxBroadcastPending; 
+    interface StdControl as TrackSingleBeacon;
   }
   uses
   {
     interface MLME_GET;
     interface MLME_SET;
     interface FrameUtility;
-    interface Notify<bool> as FindBeacon;
     interface IEEE154BeaconFrame as BeaconFrame;
     interface Alarm<TSymbolIEEE802154,uint32_t> as TrackAlarm;
     interface RadioRx as BeaconRx;
     interface RadioOff;
-    interface Get<bool> as IsBeaconEnabledPAN;
     interface DataRequest;
     interface FrameRx as CoordRealignmentRx;
-    interface Resource as Token;
-    interface ResourceTransfer as TokenToCap;
-    interface ResourceTransferred as TokenTransferred;
-    interface GetNow<bool> as IsSendingBeacons;
+    interface TransferableResource as RadioToken;
     interface TimeCalc;
     interface IEEE154Frame as Frame;
     interface Leds;
-    interface Ieee802154Debug as Debug;
   }
 }
 implementation
 {
+  command error_t Reset.init() { return SUCCESS; }  
 
-  command error_t Init.init() { return SUCCESS; }
-
-  command ieee154_status_t MLME_SYNC.request  (
-      uint8_t logicalChannel,
-      uint8_t channelPage,
-      bool trackBeacon
-      )
+  command ieee154_status_t MLME_SYNC.request  ( uint8_t logicalChannel, uint8_t channelPage, bool trackBeacon)
   {
     return IEEE154_TRANSACTION_OVERFLOW;
   }
 
-  event void Token.granted() { }
+  event void RadioToken.granted() { }
 
-  event void TokenTransferred.transferred() { call Token.release(); }
+  async event void RadioToken.transferredFrom(uint8_t fromClient) { call RadioToken.transferTo(RADIO_CLIENT_BEACONTRANSMIT); }
 
-  async event void TrackAlarm.fired() {}
+  async event void RadioOff.offDone() { }
 
-  async event void BeaconRx.prepareDone() {}
+  async event void BeaconRx.enableRxDone() { }
 
-  event message_t* BeaconRx.received(message_t* frame, ieee154_reftime_t *timestamp) { return frame;}
+  async event void TrackAlarm.fired() { }
 
-  async event void RadioOff.offDone() {}
+  event message_t* BeaconRx.received(message_t *frame, const ieee154_timestamp_t *timestamp) { return frame; }
 
-  async command bool IsTrackingBeacons.getNow(){ return FALSE;}
-  command uint32_t GetLastBeaconRxTime.get(){ return 0;}
-  async command uint8_t* GtsField.getNow() { return 0; }
-  async command uint32_t SfSlotDuration.getNow() { return 0; }
-  async command uint8_t FinalCapSlot.getNow() { return 0; }
+  command error_t TrackSingleBeacon.start()
+  {
+    return FAIL;
+  }
+
+  command error_t TrackSingleBeacon.stop()
+  {
+    return FAIL;
+  }
+  
+  /* -----------------------  SF Structure, etc. ----------------------- */
+
+  async command uint32_t IncomingSF.sfStartTime() { return 0; }
+  async command uint16_t IncomingSF.sfSlotDuration() { return 0; }
+  async command uint8_t IncomingSF.numCapSlots() { return 0; }
+  async command uint8_t IncomingSF.numGtsSlots() { return 0; }
+  async command uint16_t IncomingSF.battLifeExtDuration() { return 0; }
+  async command const uint8_t* IncomingSF.gtsFields() { return NULL; }
+  async command uint16_t IncomingSF.guardTime() { return 0; }
+  async command const ieee154_timestamp_t* IncomingSF.sfStartTimeRef() { return NULL; }
+  async command bool IncomingSF.isBroadcastPending() { return 0; }
+  async command bool IsTrackingBeacons.getNow() { return 0; }
 
   event void DataRequest.pollDone(){}
-  async command uint32_t CapEnd.getNow() { return 0; }
-  async command uint32_t CapStart.getNow() { return 0; }
-  async command uint32_t CapLen.getNow() { return 0; }
-  async command uint32_t CfpEnd.getNow() { return 0; }
-  async command ieee154_reftime_t* CapStartRefTime.getNow() { return NULL; }
-  async command uint32_t CfpLen.getNow(){ return 0;}
-  async command uint32_t BeaconInterval.getNow(){ return 0;}
-  async command bool IsBLEActive.getNow(){ return 0;}
-  async command uint16_t BLELen.getNow(){ return 0;}
-  async command uint8_t NumGtsSlots.getNow() { return 0; }
-  async command bool IsRxBroadcastPending.getNow() { return FALSE; }
-  event message_t* CoordRealignmentRx.received(message_t* frame) {return frame;}
-  event void FindBeacon.notify( bool val ){}
+
+  default event message_t* MLME_BEACON_NOTIFY.indication (message_t* frame){return frame;}
+  default event void MLME_SYNC_LOSS.indication (
+                          ieee154_status_t lossReason,
+                          uint16_t panID,
+                          uint8_t logicalChannel,
+                          uint8_t channelPage,
+                          ieee154_security_t *security){}
+
+  event message_t* CoordRealignmentRx.received(message_t* frame) { return frame; }
 }
index 69b02085a778071443b6d389139480634c2308ea..673adbb1d4726919311b466807d7a36fe16a60f3 100644 (file)
  * ========================================================================
  */
 
+ /** Empty placeholder component for BeaconTransmitP. */
+
 #include "TKN154_MAC.h"
 #include "TKN154_PHY.h"
 module NoBeaconTransmitP
 {
   provides
   {
-    interface Init;
+    interface Init as Reset;
     interface MLME_START;
-    interface WriteBeaconField as SuperframeSpecWrite;
-    interface Get<bool> as IsSendingBeacons;
-    interface GetNow<uint32_t> as CapStart; 
-    interface GetNow<ieee154_reftime_t*> as CapStartRefTime; 
-    interface GetNow<uint32_t> as CapLen; 
-    interface GetNow<uint32_t> as CapEnd; 
-    interface GetNow<uint32_t> as CfpEnd; 
-    interface GetNow<uint32_t> as CfpLen; 
-    interface GetNow<bool> as IsBLEActive; 
-    interface GetNow<uint16_t> as BLELen; 
-    interface GetNow<uint8_t*> as GtsField; 
-    interface GetNow<uint32_t> as SfSlotDuration; 
-    interface GetNow<uint32_t> as BeaconInterval; 
-    interface GetNow<uint8_t> as FinalCapSlot;
-    interface GetNow<uint8_t> as NumGtsSlots;
-    interface GetNow<bool> as BeaconFramePendingBit;
     interface IEEE154TxBeaconPayload;
+    interface SuperframeStructure as OutgoingSF;
+    interface GetNow<bool> as IsSendingBeacons;
   } uses {
     interface Notify<bool> as GtsSpecUpdated;
     interface Notify<bool> as PendingAddrSpecUpdated;
     interface Notify<const void*> as PIBUpdate[uint8_t attributeID];
-    interface Alarm<TSymbolIEEE802154,uint32_t> as BeaconTxAlarm;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as BeaconSendAlarm;
     interface Timer<TSymbolIEEE802154> as BeaconPayloadUpdateTimer;
     interface RadioOff;
-    interface Get<bool> as IsBeaconEnabledPAN;
     interface RadioTx as BeaconTx;
     interface MLME_GET;
     interface MLME_SET;
-    interface Resource as Token;
-    interface ResourceTransfer as TokenToBroadcast;
+    interface TransferableResource as RadioToken;
     interface FrameTx as RealignmentBeaconEnabledTx;
     interface FrameTx as RealignmentNonBeaconEnabledTx;
     interface FrameRx as BeaconRequestRx;
@@ -78,24 +64,21 @@ module NoBeaconTransmitP
     interface WriteBeaconField as PendingAddrWrite;
     interface FrameUtility;
     interface GetNow<bool> as IsTrackingBeacons;
-    interface GetNow<uint32_t> as LastBeaconRxTime;
-    interface GetNow<ieee154_reftime_t*> as LastBeaconRxRefTime; 
-    interface Ieee802154Debug as Debug;
+    interface SuperframeStructure as IncomingSF;
     interface Set<ieee154_macSuperframeOrder_t> as SetMacSuperframeOrder;
     interface Set<ieee154_macBeaconTxTime_t> as SetMacBeaconTxTime;
     interface Set<ieee154_macPanCoordinator_t> as SetMacPanCoordinator;
     interface GetSet<ieee154_txframe_t*> as GetSetRealignmentFrame;
     interface GetNow<bool> as IsBroadcastReady; 
     interface TimeCalc;
+    interface Random;
     interface Leds;
   }
 }
 implementation
 {
-  command error_t Init.init()
-  {
-    return SUCCESS;
-  }
+  command error_t Reset.init() { return SUCCESS; }
+
   command ieee154_status_t MLME_START.request  (
                           uint16_t panID,
                           uint8_t logicalChannel,
@@ -112,16 +95,15 @@ implementation
     return IEEE154_TRANSACTION_OVERFLOW;
   }
 
-  event void Token.granted() { }
+  event void RadioToken.granted() { }
 
-  async event void RadioOff.offDone() { }
+  async event void RadioToken.transferredFrom(uint8_t from) { call RadioToken.transferTo(RADIO_CLIENT_BEACONSYNCHRONIZE); }
 
-  async event void BeaconTxAlarm.fired() {}
+  async event void RadioOff.offDone() { }
 
-  async event void BeaconTx.loadDone() {}
+  async event void BeaconSendAlarm.fired() {}
 
-  async event void BeaconTx.transmitDone(ieee154_txframe_t *frame, 
-      ieee154_reftime_t *referenceTime, bool pendingFlag, error_t error) { }
+  async event void BeaconTx.transmitDone(ieee154_txframe_t *frame, const ieee154_timestamp_t *timestamp, error_t result){}
 
   command error_t IEEE154TxBeaconPayload.setBeaconPayload(void *beaconPayload, uint8_t length) { return ESIZE; }
 
@@ -150,16 +132,6 @@ implementation
   {
   }
 
-  command uint8_t SuperframeSpecWrite.write(uint8_t *superframeSpecField, uint8_t maxlen)
-  {
-    return 0;
-  }
-
-  command uint8_t SuperframeSpecWrite.getLength()
-  {
-    return 0;
-  }
-
   event void RealignmentBeaconEnabledTx.transmitDone(ieee154_txframe_t *frame, ieee154_status_t status)
   {
   }
@@ -173,43 +145,23 @@ implementation
     return frame;
   }
 
-  command bool IsSendingBeacons.get(){ return FALSE;}
+  async command uint32_t OutgoingSF.sfStartTime() {return 0;}
 
-  async command uint32_t CapStart.getNow() { return 0; }
-  async command ieee154_reftime_t* CapStartRefTime.getNow() { return NULL; }
-  async command uint32_t CapLen.getNow() { return 0;}
-  async command uint32_t CapEnd.getNow() 
-  {
-    return 0;
-  }
-  async command uint32_t CfpEnd.getNow() 
-  {
-    return 0;
-  }
-  async command uint32_t CfpLen.getNow()
-  {
-    return 0;
-  }
-  async command bool IsBLEActive.getNow(){ return FALSE;}
-  async command uint16_t BLELen.getNow(){ return 0;}
-  async command bool BeaconFramePendingBit.getNow(){ return FALSE;}
+  async command uint16_t OutgoingSF.sfSlotDuration() {return 0;}
+
+  async command uint8_t OutgoingSF.numCapSlots() {return 0;}
 
-  async command uint8_t* GtsField.getNow() { return NULL; }
-  async command uint32_t SfSlotDuration.getNow() { return 0; }
-  async command uint32_t BeaconInterval.getNow() { return 0; }
-  async command uint8_t FinalCapSlot.getNow() { return 0; }
-  async command uint8_t NumGtsSlots.getNow() { return 0; }
+  async command uint8_t OutgoingSF.numGtsSlots() {return 0;}
 
-  default event void MLME_START.confirm    (
-                          ieee154_status_t status
-                        ){}
+  async command uint16_t OutgoingSF.battLifeExtDuration() {return 0;}
 
-  default event void IEEE154TxBeaconPayload.setBeaconPayloadDone(void *beaconPayload, uint8_t length){}
+  async command const uint8_t* OutgoingSF.gtsFields() {return NULL;}
 
-  default event void IEEE154TxBeaconPayload.modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength){}
+  async command uint16_t OutgoingSF.guardTime() {return 0;}
 
-  default event void IEEE154TxBeaconPayload.aboutToTransmit(){}
+  async command const ieee154_timestamp_t* OutgoingSF.sfStartTimeRef() {return NULL;}
 
-  default event void IEEE154TxBeaconPayload.beaconTransmitted(){}
+  async command bool OutgoingSF.isBroadcastPending() {return FALSE;}
 
+  async command bool IsSendingBeacons.getNow() {return FALSE;}
 }
diff --git a/tos/lib/mac/tkn154/dummies/NoCapP.nc b/tos/lib/mac/tkn154/dummies/NoCapP.nc
deleted file mode 100644 (file)
index ef3cff8..0000000
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-#include "TKN154_PHY.h"
-#include "TKN154_MAC.h"
-
-generic module NoCapP()
-{
-  provides
-  {
-    interface Init as Reset;
-    interface FrameTx as CapTx;
-    interface FrameRx as FrameRx[uint8_t frameType];
-    interface FrameExtracted as FrameExtracted[uint8_t frameType];
-    interface FrameTxNow as BroadcastTx;
-    interface Notify<bool> as WasRxEnabled;
-    interface Notify<bool> as FindBeacon;
-  }
-  uses
-  {
-    interface Random;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as CapEndAlarm;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as BLEAlarm;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as IndirectTxWaitAlarm;
-    interface Alarm<TSymbolIEEE802154,uint32_t> as BroadcastAlarm;
-    interface Resource as Token;
-    interface ResourceTransfer as TokenToCfp;
-    interface ResourceTransferred as TokenTransferred;
-    interface ResourceRequested as TokenRequested;
-    interface GetNow<bool> as IsTokenRequested;
-    interface GetNow<uint32_t> as CapStart; 
-    interface GetNow<ieee154_reftime_t*> as CapStartRefTime; 
-    interface GetNow<uint32_t> as CapLen; 
-    interface GetNow<bool> as IsBLEActive; 
-    interface GetNow<uint16_t> as BLELen; 
-    interface GetNow<bool> as IsRxEnableActive; 
-    interface GetNow<bool> as IsRxBroadcastPending; 
-    interface Notify<bool> as RxEnableStateChange;
-    interface GetNow<bool> as IsTrackingBeacons;
-    interface FrameUtility;
-    interface RadioTx;
-    interface RadioRx;
-    interface RadioOff;
-    interface Get<bool> as IsBeaconEnabledPAN;
-    interface MLME_GET;
-    interface MLME_SET;
-    interface Ieee802154Debug as Debug;
-    interface TimeCalc;
-    interface Leds;
-    interface SetNow<ieee154_cap_frame_backup_t*> as FrameBackup;
-    interface GetNow<ieee154_cap_frame_backup_t*> as FrameRestore;
-  }
-}
-implementation
-{
-  command error_t Reset.init()
-  {
-    return SUCCESS;
-  }
-
-  event void TokenTransferred.transferred()
-  {
-    call TokenToCfp.transfer();
-  }
-
-  command ieee154_status_t CapTx.transmit(ieee154_txframe_t *frame)
-  {
-    return IEEE154_TRANSACTION_OVERFLOW;
-  }
-
-  async event void RadioTx.loadDone(){ }
-  async event void RadioOff.offDone(){ }
-  async event void RadioRx.prepareDone(){ }
-
-  async event void CapEndAlarm.fired(){ }
-  async event void BLEAlarm.fired(){ }
-  event void RxEnableStateChange.notify(bool x){ }
-  async event void BroadcastAlarm.fired(){ }
-
-  async event void IndirectTxWaitAlarm.fired() { }
-
-  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, ieee154_reftime_t
-       *referenceTime, bool ackPendingFlag, error_t error) { }
-
-  event message_t* RadioRx.received(message_t* frame, ieee154_reftime_t* referenceTime) { return frame; }
-  async command ieee154_status_t  BroadcastTx.transmitNow(ieee154_txframe_t *frame){ return IEEE154_TRANSACTION_OVERFLOW; }
-
-  async event void TokenRequested.requested() {}
-  async event void TokenRequested.immediateRequested() {}
-  event void Token.granted(){}
-  command error_t WasRxEnabled.enable(){return FAIL;}
-  command error_t WasRxEnabled.disable(){return FAIL;}
-  command error_t FindBeacon.enable(){return FAIL;}
-  command error_t FindBeacon.disable(){return FAIL;}
-}
diff --git a/tos/lib/mac/tkn154/dummies/NoCapQueueP.nc b/tos/lib/mac/tkn154/dummies/NoCapQueueP.nc
deleted file mode 100644 (file)
index 7796ad1..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154_MAC.h"
-generic module NoCapQueueP()
-{
-  provides
-  {
-    interface Init;
-    interface FrameTx[uint8_t client];
-    interface FrameRx as FrameExtracted[uint8_t client];
-    interface Purge;
-  }
-  uses
-  {
-    interface Queue<ieee154_txframe_t*>; 
-    interface FrameTx as CapTx;
-    interface FrameRx as SubFrameExtracted;
-  }
-}
-implementation
-{
-  command error_t Init.init()
-  {
-    return SUCCESS;
-  }
-
-  command ieee154_status_t FrameTx.transmit[uint8_t client](ieee154_txframe_t *data)
-  {
-    return IEEE154_TRANSACTION_OVERFLOW;
-  }
-
-  event void CapTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) { }
-
-  event message_t* SubFrameExtracted.received(message_t* frame) { return frame; }
-
-  command ieee154_status_t Purge.purge(uint8_t msduHandle) { return IEEE154_INVALID_HANDLE; }
-}
diff --git a/tos/lib/mac/tkn154/dummies/NoCoordBroadcastP.nc b/tos/lib/mac/tkn154/dummies/NoCoordBroadcastP.nc
new file mode 100644 (file)
index 0000000..93d6b99
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+ /** Empty placeholder component for CoordBroadcastP. */
+
+#include "TKN154_MAC.h"
+module NoCoordBroadcastP
+{
+  provides
+  {
+    interface Init as Reset;
+    interface FrameTx as BroadcastDataFrame;
+    interface FrameTx as RealignmentTx;
+    interface GetNow<bool> as IsBroadcastReady; 
+  } uses {
+    interface Queue<ieee154_txframe_t*>; 
+    interface FrameTxNow as CapTransmitNow;
+    interface TransferableResource as RadioToken;
+    interface GetNow<bool> as BeaconFramePendingBit;
+    interface SuperframeStructure as OutgoingSF;
+    interface Leds;
+  }
+}
+implementation
+{
+
+  command error_t Reset.init() { return SUCCESS; }
+
+  command ieee154_status_t BroadcastDataFrame.transmit(ieee154_txframe_t *txFrame)
+  {
+    return IEEE154_TRANSACTION_OVERFLOW;
+  }
+
+  command ieee154_status_t RealignmentTx.transmit(ieee154_txframe_t *frame)
+  {
+    return IEEE154_TRANSACTION_OVERFLOW;
+  }
+
+  async command bool IsBroadcastReady.getNow()
+  {
+    return FALSE;
+  }
+
+  async event void RadioToken.transferredFrom(uint8_t fromClient)
+  {
+    call RadioToken.transferTo(RADIO_CLIENT_COORDCAP);
+  }
+
+  async event void CapTransmitNow.transmitNowDone(ieee154_txframe_t *txFrame, ieee154_status_t status)
+  {
+  }
+  event void RadioToken.granted(){ }
+}
index f805fa1aa1298c71e25ff35eaaaf6da0ea4ab9a9..b8ba907ffdb1d3a454290e6456b00087b8768bff 100644 (file)
@@ -32,7 +32,7 @@
  * @author Jan Hauer <hauer@tkn.tu-berlin.de>
  * ========================================================================
  */
-
 /**
  * The contention free period (CFP) in beacon mode, a.k.a. GTS, is not yet
  * implemented - this is only an empty placeholder. In contrast to the CAP
@@ -52,16 +52,10 @@ module NoCoordCfpP
     interface FrameTx as CfpTx;
     interface Purge;
   } uses {
-    interface Resource as Token;
-    interface ResourceTransferred as TokenTransferred;
-    interface ResourceRequested as TokenRequested;
-    interface GetNow<uint32_t> as CfpEnd; 
-    interface GetNow<ieee154_reftime_t*> as CapStartRefTime; 
-    interface GetNow<uint8_t*> as GtsField; 
-    interface GetNow<uint32_t> as SfSlotDuration; 
-    interface GetNow<uint8_t> as FinalCapSlot; 
+    interface TransferableResource as RadioToken;
     interface Alarm<TSymbolIEEE802154,uint32_t> as CfpSlotAlarm;
     interface Alarm<TSymbolIEEE802154,uint32_t> as CfpEndAlarm;
+    interface SuperframeStructure as OutgoingSF; 
     interface RadioTx;
     interface RadioRx;
     interface RadioOff;
@@ -89,23 +83,22 @@ implementation
     return IEEE154_INVALID_HANDLE; 
   } 
 
-  event void TokenTransferred.transferred()
+  async event void RadioToken.transferredFrom(uint8_t fromClient)
   {
     // the CFP has started, this component now owns the token -  
-    // because GTS is not implemented we release the token
-    // immediately; the general rule is: as long as a component
-    // owns the token it has exclusive access to the radio
-    call Token.release();
+    // because GTS is not implemented we pass it on
+#ifndef IEEE154_BEACON_SYNC_DISABLED
+    call RadioToken.transferTo(RADIO_CLIENT_BEACONSYNCHRONIZE);
+#else
+    call RadioToken.transferTo(RADIO_CLIENT_BEACONTRANSMIT);
+#endif
   }
 
-  async event void CfpEndAlarm.fired() { }
+  async event void CfpEndAlarm.fired() {}
 
   async event void CfpSlotAlarm.fired() {}
 
-  async event void RadioOff.offDone()
-  {
-    call Token.release();
-  }
+  async event void RadioOff.offDone() {}
     
   command uint8_t GtsInfoWrite.write(uint8_t *gtsSpecField, uint8_t maxlen)
   {
@@ -123,19 +116,13 @@ implementation
     return 1;
   }  
 
-  async event void RadioTx.loadDone(){}
-  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, 
-      ieee154_reftime_t *referenceTime, bool ackPendingFlag, error_t error){}
+  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, const ieee154_timestamp_t *timestamp, error_t result){}
 
-  async event void RadioRx.prepareDone(){} 
-  event message_t* RadioRx.received(message_t *frame, ieee154_reftime_t *timestamp){return frame;}
+  async event void RadioRx.enableRxDone(){} 
+  event message_t* RadioRx.received(message_t *frame, const ieee154_timestamp_t *timestamp){return frame;}
 
-  async event void TokenRequested.requested()
+  event void RadioToken.granted()
   {
-    // someone (e.g. SCAN component) requested access to the radio,
-    // you might want to release the token...
-  }
-
-  async event void TokenRequested.immediateRequested(){ }
-  event void Token.granted(){ }
+    ASSERT(0); // should never happen, because we never call RadioToken.request()
+  }  
 }
diff --git a/tos/lib/mac/tkn154/dummies/NoCoordRealignmentP.nc b/tos/lib/mac/tkn154/dummies/NoCoordRealignmentP.nc
new file mode 100644 (file)
index 0000000..fde191a
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+ /** Empty placeholder component for CoordRealignmentP. */
+
+#include "TKN154_MAC.h"
+module NoCoordRealignmentP
+{
+  provides
+  {
+    interface Init;
+    interface MLME_ORPHAN;
+    interface MLME_COMM_STATUS;
+    interface GetSet<ieee154_txframe_t*> as GetSetRealignmentFrame;
+  }
+  uses
+  {
+    interface FrameTx as CoordRealignmentTx;
+    interface FrameRx as OrphanNotificationRx;
+    interface FrameUtility;
+    interface MLME_GET;
+    interface IEEE154Frame as Frame;
+    interface Pool<ieee154_txframe_t> as TxFramePool;
+    interface Pool<ieee154_txcontrol_t> as TxControlPool;
+    interface Get<uint64_t> as LocalExtendedAddress;
+  }
+}
+implementation
+{
+
+  command error_t Init.init() { return SUCCESS; }
+
+  command ieee154_txframe_t* GetSetRealignmentFrame.get() { return NULL; }
+
+  command void GetSetRealignmentFrame.set(ieee154_txframe_t*  frame) { }
+
+  event message_t* OrphanNotificationRx.received(message_t* frame) { return frame; }
+
+  command ieee154_status_t MLME_ORPHAN.response (
+                          uint64_t OrphanAddress,
+                          uint16_t ShortAddress,
+                          bool AssociatedMember,
+                          ieee154_security_t *security
+                        )
+  {
+    return IEEE154_TRANSACTION_OVERFLOW;
+  }
+  
+  event void CoordRealignmentTx.transmitDone(ieee154_txframe_t *txFrame, ieee154_status_t status)
+  {
+  }
+
+  default event void MLME_COMM_STATUS.indication (
+                          uint16_t PANId,
+                          uint8_t SrcAddrMode,
+                          ieee154_address_t SrcAddr,
+                          uint8_t DstAddrMode,
+                          ieee154_address_t DstAddr,
+                          ieee154_status_t status,
+                          ieee154_security_t *security
+                        ){}
+
+  default event void MLME_ORPHAN.indication (
+                          uint64_t OrphanAddress,
+                          ieee154_security_t *security
+                        ){}
+}
diff --git a/tos/lib/mac/tkn154/dummies/NoDebugP.nc b/tos/lib/mac/tkn154/dummies/NoDebugP.nc
deleted file mode 100644 (file)
index 229ae19..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154_DEBUG.h"
-module NoDebugP
-{
-  provides
-  {
-    interface Ieee802154Debug[uint8_t client];
-  }
-}
-implementation
-{
-  async command void Ieee802154Debug.log[uint8_t client](
-      uint8_t priority,
-      uint8_t eventID,
-      uint32_t param1,
-      uint32_t param2,
-      uint32_t param3)
-  {
-  }
-  command void Ieee802154Debug.flush[uint8_t client](){}
-}
diff --git a/tos/lib/mac/tkn154/dummies/NoDeviceCapQueueP.nc b/tos/lib/mac/tkn154/dummies/NoDeviceCapQueueP.nc
deleted file mode 100644 (file)
index 31c9a28..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154_MAC.h"
-module NoDeviceCapQueueP
-{
-  provides
-  {
-    interface Init;
-    interface FrameTx[uint8_t client];
-    interface FrameRx as FrameExtracted[uint8_t client];
-    interface Purge;
-  }
-  uses
-  {
-    interface Queue<ieee154_txframe_t*>; 
-    interface FrameTx as DeviceCapTx;
-    interface FrameRx as SubFrameExtracted;
-  }
-}
-implementation
-{
-  command error_t Init.init() { return SUCCESS; }
-
-  command ieee154_status_t FrameTx.tx[uint8_t client](ieee154_txframe_t *data) { return TRANSACTION_OVERFLOW; }
-
-  event void DeviceCapTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) { }
-
-  event message_t* SubFrameExtracted.received(message_t* data) { return data; }
-
-  command ieee154_status_t Purge.purge(uint8_t msduHandle) { return INVALID_HANDLE; }
-}
index 4cbc46899c272456afc97e91abd322c6f15983d6..545c89ade8bb4235fdff3adedb2ff05aebccb3d0 100644 (file)
@@ -51,16 +51,10 @@ module NoDeviceCfpP
     interface FrameTx as CfpTx;
     interface Purge;
   } uses {
-    interface Resource as Token;
-    interface ResourceTransferred as TokenTransferred;
-    interface ResourceRequested as TokenRequested;
-    interface GetNow<ieee154_reftime_t*> as CapStartRefTime; 
-    interface GetNow<uint32_t> as CfpEnd; 
-    interface GetNow<uint8_t*> as GtsField; 
-    interface GetNow<uint32_t> as SfSlotDuration; 
-    interface GetNow<uint8_t> as FinalCapSlot; 
+    interface TransferableResource as RadioToken;
     interface Alarm<TSymbolIEEE802154,uint32_t> as CfpSlotAlarm;
     interface Alarm<TSymbolIEEE802154,uint32_t> as CfpEndAlarm;
+    interface SuperframeStructure as IncomingSF; 
     interface RadioTx;
     interface RadioRx;
     interface RadioOff;
@@ -88,37 +82,29 @@ implementation
     return IEEE154_INVALID_HANDLE; 
   } 
 
-  event void TokenTransferred.transferred()
+  async event void RadioToken.transferredFrom(uint8_t fromClient)
   { 
     // the CFP has started, this component now owns the token -  
-    // because GTS is not implemented we release the token
-    // immediately; the general rule is: as long as a component
-    // owns the token it has exclusive access to the radio
-    call Token.release();
+    // because GTS is not implemented we pass it on
+#ifndef IEEE154_BEACON_TX_DISABLED
+    call RadioToken.transferTo(RADIO_CLIENT_BEACONTRANSMIT);
+#else
+    call RadioToken.transferTo(RADIO_CLIENT_BEACONSYNCHRONIZE);
+#endif
   }
 
-  async event void CfpEndAlarm.fired() { }
+  async event void CfpEndAlarm.fired() {}
 
   async event void CfpSlotAlarm.fired() {}
 
-  async event void RadioOff.offDone()
-  {
-    call Token.release();
-  }
-
-  async event void RadioTx.loadDone(){}
-  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, 
-      ieee154_reftime_t *referenceTime, bool ackPendingFlag, error_t error){}
+  async event void RadioOff.offDone() {}
 
-  async event void RadioRx.prepareDone(){} 
-  event message_t* RadioRx.received(message_t *frame, ieee154_reftime_t *timestamp){return frame;}
+  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, const ieee154_timestamp_t *timestamp, error_t result){}
+  async event void RadioRx.enableRxDone(){} 
+  event message_t* RadioRx.received(message_t *frame, const ieee154_timestamp_t *timestamp){return frame;} 
 
-  async event void TokenRequested.requested()
+  event void RadioToken.granted()
   {
-    // someone requested access to the radio, you might
-    // consider releasing it...
-  }
-
-  async event void TokenRequested.immediateRequested(){ }
-  event void Token.granted(){ }
+    ASSERT(0); // should never happen, because we never call RadioToken.request()
+  }   
 }
diff --git a/tos/lib/mac/tkn154/dummies/NoDisassociateP.nc b/tos/lib/mac/tkn154/dummies/NoDisassociateP.nc
new file mode 100644 (file)
index 0000000..31a1956
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+ /** Empty placeholder component for DisassociateP. */
+
+#include "TKN154_MAC.h"
+
+module NoDisassociateP
+{
+  provides
+  {
+    interface Init;
+    interface MLME_DISASSOCIATE;
+  } uses {
+
+    interface FrameTx as DisassociationIndirectTx;
+    interface FrameTx as DisassociationDirectTx;
+    interface FrameTx as DisassociationToCoord;
+
+    interface FrameRx as DisassociationDirectRxFromCoord;
+    interface FrameExtracted as DisassociationExtractedFromCoord;
+    interface FrameRx as DisassociationRxFromDevice;
+
+    interface Pool<ieee154_txframe_t> as TxFramePool;
+    interface Pool<ieee154_txcontrol_t> as TxControlPool;
+    interface MLME_GET;
+    interface MLME_SET;
+    interface FrameUtility;
+    interface IEEE154Frame as Frame;
+    interface Get<uint64_t> as LocalExtendedAddress;
+  }
+}
+implementation
+{
+
+  command error_t Init.init() { return SUCCESS; }
+
+  /* ------------------- MLME_DISASSOCIATE (initiating) ------------------- */
+
+  command ieee154_status_t MLME_DISASSOCIATE.request  (
+                          uint8_t DeviceAddrMode,
+                          uint16_t DevicePANID,
+                          ieee154_address_t DeviceAddress,
+                          ieee154_disassociation_reason_t DisassociateReason,
+                          bool TxIndirect,
+                          ieee154_security_t *security
+                        )
+  {
+    return IEEE154_TRANSACTION_OVERFLOW;
+  }
+
+  event void DisassociationToCoord.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) { }
+
+  event void DisassociationIndirectTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) { }
+
+  event void DisassociationDirectTx.transmitDone(ieee154_txframe_t *data, ieee154_status_t status) { }
+
+  /* ------------------- MLME_DISASSOCIATE (receiving) ------------------- */
+
+  event message_t* DisassociationDirectRxFromCoord.received(message_t* frame) { return frame; }
+
+  event message_t* DisassociationExtractedFromCoord.received(message_t* frame, ieee154_txframe_t *txFrame) { return frame;
+  }
+
+  event message_t* DisassociationRxFromDevice.received(message_t* frame) { return frame; }
+
+  /* ------------------- Defaults ------------------- */
+
+  default event void MLME_DISASSOCIATE.indication (
+                          uint64_t DeviceAddress,
+                          ieee154_disassociation_reason_t DisassociateReason,
+                          ieee154_security_t *security
+                        ){}
+  default event void MLME_DISASSOCIATE.confirm    (
+                          ieee154_status_t status,
+                          uint8_t DeviceAddrMode,
+                          uint16_t DevicePANID,
+                          ieee154_address_t DeviceAddress
+                        ){}
+
+}
diff --git a/tos/lib/mac/tkn154/dummies/NoDispatchQueueP.nc b/tos/lib/mac/tkn154/dummies/NoDispatchQueueP.nc
new file mode 100644 (file)
index 0000000..01e1a1b
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+ /** Empty placeholder component for DispatchQueueP. */
+
+#include "TKN154_MAC.h"
+generic module NoDispatchQueueP() {
+  provides
+  {
+    interface Init as Reset;
+    interface FrameTx[uint8_t client];
+    interface FrameRx as FrameExtracted[uint8_t client];
+    interface Purge;
+  } uses {
+    interface Queue<ieee154_txframe_t*>;
+    interface FrameTx as FrameTxCsma;
+    interface FrameRx as SubFrameExtracted;
+  }
+}
+implementation
+{
+  command error_t Reset.init() { return SUCCESS; }
+
+  command ieee154_status_t FrameTx.transmit[uint8_t client](ieee154_txframe_t *txFrame)
+  {
+    return IEEE154_TRANSACTION_OVERFLOW;
+  }
+
+  event void FrameTxCsma.transmitDone(ieee154_txframe_t *txFrame, ieee154_status_t status) { }
+
+  event message_t* SubFrameExtracted.received(message_t* frame) { return frame; }
+
+  default event void FrameTx.transmitDone[uint8_t client](ieee154_txframe_t *txFrame, ieee154_status_t status){}
+
+  command ieee154_status_t Purge.purge(uint8_t msduHandle)
+  {
+    return IEEE154_INVALID_HANDLE;
+  }
+  
+  default event void Purge.purgeDone(ieee154_txframe_t *txFrame, ieee154_status_t status){}
+}
diff --git a/tos/lib/mac/tkn154/dummies/NoDispatchSlottedCsmaP.nc b/tos/lib/mac/tkn154/dummies/NoDispatchSlottedCsmaP.nc
new file mode 100644 (file)
index 0000000..f67ee03
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+ /** Empty placeholder component for DispatchSlottedCsmaP. */
+
+#include "TKN154_PHY.h"
+#include "TKN154_MAC.h"
+
+generic module NoDispatchSlottedCsmaP(uint8_t sfDirection)
+{
+  provides
+  {
+    interface Init as Reset;
+    interface FrameTx as FrameTx;
+    interface FrameRx as FrameRx[uint8_t frameType];
+    interface FrameExtracted as FrameExtracted[uint8_t frameType];
+    interface FrameTxNow as BroadcastTx;
+    interface Notify<bool> as WasRxEnabled;
+  }
+  uses
+  {
+    interface Alarm<TSymbolIEEE802154,uint32_t> as CapEndAlarm;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as BLEAlarm;
+    interface Alarm<TSymbolIEEE802154,uint32_t> as RxWaitAlarm;
+    interface GetNow<token_requested_t> as IsRadioTokenRequested;
+    interface TransferableResource as RadioToken;
+    interface ResourceRequested as RadioTokenRequested;
+    interface SuperframeStructure; 
+    interface GetNow<bool> as IsRxEnableActive; 
+    interface Get<ieee154_txframe_t*> as GetIndirectTxFrame; 
+    interface Notify<bool> as RxEnableStateChange;
+    interface GetNow<bool> as IsTrackingBeacons;
+    interface Notify<const void*> as PIBUpdateMacRxOnWhenIdle;
+    interface FrameUtility;
+    interface SlottedCsmaCa;
+    interface RadioRx;
+    interface RadioOff;
+    interface MLME_GET;
+    interface MLME_SET;
+    interface TimeCalc;
+    interface Leds;
+    interface SetNow<ieee154_cap_frame_backup_t*> as FrameBackup;
+    interface GetNow<ieee154_cap_frame_backup_t*> as FrameRestore;
+    interface StdControl as TrackSingleBeacon;
+    interface MLME_SYNC_LOSS;
+  }
+}
+implementation
+{
+  enum {
+    COORD_ROLE = (sfDirection == OUTGOING_SUPERFRAME),
+    DEVICE_ROLE = !COORD_ROLE,
+    RADIO_CLIENT_CFP = COORD_ROLE ? RADIO_CLIENT_COORDCFP : RADIO_CLIENT_DEVICECFP,
+  };  
+
+  command error_t Reset.init() { return SUCCESS; }
+
+  async event void RadioToken.transferredFrom(uint8_t c) { call RadioToken.transferTo(RADIO_CLIENT_CFP); }
+
+  command ieee154_status_t FrameTx.transmit(ieee154_txframe_t *frame) { return IEEE154_TRANSACTION_OVERFLOW; }
+
+  async event void RadioOff.offDone(){ }
+
+  async event void RadioRx.enableRxDone(){}
+
+  async event void CapEndAlarm.fired(){ }
+
+  async event void BLEAlarm.fired(){ }
+
+  event void RxEnableStateChange.notify(bool whatever){ }
+
+  async event void RxWaitAlarm.fired(){ }
+
+  async event void SlottedCsmaCa.transmitDone(ieee154_txframe_t *frame, ieee154_csma_t *csma, 
+      bool ackPendingFlag,  uint16_t remainingBackoff, error_t result) { }
+
+  event message_t* RadioRx.received(message_t* frame, const ieee154_timestamp_t *timestamp) { return frame; }
+
+  async command ieee154_status_t BroadcastTx.transmitNow(ieee154_txframe_t *frame) { return IEEE154_TRANSACTION_OVERFLOW;}
+
+  event void RadioToken.granted() { }
+
+  command error_t WasRxEnabled.enable(){return FAIL;}
+  command error_t WasRxEnabled.disable(){return FAIL;}
+  event void PIBUpdateMacRxOnWhenIdle.notify( const void* val ) {}
+  async event void RadioTokenRequested.requested(){ }
+  async event void RadioTokenRequested.immediateRequested(){ }
+  event void MLME_SYNC_LOSS.indication (
+                          ieee154_status_t lossReason,
+                          uint16_t PANId,
+                          uint8_t LogicalChannel,
+                          uint8_t ChannelPage,
+                          ieee154_security_t *security
+                        ){ }
+}
diff --git a/tos/lib/mac/tkn154/dummies/NoPromiscuousModeP.nc b/tos/lib/mac/tkn154/dummies/NoPromiscuousModeP.nc
new file mode 100644 (file)
index 0000000..57bbee8
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+ /** Empty placeholder component for PromiscuousModeP. */
+
+#include "TKN154_PHY.h"
+#include "TKN154_MAC.h"
+module NoPromiscuousModeP 
+{
+  provides {
+    interface Init;
+    interface SplitControl as PromiscuousMode;
+    interface Get<bool> as PromiscuousModeGet;
+    interface FrameRx;
+    interface GetNow<token_requested_t> as IsRadioTokenRequested;
+  } uses {
+    interface TransferableResource as RadioToken;
+    interface RadioRx as PromiscuousRx;
+    interface RadioOff;
+    interface Set<bool> as RadioPromiscuousMode;
+  }
+}
+implementation
+{
+
+  command error_t Init.init() { return SUCCESS; }
+
+  /* ----------------------- Promiscuous Mode ----------------------- */
+
+  command bool PromiscuousModeGet.get() { return FALSE; }
+
+  command error_t PromiscuousMode.start() { return FAIL; }
+
+  event void RadioToken.granted() { ASSERT(0);}
+
+  event message_t* PromiscuousRx.received(message_t *frame, const ieee154_timestamp_t *timestamp) { return frame; }
+
+  async event void PromiscuousRx.enableRxDone(){}
+
+  command error_t PromiscuousMode.stop() { return FAIL; }
+
+  async event void RadioOff.offDone() { }
+
+  default event void PromiscuousMode.startDone(error_t error){}
+  default event void PromiscuousMode.stopDone(error_t error){}
+  async command token_requested_t IsRadioTokenRequested.getNow(){ return FALSE;}
+  async event void RadioToken.transferredFrom(uint8_t clientFrom){ASSERT(0);}
+}
diff --git a/tos/lib/mac/tkn154/dummies/NoRxEnableP.nc b/tos/lib/mac/tkn154/dummies/NoRxEnableP.nc
new file mode 100644 (file)
index 0000000..69e3b3a
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+ /** Empty placeholder component for RxEnableP. */
+
+#include "TKN154_PHY.h"
+#include "TKN154_MAC.h"
+module NoRxEnableP
+{
+  provides
+  {
+    interface Init;
+    interface MLME_RX_ENABLE;
+    interface GetNow<bool> as IsRxEnableActive; 
+    interface Notify<bool> as RxEnableStateChange;
+  }
+  uses
+  {
+    interface Timer<TSymbolIEEE802154> as RxEnableTimer;
+    interface Get<ieee154_macPanCoordinator_t> as IsMacPanCoordinator;
+    interface GetNow<bool> as IsTrackingBeacons;
+    interface GetNow<bool> as IsSendingBeacons;
+    interface SuperframeStructure as IncomingSuperframeStructure;
+    interface SuperframeStructure as OutgoingSuperframeStructure;
+    interface Notify<bool> as WasRxEnabled;
+    interface TimeCalc;
+  }
+}
+implementation
+{
+
+  command error_t Init.init() { return SUCCESS; }
+
+  /* ----------------------- MLME-RX-ENABLE ----------------------- */
+
+  command ieee154_status_t MLME_RX_ENABLE.request  ( 
+                          bool DeferPermit,
+                          uint32_t RxOnTime,
+                          uint32_t RxOnDuration
+                        )
+  {
+    return IEEE154_TRANSACTION_OVERFLOW;
+  }
+
+  event void RxEnableTimer.fired() {}
+
+  async command bool IsRxEnableActive.getNow() { return FALSE; }
+
+  event void WasRxEnabled.notify( bool val ) { }
+
+  command error_t RxEnableStateChange.enable(){return FAIL;}
+  command error_t RxEnableStateChange.disable(){return FAIL;}
+  default event void MLME_RX_ENABLE.confirm(ieee154_status_t status){}
+}
index 38a7697a0c56a5beb77849ae96ddd1f56fa04c75..4bfaff48522e36bcf75ab8a39c9b031783f05d21 100644 (file)
@@ -33,6 +33,8 @@
  * ========================================================================
  */
 
+ /** Empty placeholder component for ScanP. */
+
 #include "TKN154_MAC.h"
 
 module NoScanP
@@ -42,6 +44,7 @@ module NoScanP
     interface Init;
     interface MLME_SCAN;
     interface MLME_BEACON_NOTIFY;
+    interface GetNow<token_requested_t> as IsRadioTokenRequested;
   }
   uses
   {
@@ -56,7 +59,7 @@ module NoScanP
     interface Timer<TSymbolIEEE802154> as ScanTimer;
     interface Pool<ieee154_txframe_t> as TxFramePool;
     interface Pool<ieee154_txcontrol_t> as TxControlPool;
-    interface Resource as Token;
+    interface TransferableResource as RadioToken;
     interface FrameUtility;
     interface Leds;
   }
@@ -81,26 +84,26 @@ implementation
     return IEEE154_TRANSACTION_OVERFLOW;
   }
 
-  event void Token.granted()
+  event void RadioToken.granted()
   {
-    call Token.release();
+    ASSERT(0);
   }
 
   event void EnergyDetection.done(error_t status, int8_t EnergyLevel){}
 
-  async event void RadioRx.prepareDone() { }
+  async event void RadioRx.enableRxDone(){}
 
-  event message_t* RadioRx.received(message_t *frame, ieee154_reftime_t *time)
+  event message_t* RadioRx.received(message_t *frame, const ieee154_timestamp_t *timestamp)
   {
     return frame;
   }
 
-  async event void RadioTx.loadDone() { }
-  
-  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, ieee154_reftime_t *t0, 
-      bool ackPendingFlag, error_t error){}
+  async event void RadioTx.transmitDone(ieee154_txframe_t *frame, 
+      const ieee154_timestamp_t *timestamp, error_t result){}
+
   event void ScanTimer.fired() { }
 
   async event void RadioOff.offDone() { }
+  async event void RadioToken.transferredFrom(uint8_t fromClient){ASSERT(0);}
+  async command token_requested_t IsRadioTokenRequested.getNow(){ return FALSE;}
 }
index 5870943857f8b4fae6ccc18b2f2118fe26cd5694..3cbe4725ec374cb82de96f42326aa628312fa355 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * The MCPS-DATA.request primitive requests the transfer of a data SPDU (i.e.,
+ * MSDU) from a local SSCS entity to a single peer SSCS entity. (IEEE
+ * 802.15.4-2006, Sect. 7.1.1)
+ */
+
 #include "TKN154.h"
 #include <message.h>
 
@@ -40,17 +46,15 @@ interface MCPS_DATA
 {
 
   /**
-   * "The MCPS-DATA.request primitive requests the transfer of a data 
-   * SPDU (i.e., MSDU) from a local SSCS entity to a single peer SSCS 
-   * entity." (IEEE 802.15.4-2006, Sec. 7.1.1.1) 
+   * "Requests to transfer a data SPDU (i.e., MSDU) from a local SSCS
+   * entity to a single peer SSCS entity." (IEEE 802.15.4-2006, Sec.
+   * 7.1.1.1) 
    *
-   * The MSDU is the payload portion of a message_t (<code>frame<\code>
-   * parameter) and can be accessed through the <code>IEEE154Frame<\code> 
-   * interface. In contrast to the standard interface definition address 
-   * information is not passed as separate parameters; instead, the 
-   * address information is already part of the <code>frame<\code>, 
-   * i.e. it must have been set (through the <code>IEEE154Frame<\code> 
-   * interface) before this command is called.
+   * The source/destination addressing mode, destination PAN
+   * identifier, destination address, the payload and (optionally) the
+   * security mode/key are part of the <tt>frame</tt> and must have
+   * been set (through the <tt>IEEE154Frame</tt> interface) before
+   * calling this command.
    * 
    * If this command returns IEEE154_SUCCESS, then the confirm event
    * will be signalled in the future; otherwise, the confirm event
@@ -58,12 +62,12 @@ interface MCPS_DATA
    * 
    * @param frame         The frame to send
    * @param payloadLen    The length of the frame payload
-   * @param msduHandle    Handle associated with the frame to be transmitted
+   * @param msduHandle    Handle associated with the frame
    * @param TxOptions     Bitwised OR transmission options
    *
-   * @return       IEEE154_SUCCESS if the request succeeded and a confirm event
-   *               will be signalled, an appropriate error code otherwise 
-   *               (no confirm event will be signalled in this case)
+   * @return       IEEE154_SUCCESS if the request succeeded and only
+   *               then the <tt>confirm()</tt> event will be signalled;
+   *               an appropriate error code otherwise 
    * @see          confirm
    */
 
@@ -75,14 +79,14 @@ interface MCPS_DATA
                         );
 
   /**
-   * Confirm reports the results of a request to transfer a frame to a 
-   * peer SSCS entity.
+   * Reports the result of a request to transfer a frame to a peer
+   * SSCS entity.
    *
-   * @param frame      The frame which was requested to send
+   * @param frame      The frame which was requested to be sent
    * @param msduHandle The handle associated with the frame
    * @param status     The status of the last MSDU transmission
-   * @param timestamp  Time of transmission (invalid if status is 
-   *                   not IEEE154_SUCCESS)
+   * @param timestamp  Time of transmission (invalid if <tt>status</tt> 
+   *                   is not IEEE154_SUCCESS)
    */
   event void confirm    (  
                           message_t *frame,
@@ -92,8 +96,9 @@ interface MCPS_DATA
                         );
 
   /**
-   * Indicates the arrival of a frame. Address information can be accessed 
-   * through the <code>IEEE154Frame<\code> interface.
+   * Indicates the arrival of a frame. Use the <tt>IEEE154Frame</tt>
+   * interface to get the payload, source/destination addresses, DSN
+   * and other information associated with this frame.
    * 
    * @return A frame buffer for the stack to use for the next received frame
    */
index c598a15f5a4b0d830954b30c2bdef570b6a13e42..e8bc3fe79b64877fea0769ac2bb2a27b3be2c676 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * The MCPS-PURGE.request primitive allows the next higher layer to purge an
+ * MSDU from the transaction queue. (IEEE 802.15.4-2006, Sect. 7.1.1)
+ */
+
 #include "TKN154.h"
 
 interface MCPS_PURGE {
 
   /**
-   * Request to purge a frame from the transaction queue.
-   * The result will be returned immediately (there
-   * is no confirm event for this command).
+   * Requests to purge a frame from the transaction queue. The result
+   * will be returned immediately (there is no confirm event for this
+   * command).
    * 
    * @param msduHandle The handle of the frame to be purged from the
    *                   transaction queue
+   *
    * @return       IEEE154_SUCCESS if the request succeeded, an 
    *               appropriate error code otherwise 
    */
index ce135fda5569249630a6fa7308186cce3e5fdc0f..7e1c095a7bcecc9e824ea552869078ebe7ae17ad 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * MLME-SAP association primitives define how a device becomes
+ * associated with a PAN. (IEEE 802.15.4-2006, Sect. 7.1.3)
+ */
+
 #include "TKN154.h"
 
 interface MLME_ASSOCIATE {
@@ -51,6 +56,7 @@ interface MLME_ASSOCIATE {
    *                        of the associating device
    * @param security        The security options (NULL means security is 
    *                        disabled)
+   *
    * @return       IEEE154_SUCCESS if the request succeeded and a confirm event
    *               will be signalled, an appropriate error code otherwise 
    *               (no confirm event will be signalled in this case)
@@ -67,7 +73,7 @@ interface MLME_ASSOCIATE {
                         );
 
   /**
-   * Notification that a device has requested to associate with a PAN.
+   * Notification that a device has requested to associate with this PAN.
    *
    * @param DeviceAddress the 64-bit address of the requesting device
    * @param CapabilityInformation Specifies the operational capabilities
@@ -82,7 +88,7 @@ interface MLME_ASSOCIATE {
                         );
 
   /**
-   * Send a response to a device's request to associate
+   * Sends a response to a device that requested to associate with this PAN.
    *
    * @param DeviceAddress     The 64-bit address of the device to respond to
    * @param AssocShortAddress The short device address allocated by the
@@ -90,9 +96,10 @@ interface MLME_ASSOCIATE {
    * @param status          The status of the association attempt
    * @param security        The security options (NULL means security is 
    *                        disabled)
+   *
    * @return IEEE154_SUCCESS if the request succeeded and an indication event
    *         will be signalled through the MLME_COMM_STATUS interface later,  
-   *         otherwise an appropriate error code (no MLME_COMM_STATUS.indication
+   *         an appropriate error code otherwise (no MLME_COMM_STATUS.indication
    *         event will be signalled in this case)
    */
   command ieee154_status_t response (
@@ -103,7 +110,7 @@ interface MLME_ASSOCIATE {
                         );
 
   /**
-   * Confirmation of the association attempt.
+   * Confirms an association attempt.
    *
    * @param AssocShortAddress The short device address allocated by the
    *                          coordinator on successful association
index c7e81d940b0c1c6389c9e41ff734dc97f50a80e1..e014b56d19db650427ab5e6acabaf6b9ca86e487 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * The MLME-SAP beacon notification primitive defines how a device may be
+ * notified when a beacon is received during normal operating conditions. 
+ * (IEEE 802.15.4-2006, Sect. 7.1.5)
+ */
+
 #include "TKN154.h"
 #include <message.h>
+
 interface MLME_BEACON_NOTIFY {
 
   /**
-   * A beacon frame has been received. This event is signalled only if 
-   * either the PIB attribute macAutoRequest is set to FALSE or the 
-   * beacon payload is not empty.
+   * A beacon frame has been received. This event is signalled only if
+   * either the PIB attribute <tt>macAutoRequest</tt> is set to FALSE
+   * or the beacon payload is not empty.
    *
-   * The beacon parameters can be accessed through the 
-   * <code>IEEE154BeaconFrame<\code> interface. The 
-   * <code>IEEE154Frame<\code> interface can be used to
-   * inspect the addressing fields in the MAC header.
+   * The beacon parameters can be accessed through the
+   * <tt>IEEE154BeaconFrame</tt> interface. The <tt>IEEE154Frame</tt>
+   * interface can be used to inspect the addressing fields in the MAC
+   * header.
    *
    * @param beacon The beacon frame
+   *
    * @return A frame buffer for the stack to use for the next received frame
    */
   event message_t* indication ( message_t *beaconFrame );
index e435e30c4a8be13e57d5aa65f084775631427b49..ff8934ed833610956e326677ca9f7702566bfaea 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * The MLME-SAP communication status primitive defines how the MLME
+ * communicates to the next higher layer about transmission status,
+ * when the transmission was instigated by a response primitive, and
+ * about security errors on incoming packets. (IEEE 802.15.4-2006,
+ * Sect. 7.1.12)
+ */
+
 #include "TKN154.h"
 interface MLME_COMM_STATUS {
 
index 9602ba3d9660393e01dbc8b596feb248244e69f2..902b0f4e400e3a2204275334cbf8feeff0ca0b79 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * The MLME-SAP disassociation primitives define how a device can
+ * disassociate from a PAN. (IEEE 802.15.4-2006, Sect. 7.1.4)
+ */
+
 #include "TKN154.h"
 interface MLME_DISASSOCIATE {
 
   /**
-   * Request disassociation from a PAN.
+   * Requests disassociation from a PAN.
    * 
    * @param DeviceAddrMode The addressing mode of the device to which to send 
    *                       the disassociation notification command.
@@ -50,6 +55,7 @@ interface MLME_DISASSOCIATE {
    *                   indirectly
    * @param security   The security options (NULL means security is 
    *                   disabled)
+   *
    * @return       IEEE154_SUCCESS if the request succeeded and a confirm event
    *               will be signalled, an appropriate error code otherwise 
    *               (no confirm event will be signalled in this case)
@@ -65,7 +71,7 @@ interface MLME_DISASSOCIATE {
                         );
 
   /**
-   * Signals that a device has requested disassociation.
+   * Signals that a device has requested disassociation from this PAN.
    *
    * @param DeviceAddress the 64-bit address of the requesting device
    * @param DisassociateReason Reason for the disassociation
@@ -79,7 +85,7 @@ interface MLME_DISASSOCIATE {
                         );
 
   /**
-   * Confirmation of the disassociation attempt.
+   * Confirmsn a disassociation attempt.
    *
    * @param status The status of the disassociation attempt
    * @param DeviceAddrMode The addressing mode of the device that has either
index 7378323080eb005e5ece0f845302817d25664c5c..5cd117c561d8559668deefdc2a90d5965d6557d0 100644 (file)
  * ========================================================================
  */
 
-/** 
- * This interface can be used to read attribute values from the PHY/MAC PIB.
+/**
+ * This interface allows to read attribute values from the PHY/MAC PIB.
  * Instead of passing the PIB attribute identifier, there is a separate
  * command per attribute (and there are no confirm events). 
  *
- * NOTE: for the attributes macBeaconPayload (0x45) and
- * macBeaconPayloadLength (0x46) use the <code>IEEE154TxBeaconPayload <\code> 
- * interface; for promiscuous mode there is a separate (SplitControl)
- * interface. 
- **/
+ * NOTE: for the attributes <tt>macBeaconPayload</tt> (0x45) and
+ * <tt>macBeaconPayloadLength </tt>(0x46) use the
+ * <tt>IEEE154TxBeaconPayload</tt> interface; for promiscuous mode
+ * there is a separate (SplitControl) interface. 
+ */
 
 #include "TKN154.h" 
 interface MLME_GET {
@@ -87,7 +87,7 @@ interface MLME_GET {
   command ieee154_macBattLifeExtPeriods_t macBattLifeExtPeriods();
 
   /* macBeaconPayload (0x45) and macBeaconPayloadLength (0x46) are read
-   * through the <code>IEEE154TxBeaconPayload<\code> interface. */
+   * through the <tt>IEEE154TxBeaconPayload</tt> interface. */
 
   /** @return PIB attribute macBeaconOrder (0x47) */
   command ieee154_macBeaconOrder_t macBeaconOrder();
@@ -163,4 +163,7 @@ interface MLME_GET {
 
   /** @return PIB attribute macMinSIFSPeriod */
   command ieee154_macMinSIFSPeriod_t macMinSIFSPeriod();
+
+  /** @return custom attribute macPanCoordinator */
+  command ieee154_macPanCoordinator_t macPanCoordinator();
 }
index d90bbe57233a2f0cf20ea9fec0a2f95be7477b6e..74b5426eb93d394306b6081aa80c73bb950ec036 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * The MLME-SAP GTS management primitives define how GTSs are
+ * requested and maintained. A device wishing to use these primitives
+ * and GTSs in general will already be tracking the beacons of its PAN
+ * coordinator. (IEEE 802.15.4-2006, Sect. 7.1.7)
+ */
+
 #include "TKN154.h"
 interface MLME_GTS {
 
index 5f9aca89e1f5c5c782396a8cf1aa5034feecf2ce..abc433e11aa1c938384b58743a57af3d3da7299c 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * MLME-SAP orphan notification primitives define how a coordinator
+ * can issue a notification of an orphaned device. (IEEE 802.15.4-2006,
+ * Sect. 7.1.8)
+ */
+
 #include "TKN154.h" 
 interface MLME_ORPHAN {
 
index 77a801a735ae8750f66616bf6c0a0e61162efbe0..ecd7cf4df1148d4d765af85c9901407e32bebf0e 100644 (file)
  * @author Jan Hauer <hauer@tkn.tu-berlin.de>
  * ========================================================================
  */
+
+/** 
+ * MLME-SAP polling primitives define how to request data from a
+ * coordinator. (IEEE 802.15.4-2006, Sect. 7.1.16)
+ */
+
 #include "TKN154.h"
 
 interface MLME_POLL {
index 480a1b90ca24e8f1bf10e527d840826e6dbdf02b..90aab473ca4f955483a48fa82997ade166ca8cd1 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * MLME-SAP reset primitives specify how to reset the MAC sublayer to
+ * its default values. (IEEE 802.15.4-2006, Sect. 7.1.9)
+ */
+
 #include "TKN154.h"
 interface MLME_RESET {
 
   /**
    * Allows the next higher layer to request that the MLME performs a
-   * reset operation. This command initializes the MAC and must be called 
-   * before calling any other MAC primitive. It extends the standard  
-   * interface definition by a parameter <tt>PANType</tt>, which defines 
-   * whether the device/coordinator will operate on a beacon-enabled PAN
-   * or on a nonbeacon-enabled PAN.
+   * reset operation. This command initializes the MAC and must be 
+   * called at least once before the MAC can be used.
    *
    * Two things are important:
    * (1) This command will fail while promiscuous mode is enabled 
@@ -58,8 +60,6 @@ interface MLME_RESET {
    *                      FALSE, the MAC sublayer is reset but all MAC PIB
    *                      attributes retain their values prior to the
    *                      generation of the reset primitive.
-   * @param PANType       Either BEACON_ENABLED_PAN for beacon-enabled PANs
-   *                      or NONBEACON_ENABLED_PAN for nonbeacon-enabled PANs
    *
    * @return       IEEE154_SUCCESS if the request succeeded and a confirm event
    *               will be signalled, an appropriate error code otherwise 
@@ -67,8 +67,7 @@ interface MLME_RESET {
    *                      
    */
   command ieee154_status_t request  (
-                          bool SetDefaultPIB,
-                          uint8_t PANType
+                          bool SetDefaultPIB
                         );
 
   /**
index 7abdb3f69039c9176f65eaac703b8ffe398ff1cf..ad880b2f3cff6eebdb566c7126b97fb28d701bb1 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * MLME-SAP receiver state primitives define how a device can enable
+ * or disable the receiver at a given time. (IEEE 802.15.4-2006, Sect.
+ * 7.1.10)
+ */
+
 #include "TKN154.h"
 interface MLME_RX_ENABLE {
 
index 551e35d6a4dc651ee56316e3b8cf1ca45636a3bc..a68b3cf338ef99aca3c747ce708759707591b88d 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * MLME-SAP scan primitives define how a device can determine the
+ * energy usage or the presence or absence of PANs in a communications
+ * channel. (IEEE 802.15.4-2006, Sect. 7.1.10)
+ */
+
 #include "TKN154.h"
 interface MLME_SCAN 
 {
index b2ba46ee5e3699a13d5cff77c9940ff5d8c04b9b..605727294a605c06df51d82b6ac0e32a48ab7b24 100644 (file)
 
 
 /** 
- * This interface can be used to set attribute values in the PHY/MAC PIB.
+ * This interface allows to set attribute values in the PHY/MAC PIB.
  * Instead of passing the PIB attribute identifier, there is a separate
  * command per attribute (and there are no confirm events). 
  *
- * NOTE: for the attributes macBeaconPayload (0x45) and
- * macBeaconPayloadLength (0x46) use the <code>IEEE154TxBeaconPayload <\code> 
- * interface; for promiscuous mode there is a separate (SplitControl)
- * interface. 
- **/
+ * NOTE: for the attributes <tt>macBeaconPayload</tt> (0x45) and
+ * <tt>macBeaconPayloadLength</tt> (0x46) use the
+ * <tt>IEEE154TxBeaconPayload</tt> interface; for promiscuous mode
+ * there is a separate (SplitControl) interface. 
+ */
 
 #include "TKN154.h" 
 interface MLME_SET {
@@ -90,7 +90,7 @@ interface MLME_SET {
   command ieee154_status_t macBattLifeExtPeriods(ieee154_macBattLifeExtPeriods_t value);
 
   /* macBeaconPayload (0x45) and macBeaconPayloadLength (0x46) are set
-   * through the <code>IEEE154TxBeaconPayload<\code> interface. */
+   * through the <tt>IEEE154TxBeaconPayload</tt> interface. */
 
   /** @param value new PIB attribute value for macBeaconOrder (0x47) 
    *  @returns IEEE154_SUCCESS if PIB attribute was updated, INVALID_PARAMETER if 
@@ -138,7 +138,7 @@ interface MLME_SET {
   command ieee154_status_t macPANId(ieee154_macPANId_t value);
 
   /* macPromiscuousMode (0x51) is (re-)set through the 
-   * <code>PromiscuousMode<\code> (SplitControl) interface. */
+   * <tt>PromiscuousMode</tt> (SplitControl) interface. */
 
   /** @param value new PIB attribute value for macRxOnWhenIdle (0x52) 
    *  @returns IEEE154_SUCCESS if PIB attribute was updated, INVALID_PARAMETER if 
index b5e44b250dc1ee03cfe50173e83ded678741d2a9..1daf81710b2d0803fb4c48264494ac49bac9f376 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * MLME-SAP start primitives define how an FFD can request to start
+ * using a new superframe configuration in order to initiate a PAN,
+ * begin transmitting beacons on an already existing PAN, thus
+ * facilitating device discovery, or to stop transmitting beacons.
+ * (IEEE 802.15.4-2006, Sect. 7.1.14)
+ */
+
 #include "TKN154.h"
 interface MLME_START {
 
@@ -70,7 +78,7 @@ interface MLME_START {
    * @param coordRealignSecurity The security options for the coordinator
    *                         realignment command (NULL means security
    *                         is disabled)
-   * @param coordRealignSecurity The security options for beacon frames
+   * @param beaconSecurity The security options for beacon frames
    *                         (NULL means security is disabled)
    *
    * @return       IEEE154_SUCCESS if the request succeeded and a confirm event
index f10ab9f31f1bbc1347843c5ba55d76eae8665b57..35f370bb741bdb16978739a1804303e070c667fe 100644 (file)
  * @author Jan Hauer <hauer@tkn.tu-berlin.de>
  * ========================================================================
  */
+
+/** 
+ * MLME-SAP synchronization primitives define how synchronization with
+ * a coordinator may be achieved and how a loss of synchronization is
+ * communicated to the next higher layer. (IEEE 802.15.4-2006, Sect.
+ * 7.1.15)
+ */
+
 interface MLME_SYNC {
 
   /**
index 9266822b393a7ec35f215dc9083b1a8c51b84e36..4c0a1391b42a1b9925a7a99857d0c0d43c842adf 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * MLME-SAP synchronization primitives define how synchronization with
+ * a coordinator may be achieved and how a loss of synchronization is
+ * communicated to the next higher layer. (IEEE 802.15.4-2006, Sect.
+ * 7.1.15)
+ */
+
 #include "TKN154.h"
 interface MLME_SYNC_LOSS {
 
index fb17fe46746afa8c9862a21aba0ad4729198b9ab..a6a5b55c2865ed3021fe48147d7f31a45d995caf 100644 (file)
@@ -37,24 +37,24 @@ interface EnergyDetection
 {
   /**
    * Requests to measure the energy level on the current channel; the
-   * measurement should last for <code>duration<\code> symbols and the  
-   * maximum energy level is signalled through the <code>done<\code>
+   * measurement should last for <tt>duration</tt> symbols and the  
+   * maximum energy level is signalled through the <tt>done</tt>
    * event.
    *
    * @param duration Duration of the energy detection measurement 
    * (in symbol time)
    * @return SUCCESS if the request was accepted and only then 
-   * the <code>done<\code> event will be signalled, FAIL otherwise
+   * the <tt>done</tt> event will be signalled, FAIL otherwise
    **/
   command error_t start(uint32_t duration);
 
   /**
-   * Signalled in response to a call to <code>start<\code>;
+   * Signalled in response to a call to <tt>start</tt>;
    * returns the maximum energy measured on the channel over the
    * specified period of time.
    *
    * @param status SUCCESS if the measurement succeeded
-   * and only then <code>EnergyLevel<\code> is valid, FAIL 
+   * and only then <tt>EnergyLevel</tt> is valid, FAIL 
    * otherwise
    * @param EnergyLevel The maximum energy on the channel
    **/
index 29fa071ad3fbb48463924b1b425d522f81d06d42..e3c0cfe7b7eba521032dae6d379572efed5cb6cd 100644 (file)
@@ -34,8 +34,7 @@
 interface FrameRx
 {
   /**
-   * Received a frame buffer, returning a buffer for the signaling
-   * component to use for the next reception.
+   * Received a frame.
    *
    * @param   frame     the received frame
    * @return            a buffer to be used by the stack for the next 
index d9e3aef6d088a0e5f850b3ccebd97a3d47ceff3c..458ddf937d9c7cb170cd900c2f2edaf3ad04aa75 100644 (file)
 interface FrameTx
 {
   /**
-   * Transmits a frame buffer.
+   * Transmits a frame.
    *
    * @param  txFrame    the frame to transmit
    * @return IEEE154_SUCCESS if the request was accepted and
-   * only then <code>transmitDone()</code> will be signalled
+   * only then <tt>transmitDone()</tt> will be signalled
    */  
   command ieee154_status_t transmit(ieee154_txframe_t *txFrame); 
 
   /**
-   * Signals the completion of the transmission of a frame buffer.
+   * Signals the completion of the transmission of a frame.
    *
    * @param  txFrame    the frame that was transmitted
    * @param  status     the result of the transmission
index ce876296339aaba385d507cafd763bc466dff8b4..7ac79658e130afe560d5eb4affbeed359a9b0fcd 100644 (file)
 interface FrameTxNow
 {
   /**
-   * Transmits a frame buffer.
+   * Transmits a frame.
    *
    * @param  txFrame    the frame to transmit
    * @return IEEE154_SUCCESS if the request was accepted and
-   * only then <code>transmitDone()</code> will be signalled
+   * only then <tt>transmitDone()</tt> will be signalled
    */  
   async command ieee154_status_t transmitNow(ieee154_txframe_t *frame); 
 
 
   /**
-   * Signals the completion of the transmission of a frame buffer.
+   * Signals the completion of the transmission of a frame.
    *
    * @param  txFrame    the frame that was transmitted
    * @param  status     the result of the transmission
diff --git a/tos/lib/mac/tkn154/interfaces/private/Ieee802154Debug.nc b/tos/lib/mac/tkn154/interfaces/private/Ieee802154Debug.nc
deleted file mode 100644 (file)
index c25e8cf..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-interface Ieee802154Debug
-{
-  async command void log(uint8_t priority, uint8_t eventID, uint32_t param1, uint32_t param2, uint32_t param3);
-  command void flush();
-}
index 24317842876f3fac0055f126c285827b5df3dfdf..1a110723172970dae0c4424213704bb8b6211afc 100644 (file)
 
 interface RadioOff
 {
-
   /** 
-   * Switches the radio off and changes the radio state to RADIO_OFF. This
-   * command will succeed only if the current state of the radio is either
-   * TX_LOADED, RX_PREPARED or RECEIVING.
+   * Disables the transceiver and changes the radio state to RADIO_OFF. This
+   * command will succeed only if the current state of the radio is RECEIVING.
    *
-   * @return EALREADY if radio is already switched off <br> FAIL if radio the
-   * current radio state is neither TX_LOADED, RX_PREPARED nor RECEIVING <br>
-   * SUCCESS if the command was accepted and the <tt>offDone()</tt> event will
-   * be signalled.
+   * @return SUCCESS if the command was accepted and the <tt>offDone()</tt>
+   * event will be signalled; EALREADY if the radio is already switched off,
+   * i.e. in state RADIO_OFF; FAIL if the radio was not switched of because 
+   * the current state is not RECEIVING.
    */
   async command error_t off();
 
@@ -54,6 +52,10 @@ interface RadioOff
    **/  
   async event void offDone();
 
- /** @return TRUE if the radio is in the state RADIO_OFF, FALSE otherwise */
-  async command bool isOff();
+  /** 
+   * Tells whether the radio is in state RADIO_OFF.
+   *
+   * @return TRUE if the radio is in the state RADIO_OFF, FALSE otherwise 
+   */
+  async command bool isOff(); 
 }
index e548e20f08e5f077028b0583f0b472f3228b720f..ec0bbb41e9f6e75fd44717c6cb1c17405c1429db 100644 (file)
  * @author Jan Hauer <hauer@tkn.tu-berlin.de>
  * ========================================================================
  */
+
 #include "TKN154_platform.h"
 interface RadioRx
 {
-
   /** 
-   * Prepares the radio for receive mode. This command will fail, if the radio
-   * is not in the state RADIO_OFF. The actual receive operation will be
-   * triggered through a call to <tt>receive()</tt>.  
+   * Switches the radio to receive mode at time <tt>t0 + dt</tt> or immediately
+   * if <tt>t0 + dt</tt> lies in the past. Analogous to the <tt>Timer</tt>
+   * interface <tt>t0</tt> is interpreted as a time in the past. Consequently,
+   * if <tt>dt = 0</tt> then the radio is always switched to receive mode
+   * immediately. This command will fail, if the radio is currently not in
+   * state RADIO_OFF. Once the radio is in receive mode an event
+   * <tt>enableRxDone</tt> will be signalled.
+   *
+   * @param t0 Reference time for receive operation  
    *
-   * @return SUCCESS if the command was accepted and <tt>prepareDone()</tt>
-   * will be signalled; EALREADY if the radio is already in state RX_PREPARED,
-   * FAIL otherwise
-   **/ 
-  async command error_t prepare();
+   * @param dt A positive offset relative to <tt>t0</tt>.  
+   *
+   * @return SUCCESS if the command was accepted and only then the
+   * <tt>enableRxDone()</tt> event will be signalled; FAIL, if the command was
+   * not accepted, because the radio is currently not in the state RADIO_OFF.
+   */
+  async command error_t enableRx(uint32_t t0, uint32_t dt);
 
   /** 
-   * Signalled in response to a successful call to <tt>prepare()</tt>. This  
-   * event is completing the preparation of a receive operation, the radio is
-   * now in the state RX_PREPARED. The actual receive operation will be
-   * triggered through a call to <tt>receive()</tt>.
+   * Signalled in response to a successful call to <tt>enableRx()</tt>. This
+   * event is completing the <tt>enableRx()</tt> operation, the radio is now in
+   * the state RECEIVING. It will stay in receive mode until it is switched off
+   * through the <tt>RadioOff</tt> interface. Received frames will be signalled
+   * through the <tt>received()</tt> event.
    **/    
-  async event void prepareDone(); 
+  async event void enableRxDone(); 
 
-  /** @return TRUE if the radio is in the state RX_PREPARED, FALSE otherwise */
-  async command bool isPrepared();
-
-  /** 
-   * Switches the radio to receive mode at time <tt>t0 + dt</tt>.  If
-   * <tt>t0</tt> is NULL, then the callee interprets <tt>t0</tt> as the current
-   * time. 
-   *
-   * @param t0 Reference time for receive operation (NULL means now)  
-   *
-   * @param dt A positive offset relative to <tt>t0</tt>.  
+  /**
+   * Tells whether the radio is in state RECEIVING, i.e. in receive
+   * mode.
    *
-   * @return SUCCESS if the the command was accepted and the radio will be 
-   * switched to receive mode; FAIL, if the radio is not in the state 
-   * RX_PREPARED
+   * @return TRUE if the radio is in the state RECEIVING, FALSE otherwise 
    */
-  async command error_t receive(ieee154_reftime_t *t0, uint32_t dt); 
-  
-  /** @return TRUE if the radio is in the state RECEIVING, FALSE otherwise */
   async command bool isReceiving();
 
   /** 
    * A frame was received and passed the filters described in 
    * IEEE 802.15.4-2006 Sec. 7.5.6.2 ("Reception and rejection").
    *
-   * @param timestamp The point in time when the first bit of the PPDU
-   * was received or NULL if timestamp is not available.
+   * @param timestamp The point in time when the first bit of the PPDU was
+   * received or NULL if a timestamp is not available. The timestamp's data
+   * type is platform-specific, you can use the
+   * <tt>IEEE154Frame.getTimestamp()</tt> command to get a platform-
+   * independent variant (uint32_t) of the timestamp. This pointer is only
+   * valid while the event is signalled and no reference must be kept to it
+   * afterwards.
    *
    * @param frame The received frame  
    *
    * @return            a buffer to be used by the driver for the next 
    *                    incoming frame 
    */
-  event message_t* received(message_t *frame, ieee154_reftime_t *timestamp); 
+  event message_t* received(message_t *frame, const ieee154_timestamp_t *timestamp); 
 }
 
index 7229b1921f52e7bed12b6e60493c325b920ff698..37b8c0a98bdd8e0c39035736d841e2ec7283ed98 100644 (file)
  * ========================================================================
  */
 #include "TKN154_MAC.h"
-#include "TKN154_PHY.h"
+#include "TKN154_platform.h"
 
 interface RadioTx 
 {
-
   /** 
-   * Prepares the transmission of a frame. This command will fail, if the
-   * radio is neither in state RADIO_OFF nor in state TX_LOADED. The actual
-   * transmission will be triggered through a call to <tt>transmit()</tt>. Any
-   * frame that was previously prepared for transmission ("loaded") will be
-   * overwritten.  The <tt>loadDone()</tt> event signals the completion of the
-   * <tt>load()</tt> command.  
-   *
-   * The frame will be loaded (and the radio will stay in the state
-   * TX_LOADED) until either the transmission was successful, i.e.
-   * <tt>transmitDone()</tt> was signalled with a status IEEE154_SUCCESS, or
-   * the radio is explicitly switched off through the <tt>RadioOff</tt>
-   * interface. Until then the callee might have to reserve certain resources
-   * (e.g. the bus connected to the radio), so the caller should keep the time
-   * while a frame is loaded as short as possible.
-   *
-   * @param frame The frame to transmit.
+   * Transmits a frame at time <tt>t0 + dt</tt> or immediately if <tt>t0 +
+   * dt</tt> lies in the past. The frame is transmitted in any case (without
+   * prior CCA). Analogous to the <tt>Timer</tt> interface <tt>t0</tt> is
+   * interpreted as a time in the past. If <tt>t0</tt> is NULL or if
+   * <tt>dt</tt> is zero then the frame is transmitted immediately. This
+   * command will fail, if the radio is currently not in state RADIO_OFF.
+   *
+   * Iff the ACK_REQUESTED flag is set in the frame's header a successful
+   * transmission will include an acknowledgement from the destination; then,
+   * the callee will perform the necessary steps for receiving this
+   * acknowledgement following the specification in IEEE 802.15.4-2006 Sect.
+   * 7.5.6.4. 
+   *
+   * @param frame The frame to transmit
+   *
+   * @param t0 Reference time for transmission, NULL means frame will be 
+   * transmitted immediately
+   *
+   * @param dt A positive offset relative to <tt>t0</tt>, ignored
+   * if <tt>t0</tt> is NULL
    * 
-   * @return SUCCESS if the command was accepted and <tt>loadDone()</tt> will 
-   * be signalled; FAIL otherwise
-   **/ 
-  async command error_t load(ieee154_txframe_t *frame); 
-
-  /** 
-   * Signalled in response to a successful call to <tt>load()</tt>. This  
-   * event is completing the preparation of a transmission, the radio is
-   * now in the state TX_LOADED. The actual transmission is triggered 
-   * through a call to <tt>transmit()</tt>.
-   **/  
-  async event void loadDone(); 
-
-  /** 
-   * If the radio is in state TX_LOADED then this commands returns the
-   * the frame that was loaded last; it returns NULL otherwise.
-   *
-   * @return last frame loaded if radio is in the state TX_LOADED, 
-   * NULL otherwise
-   **/  
-  async command ieee154_txframe_t* getLoadedFrame();
-
-  /** 
-   * Transmits the frame whose transmission has previously been prepared
-   * through a call to <tt>load()</tt>. The actual time of transmission -- the
-   * point in time when the first symbol of the PPDU is transmitted -- is
-   * defined by: <tt>t0 + dt</tt>. The data type of the <tt>t0</tt> parameter
-   * is platform-specific (symbol precision or better) while <tt>dt</tt> is
-   * expressed in 802.15.4 symbols. If <tt>t0</tt> is NULL, then the callee
-   * interprets <tt>t0</tt> as the current time. The caller guarantees (through
-   * platform-specific guard times and by calling <tt>transmit</tt> in an
-   * atomic block) that the callee can start the transmission on time, taking
-   * any prior clear channel assesment(s) into consideration. 
-   *
-   * A transmission may require 0, 1 or 2 prior clear channel assesments
-   * (<tt>numCCA</tt> parameter) to be performed 0, 20 or 40 symbols,
-   * respectively, before the actual transmission. If a CCA determines a busy
-   * channel, then the frame will not be transmitted. 
-   *
-   * A successful transmission may also require an acknowledgement from the
-   * destination (indicated through the <tt>ackRequest</tt> parameter); then,
-   * the callee has to perform the necessary steps for receiving that
-   * acknowledgement (switching the radio to Rx mode immediately after
-   * transmission, etc.; for details see IEEE 802.15.4-2006).
-   *
-   * The <tt>transmit()</tt> command will succeed iff the radio is in state
-   * TX_LOADED. The <tt>transmitDone()</tt> event will then signal the result
-   * of the transmission.
-   *
-   * @param t0 Reference time for transmission (NULL means now)  
-   *
-   * @param dt A positive offset relative to <tt>t0</tt>.  
-   *
-   * @param numCCA Number of clear channel assesments.
-   *
-   * @param ackRequest TRUE means an acknowledgement is required, FALSE means
-   * no acknowledgement is not required
-   *
    * @return SUCCESS if the transmission was triggered successfully and only
-   * then <tt>transmitDone()</tt> will be signalled; FAIL, if the transmission
-   * was not triggered because no frame was loaded.
-   */  
-  async command error_t transmit(ieee154_reftime_t *t0, uint32_t dt, 
-      uint8_t numCCA, bool ackRequest);
+   * then <tt>transmitDone()</tt> will be signalled; FAIL, if the command was
+   * not accepted, because the radio is currently not in the state RADIO_OFF;
+   * EINVAL if <tt>frame</tt> or a pointer therein is invalid, or the length
+   * of the frame is invalid
+   */
+  async command error_t transmit(ieee154_txframe_t *frame, const ieee154_timestamp_t *t0, uint32_t dt);
 
   /**
-   * Signalled in response to a call to <tt>transmit()</tt>. Depending on the
-   * <tt>error</tt> parameter the radio is now in state RADIO_OFF
-   * (<tt>error</tt> == IEEE154_SUCCESS) or still in state TX_LOADED
-   * (<tt>error</tt> != IEEE154_SUCCESS).  If the transmission succeeded then
-   * the time of transmission -- the point in time when the first symbol of the
-   * PPDU was transmitted -- will be stored in the metadata field of the frame.
-   * In addition, the <tt>t0</tt> parameter will hold a platform-specific
-   * representation of the same point in time (possibly with higher precision)
-   * to be used as future reference time in a <tt>transmit()</tt> command. If
-   * the transmission did not succeed no timestamp will be stored in the
-   * metadata portion, but <tt>t0</tt> will still represent the hypothetical
-   * transmission time. 
-   *
-   * If <tt>error</tt> has a value other than IEEE154_SUCCESS the frame will
-   * stay loaded and a subsequent call to <tt>transmit</tt> will (re-)transmit
-   * the same <tt>frame</tt> again. If <tt>error</tt> has a value of
-   * IEEE154_SUCCESS then the frame was automatically un-loaded and a new frame
-   * has to be loaded before the <tt>transmit()</tt> command will succeed.
-   *
-   * When the <tt>transmit()</tt> command was called with an
-   * <tt>ackRequest</tt> parameter with value TRUE, and <tt>error</tt> has a
-   * value of IEEE154_SUCCESS, then this means that a corresponding
-   * acknowledgement was successfully received. In this case, the
-   * <tt>ackPendingFlag</tt> represents the "pending" flag in the header of the
-   * acknowledgement frame (TRUE means set, FALSE means reset).
+   * Signalled in response to a call to <tt>transmit()</tt> and completing 
+   * the transmission of a frame. The radio is now back in state RADIO_OFF. 
+   * The time of the transmission -- the point in time when the first bit of the
+   * PPDU was transmitted -- is given by <tt>timestamp</tt>. Since the
+   * frame was transmitted without CCA the transmission can only have
+   * failed if no acknowledgement was received although one was requested.
    *
    * @param frame The frame that was transmitted.  
    *
-   * @param t0 The (hypothetical) transmission time; the pointer is only valid
-   * until the eventhandler returns.  
-   *
-   * @param ackPendingFlag TRUE if an acknowledgement was received and the
-   * "pending" flag is set in the header of the ACK frame, FALSE otherwise
-   *
-   * @param error SUCCESS if the transmission succeeded (including successful
-   * CCA and acknowledgement reception, if requested); EBUSY if CCA was
-   * unsuccessful (frame was not transmitted); ENOACK if frame was transmitted
-   * but no matching acknowledgement was received.
-   **/  
-  async event void transmitDone(ieee154_txframe_t *frame, ieee154_reftime_t *t0, 
-      bool ackPendingFlag, error_t error);   
+   * @param timestamp The point in time when the first bit of the PPDU
+   * was received or NULL if a timestamp is not available. The 
+   * timestamp's data type is platform-specific, you can use the 
+   * <tt>IEEE154Frame.getTimestamp()</tt> command to get a platform-
+   * independent variant (uint32_t) of the timestamp. This pointer
+   * is only valid while the event is signalled and no reference must
+   * be kept to it afterwards.
+   *
+   * @param result SUCCESS if the frame was transmitted (and a matching
+   * acknowledgement was received, if requested); ENOACK if the frame was 
+   * transmitted, but no matching acknowledgement was received although one
+   * was requested     
+   **/
+  async event void transmitDone(ieee154_txframe_t *frame, const ieee154_timestamp_t *timestamp, error_t result);
 }
diff --git a/tos/lib/mac/tkn154/interfaces/private/ResourceTransfer.nc b/tos/lib/mac/tkn154/interfaces/private/ResourceTransfer.nc
deleted file mode 100644 (file)
index ac224e9..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * - Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.  - Redistributions in
- * binary form must reproduce the above copyright notice, this list of
- * conditions and the following disclaimer in the documentation and/or other
- * materials provided with the distribution.  - Neither the name of the
- * Technische Universitaet Berlin nor the names of its contributors may be used
- * to endorse or promote products derived from this software without specific
- * prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-interface ResourceTransfer
-{
-
-  /** 
-   * Transfer control of a resource to another client. Conceptually, this
-   * command is similar to calling Resource.release() and then forcing the
-   * arbiter to signal the Resource.granted() event to the target client. But
-   * there is one difference: when a resource that was transferred through this
-   * command is released, it is released on behalf of the "original" client,
-   * i.e. who was last signalled the Resource.granted() event.  Releasing a
-   * transferred resource is thus equivalent to first transferring it back to
-   * the original client and then forcing the latter to release the resource
-   * through a call to Resource.release() -- this ensures that the arbitration
-   * policy can continue properly (and avoids possible starvation).
-   *
-   * Note that a resource may be transferred multiple times, before it is
-   * released. Then the current owner will change, but the "original" client
-   * will stay the same.
-   *
-   * @return SUCCESS If ownership has been transferred.<br> FAIL ownership has
-   * not been transferred, because the caller is not owner of the resource
-   */
-
-  async command error_t transfer();
-}
diff --git a/tos/lib/mac/tkn154/interfaces/private/ResourceTransferConnector.nc b/tos/lib/mac/tkn154/interfaces/private/ResourceTransferConnector.nc
deleted file mode 100644 (file)
index ec8c8ac..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * - Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.  - Redistributions in
- * binary form must reproduce the above copyright notice, this list of
- * conditions and the following disclaimer in the documentation and/or other
- * materials provided with the distribution.  - Neither the name of the
- * Technische Universitaet Berlin nor the names of its contributors may be used
- * to endorse or promote products derived from this software without specific
- * prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-interface ResourceTransferConnector 
-{
-  async command uint8_t getUserId();
-  async command void transfer();
-}
diff --git a/tos/lib/mac/tkn154/interfaces/private/ResourceTransferControl.nc b/tos/lib/mac/tkn154/interfaces/private/ResourceTransferControl.nc
deleted file mode 100644 (file)
index 0601358..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * - Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.  - Redistributions in
- * binary form must reproduce the above copyright notice, this list of
- * conditions and the following disclaimer in the documentation and/or other
- * materials provided with the distribution.  - Neither the name of the
- * Technische Universitaet Berlin nor the names of its contributors may be used
- * to endorse or promote products derived from this software without specific
- * prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-interface ResourceTransferControl 
-{
-  async command error_t transfer(uint8_t fromClient, uint8_t toClient);
-  async command error_t release(uint8_t client);
-}
diff --git a/tos/lib/mac/tkn154/interfaces/private/ResourceTransferred.nc b/tos/lib/mac/tkn154/interfaces/private/ResourceTransferred.nc
deleted file mode 100644 (file)
index 14a5b59..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/* 
- * Copyright (c) 2008, Technische Universitaet Berlin All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * - Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.  - Redistributions in
- * binary form must reproduce the above copyright notice, this list of
- * conditions and the following disclaimer in the documentation and/or other
- * materials provided with the distribution.  - Neither the name of the
- * Technische Universitaet Berlin nor the names of its contributors may be used
- * to endorse or promote products derived from this software without specific
- * prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-
-interface ResourceTransferred 
-{
-
-  /** 
-   * Control of a resource was transferred to this component from another
-   * client. This event is similar to the Resource.granted() event, but when a
-   * the resource is released, it is released on behalf of the client who was
-   * last signalled the Resource.granted() event.
-   *
-   * @see ResourceTransfer interface
-   */
-  event void transferred();
-}
diff --git a/tos/lib/mac/tkn154/interfaces/private/SlottedCsmaCa.nc b/tos/lib/mac/tkn154/interfaces/private/SlottedCsmaCa.nc
new file mode 100644 (file)
index 0000000..ed70554
--- /dev/null
@@ -0,0 +1,117 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154_MAC.h"
+#include "TKN154_PHY.h"
+
+interface SlottedCsmaCa 
+{
+  /** 
+   * Transmits a frame using the slotted CSMA-CA algorithm as specified in IEEE
+   * 802.15.4-2006 standard Sect. 7.5.1.4. This command will fail if the
+   * current state of the radio is not RADIO_OFF. The initial CSMA-CA
+   * parameters are passed as a parameter and may be modified by the callee.
+   * The caller must not access <tt>csma</tt> until the <tt>transmitDone</tt>
+   * event has been signalled.
+   *
+   * <tt>slot0Time</tt> defines the beginning of the first slot in the CAP.
+   * Any transmission must commence on a backoff slot boundary relative to
+   * <tt>slot0Time</tt>. The last possible time for transmission is defined by
+   * <tt>slot0Time+dtMax</tt>. If the transmission cannot commence at or before
+   * <tt>slot0Time+dtMax</tt> then an event <tt>transmitDone()</tt> with error
+   * code ERETRY will be signalled and <tt>csma</tt> will reflect the current
+   * state of the CSMA-CA algorithm. The caller can then resume the
+   * transmission of this frame in the next CAP based on the
+   * <tt>remainingBackoff</tt> passed in the <tt>transmitDone()</tt> event, by
+   * setting <tt>resume</tt> to TRUE in the <tt>transmit()</tt> call.
+   *
+   * Iff the ACK_REQUESTED flag is set in the frame's header a successful
+   * transmission will include an acknowledgement from the destination; then,
+   * the callee will perform the necessary steps for receiving this
+   * acknowledgement following the specification in IEEE 802.15.4-2006 Sect.
+   * 7.5.6.4. 
+   * 
+   * @param frame The frame to transmit.
+   *
+   * @param csma Initial parameters for the slotted CSMA-CA algorithm. 
+   *
+   * @param slot0Time Reference time for the backoff slot boundaries  
+   *
+   * @param dtMax <tt>slot0Time+dtMax</tt> is the last time the frame may be 
+   *              transmitted.
+   *
+   * @param resume TRUE means that the initial backoff is defined by the
+   *               <tt>remainingBackoff</tt> parameter, FALSE means the 
+   *               <tt>remainingBackoff</tt> is to be ignored.
+   *
+   * @param remainingBackoff initial backoff (ignored if <tt>resume</tt>
+   * is FALSE.
+   *
+   * @return SUCCESS if the slotted CSMA-CA was triggered successfully;
+   * EINVAL if <tt>frame</tt> or a pointer therein is invalid; FAIL otherwise.
+   */
+  async command error_t transmit(ieee154_txframe_t *frame, ieee154_csma_t *csma,
+      const ieee154_timestamp_t *slot0Time, uint32_t dtMax, bool resume, uint16_t remainingBackoff);
+
+  /**
+   * Signalled in response to a call to <tt>transmit()</tt>. This event
+   * completes the <tt>transmit</tt> operation. A transmission failed if either
+   * the channel was never idle during any of the <tt>macMaxCsmaBackoffs+1</tt>
+   * transmission attempts, if no acknowledgement was received although one was
+   * requested or if the frame could not be transmitted before the specified
+   * deadline (<tt>slot0Time+dtMax</tt>).
+   *
+   * @param frame The frame that was to be transmitted.  
+   *
+   * @param csma Parameters for the slotted CSMA-CA algorithm; this pointer is
+   * identical to the one passed to the <tt>transmit</tt> command, the content,
+   * however, may have changed.
+   *
+   * @param ackPendingFlag TRUE if an acknowledgement was received and the
+   * "pending" flag is set in the header of the ACK frame, FALSE otherwise
+   * (this is typically only relevant for indirect transmissions)
+   * 
+   * @param remainingBackoff Only valid if <tt>result = ERETRY</tt>, and
+   * then it describes the remaining backoff time (in symbols) to be used
+   * for the transmission of the frame in the following CAP.   
+   *
+   * @result result SUCCESS if the the frame was transmitted (and a matching
+   * acknowledgement was received, if requested); FAIL if the CSMA-CA algorithm
+   * failed because NB > macMaxCsmaBackoffs; ERETRY if the frame could not be 
+   * transmitted because transmission would have started later than 
+   * <tt>slot0Time+dtMax</tt>
+   */
+  async event void transmitDone(ieee154_txframe_t *frame, ieee154_csma_t *csma, 
+      bool ackPendingFlag,  uint16_t remainingBackoff, error_t result);
+}
diff --git a/tos/lib/mac/tkn154/interfaces/private/SuperframeStructure.nc b/tos/lib/mac/tkn154/interfaces/private/SuperframeStructure.nc
new file mode 100644 (file)
index 0000000..0892160
--- /dev/null
@@ -0,0 +1,115 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin 
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ * this list of conditions and the following disclaimer.  - Redistributions in
+ * binary form must reproduce the above copyright notice, this list of
+ * conditions and the following disclaimer in the documentation and/or other
+ * materials provided with the distribution.  - Neither the name of the
+ * Technische Universitaet Berlin nor the names of its contributors may be used
+ * to endorse or promote products derived from this software without specific
+ * prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+ /* A superframe is bounded by beacons and divided into 16 equally-sized slots,
+  * which are part of CAP, CFP (GTS) or the inactive period. This interface
+  * can be used to determine the various parameters of a superframe,
+  * for example the begin of an inactive period would be calculated as
+  * "sfStartTime + (numCapSlot + numGtsSlots) * sfSlotDuration"
+  **/
+
+interface SuperframeStructure 
+{
+  /**
+   * Returns the absolute time (in symbols) when the superframe started, 
+   * i.e. the timestamp of the beacon marking the first slot.
+   * 
+   * @returns  superframe start time 
+   **/
+  async command uint32_t sfStartTime(); 
+
+  /**
+   * Duration (in symbols) of a single superframe slot.
+   * Zero means, the CAP is not valid (no valid beacon was received).
+   * 
+   * @returns  superframe slot duration
+   **/
+  async command uint16_t sfSlotDuration();
+
+  /**
+   * Number of CAP slots.
+   * 
+   * @returns  number of CAP slots
+   **/
+  async command uint8_t numCapSlots();
+
+  /**
+   * Number of CAP slots (following the last CAP slot).
+   * 
+   * @returns  number of CAP slots
+   **/
+  async command uint8_t numGtsSlots();
+
+  /**
+   * Duration of the battery life extension period (in symbols), 
+   * Zero means battery life extension is not used (disabled).
+   * 
+   * @returns  duration of the battery life extension period, 
+   * zero means battery life extension is disabled
+   **/
+  async command uint16_t battLifeExtDuration();     
+
+  /**
+   * Returns a pointer to the content of the GTS fields of the 
+   * last received/transmitted beacon. 
+   * 
+   * @returns GTS fields 
+   **/
+  async command const uint8_t* gtsFields();
+
+  /**
+   * The last "guardTime" symbols of CAP/CFP should not be used,
+   * i.e. transmission/reception should stop "guardTime" symbols
+   * before the actual end of the CAP/CFP.
+   * 
+   * @returns guard time
+   **/
+  async command uint16_t guardTime();
+
+  /**
+   * Platform-specific representation of "sfStartTime" marking
+   * the reception/tranmission time of a beacon.
+   * 
+   * @returns reception/tranmission time of the beacon
+   **/
+  async command const ieee154_timestamp_t* sfStartTimeRef();
+
+  /**
+   * Tells whether the frame pending bit is set in the header
+   * of the beacon frame.
+   * 
+   * @returns TRUE is frame pending bit in beacon header is set, FALSE otherwise
+   **/
+  async command bool isBroadcastPending();  
+}
diff --git a/tos/lib/mac/tkn154/interfaces/private/TransferableResource.nc b/tos/lib/mac/tkn154/interfaces/private/TransferableResource.nc
new file mode 100644 (file)
index 0000000..3aed6e5
--- /dev/null
@@ -0,0 +1,136 @@
+/*
+ * "Copyright (c) 2005 Washington University in St. Louis.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL WASHINGTON UNIVERSITY IN ST. LOUIS BE LIABLE TO ANY PARTY 
+ * FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING 
+ * OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF WASHINGTON 
+ * UNIVERSITY IN ST. LOUIS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * WASHINGTON UNIVERSITY IN ST. LOUIS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND WASHINGTON UNIVERSITY IN ST. LOUIS HAS NO 
+ * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
+ * MODIFICATIONS."
+ */
+/*
+ * Copyright (c) 2004, Technische Universitat Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitat Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+  /** 
+   * This interface is the same as the standard <tt>Resource</tt> 
+   * interface, except that it has one new command <tt>transferTo()</tt> 
+   * and one new event <tt>transferred()</tt>, which allow to pass 
+   * the resource from one component to another.
+   *
+   * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+   */
+
+interface TransferableResource
+{
+  /**
+   * Request access to a shared resource. You must call release()
+   * when you are done with it.
+   *
+   * @return SUCCESS When a request has been accepted. The granted()
+   *                 event will be signaled once you have control of the
+   *                 resource.<br>
+   *         EBUSY You have already requested this resource and a
+   *               granted event is pending
+   */
+  async command error_t request();
+
+  /**
+  * Request immediate access to a shared resource. You must call release()
+  * when you are done with it.
+  *
+  * @return SUCCESS When a request has been accepted. <br>
+  *            FAIL The request cannot be fulfilled
+  */
+  async command error_t immediateRequest();
+
+  /**
+   * You are now in control of the resource.
+   */
+  event void granted();
+
+  /** 
+   * Transfers ownership of a resource to another client, which will in turn
+   * be signalled the <tt>transferred()</tt> event. This command may override 
+   * the default queueing policy.
+   *
+   * @param dstClient The identifier of the client to transfer the resource to.
+   *
+   * @return SUCCESS If ownership has been transferred; FAIL if ownership has
+   * not been transferred, because the caller is not owner of the resource or
+   * a client with the identifer <tt>dstClient</tt> is not present.
+   */   
+  async command error_t transferTo(uint8_t dstClient); 
+
+  /** 
+   * Another client transferred ownership of the resource to you by calling
+   * the <tt>transfer()</tt> command, i.e. you are now in control of the resource.
+   *
+   * @param srcClient The identifier of the client that transferred the resource to you.
+   */
+  async event void transferredFrom(uint8_t srcClient); 
+
+  /**
+  * Release a shared resource you previously acquired.  
+  *
+  * @return SUCCESS The resource has been released <br>
+  *         FAIL You tried to release but you are not the
+  *              owner of the resource 
+  *
+  * @note This command should never be called between putting in a request       
+  *       and waiting for a granted event.  Doing so will result in a
+  *       potential race condition.  There are ways to guarantee that no
+  *       race will occur, but they are clumsy and overly complicated.
+  *       Since it doesn't logically make since to be calling
+  *       <code>release</code> before receiving a <code>granted</code> event, 
+  *       we have opted to keep thing simple and warn you about the potential 
+  *       race.
+  */
+  async command error_t release();
+
+  /**
+   *  Check if the user of this interface is the current
+   *  owner of the Resource
+   *  @return TRUE  It is the owner <br>
+   *             FALSE It is not the owner
+   */
+  async command bool isOwner();
+}
diff --git a/tos/lib/mac/tkn154/interfaces/private/UnslottedCsmaCa.nc b/tos/lib/mac/tkn154/interfaces/private/UnslottedCsmaCa.nc
new file mode 100644 (file)
index 0000000..765d9c5
--- /dev/null
@@ -0,0 +1,90 @@
+/* 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154_MAC.h"
+#include "TKN154_platform.h"
+
+interface UnslottedCsmaCa
+{
+  /** 
+   * Transmits a frame using the unslotted CSMA-CA algorithm as specified in 
+   * IEEE 802.15.4-2006 standard Sect. 7.5.1.4. This command will fail if the
+   * current state of the radio is not RADIO_OFF. The initial CSMA-CA parameters
+   * are passed as a parameter and may be modified by the callee. The caller
+   * must not access <tt>csma</tt> until the <tt>transmitDone</tt> event
+   * has been signalled. 
+   *
+   * Iff the ACK_REQUESTED flag is set in the frame's header a successful 
+   * transmission will include an acknowledgement from the destination; 
+   * then, the callee will perform the necessary steps for receiving this
+   * acknowledgement following the specification in IEEE 802.15.4-2006 
+   * Sect. 7.5.6.4. 
+   * 
+   * @param frame The frame to transmit.
+   *
+   * @param csma Parameters for the unslotted CSMA-CA algorithm. 
+   *
+   * @return SUCCESS if the unslotted CSMA-CA algorithm was triggered 
+   * successfully; EINVAL if <tt>frame</tt> or a pointer therein is invalid; 
+   * FAIL if the radio is not in state RADIO_OFF.
+   */
+  async command error_t transmit(ieee154_txframe_t *frame, ieee154_csma_t *csma);
+
+  /**
+   * Signalled in response to a call to <tt>transmit()</tt>. This event completes
+   * the <tt>transmit</tt> operation. If the transmission succeeded then
+   * the time of the transmission -- the point in time when the first bit of the
+   * PPDU was transmitted -- will be stored in the metadata field of the frame. 
+   * A transmission failed if either all CCA operation(s) failed (including
+   * backoffs, i.e. NB > macMaxCsmaBackoffs) or if no acknowledgement was received
+   * although one was requested.
+   *
+   * @param frame The frame that was to be transmitted.  
+   *
+   * @param csma Parameters for the unslotted CSMA-CA algorithm; this
+   * pointer is identical to the one passed to the <tt>transmit</tt> command,
+   * the content, however, may have changed.
+   *
+   * @param ackPendingFlag TRUE if an acknowledgement was received and the
+   * "pending" flag is set in the header of the ACK frame, FALSE otherwise
+   * (this is typically only relevant for indirect transmissions)
+   *
+   * @param result SUCCESS if the frame was transmitted (and a matching
+   * acknowledgement was received, if requested); ENOACK if the frame was 
+   * transmitted, but no matching acknowledgement was received, although one
+   * was requested; FAIL if the CSMA-CA algorithm failed because 
+   * NB > macMaxCsmaBackoffs.  
+   */
+  async event void transmitDone(ieee154_txframe_t *frame, ieee154_csma_t *csma, bool ackPendingFlag, error_t result);
+}
index aae98efc8d5cba9f68f58421320e1e913edae8a3..87eb976ced398020c288dd27fd6e26825704ddae 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * The IEEE154BeaconFrame interface allows to access the content of a beacon
+ * frame.
+ */
 
 #include <TKN154.h>
 
@@ -100,7 +104,7 @@ interface IEEE154BeaconFrame
    *                       otherwise
    */
   command error_t parsePANDescriptor(message_t *frame, uint8_t LogicalChannel,
-      uint8_t ChannelPage, ieee154_PANDescriptor_t *PANDescriptor);  
+      uint8_t ChannelPage, ieee154_PANDescriptor_t *pdescriptor);  
 
  /**
    * Returns a pointer to the beacon payload.
index 01d59541c4e7858bce2a6fc89ca5f8898369aa25..1f3184c56285b3c586fa43798dbc420d3e6cb7ee 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * The IEEE154Frame interface allows to access the content of a IEEE 802.15.4
+ * frame.
+ */
 
 #include <TKN154.h>
 #include <message.h>
@@ -115,10 +119,10 @@ interface IEEE154Frame
  /**
    * Sets the addressing fields in the MAC header of a frame. The source 
    * PAN identifier and the source address will be set automatically, their
-   * values depend on the <code>SrcAddrMode</code> parameter: if 
-   * <code>SrcAddrMode</code> is a short or extended address, then
-   * the current PIB attributes <code>macShortAddress</code> or 
-   * <code>aExtendedAddress</code> and <code>macPANId</code> are used.
+   * values depend on the <tt>SrcAddrMode</tt> parameter: if 
+   * <tt>SrcAddrMode</tt> is a short or extended address, then
+   * the current PIB attributes <tt>macShortAddress</tt> or 
+   * <tt>aExtendedAddress</tt> and <tt>macPANId</tt> are used.
    *
    * @param frame         the frame
    * @param srcAddrMode   the source addressing mode
@@ -157,7 +161,7 @@ interface IEEE154Frame
 
  /**
    * Returns the point in time when the frame was received. If 
-   * <code>isTimestampValid()<\code> returns FALSE then the 
+   * <tt>isTimestampValid()</tt> returns FALSE then the 
    * timestamp is not valid and must be ignored.
    *
    * @param frame     the frame
@@ -192,7 +196,7 @@ interface IEEE154Frame
     * Returns the type of the frame
     * BEACON=0, DATA=1, ACK=2, COMMAND=3.
     *
-    * Note: For beacon frames one can use the <code>IEEE154BeaconFrame<\code>
+    * Note: For beacon frames one can use the <tt>IEEE154BeaconFrame</tt>
     * interface to inspect additional fields of the frame.
     *
     * @param  frame   the frame
@@ -233,8 +237,8 @@ interface IEEE154Frame
     * received while in promiscuous mode, because then no filtering
     * (except CRC check) was applied. Note: if this command returns
     * FALSE, then all other commands in this interface (except
-    * <code>wasPromiscuousModeEnabled()</code>) and the 
-    * <code>IEEE154BeaconFrame</code> interface return undefined values!
+    * <tt>wasPromiscuousModeEnabled()</tt>) and the 
+    * <tt>IEEE154BeaconFrame</tt> interface return undefined values!
     *
     * @param  frame   the frame
     * @return         TRUE if frame has a standard compliant header,
index 4415ee60373e2955ca6f08468874d03ba8766738..33768e3c99d4176fb592edea32e9e22b6a678d89 100644 (file)
  * ========================================================================
  */
 
+/** 
+ * The IEEE154TxBeaconPayload interface allows to access the payload portion of
+ * the beacon frame that is periodically transmitted by a coordinator in a
+ * beacon-enabled PAN. This interface replaces the MLME-SET command for the PIB
+ * attribute values 0x45 (macBeaconPayload) and 0x46 (macBeaconPayloadLength).
+ */
 
 #include <TKN154.h>
 
@@ -42,33 +48,33 @@ interface IEEE154TxBeaconPayload
    * Sets the beacon payload portion for all subsequently transmitted beacons.
    * This command replaces the MLME-SET command for the PIB attribute values
    * 0x45 (macBeaconPayload) and 0x46 (macBeaconPayloadLength). The
-   * <code>setBeaconPayloadDone()<\code> event will be signalled when the 
-   * beacon payload has been set -- until then <code>beaconPayload<\code> must 
+   * <tt>setBeaconPayloadDone()</tt> event will be signalled when the 
+   * beacon payload has been set -- until then <tt>beaconPayload</tt> must 
    * not be modified.
    *
    * @param beaconPayload   the new beacon payload
    * @param length          the length of the new beacon payload (in byte)
    *
    * @return EBUSY if another transaction is pending, ESIZE if length is too big, 
-   * SUCCESS otherwise (and only then the <code>setBeaconPayloadDone<\code> event 
+   * SUCCESS otherwise (and only then the <tt>setBeaconPayloadDone</tt> event 
    * will be signalled)
    */
  command error_t setBeaconPayload(void *beaconPayload, uint8_t length);
 
   /**
-   * Signalled in response to a <code>setBeaconPayload()<\code> request.
+   * Signalled in response to a <tt>setBeaconPayload()</tt> request.
    * Indicates that the beacon payload has been copied and returns the
    * ownership of the buffer to the next higher layer. 
    * 
-   * @param beaconPayload   the <code>beaconPayload<\code> passed in the 
-   *                        <code>setBeaconPayload()<\code> command
-   * @param length          the <code>length<\code> passed in the 
-   *                        <code>setBeaconPayload()<\code> command
+   * @param beaconPayload   the <tt>beaconPayload</tt> passed in the 
+   *                        <tt>setBeaconPayload()</tt> command
+   * @param length          the <tt>length</tt> passed in the 
+   *                        <tt>setBeaconPayload()</tt> command
    */
  event void setBeaconPayloadDone(void *beaconPayload, uint8_t length);
 
   /**
-   * Returns a pointer to the current beacon payload. 
+   * Returns a pointer to the current beacon payload.
    * 
    * @return the current beacon payload
    */
@@ -84,31 +90,31 @@ interface IEEE154TxBeaconPayload
   /**
    * Replaces (overwrites) a portion of the current beacon payload. Whenever
    * possible, to minimize overhead, the next higher layer should prefer this
-   * command over the <code>setBeaconPayload()<\code> command.  The
-   * <code>modifyBeaconPayloadDone()<\code> event will be signalled when the 
-   * beacon payload has been updated -- until then <code>buffer<\code> must 
-   * not be modified.
+   * command over the <tt>setBeaconPayload()</tt> command.  The
+   * <tt>modifyBeaconPayloadDone()</tt> event will be signalled when the beacon
+   * payload has been updated -- until then <tt>buffer</tt> must not be
+   * modified.
    *
    * @param offset      offset into the current beacon payload
    * @param buffer      the buffer to be written 
    * @param length      the length of the buffer
    *
-   * @return EBUSY if another transaction is pending, ESIZE if offset+length is too big, 
-   * SUCCESS otherwise (and only then the <code>modifyBeaconPayloadDone<\code> event 
-   * will be signalled)
+   * @return EBUSY if another transaction is pending, ESIZE if offset+length is
+   * too big, SUCCESS otherwise (and only then the
+   * <tt>modifyBeaconPayloadDone</tt> event will be signalled)
    */
  command error_t modifyBeaconPayload(uint8_t offset, void *buffer, uint8_t bufferLength);
 
   /**
-   * Signalled in response to a <code>modifyBeaconPayload()<\code> request.
+   * Signalled in response to a <tt>modifyBeaconPayload()</tt> request.
    * Indicates that the beacon payload has been updated. 
    * 
-   * @param offset        the <code>offset<\code> passed in the 
-   *                      <code>modifyBeaconPayload()<\code> command
-   * @param buffer        the <code>buffer<\code> passed in the 
-   *                      <code>modifyBeaconPayload()<\code> command
-   * @param bufferLength  the <code>bufferLength<\code> passed in the 
-   *                      <code>modifyBeaconPayload()<\code> command
+   * @param offset        the <tt>offset</tt> passed in the 
+   *                      <tt>modifyBeaconPayload()</tt> command
+   * @param buffer        the <tt>buffer</tt> passed in the 
+   *                      <tt>modifyBeaconPayload()</tt> command
+   * @param bufferLength  the <tt>bufferLength</tt> passed in the 
+   *                      <tt>modifyBeaconPayload()</tt> command
    */
  event void modifyBeaconPayloadDone(uint8_t offset, void *buffer, uint8_t bufferLength);
 
@@ -117,8 +123,8 @@ interface IEEE154TxBeaconPayload
    * time to update the beacon payload (if desired).
    *
    * The usual policy is that (1) this event is signalled before every beacon
-   * transmission, and (2) that a subsequent call to <code>setPayload<\code>
-   * will update the beacon payload portion of this beacon.  However, 
+   * transmission, and (2) that a subsequent call to <tt>setPayload</tt>
+   * will still update the beacon payload portion of this beacon. However, 
    * because of tight timing constraints in beacon-enabled mode neither can be
    * guaranteed!
    */
@@ -126,7 +132,7 @@ interface IEEE154TxBeaconPayload
 
   /** 
    * Indicates that a beacon frame has been transmitted (the 
-   * <code>getBeaconPayload<\code> command can be used to inspect the
+   * <tt>getBeaconPayload</tt> command can be used to inspect the
    * beacon payload).
    */
  event void beaconTransmitted();  
index 5969e662bcd395d6e33fe29636eaf861bc3ba7ac..e1da6a25af43e536dd4f561f67ab420f9d8d4720 100644 (file)
@@ -95,15 +95,12 @@ typedef struct neighbor_table_entry {
   uint8_t failcnt;
   // flags to describe the state of this entry
   uint8_t flags;
-  // MAXAGE-inage gives the number of update rounds we haven't been able
-  // update the inbound beacon estimator
-  uint8_t inage;
   // inbound qualities in the range [1..255]
   // 1 bad, 255 good
   uint8_t inquality;
-  // EETX for the link to this neighbor. This is the quality returned to
+  // ETX for the link to this neighbor. This is the quality returned to
   // the users of the link estimator
-  uint16_t eetx;
+  uint16_t etx;
   // Number of data packets successfully sent (ack'd) to this neighbor
   // since the last data estimator update round. This update happens
   // every DLQ_PKT_WINDOW data packets
index 7e5c9dacc8264d4b1f5994de2599e63b69ffd557..a90d0b1ebf9c9599d2916b089877dbaccd9ee6fe 100644 (file)
@@ -29,7 +29,7 @@
  @ Created: April 24, 2006
  */
 
-#include "LinkEstimator.h"
+#include "./LinkEstimator.h"
 
 module LinkEstimatorP {
   provides {
@@ -56,20 +56,18 @@ implementation {
 
   // configure the link estimator and some constants
   enum {
-    // If the eetx estimate is below this threshold
+    // If the etx estimate is below this threshold
     // do not evict a link
-    EVICT_EETX_THRESHOLD = 55,
-    // maximum link update rounds before we expire the link
-    MAX_AGE = 6,
+    EVICT_ETX_THRESHOLD = 65,
     // if received sequence number if larger than the last sequence
     // number by this gap, we reinitialize the link
     MAX_PKT_GAP = 10,
-    BEST_EETX = 0,
+    BEST_ETX = 10,
     INVALID_RVAL = 0xff,
     INVALID_NEIGHBOR_ADDR = 0xff,
     // if we don't know the link quality, we need to return a value so
     // large that it will not be used to form paths
-    VERY_LARGE_EETX_VALUE = 0xff,
+    VERY_LARGE_ETX_VALUE = 0xffff,
     // decay the link estimate using this alpha
     // we use a denominator of 10, so this corresponds to 0.2
     ALPHA = 9,
@@ -79,10 +77,10 @@ implementation {
     // number of beacons to wait before computing a new
     // BLQ (Beacon-driven Link Quality)
     BLQ_PKT_WINDOW = 3,
-    // largest EETX value that we feed into the link quality EWMA
-    // a value of 60 corresponds to having to make six transmissions
+    // largest ETX value that we feed into the link quality EWMA
+    // a value of 70 corresponds to having to make six transmissions
     // to successfully receive one acknowledgement
-    LARGE_EETX_VALUE = 60
+    LARGE_ETX_VALUE = 70
   };
 
   // keep information about links from the neighbors
@@ -170,9 +168,8 @@ implementation {
     ne->rcvcnt = 0;
     ne->failcnt = 0;
     ne->flags = (INIT_ENTRY | VALID_ENTRY);
-    ne->inage = MAX_AGE;
     ne->inquality = 0;
-    ne->eetx = 0;
+    ne->etx = 0;
   }
 
   // find the index to the entry for neighbor ll_addr
@@ -202,12 +199,12 @@ implementation {
 
   // find the index to the worst neighbor if the eetx
   // estimate is greater than the given threshold
-  uint8_t findWorstNeighborIdx(uint8_t thresholdEETX) {
+  uint8_t findWorstNeighborIdx(uint8_t thresholdETX) {
     uint8_t i, worstNeighborIdx;
-    uint16_t worstEETX, thisEETX;
+    uint16_t worstETX, thisETX;
 
     worstNeighborIdx = INVALID_RVAL;
-    worstEETX = 0;
+    worstETX = 0;
     for (i = 0; i < NEIGHBOR_TABLE_SIZE; i++) {
       if (!(NeighborTable[i].flags & VALID_ENTRY)) {
        dbg("LI", "Invalid so continuing\n");
@@ -221,13 +218,13 @@ implementation {
        dbg("LI", "Pinned entry, so continuing\n");
        continue;
       }
-      thisEETX = NeighborTable[i].eetx;
-      if (thisEETX >= worstEETX) {
+      thisETX = NeighborTable[i].etx;
+      if (thisETX >= worstETX) {
        worstNeighborIdx = i;
-       worstEETX = thisEETX;
+       worstETX = thisETX;
       }
     }
-    if (worstEETX >= thresholdEETX) {
+    if (worstETX >= thresholdETX) {
       return worstNeighborIdx;
     } else {
       return INVALID_RVAL;
@@ -272,45 +269,44 @@ implementation {
   }
 
 
-  // update the EETX estimator
+  // update the ETX estimator
   // called when new beacon estimate is done
   // also called when new DEETX estimate is done
-  void updateEETX(neighbor_table_entry_t *ne, uint16_t newEst) {
-    ne->eetx = (ALPHA * ne->eetx + (10 - ALPHA) * newEst)/10;
+  void updateETX(neighbor_table_entry_t *ne, uint16_t newEst) {
+    ne->etx = (ALPHA * ne->etx + (10 - ALPHA) * newEst)/10;
   }
 
 
-  // update data driven EETX
-  void updateDEETX(neighbor_table_entry_t *ne) {
+  // update data driven ETX
+  void updateDETX(neighbor_table_entry_t *ne) {
     uint16_t estETX;
 
     if (ne->data_success == 0) {
       // if there were no successful packet transmission in the
       // last window, our current estimate is the number of failed
       // transmissions
-      estETX = (ne->data_total - 1)* 10;
+      estETX = ne->data_total * 10;
     } else {
-      estETX = (10 * ne->data_total) / ne->data_success - 10;
+      estETX = (10 * ne->data_total) / ne->data_success;
       ne->data_success = 0;
       ne->data_total = 0;
     }
-    updateEETX(ne, estETX);
+    updateETX(ne, estETX);
   }
 
 
-  // EETX (Extra Expected number of Transmission)
-  // EETX = ETX - 1
-  // computeEETX returns EETX*10
-  uint8_t computeEETX(uint8_t q1) {
+  // ETX (Expected number of Transmission)
+  // computeETX returns ETX*10
+  uint16_t computeETX(uint8_t q1) {
     uint16_t q;
     if (q1 > 0) {
-      q =  2550 / q1 - 10;
-      if (q > 255) {
-       q = VERY_LARGE_EETX_VALUE;
+      q =  2500 / q1;
+      if (q > 250) {
+       q = VERY_LARGE_ETX_VALUE;
       }
-      return (uint8_t)q;
+      return q;
     } else {
-      return VERY_LARGE_EETX_VALUE;
+      return VERY_LARGE_ETX_VALUE;
     }
   }
 
@@ -328,33 +324,24 @@ implementation {
       ne = &NeighborTable[i];
       if (ne->ll_addr == n) {
        if (ne->flags & VALID_ENTRY) {
-         if (ne->inage > 0)
-           ne->inage--;
-         
-         if (ne->inage == 0) {
-           ne->flags ^= VALID_ENTRY;
-           ne->inquality = 0;
+         dbg("LI", "Making link: %d mature\n", i);
+         ne->flags |= MATURE_ENTRY;
+         totalPkt = ne->rcvcnt + ne->failcnt;
+         dbg("LI", "MinPkt: %d, totalPkt: %d\n", minPkt, totalPkt);
+         if (totalPkt < minPkt) {
+           totalPkt = minPkt;
+         }
+         if (totalPkt == 0) {
+           ne->inquality = (ALPHA * ne->inquality) / 10;
          } else {
-           dbg("LI", "Making link: %d mature\n", i);
-           ne->flags |= MATURE_ENTRY;
-           totalPkt = ne->rcvcnt + ne->failcnt;
-           dbg("LI", "MinPkt: %d, totalPkt: %d\n", minPkt, totalPkt);
-           if (totalPkt < minPkt) {
-             totalPkt = minPkt;
-           }
-           if (totalPkt == 0) {
-             ne->inquality = (ALPHA * ne->inquality) / 10;
-           } else {
-             newEst = (255 * ne->rcvcnt) / totalPkt;
-             dbg("LI,LITest", "  %hu: %hhu -> %hhu", ne->ll_addr, ne->inquality, (ALPHA * ne->inquality + (10-ALPHA) * newEst)/10);
-             ne->inquality = (ALPHA * ne->inquality + (10-ALPHA) * newEst)/10;
-           }
-           ne->rcvcnt = 0;
-           ne->failcnt = 0;
+           newEst = (250UL * ne->rcvcnt) / totalPkt;
+           dbg("LI,LITest", "  %hu: %hhu -> %hhu", ne->ll_addr, ne->inquality, (ALPHA * ne->inquality + (10-ALPHA) * newEst)/10);
+           ne->inquality = (ALPHA * ne->inquality + (10-ALPHA) * newEst)/10;
          }
-         updateEETX(ne, computeEETX(ne->inquality));
-       }
-       else {
+         ne->rcvcnt = 0;
+         ne->failcnt = 0;
+         updateETX(ne, computeETX(ne->inquality));
+       } else {
          dbg("LI", " - entry %i is invalid.\n", (int)i);
        }
       }
@@ -379,20 +366,23 @@ implementation {
        NeighborTable[idx].lastseq, seq, packetGap);
     NeighborTable[idx].lastseq = seq;
     NeighborTable[idx].rcvcnt++;
-    NeighborTable[idx].inage = MAX_AGE;
     if (packetGap > 0) {
       NeighborTable[idx].failcnt += packetGap - 1;
     }
-    if (packetGap > MAX_PKT_GAP) {
-      NeighborTable[idx].failcnt = 0;
-      NeighborTable[idx].rcvcnt = 1;
-      NeighborTable[idx].inquality = 0;
-    }
 
-    if (NeighborTable[idx].rcvcnt >= BLQ_PKT_WINDOW) {
+    // The or with packetGap >= BLQ_PKT_WINDOW is needed in case
+    // failcnt gets reset above
+
+    if (((NeighborTable[idx].rcvcnt + NeighborTable[idx].failcnt) >= BLQ_PKT_WINDOW)
+       || (packetGap >= BLQ_PKT_WINDOW)) {
       updateNeighborTableEst(NeighborTable[idx].ll_addr);
     }
 
+    if (packetGap > MAX_PKT_GAP) {
+      initNeighborIdx(idx, NeighborTable[idx].ll_addr);
+      NeighborTable[idx].lastseq = seq;
+      NeighborTable[idx].rcvcnt = 1;
+    }
   }
 
 
@@ -404,9 +394,9 @@ implementation {
     for (i = 0; i < NEIGHBOR_TABLE_SIZE; i++) {
       ne = &NeighborTable[i];
       if (ne->flags & VALID_ENTRY) {
-       dbg("LI,LITest", "%d:%d inQ=%d, inA=%d, rcv=%d, fail=%d, Q=%d\n",
-           i, ne->ll_addr, ne->inquality, ne->inage,
-           ne->rcvcnt, ne->failcnt, computeEETX(ne->inquality));
+       dbg("LI,LITest", "%d:%d inQ=%d, rcv=%d, fail=%d, Q=%d\n",
+           i, ne->ll_addr, ne->inquality, 
+           ne->rcvcnt, ne->failcnt, computeETX(ne->inquality));
       }
     }
   }
@@ -452,12 +442,12 @@ implementation {
     uint8_t idx;
     idx = findIdx(neighbor);
     if (idx == INVALID_RVAL) {
-      return VERY_LARGE_EETX_VALUE;
+      return VERY_LARGE_ETX_VALUE;
     } else {
       if (NeighborTable[idx].flags & MATURE_ENTRY) {
-       return NeighborTable[idx].eetx;
+       return NeighborTable[idx].etx;
       } else {
-       return VERY_LARGE_EETX_VALUE;
+       return VERY_LARGE_ETX_VALUE;
       }
     }
   }
@@ -479,7 +469,7 @@ implementation {
       initNeighborIdx(nidx, neighbor);
       return SUCCESS;
     } else {
-      nidx = findWorstNeighborIdx(BEST_EETX);
+      nidx = findWorstNeighborIdx(BEST_ETX);
       if (nidx != INVALID_RVAL) {
        dbg("LI", "insert: inserted by replacing an entry for neighbor: %d\n",
            NeighborTable[nidx].ll_addr);
@@ -524,7 +514,7 @@ implementation {
     ne->data_success++;
     ne->data_total++;
     if (ne->data_total >= DLQ_PKT_WINDOW) {
-      updateDEETX(ne);
+      updateDETX(ne);
     }
     return SUCCESS;
   }
@@ -541,7 +531,7 @@ implementation {
     ne = &NeighborTable[nidx];
     ne->data_total++;
     if (ne->data_total >= DLQ_PKT_WINDOW) {
-      updateDEETX(ne);
+      updateDETX(ne);
     }
     return SUCCESS;
   }
@@ -636,7 +626,7 @@ implementation {
          initNeighborIdx(nidx, ll_addr);
          updateNeighborEntryIdx(nidx, hdr->seq);
        } else {
-         nidx = findWorstNeighborIdx(EVICT_EETX_THRESHOLD);
+         nidx = findWorstNeighborIdx(EVICT_ETX_THRESHOLD);
          if (nidx != INVALID_RVAL) {
            dbg("LI", "Evicted neighbor %d at idx %d\n",
                NeighborTable[nidx].ll_addr, nidx);
@@ -644,14 +634,20 @@ implementation {
            initNeighborIdx(nidx, ll_addr);
          } else {
            dbg("LI", "No room in the table\n");
-           if (signal CompareBit.shouldInsert(msg, 
-                                              call Packet.getPayload(msg, call Packet.payloadLength(msg)),
-                                              call Packet.payloadLength(msg),
-                                              call LinkPacketMetadata.highChannelQuality(msg))) {
-             nidx = findRandomNeighborIdx();
-             if (nidx != INVALID_RVAL) {
-               signal LinkEstimator.evicted(NeighborTable[nidx].ll_addr);
-               initNeighborIdx(nidx, ll_addr);
+
+           /* if the white bit is set, lets ask the router if the path through
+              this link is better than at least one known path - if so
+              lets insert this link into the table.
+           */
+           if (call LinkPacketMetadata.highChannelQuality(msg)) {
+             if (signal CompareBit.shouldInsert(msg, 
+                                                call Packet.getPayload(msg, call Packet.payloadLength(msg)),
+                                                call Packet.payloadLength(msg))) {
+               nidx = findRandomNeighborIdx();
+               if (nidx != INVALID_RVAL) {
+                 signal LinkEstimator.evicted(NeighborTable[nidx].ll_addr);
+                 initNeighborIdx(nidx, ll_addr);
+               }
              }
            }
          }
index 5feb30312607bc0ac31a638894163dc7a99c88b1..d350aed9e0e49331107b50c27ddb0d33688fe367 100644 (file)
@@ -69,7 +69,7 @@ implementation
   BlockStorageManagerP.SubStorageMap[VOLUME_DELUGE1]     -> BlockStorageC_1;
   BlockStorageManagerP.SubStorageMap[VOLUME_DELUGE2]     -> BlockStorageC_2;
   BlockStorageManagerP.SubStorageMap[VOLUME_DELUGE3]     -> BlockStorageC_3;
-#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_IRIS)
+#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_IRIS) || defined(PLATFORM_EPIC) || defined(PLATFORM_MULLE) || defined(PLATFORM_TINYNODE)
   components At45dbStorageManagerC;
   BlockStorageManagerP.At45dbVolume -> At45dbStorageManagerC;
 #endif
index 9fbd9e40ae52c64df0f989726206d6ecd594c887..3c0e34e85041e0e9017833adbae1de2eea754cd7 100644 (file)
@@ -37,7 +37,7 @@ generic module BlockStorageManagerP(uint8_t clients)
     interface VolumeId[uint8_t client];
 #if defined(PLATFORM_TELOSB)
     interface StorageMap as SubStorageMap[volume_id_t volume_id];
-#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_IRIS)
+#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_IRIS) || defined(PLATFORM_EPIC) || defined(PLATFORM_MULLE) || defined(PLATFORM_TINYNODE)
     interface At45dbVolume[volume_id_t volume_id];
 #endif
   }
@@ -180,13 +180,7 @@ implementation
     storage_addr_t p_addr = 0xFFFFFFFF;
 #if defined(PLATFORM_TELOSB)
     p_addr = call SubStorageMap.getPhysicalAddress[volume_id](addr);
-#elif defined(PLATFORM_MICAZ)
-    at45page_t page = call At45dbVolume.remap[volume_id]((addr >> AT45_PAGE_SIZE_LOG2));
-    at45pageoffset_t offset = addr & ((1 << AT45_PAGE_SIZE_LOG2) - 1);
-    p_addr = page;
-    p_addr = p_addr << AT45_PAGE_SIZE_LOG2;
-    p_addr += offset;
-#elif defined(PLATFORM_IRIS)
+#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_IRIS) || defined(PLATFORM_EPIC) || defined(PLATFORM_MULLE) || defined(PLATFORM_TINYNODE)
     at45page_t page = call At45dbVolume.remap[volume_id]((addr >> AT45_PAGE_SIZE_LOG2));
     at45pageoffset_t offset = addr & ((1 << AT45_PAGE_SIZE_LOG2) - 1);
     p_addr = page;
diff --git a/tos/lib/net/Deluge/Crc.nc b/tos/lib/net/Deluge/Crc.nc
deleted file mode 100644 (file)
index 93283aa..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/* 
- * "Copyright (c) 2000-2004 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-interface Crc
-{
-  command uint16_t crc16(void* COUNT(len) buf, uint8_t len);
-}
diff --git a/tos/lib/net/Deluge/CrcP.nc b/tos/lib/net/Deluge/CrcP.nc
deleted file mode 100644 (file)
index a14a14e..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/* 
- * "Copyright (c) 2000-2004 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-#include "crc.h"
-
-module CrcP
-{
-  provides interface Crc;
-}
-
-implementation
-{
-  // From T1 "tos/system/CrcC.nc"
-  command uint16_t Crc.crc16(void* buf, uint8_t len)
-  {
-    uint8_t* tmpBuf = (uint8_t*)buf;
-    uint16_t crc;
-    
-    for (crc = 0; len > 0; len--) {
-      crc = crcByte(crc, *tmpBuf);   // Calculates running CRC
-      tmpBuf++;
-    }
-    
-    return crc;
-  }
-}
index 26eeadb70ac7918498b7dc9d1fffebbc3284eedd..ec1952010c6bf66cd7a164e54c4a9086ada70a62 100644 (file)
@@ -65,7 +65,7 @@ typedef nx_struct DelugeCmd {
   nx_uint8_t type;
   nx_uint32_t uidhash;  // unique id of image
   nx_uint8_t  imgNum;   // image number
-  nx_uint16_t size;     // size of the image
+  nx_uint32_t size;     // size of the image
 } DelugeCmd;
 
 typedef struct BootArgs {
index f10b3144b1c0481de8c390bbde06a3d0f1f4b159..948a470433ccd8f26835de18f92431a3430397ce 100644 (file)
@@ -71,7 +71,7 @@ implementation
   {
     return DELUGE_IDENT_SIZE + currentPage * sizeof(uint16_t);
   }
-  
+
   uint32_t calcPageAddr()
   {
     return DELUGE_IDENT_SIZE + DELUGE_CRC_BLOCK_SIZE + currentPage * DELUGE_BYTES_PER_PAGE;
@@ -87,7 +87,7 @@ implementation
     state = S_READ_IDENT;
     currentImageIdx = 0;
     currentVolume = _imgNum2volumeId[currentImageIdx];
-    nextImage();    
+    nextImage();
   }
 
   command error_t DelugeMetadata.read[uint8_t client](uint8_t imgNum)
@@ -117,6 +117,7 @@ implementation
           call BlockRead.read[currentVolume](calcCrcAddr(), &currentCrc, sizeof(currentCrc));
         } else {
           currentImageIdx++;
+          currentVolume = _imgNum2volumeId[currentImageIdx];
           nextImage();
         }
       }
@@ -143,7 +144,7 @@ implementation
           call BlockRead.read[currentVolume](calcCrcAddr(), &currentCrc, sizeof(currentCrc));
         } else {
           currentImageIdx++;
-         currentVolume = _imgNum2volumeId[currentImageIdx];
+          currentVolume = _imgNum2volumeId[currentImageIdx];
           nextImage();
         }
       }
index f2df208fe73cafde10b1cdfe5ae0850454d66864..e5dc2efa62722082bf6d277096b649c26e086ec8 100644 (file)
@@ -153,7 +153,7 @@ implementation
 
   event void DelugeMetadata.readDone(uint8_t imgNum, DelugeIdent* ident, error_t error)
   {
-//    printf("readDone 0x%lx imgNum: %d size: %u\n", lastCmd.uidhash, lastCmd.imgNum, lastCmd.size);
+//    printf("readDone 0x%lx imgNum: %d size: %lu\n", lastCmd.uidhash, lastCmd.imgNum, lastCmd.size);
     if (ident->uidhash == lastCmd.uidhash) {
       if (lastCmd.type == DELUGE_CMD_DISSEMINATE_AND_REPROGRAM) {
        call NetProg.programImageAndReboot(call StorageMap.getPhysicalAddress[imgNum](0));
index c491dffb0a460387c71f65cb76d3a62b74b6a155..49ed1e99f46e0545c36bf0ee9286b671226b97a7 100644 (file)
 #ifndef DELUGEPAGETRANSFER_H
 #define DELUGEPAGETRANSFER_H
 
-#if defined(PLATFORM_TELOSB)
+#if defined(PLATFORM_TELOSB) || defined(PLATFORM_EPIC)
   #include "extra/telosb/TOSBoot_platform.h"
 #elif defined(PLATFORM_MICAZ) || defined(PLATFORM_IRIS)
   #include "extra/micaz/TOSBoot_platform.h"
+#elif defined(PLATFORM_MULLE)
+  #include "extra/mulle/TOSBoot_platform.h"
+#elif defined(PLATFORM_TINYNODE)
+  #include "extra/tinynode/TOSBoot_platform.h"
 #else
   #error "Target platform is not currently supported by Deluge T2"
 #endif
index 06420ce4a02ab4037f13cd7937738a9cf2d6eb98..b91f194bee9f4ded4544df14a5b030819dd0ba19 100644 (file)
@@ -45,7 +45,7 @@ implementation
   typedef nx_struct SerialReqPacket {
     nx_uint8_t cmd;
     nx_uint8_t imgNum;
-    nx_uint16_t offset;
+    nx_uint32_t offset;
     nx_uint16_t len;
     nx_uint8_t data[0];
   } SerialReqPacket;
@@ -200,7 +200,11 @@ implementation
        switch (request->cmd) {
         case CMD_ERASE:    // === Erases a volume ===
           state = S_ERASE;
+#if defined(PLATFORM_MICAZ) || defined(PLATFORM_IRIS) || defined(PLATFORM_EPIC)
+          error = FAIL;
+#else
           error = call BlockWrite.erase[imgNum]();
+#endif
           break;
         case CMD_WRITE:    // === Writes to a volume ===
           state = S_WRITE;
index 8e77dc630ca5faa8398d2dffd9a594e64dbfde3a..72b9db5a56d8d9661e93ceaceccbec0b22ed5c51 100644 (file)
@@ -40,13 +40,13 @@ configuration ObjectTransferC
 implementation
 {
   components ObjectTransferP, DelugePageTransferC;
-  components CrcP;
+  components CrcC;
   
   ObjectTransfer = ObjectTransferP;
   DelugePageTransferC.BlockRead = BlockRead;
   DelugePageTransferC.BlockWrite = BlockWrite;
   ObjectTransferP.DelugePageTransfer -> DelugePageTransferC.DelugePageTransfer;
-  ObjectTransferP.Crc -> CrcP.Crc;
+  ObjectTransferP.Crc -> CrcC.Crc;
   
   components new AMSenderC(AM_DELUGEADVMSG) as SendAdvMsg, 
              new AMReceiverC(AM_DELUGEADVMSG) as ReceiveAdvMsg,
index 462ff7da4883f412557da2857805b3ff19a52304..79bad7651dd654b4bde4b9323cf9de1b9687ada2 100644 (file)
@@ -40,20 +40,24 @@ configuration NetProgC {
 
 implementation {
 
-  components MainC, InternalFlashC as IFlash, CrcP;
+  components MainC, InternalFlashC as IFlash, CrcC;
   components NetProgM, ReprogramGuardC;
 
   NetProg = NetProgM;
 
   MainC.SoftwareInit -> NetProgM.Init;
   NetProgM.IFlash -> IFlash;
-  NetProgM.Crc -> CrcP;
+  NetProgM.Crc -> CrcC;
   NetProgM.ReprogramGuard -> ReprogramGuardC;
 
   components LedsC;
   NetProgM.Leds -> LedsC;
   
-  components CC2420ControlP, ActiveMessageAddressC;
-  NetProgM.CC2420Config -> CC2420ControlP;
+  components ActiveMessageAddressC;
   NetProgM.setAmAddress -> ActiveMessageAddressC;
+
+#if !defined(PLATFORM_TINYNODE)
+  components CC2420ControlP;
+  NetProgM.CC2420Config -> CC2420ControlP;
+#endif
 }
index e77ebeedeb4b09780359cfa6b8eb8cc0dbe91055..fc054cff8fc0f13e00d657a1ca6da95241129eff 100644 (file)
@@ -40,7 +40,9 @@ module NetProgM {
     interface InternalFlash as IFlash;
     interface Crc;
     interface Leds;
+#if !defined(PLATFORM_TINYNODE)
     interface CC2420Config;
+#endif
     async command void setAmAddress(am_addr_t a);
     interface ReprogramGuard;
   }
@@ -60,9 +62,10 @@ implementation {
       TOS_NODE_ID = bootArgs.address;
       call setAmAddress(bootArgs.address);
     }
+#if !defined(PLATFORM_TINYNODE)
     call CC2420Config.setShortAddr(bootArgs.address);
     call CC2420Config.sync();
-    
+#endif    
     return SUCCESS;
   }
   
@@ -113,5 +116,7 @@ implementation {
     }
   }
 
+#if !defined(PLATFORM_TINYNODE)
   event void CC2420Config.syncDone(error_t error) {}
+#endif
 }
diff --git a/tos/lib/net/Deluge/extra/epic/TOSBoot_platform.h b/tos/lib/net/Deluge/extra/epic/TOSBoot_platform.h
new file mode 100644 (file)
index 0000000..c892207
--- /dev/null
@@ -0,0 +1,38 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * @author  Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#ifndef __TOSBOOT_PLATFORM_H__
+#define __TOSBOOT_PLATFORM_H__
+
+enum {
+  TOSBOOT_ARGS_ADDR = 0x70,       // address of TOSBoot args in internal flash
+  TOSBOOT_GESTURE_MAX_COUNT = 3,  // number of resets to force golden image
+  TOSBOOT_GOLDEN_IMG_ADDR = 0x0L, // address of the golden image in external flash
+  TOSBOOT_INT_PAGE_SIZE = 512L,   // size of each internal program flash page
+};
+
+#endif
index 1d785b43ca91bf275aff877239d425bc8f175508..7a508e11ea5d0dc671f17ba12102219b70324cdb 100644 (file)
@@ -40,13 +40,13 @@ configuration NetProgC {
 
 implementation {
 
-  components MainC, InternalFlashC as IFlash, CrcP, NetProgM;
+  components MainC, InternalFlashC as IFlash, CrcC, NetProgM;
 
   NetProg = NetProgM;
 
   MainC.SoftwareInit -> NetProgM.Init;
   NetProgM.IFlash -> IFlash;
-  NetProgM.Crc -> CrcP;
+  NetProgM.Crc -> CrcC;
 
   components LedsC;
   NetProgM.Leds -> LedsC;
diff --git a/tos/lib/net/Deluge/extra/m16c62p/HplM16c62pFlash.nc b/tos/lib/net/Deluge/extra/m16c62p/HplM16c62pFlash.nc
new file mode 100644 (file)
index 0000000..df011b8
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * Interface to access the program flash of the M16c/62p mcu.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+interface HplM16c62pFlash
+{
+  /**
+   * Erases a block in the program flash.
+   *
+   * @param block The block that should be erased.
+   * @return False if the erase failed.
+   */
+  command bool FlashRead(unsigned long flash_addr_in);
+  
+  /**
+   * Writes bytes into the program flash.
+   *
+   * @param flash_addr The program flash address where the write should begin. This MUST be an EVEN address.
+   * @param buffer_addr The bytes that should be written to the address.
+   * @param bytes The number of bytes that should be written. This MUST be an EVEN number.
+   * @return 1 if the flash control register reported an error. 2 if the parameters that where passed contained an error.
+   */
+  command uint8_t FlashErase(unsigned char block);
+  
+  /**
+   * Reads the byte at am address using a LDE instruction.
+   *
+   * @param address The address that a byte should be read from.
+   * @return Byte read.
+   */
+  command uint8_t FlashWrite(unsigned long flash_addr_in,
+                              unsigned int* buffer_addr,
+                              unsigned int bytes);
+}
\ No newline at end of file
diff --git a/tos/lib/net/Deluge/extra/m16c62p/HplM16c62pFlashC.nc b/tos/lib/net/Deluge/extra/m16c62p/HplM16c62pFlashC.nc
new file mode 100644 (file)
index 0000000..bc8255d
--- /dev/null
@@ -0,0 +1,241 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "M16c62pFlash.h"
+#include "iom16c62p.h"
+
+/**
+ * Implementation of the HplM16c62pFlash interface. Note that this module
+ * should be used with caution so that one doesn't erase the flash where the
+ * executing program lies.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Renesas
+ */
+// TODO(henrik) This implementation expects a main clock speed <=10 MHz, fix it.
+module HplM16c62pFlashC
+{
+  provides interface HplM16c62pFlash;
+}
+implementation
+{
+
+// Defines an array of highest even addresses for each block
+const unsigned long block_addresses[14] =
+  {0xFFFFE,0xFEFFE,0xFDFFE,0xFBFFE,0xF9FFE,0xF7FFE,0xEFFFE,0xDFFFE,0xCFFFE,
+   0xBFFFE,0xAFFFE,0x9FFFE,0x8FFFE,0xFFFE };
+  
+unsigned char cm0_saved;                       // For saving the Clock Mode 0 register
+unsigned char cm1_saved;                       // For saving the Clock Mode 1 register
+unsigned char pm0_saved;                       // For saving the Processor Mode 0 register
+unsigned char pm1_saved;                       // For saving the Processor Mode 1 register
+unsigned char prcr_saved;                      //  Save Protection register
+  
+/**   
+ * Sets the processor mode for programming flash and saves current
+ * settings to restore later. You cannot run the processor faster
+ * than 10.0 MHz (with wait state) or 6.25MHz (without wait state)
+ * when sending commands to the flash controller.
+ */
+void SlowMCUClock(void)
+{
+  // Unprotect registers CM0 and CM1 and PM0 registers by writting to protection register
+  prcr_saved = *((char *)0xA); // Save Protection register
+  *((char *)0xA) = 3;                          // Allow writting to protected system registers
+  // Force to Single chip mode for processors that have memory expansion mode
+  pm0_saved = *((char *)0x4);                          // Save pm0 register
+  *((char *)0x4) = pm0_saved & 0xFC;           // bit 0 and 1 to zero
+
+  cm0_saved = *((char *)0x6);          // Save cm0 register
+  cm1_saved = *((char *)0x7);          // Save cm1 register
+  pm1_saved = *((char *)0x5);          // Save pm1 register
+
+  // Insert Wait state for all bus access (needed for talking to the
+  // internal flash controller)
+  asm("BSET    7,0x05"); // Set bit PM17
+  CM0.BYTE = 0;
+  CM1.BYTE = 0;
+}
+
+/**
+ * Restores the processor mode back to original settings.
+ */
+void RestoreMCUClock(void)                     
+{
+  *((char *)0x4) = pm0_saved;          // Restore pm0 register
+
+  /* Clock settings for R8C and M16C */
+  *((char *)0x7) = cm1_saved;          // Restore cm1 register
+  *((char *)0x6) = cm0_saved;          // Restore cm0 register
+  *((char *)0x5) = pm1_saved;          // Restore pm1 register
+  *((char *)0xA) = prcr_saved; // Protection back on
+}
+
+command bool HplM16c62pFlash.FlashErase( unsigned char block )
+{
+    unsigned int low = (unsigned int) block_addresses[ block ];
+    unsigned int high = (unsigned int)( block_addresses[ block ] >> 16);
+
+       // Must change main clock speed to meet flash requirements
+       SlowMCUClock();                 
+        FMR0.BIT.FMR01 = 0;
+        FMR0.BIT.FMR01 = 1;
+        FMR1.BIT.FMR11 = 0;
+        FMR1.BIT.FMR11 = 1;
+
+    asm volatile ("mov.w %[low], a0\n\t"
+                  "mov.w %[high], a1\n\t"
+                  
+                  "mov.w #0x0050, r0\n\t"
+                  "ste.w r0, [a1a0]\n\t"
+                  
+                  "mov.w #0x0020, r0\n\t"
+                  "ste.w r0, [a1a0]\n\t"
+                  
+                  "mov.w #0x00D0, r0\n\t"
+                  "ste.w r0, [a1a0]\n\t"
+                  :
+                  :[low] "r" (low), [high] "r" (high)
+                  : "memory", "r0", "a0", "a1");
+
+       // Note: In EW1 Mode, the MCU is suspended until the operation is completed.
+    while (!FMR0.BIT.FMR00);
+       // Disable CPU rewriting commands by clearing EW entry bit.
+       FMR0.BYTE = 0;
+
+       RestoreMCUClock(); // Restore clock back to original speed
+
+       if( FMR0.BIT.FMR07)     // Erasing error?
+       {
+               return 1;  // Erase Fail
+       }
+
+       return 0;  // Erase Pass
+}
+
+command uint8_t HplM16c62pFlash.FlashWrite( unsigned long flash_addr,
+                            unsigned int * buffer_addr,
+                            unsigned int bytes)
+{
+  unsigned char ret_value = 0;
+  unsigned int low = (unsigned int) flash_addr;
+  unsigned int high = (unsigned int)( flash_addr >> 16);
+  unsigned int i;
+  // Check for odd number of bytes 
+  if( bytes & 1)
+    return 2;  // ERROR!! You must always pass an even number of bytes.
+
+  // Check for odd address
+  if( (int)flash_addr & 1)
+    return 2;  // ERROR!! You must always pass an even flash address
+
+  // Must change main clock speed to meet flash requirements
+  SlowMCUClock();                      
+
+  FMR0.BIT.FMR01 = 0;
+  FMR0.BIT.FMR01 = 1;
+  FMR1.BIT.FMR11 = 0;
+  FMR1.BIT.FMR11 = 1;
+
+  // Clear status register
+  asm volatile ("mov.w %[low], a0\n\t"
+      "mov.w %[high], a1\n\t"
+
+      "mov.w #0x0050, r0\n\t"
+      "ste.w r0, [a1a0]\n\t"
+      :
+      :[low] "r" (low), [high] "r" (high)
+      : "memory", "r0", "a1", "a0");
+
+  for (i = 0; i < (bytes >> 1); ++i)
+  {
+    // Write to the flash sequencer by writing to that area of flash memory
+    asm volatile (
+        "mov.w %[low], a0\n\t"
+        "mov.w %[high], a1\n\t"
+
+        "mov.w #0x0040, r1\n\t" // Send write command
+        "ste.w r1, [a1a0]\n\t"
+
+        "mov.w %[data], r1\n\t" // Write data
+        "ste.w r1, [a1a0]\n\t"
+        :
+        :[low] "r" (low), [high] "r" (high), [data] "r" (*buffer_addr)
+        : "memory", "a1", "a0", "r1");
+
+    // Note: In EW1 Mode, the MCU is suspended until the operation completed
+
+    // Read flash program status flag
+    if( FMR0.BIT.FMR06 ) // Write error?
+    {
+      ret_value = 1;           // Signal that we had got an error
+      break;                           // Break out of while loop
+    }
+
+    flash_addr += 2;           // Advance to next flash write address
+    buffer_addr++;                     // Advance to next data buffer address
+    low = (unsigned int) flash_addr;
+    high = (unsigned int)( flash_addr >> 16);
+  }
+
+    asm volatile ("mov.w %[low], a0\n\t"
+                  "mov.w %[high], a1\n\t"
+                  "ste.w 0x00FF, [a1a0]\n\t"
+                  :
+                  :[low] "r" (low), [high] "r" (high)
+                  : "memory", "a0", "a1");
+
+  // Disable CPU rewriting commands by clearing EW entry bit
+  FMR0.BYTE = 0;
+  RestoreMCUClock();           // Restore clock back to original speed
+
+  return ret_value;            // Return Pass/Fail
+}
+
+command uint8_t HplM16c62pFlash.FlashRead(unsigned long address) {
+  unsigned int low = (unsigned int)(address);
+  unsigned int high = (unsigned int)(address >> 16);
+  unsigned int data;
+  asm volatile ("mov.w %[low], a0\n\t"
+                "mov.w %[high], a1\n\t"
+                "ste.w 0x00FF, [a1a0]\n\t"
+                "lde.w [a1a0], %[data]"
+                :[data] "=r" (data)
+                :[low] "r" (low), [high] "r" (high)
+                : "memory", "a0", "a1");
+  return data;
+}
+}
diff --git a/tos/lib/net/Deluge/extra/m16c62p/InternalFlashC.nc b/tos/lib/net/Deluge/extra/m16c62p/InternalFlashC.nc
new file mode 100644 (file)
index 0000000..5b14bb0
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * Wiring so that the M16c/62p InternalFlashP module gets access to the 
+ * HplM16c62pFlashC module.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration InternalFlashC
+{
+  provides interface InternalFlash;
+}
+implementation
+{
+  components HplM16c62pFlashC, InternalFlashP;
+  InternalFlashP.Flash -> HplM16c62pFlashC;
+  InternalFlash = InternalFlashP;
+}
\ No newline at end of file
diff --git a/tos/lib/net/Deluge/extra/m16c62p/InternalFlashP.nc b/tos/lib/net/Deluge/extra/m16c62p/InternalFlashP.nc
new file mode 100644 (file)
index 0000000..5c73e54
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "M16c62pFlash.h"
+
+/**
+ * Implementation of the InternalFlash interface for the
+ * M16c/62p mcu. Currently flash block 5 is used for the
+ * internal flash and is hard coded.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+// TODO(henrik) Fix the hard coded value of the flash block.
+module InternalFlashP {
+  provides interface InternalFlash;
+  
+  uses interface HplM16c62pFlash as Flash;
+}
+
+implementation {
+
+#define INTERNAL_ADDRESS 0xF0000L 
+#define INTERNAL_BLOCK BLOCK_5
+
+  command error_t InternalFlash.write(void* addr, void* buf, uint16_t size) {
+    // TODO(henrik) Make this more sain by making use of the whole block before
+    // erasing the whole block.
+    if (call Flash.FlashErase(INTERNAL_BLOCK) != 0)
+    {
+      return FAIL;
+    }
+    if (call Flash.FlashWrite(INTERNAL_ADDRESS, (unsigned int*)buf, size) != 0)
+    {
+      return FAIL;
+    }
+    return SUCCESS;
+  }
+
+  command error_t InternalFlash.read(void* addr, void* buf, uint16_t size) {
+    unsigned long address = INTERNAL_ADDRESS;
+    uint16_t i;
+    uint8_t* buffer = (uint8_t*)buf;
+
+    for (i = 0; i < size; ++i, ++address)
+    {
+      buffer[i] = call Flash.FlashRead(address);
+    }
+    return SUCCESS;
+  }
+}
diff --git a/tos/lib/net/Deluge/extra/m16c62p/M16c62pFlash.h b/tos/lib/net/Deluge/extra/m16c62p/M16c62pFlash.h
new file mode 100644 (file)
index 0000000..7b37214
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * Defines for the program flash blocks.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Renesas
+ */
+#ifndef __M16C62PFLASH_H__
+#define __M16C62PFLASH_H__
+
+// User Block Area
+#define BLOCK_0 0              //  4KB: FF000 - FFFFF
+#define BLOCK_1 1              //  4KB: FE000 - FEFFF
+#define BLOCK_2 2              //  8KB: FC000 - FDFFF
+#define BLOCK_3 3              //  8KB: FA000 - FBFFF
+#define BLOCK_4        4               //  8KB: F8000 - F9FFF
+#define BLOCK_5        5               // 32KB: F0000 - F7FFF
+#define BLOCK_6 6              // 64KB: E0000 - EFFFF
+#define BLOCK_7        7               // 64KB: D0000 - DFFFF
+#define BLOCK_8        8               // 64KB: C0000 - CFFFF
+#define BLOCK_9        9               // 64KB: B0000 - BFFFF
+#define BLOCK_10 10            // 64KB: A0000 - AFFFF
+#define BLOCK_11 11            // 64KB: 90000 - 9FFFF
+#define BLOCK_12 12            // 64KB: 80000 - 8FFFF
+
+// Data Block Area
+#define BLOCK_A 13             // 4KB: F000 - FFFF
+
+#endif  // __M16C62PFLASH_H__
\ No newline at end of file
index 563720fa6e6857206b92b87f86e8c5346d90251a..c41e13a6d18070d9ef71dd03ace14c984a5fd98e 100644 (file)
@@ -39,8 +39,6 @@
  * @author Jonathan Hui <jwhui@cs.berkeley.edu>
  */
 
-includes InternalFlash;
-
 module InternalFlashC {
   provides interface InternalFlash;
 }
diff --git a/tos/lib/net/Deluge/extra/mulle/NetProg_platform.h b/tos/lib/net/Deluge/extra/mulle/NetProg_platform.h
new file mode 100644 (file)
index 0000000..8081215
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * This file contains the netprog_reboot function that
+ * reboots the mcu.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#ifndef __NETPROG_PLATFORM_H__
+#define __NETPROG_PLATFORM_H__
+
+void netprog_reboot() {
+    PRCR.BIT.PRC0 = 1; // Turn off protection on CM registers.
+    PRCR.BIT.PRC1 = 1; // Turn off protection on PM registers.
+    CM0.BIT.CM0_6 = 1;  
+    PM1.BIT.PM1_2 = 1; // Reset on WDT underflow.
+    WDTS = 1; // Start watchdog timer.
+    PRCR.BIT.PRC0 = 0; // Turn on protection on CM registers.
+    PRCR.BIT.PRC1 = 0; // Turn on protection on PM registers.
+    while (1); // Wait for underflow in the watchdog timer.
+}
+
+#endif  // __NETPROG_PLATFORM_H__
diff --git a/tos/lib/net/Deluge/extra/mulle/ReprogramGuardC.nc b/tos/lib/net/Deluge/extra/mulle/ReprogramGuardC.nc
new file mode 100644 (file)
index 0000000..943289d
--- /dev/null
@@ -0,0 +1,11 @@
+configuration ReprogramGuardC
+{
+  provides interface ReprogramGuard;
+}
+
+implementation
+{
+  components ReprogramGuardP;
+  
+  ReprogramGuard = ReprogramGuardP;
+}
diff --git a/tos/lib/net/Deluge/extra/mulle/ReprogramGuardP.nc b/tos/lib/net/Deluge/extra/mulle/ReprogramGuardP.nc
new file mode 100644 (file)
index 0000000..b8064cb
--- /dev/null
@@ -0,0 +1,22 @@
+// TODO(henrik) implement.
+
+module ReprogramGuardP
+{
+  provides interface ReprogramGuard;
+}
+implementation
+{
+  enum {
+    VTHRESH = 0x0, // 0V
+  };
+  task void sendOk()
+  {
+    signal ReprogramGuard.okToProgramDone(true);
+  }
+
+  command error_t ReprogramGuard.okToProgram()
+  {
+    post sendOk();
+    return SUCCESS;
+  }
+}
diff --git a/tos/lib/net/Deluge/extra/mulle/TOSBoot_platform.h b/tos/lib/net/Deluge/extra/mulle/TOSBoot_platform.h
new file mode 100644 (file)
index 0000000..ebeb735
--- /dev/null
@@ -0,0 +1,15 @@
+/**
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#ifndef __TOSBOOT_PLATFORM_H__
+#define __TOSBOOT_PLATFORM_H__
+
+enum {
+  TOSBOOT_ARGS_ADDR = 0,      // address of TOSBoot args in internal flash
+  TOSBOOT_GESTURE_MAX_COUNT = 3,  // number of resets to force golden image
+  TOSBOOT_GOLDEN_IMG_ADDR = 0x0L, // address of the golden image in external flash
+  TOSBOOT_INT_PAGE_SIZE = 512L, // size of each internal program flash page. Each page is 64Kbytes but it is better to split it into 128 parts (65536/512=128).
+};
+
+#endif  // __TOSBOOT_PLATFORM_H__
diff --git a/tos/lib/net/Deluge/extra/telos/ReprogramGuardC.nc b/tos/lib/net/Deluge/extra/telos/ReprogramGuardC.nc
new file mode 100644 (file)
index 0000000..9f25e50
--- /dev/null
@@ -0,0 +1,13 @@
+configuration ReprogramGuardC
+{
+  provides interface ReprogramGuard;
+}
+
+implementation
+{
+  components ReprogramGuardP;
+  components new VoltageC();
+  
+  ReprogramGuard = ReprogramGuardP;
+  ReprogramGuardP.Voltage -> VoltageC;
+}
diff --git a/tos/lib/net/Deluge/extra/telos/ReprogramGuardP.nc b/tos/lib/net/Deluge/extra/telos/ReprogramGuardP.nc
new file mode 100644 (file)
index 0000000..1ffb1e9
--- /dev/null
@@ -0,0 +1,23 @@
+module ReprogramGuardP
+{
+  provides interface ReprogramGuard;
+  uses interface Read<uint16_t> as Voltage;
+}
+
+implementation
+{
+  enum {
+    VTHRESH = 0xE66, // 2.7V
+  };
+
+  command error_t ReprogramGuard.okToProgram()
+  {
+    return call Voltage.read();
+  }
+
+  event void Voltage.readDone(error_t result, uint16_t val)
+  {
+    signal ReprogramGuard.okToProgramDone(result == SUCCESS && val > VTHRESH);
+  }
+  
+}
diff --git a/tos/lib/net/Deluge/extra/telosb/InternalFlash.h b/tos/lib/net/Deluge/extra/telosb/InternalFlash.h
deleted file mode 100644 (file)
index eca3667..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2004 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * InternalFlash.h - Internal flash implementation for telos msp
- * platform. On the msp, the flash must first be erased before a value
- * can be written. However, the msp can only erase the flash at a
- * segment granularity (128 bytes for the information section). This
- * module allows transparent read/write of individual bytes to the
- * information section by dynamically switching between the two
- * provided segments in the information section.
- *
- * Valid address range is 0x1000 - 0x107E (0x107F is used to store the
- * version number of the information segment).
- *
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-#ifndef __INTERNAL_FLASH_H__
-#define __INTERNAL_FLASH_H__
-
-#endif
diff --git a/tos/lib/net/Deluge/extra/telosb/InternalFlash.nc b/tos/lib/net/Deluge/extra/telosb/InternalFlash.nc
deleted file mode 100644 (file)
index d41d52b..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2004 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * InternalFlash.nc - A generic interface to read and store values in
- * the internal flash of a microcontroller.
- *
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-interface InternalFlash {
-  command error_t write(void* addr, void* buf, uint16_t size);
-  command error_t read(void* addr, void* buf, uint16_t size);
-}
diff --git a/tos/lib/net/Deluge/extra/tinynode/NetProg_platform.h b/tos/lib/net/Deluge/extra/tinynode/NetProg_platform.h
new file mode 100644 (file)
index 0000000..8b80b52
--- /dev/null
@@ -0,0 +1,39 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#ifndef __NETPROG_PLATFORM_H__
+#define __NETPROG_PLATFORM_H__
+
+void netprog_reboot() {
+  WDTCTL = WDT_ARST_1_9; 
+  while(1);
+}
+
+#endif
diff --git a/tos/lib/net/Deluge/extra/tinynode/README b/tos/lib/net/Deluge/extra/tinynode/README
new file mode 100644 (file)
index 0000000..4b5cd7d
--- /dev/null
@@ -0,0 +1,15 @@
+Deluge T2 for TinyNode
+----------------------------------
+
+
+These files are needed by Deluge T2 to compile for the TinyNode platform. 
+
+Note: 
+
+Reprogramming fails if the voltage of the node is not above a given 
+threshold. Currently, this is set to 2.7V, which may be too high if 
+you run your mote on batteries. In this case, set the value of
+VTHRESH in the ReprogramGaurdP.nc file to a different value. 
+
+In case you wish not to test the voltage at all, modify ReprogramGuardP.nc
+s.t. the command okToProgram() posts readDone with SUCCESS. 
\ No newline at end of file
diff --git a/tos/lib/net/Deluge/extra/tinynode/ReprogramGuardC.nc b/tos/lib/net/Deluge/extra/tinynode/ReprogramGuardC.nc
new file mode 100644 (file)
index 0000000..9f25e50
--- /dev/null
@@ -0,0 +1,13 @@
+configuration ReprogramGuardC
+{
+  provides interface ReprogramGuard;
+}
+
+implementation
+{
+  components ReprogramGuardP;
+  components new VoltageC();
+  
+  ReprogramGuard = ReprogramGuardP;
+  ReprogramGuardP.Voltage -> VoltageC;
+}
diff --git a/tos/lib/net/Deluge/extra/tinynode/ReprogramGuardP.nc b/tos/lib/net/Deluge/extra/tinynode/ReprogramGuardP.nc
new file mode 100644 (file)
index 0000000..2a3b010
--- /dev/null
@@ -0,0 +1,18 @@
+module ReprogramGuardP {
+  provides interface ReprogramGuard;
+  uses interface Read<uint16_t> as Voltage;
+}
+
+implementation {
+  enum {
+    VTHRESH = 0xE66, // 2.7V
+  };
+
+  command error_t ReprogramGuard.okToProgram() {
+    return call Voltage.read();
+  }
+
+  event void Voltage.readDone(error_t result, uint16_t val) {
+    signal ReprogramGuard.okToProgramDone(result == SUCCESS && val > VTHRESH);
+  }
+}
diff --git a/tos/lib/net/Deluge/extra/tinynode/TOSBoot_platform.h b/tos/lib/net/Deluge/extra/tinynode/TOSBoot_platform.h
new file mode 100644 (file)
index 0000000..87e1756
--- /dev/null
@@ -0,0 +1,38 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * @author  Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#ifndef __TOSBOOT_PLATFORM_H__
+#define __TOSBOOT_PLATFORM_H__
+
+enum {
+  TOSBOOT_ARGS_ADDR = 0x70,      // address of TOSBoot args in internal flash
+  TOSBOOT_GESTURE_MAX_COUNT = 3, // number of resets to force golden image
+  TOSBOOT_GOLDEN_IMG_ADDR = 0x0L, // address of the golden image in external flash
+  TOSBOOT_INT_PAGE_SIZE = 512L,  // size of each internal program flash page
+};
+
+#endif
index 68ffc4669263593dff6ecbd696620fe261e09929..12e9d5bd2a5deefc667015dfd3c772ae8754b29b 100644 (file)
@@ -168,7 +168,7 @@ implementation {
   event void Timer.fired() {
     uint8_t i;
     uint32_t dt = call Timer.getdt();
-
+    dbg("Trickle", "Trickle Sub-timer fired\n");
     for (i = 0; i < count; i++) {
       uint32_t remaining = trickles[i].time;
       if (remaining != 0) {
@@ -176,11 +176,12 @@ implementation {
        if (remaining == 0) {
          if (trickles[i].count < k) {
            atomic {
+             dbg("Trickle", "Trickle: mark timer %hhi as pending\n", i);
              call Pending.set(i);
            }
            post timerTask();
          }
-
+         call Changed.set(i);
          generateTime(i);
            
          /* Note that this logic is not the exact trickle algorithm.
@@ -191,9 +192,6 @@ implementation {
           */
          trickles[i].count = 0;
        }
-       else {
-         trickles[i].time = remaining;
-       }
       }
     }
     adjustTimer();
@@ -213,26 +211,42 @@ implementation {
        
     for (i = 0; i < count; i++) {
       uint32_t timeRemaining = trickles[i].time;
-      if (timeRemaining != 0) {
-       atomic {
-         if (!call Changed.get(i)) {
-           call Changed.clear(i);
+      dbg("Trickle", "Adjusting: timer %hhi (%u)\n", i, timeRemaining);
+
+      if (timeRemaining == 0) { // Not running, go to next timer
+       continue;
+      }
+      
+      atomic {
+       if (!call Changed.get(i)) {
+         if (timeRemaining > elapsed) {
+           dbg("Trickle", "  not changed, elapse time remaining to %u.\n", trickles[i].time - elapsed);
            timeRemaining -= elapsed;
+           trickles[i].time -= elapsed;
+         }
+         else { // Time has already passed, so fire immediately
+           dbg("Trickle", "  not changed, ready to elapse, fire immediately\n");
+           timeRemaining = 1;
+           trickles[i].time = 1;
          }
        }
-       if (!set) {
-         lowest = timeRemaining;
-         set = TRUE;
-       }
-       else if (timeRemaining < lowest) {
-         lowest = timeRemaining;
+       else {
+         dbg("Trickle", "  changed, fall through.\n");
+         call Changed.clear(i);
        }
       }
+      if (!set) {
+       lowest = timeRemaining;
+       set = TRUE;
+      }
+      else if (timeRemaining < lowest) {
+       lowest = timeRemaining;
+      }
     }
+    
     if (set) {
       uint32_t timerVal = lowest;
-      timerVal = timerVal;
-      dbg("Trickle", "Starting time with time %u.\n", timerVal);
+      dbg("Trickle", "Starting sub-timer with interval %u.\n", timerVal);
       call Timer.startOneShot(timerVal);
     }
     else {
@@ -262,7 +276,7 @@ implementation {
     rval = call Random.rand16() % (trickles[id].period << (scale - 1));
     newTime += rval;
     
-    trickles[id].remainder = (trickles[id].period << scale) - newTime;
+    trickles[id].remainder = (((uint32_t)trickles[id].period) << scale) - newTime;
     trickles[id].time += newTime;
     dbg("Trickle,TrickleTimes", "Generated time for %hhu with period %hu (%u) is %u (%i + %hu)\n", id, trickles[id].period, (uint32_t)trickles[id].period << scale, trickles[id].time, (trickles[id].period << (scale - 1)), rval);
   }
diff --git a/tos/lib/net/blip/ICMP.h b/tos/lib/net/blip/ICMP.h
new file mode 100644 (file)
index 0000000..eac35a6
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _ICMP_H_
+#define _ICMP_H_
+
+enum {
+  ICMP_EXT_TYPE_PREFIX = 3,
+  ICMP_EXT_TYPE_BEACON = 17,
+};
+
+#ifndef LOW_POWER_LISTENING     /* parameters for CSMA MAC */
+enum {
+  // jitter start requests by 10 seconds
+  TRICKLE_JITTER = 10240,
+  // have a trickle timer with a period of 4
+  TRICKLE_PERIOD = 4096,
+
+  // send a maximum of three trickle messages
+  TRICKLE_MAX = (TRICKLE_PERIOD << 5),
+  
+};
+#else  /* parameters for LPL */
+enum {
+  // have a trickle timer with a period of 4
+  TRICKLE_PERIOD = 16384L, 
+  // jitter start requests by 10 seconds
+  TRICKLE_JITTER = TRICKLE_PERIOD,
+
+  // send a maximum of three trickle messages
+  TRICKLE_MAX = (TRICKLE_PERIOD << 5),
+  
+};
+#endif
+
+typedef nx_struct icmp6_echo_hdr {
+  nx_uint8_t        type;     /* type field */
+  nx_uint8_t        code;     /* code field */
+  nx_uint16_t       cksum;    /* checksum field */
+  nx_uint16_t       ident;
+  nx_uint16_t       seqno;
+} icmp_echo_hdr_t;
+
+typedef nx_struct radv {
+  nx_uint8_t        type;
+  nx_uint8_t        code;
+  nx_uint16_t       cksum;
+  nx_uint8_t        hlim;
+  nx_uint8_t        flags;
+  nx_uint16_t       lifetime;
+  nx_uint32_t       reachable_time;
+  nx_uint32_t       retrans_time;
+  nx_uint8_t        options[0];
+} radv_t;
+
+typedef nx_struct rsol {
+  nx_uint8_t type;
+  nx_uint8_t code;
+  nx_uint16_t cksum;
+  nx_uint32_t reserved;
+} rsol_t;
+
+typedef nx_struct rpfx {
+  nx_uint8_t type;
+  nx_uint8_t length;
+  nx_uint8_t pfx_len;
+  nx_uint8_t flags;
+  nx_uint32_t valid_lifetime;
+  nx_uint32_t preferred_lifetime;
+  nx_uint32_t reserved;
+  nx_uint8_t  prefix[16];
+} pfx_t;
+
+typedef nx_struct {
+  nx_uint8_t type;
+  nx_uint8_t length;
+  nx_uint16_t metric;
+  nx_uint16_t seqno;
+  nx_uint8_t pad[2];
+} rqual_t;
+
+struct icmp_stats {
+  uint16_t seq;
+  uint8_t ttl;
+  uint32_t rtt;
+};
+
+#endif
diff --git a/tos/lib/net/blip/ICMPResponderC.nc b/tos/lib/net/blip/ICMPResponderC.nc
new file mode 100644 (file)
index 0000000..1438171
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <6lowpan.h>
+
+configuration ICMPResponderC {
+  provides interface ICMP;
+  provides interface ICMPPing[uint16_t client];
+  provides interface Statistics<icmp_statistics_t>;
+} implementation {
+  components NoLedsC as LedsC;
+  components IPDispatchC, IPRoutingP, ICMPResponderP, IPAddressC;
+
+  ICMP = ICMPResponderP;
+  ICMPPing = ICMPResponderP;
+  Statistics = ICMPResponderP;
+
+  ICMPResponderP.Leds -> LedsC;
+
+  ICMPResponderP.IP -> IPDispatchC.IP[IANA_ICMP];
+
+  ICMPResponderP.IPAddress -> IPAddressC;
+
+  ICMPResponderP.IPRouting -> IPRoutingP;
+
+  components RandomC;
+  ICMPResponderP.Random -> RandomC;
+
+  components new TimerMilliC() as STimer,
+    new TimerMilliC() as ATimer,
+    new TimerMilliC() as PTimer;
+  ICMPResponderP.Solicitation -> STimer;
+  ICMPResponderP.Advertisement -> ATimer;
+  ICMPResponderP.PingTimer -> PTimer;
+
+  components HilTimerMilliC;
+  ICMPResponderP.LocalTime -> HilTimerMilliC;
+}
diff --git a/tos/lib/net/blip/ICMPResponderP.nc b/tos/lib/net/blip/ICMPResponderP.nc
new file mode 100644 (file)
index 0000000..2a9b98f
--- /dev/null
@@ -0,0 +1,446 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <lib6lowpan.h>
+#include <6lowpan.h>
+#include <ip_malloc.h>
+#include <Statistics.h>
+#include "in_cksum.h"
+#include "PrintfUART.h"
+#include "ICMP.h"
+
+extern uint8_t multicast_prefix[8];
+
+module ICMPResponderP {
+  provides interface ICMP;
+  provides interface ICMPPing[uint16_t client];
+  provides interface Statistics<icmp_statistics_t>;
+
+  uses interface IP;
+  uses interface IPAddress;
+
+  uses interface Leds;
+
+  uses interface Timer<TMilli> as Solicitation;
+  uses interface Timer<TMilli> as Advertisement;
+  uses interface Timer<TMilli> as PingTimer;
+  uses interface LocalTime<TMilli>;
+  uses interface Random;
+
+  uses interface IPRouting;
+
+} implementation {
+
+  icmp_statistics_t stats;
+  uint32_t solicitation_period;
+  uint32_t advertisement_period;
+  uint16_t nd_seqno = 0;
+
+  uint16_t ping_seq, ping_n, ping_rcv, ping_ident;
+  struct in6_addr ping_dest;
+
+#ifdef PRINTFUART_ENABLED
+#undef dbg
+#define dbg(X, fmt, args ...) printfUART(fmt, ## args)
+#endif
+
+  command uint16_t ICMP.cksum(struct split_ip_msg *msg, uint8_t nxt_hdr) {
+    return msg_cksum(msg, nxt_hdr);
+  }
+
+
+  command void ICMP.sendSolicitations() {
+    uint16_t jitter = (call Random.rand16()) % TRICKLE_JITTER;
+    if (call Solicitation.isRunning()) return;
+    solicitation_period = TRICKLE_PERIOD;
+    call Solicitation.startOneShot(jitter);
+  }
+
+  command void ICMP.sendAdvertisements() {
+
+
+    uint16_t jitter = (call Random.rand16()) % TRICKLE_JITTER;
+    if (call Advertisement.isRunning()) return;
+    advertisement_period = TRICKLE_PERIOD;
+    call Advertisement.startOneShot(jitter);
+  }
+
+  command void ICMP.sendTimeExceeded(struct ip6_hdr *hdr, unpack_info_t *u_info, uint16_t amount_here) {
+    uint8_t i_hdr_buf[sizeof(struct icmp6_hdr) + 4];
+    struct split_ip_msg *msg = (struct split_ip_msg *)ip_malloc(sizeof(struct split_ip_msg));
+    struct generic_header g_hdr[3];
+    struct icmp6_hdr *i_hdr = (struct icmp6_hdr *)i_hdr_buf;
+
+    if (msg == NULL) return;
+
+    dbg("ICMPResponder", "send time exceeded\n");
+
+    msg->headers = NULL;
+    msg->data = u_info->payload_start;
+    msg->data_len = amount_here;
+
+    // make sure to include the udp header if necessary
+    if (u_info->nxt_hdr == IANA_UDP) {
+      g_hdr[2].hdr.udp = (struct udp_hdr *)u_info->transport_ptr;
+      g_hdr[2].len = sizeof(struct udp_hdr);
+      g_hdr[2].next = NULL;
+      
+      // since the udp headers are included in the offset we need to
+      // add that length so the payload length in the encapsulated
+      // packet will be correct.
+      hdr->plen = htons(ntohs(hdr->plen) + sizeof(struct udp_hdr));
+      msg->headers = &g_hdr[2];
+    }
+    // the fields in the packed packet is not necessarily the same as
+    // the fields in canonical packet which was packed.  This is due
+    // to the insertion of transient routing headers.
+    hdr->nxt_hdr = u_info->nxt_hdr;
+    hdr->plen = htons(ntohs(hdr->plen) - u_info->payload_offset);
+
+    // the IP header is part of the payload
+    g_hdr[1].hdr.data = (void *)hdr;
+    g_hdr[1].len = sizeof(struct ip6_hdr);
+    g_hdr[1].next = msg->headers;
+    msg->headers = &g_hdr[1];
+
+    // and is preceeded by the icmp time exceeded message
+    g_hdr[0].hdr.data = (void *)i_hdr;
+    g_hdr[0].len = sizeof(struct icmp6_hdr) + 4;
+    g_hdr[0].next = msg->headers;
+    msg->headers = &g_hdr[0];
+
+    ip_memcpy(&msg->hdr.ip6_dst, &hdr->ip6_src, 16);
+    call IPAddress.getIPAddr(&msg->hdr.ip6_src);
+
+    i_hdr->type = ICMP_TYPE_ECHO_TIME_EXCEEDED;
+    i_hdr->code = ICMP_CODE_HOPLIMIT_EXCEEDED;
+    i_hdr->cksum = 0;
+    ip_memclr((void *)(i_hdr + 1), 4);
+
+    msg->hdr.nxt_hdr = IANA_ICMP;
+
+    i_hdr->cksum = htons(call ICMP.cksum(msg, IANA_ICMP));
+
+    call IP.send(msg);
+
+    ip_free(msg);
+  }
+  /*
+   * Solicitations
+   */ 
+  void sendSolicitation() {
+    struct split_ip_msg *ipmsg = (struct split_ip_msg *)ip_malloc(sizeof(struct split_ip_msg) + sizeof(rsol_t));
+    rsol_t *msg = (rsol_t *)(ipmsg + 1);
+
+    if (ipmsg == NULL) return;
+
+    BLIP_STATS_INCR(stats.sol_tx);
+
+    msg->type = ICMP_TYPE_ROUTER_SOL;
+    msg->code = 0;
+    msg->cksum = 0;
+    msg->reserved = 0;
+
+    ipmsg->headers = NULL;
+    ipmsg->data = (void *)msg;
+    ipmsg->data_len = sizeof(rsol_t);
+    
+    // this is required for solicitation messages
+    ipmsg->hdr.hlim = 0xff;
+
+
+    call IPAddress.getLLAddr(&ipmsg->hdr.ip6_src);
+    ip_memclr((uint8_t *)&ipmsg->hdr.ip6_dst, 16);
+    ipmsg->hdr.ip6_dst.s6_addr16[0] = htons(0xff02);
+    ipmsg->hdr.ip6_dst.s6_addr16[7] = htons(2);
+
+    msg->cksum = call ICMP.cksum(ipmsg, IANA_ICMP);
+
+    call IP.send(ipmsg);
+
+    ip_free(ipmsg);
+  }
+
+  void sendPing(struct in6_addr *dest, uint16_t seqno) {
+    struct split_ip_msg *ipmsg = (struct split_ip_msg *)ip_malloc(sizeof(struct split_ip_msg) + 
+                                                                  sizeof(icmp_echo_hdr_t) + 
+                                                                  sizeof(nx_uint32_t));
+    icmp_echo_hdr_t *e_hdr = (icmp_echo_hdr_t *)ipmsg->next;
+    nx_uint32_t *sendTime = (nx_uint32_t *)(e_hdr + 1);
+
+    if (ipmsg == NULL) return;
+    ipmsg->headers = NULL;
+    ipmsg->data = (void *)e_hdr;
+    ipmsg->data_len = sizeof(icmp_echo_hdr_t) + sizeof(nx_uint32_t);
+
+    e_hdr->type = ICMP_TYPE_ECHO_REQUEST;
+    e_hdr->code = 0;
+    e_hdr->cksum = 0;
+    e_hdr->ident = ping_ident;
+    e_hdr->seqno = seqno;
+    *sendTime = call LocalTime.get();
+
+    memcpy(&ipmsg->hdr.ip6_dst, dest->s6_addr, 16);
+    call IPAddress.getIPAddr(&ipmsg->hdr.ip6_src);
+
+    e_hdr->cksum = call ICMP.cksum(ipmsg,IANA_ICMP);
+
+    call IP.send(ipmsg);
+    ip_free(ipmsg);
+  }
+
+  /*
+   * Router advertisements
+   */ 
+  void handleRouterAdv(void *payload, uint16_t len, struct ip_metadata *meta) {
+    
+    radv_t *r = (radv_t *)payload;
+    pfx_t  *pfx = (pfx_t *)(r->options);
+    rqual_t *beacon = (rqual_t *)(pfx + 1);
+
+    if (len > sizeof(radv_t) + sizeof(pfx_t) && 
+        beacon->type == ICMP_EXT_TYPE_BEACON) {
+
+      printfUART("beacon seqno: %i my seqno: %i\n", beacon->seqno, nd_seqno);
+
+      if (beacon->seqno > nd_seqno || 
+          (nd_seqno > 0 && beacon->seqno == 0) ||
+          !call IPRouting.hasRoute()) {
+        call IPRouting.reset();
+        nd_seqno = beacon->seqno;
+      }
+
+      if (beacon->seqno == nd_seqno) {
+        call IPRouting.reportAdvertisement(meta->sender, r->hlim,
+                                           meta->lqi, beacon->metric);
+        // push out the seqno update
+        // call Advertisement.stop();
+        // call ICMP.sendAdvertisements();
+
+        if (pfx->type != ICMP_EXT_TYPE_PREFIX) return;
+
+        call IPAddress.setPrefix((uint8_t *)pfx->prefix);
+      }
+
+
+      dbg("ICMPResponder", " * beacon cost: 0x%x\n", beacon->metric);
+    } else {
+        dbg("ICMPResponder", " * no beacon cost\n");
+    }
+
+
+    // TODO : get short address here...
+  }
+
+  void sendAdvertisement() {
+    struct split_ip_msg *ipmsg = (struct split_ip_msg *)ip_malloc(sizeof(struct split_ip_msg) + 
+                                                                  sizeof(radv_t) + 
+                                                                  sizeof(pfx_t) +
+                                                                  sizeof(rqual_t));
+    uint16_t len = sizeof(radv_t);
+    radv_t *r = (radv_t *)(ipmsg + 1);
+    pfx_t *p = (pfx_t *)r->options;
+    rqual_t *q = (rqual_t *)(p + 1);
+
+    if (ipmsg == NULL) return;
+    // don't sent the advertisement if we don't have a valid route
+    if (!call IPRouting.hasRoute()) {
+      ip_free(ipmsg);
+      return;
+    }
+    BLIP_STATS_INCR(stats.adv_tx);
+
+    r->type = ICMP_TYPE_ROUTER_ADV;
+    r->code = 0;
+    r->hlim = call IPRouting.getHopLimit();
+    r->flags = 0;
+    r->lifetime = 1;
+    r->reachable_time = 0;
+    r->retrans_time = 0;
+
+    ipmsg->hdr.hlim = 0xff;
+    
+    if (globalPrefix) {
+      len += sizeof(pfx_t);
+      p->type = ICMP_EXT_TYPE_PREFIX;
+      p->length = sizeof(pfx_t) >> 3;
+      p->pfx_len = 64;
+      memcpy(p->prefix, call IPAddress.getPublicAddr(), 8);
+    }
+
+    len += sizeof(rqual_t);
+    q->type = ICMP_EXT_TYPE_BEACON;
+    q->length = sizeof(rqual_t) >> 3;;
+    q->metric = call IPRouting.getQuality();
+    q->seqno = nd_seqno;
+
+    call IPAddress.getLLAddr(&ipmsg->hdr.ip6_src);
+    ip_memclr((uint8_t *)&ipmsg->hdr.ip6_dst, 16);
+    ipmsg->hdr.ip6_dst.s6_addr16[0] = htons(0xff02);
+    ipmsg->hdr.ip6_dst.s6_addr16[7] = htons(1);
+
+    //dbg("ICMPResponder", "My Address: [0x%x] [0x%x] [0x%x] [0x%x]\n", ipmsg->hdr.src_addr[12], ipmsg->hdr.src_addr[13], ipmsg->hdr.src_addr[14], ipmsg->hdr.src_addr[15]);
+    dbg("ICMPResponder", "adv hop limit: 0x%x\n", r->hlim);
+
+    if (r->hlim >= 0xf0) {
+      ip_free(ipmsg);
+      return;
+    }
+
+    ipmsg->data = (void *)r;
+    ipmsg->data_len = len;
+    ipmsg->headers = NULL;
+
+    r->cksum = 0;
+    r->cksum = call ICMP.cksum(ipmsg, IANA_ICMP);
+
+    call IP.send(ipmsg);
+    ip_free(ipmsg);
+  }
+
+
+  event void IP.recv(struct ip6_hdr *iph,
+                     void *payload, 
+                     struct ip_metadata *meta) {
+    icmp_echo_hdr_t *req = (icmp_echo_hdr_t *)payload;
+    uint16_t len = ntohs(iph->plen);
+    BLIP_STATS_INCR(stats.rx);
+  
+    // for checksum calculation
+    printfUART ("icmp type: 0x%x code: 0x%x cksum: 0x%x ident: 0x%x seqno: 0x%x len: 0x%x\n",
+                req->type, req->code, req->cksum, req->ident, req->seqno, len);
+
+    switch (req->type) {
+    case ICMP_TYPE_ROUTER_ADV:
+      handleRouterAdv(payload, len, meta);
+      BLIP_STATS_INCR(stats.adv_rx);
+      break;
+    case ICMP_TYPE_ROUTER_SOL:
+      // only reply to solicitations if we have established a default route.
+      if (call IPRouting.hasRoute()) {
+          call ICMP.sendAdvertisements();
+      }
+      BLIP_STATS_INCR(stats.sol_rx);
+      break;
+    case ICMP_TYPE_ECHO_REPLY:
+      {
+        nx_uint32_t *sendTime = (nx_uint32_t *)(req + 1);
+        struct icmp_stats p_stat;
+        p_stat.seq = req->seqno;
+        p_stat.ttl = iph->hlim;
+        p_stat.rtt = (call LocalTime.get()) - (*sendTime);
+        signal ICMPPing.pingReply[req->ident](&iph->ip6_src, &p_stat);
+        ping_rcv++;
+        BLIP_STATS_INCR(stats.echo_rx);
+      }
+      break;
+    case ICMP_TYPE_ECHO_REQUEST:
+      {
+        // send a ping reply.
+        struct split_ip_msg msg;
+        msg.headers = NULL;
+        msg.data = payload;
+        msg.data_len = len;
+
+        memcpy(&msg.hdr.ip6_dst, &iph->ip6_src, 16);      
+        call IPAddress.setSource(&msg.hdr);
+        
+        req->type = ICMP_TYPE_ECHO_REPLY;
+        req->code = 0;
+        req->cksum = 0;
+        req->cksum = call ICMP.cksum(&msg, IANA_ICMP);
+        
+        // remember, this can't really fail in a way we care about
+        call IP.send(&msg);
+        BLIP_STATS_INCR(stats.echo_tx);
+        break;
+      }
+    default:
+      BLIP_STATS_INCR(stats.unk_rx);
+    }
+  }
+
+
+  event void Solicitation.fired() {
+    sendSolicitation();
+    dbg("ICMPResponder", "solicitation period: 0x%x max: 0x%x seq: %i\n", solicitation_period, TRICKLE_MAX, nd_seqno);
+    solicitation_period <<= 1;
+    if (solicitation_period < TRICKLE_MAX) {
+      call Solicitation.startOneShot(solicitation_period);
+    } else {
+      signal ICMP.solicitationDone();
+    }
+  }
+
+  event void Advertisement.fired() {
+    dbg("ICMPResponder", "==> Sending router advertisement\n");
+    sendAdvertisement();
+    advertisement_period <<= 1;
+    if (advertisement_period < TRICKLE_MAX) {
+      call Advertisement.startOneShot(advertisement_period);
+    }
+  }
+
+
+  
+  command error_t ICMPPing.ping[uint16_t client](struct in6_addr *target, uint16_t period, uint16_t n) {
+    if (call PingTimer.isRunning()) return ERETRY;
+    call PingTimer.startPeriodic(period);
+
+    memcpy(&ping_dest, target, 16);
+    ping_n = n;
+    ping_seq = 0;
+    ping_rcv = 0;
+    ping_ident = client;
+    return SUCCESS;
+  }
+
+  event void PingTimer.fired() {
+    // send a ping request
+    if (ping_seq == ping_n) {
+      signal ICMPPing.pingDone[ping_ident](ping_rcv, ping_n);
+      call PingTimer.stop();
+      return;
+    }
+    sendPing(&ping_dest, ping_seq);
+    ping_seq++;
+  }
+
+
+
+  command void Statistics.get(icmp_statistics_t *statistics) {
+    memcpy(statistics, &stats, sizeof(icmp_statistics_t));
+  }
+  
+  command void Statistics.clear() {
+    ip_memclr((uint8_t *)&stats, sizeof(icmp_statistics_t));
+  }
+
+  default event void ICMPPing.pingReply[uint16_t client](struct in6_addr *source, 
+                                                         struct icmp_stats *ping_stats) {
+  }
+
+  default event void ICMPPing.pingDone[uint16_t client](uint16_t n, uint16_t m) {
+
+  }
+
+}
diff --git a/tos/lib/net/blip/IPAddressC.nc b/tos/lib/net/blip/IPAddressC.nc
new file mode 100644 (file)
index 0000000..c096468
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+
+configuration IPAddressC {
+  provides interface IPAddress;
+
+} implementation {
+  components IPAddressP, ActiveMessageAddressC;
+
+  IPAddress = IPAddressP;
+
+#ifndef SIM
+  IPAddressP.ActiveMessageAddress -> ActiveMessageAddressC;
+#else
+  IPAddressP.setAmAddress -> ActiveMessageAddressC;
+#endif
+}
diff --git a/tos/lib/net/blip/IPAddressP.nc b/tos/lib/net/blip/IPAddressP.nc
new file mode 100644 (file)
index 0000000..0a9bda9
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <6lowpan.h>
+
+// defined in lib6lowpan
+extern struct in6_addr __my_address;
+extern uint8_t globalPrefix;
+
+module IPAddressP {
+  provides interface IPAddress;
+
+#ifndef SIM
+  uses interface ActiveMessageAddress;
+#else 
+  uses async command void setAmAddress(am_addr_t a);
+#endif
+} implementation {
+
+
+  command ieee154_saddr_t IPAddress.getShortAddr() {
+    return TOS_NODE_ID;
+  }
+
+  command void IPAddress.setShortAddr(ieee154_saddr_t newAddr) {
+    TOS_NODE_ID = newAddr;
+#ifndef SIM
+    call ActiveMessageAddress.setAddress(call ActiveMessageAddress.amGroup(), newAddr);
+#else
+    call setAmAddress(newAddr);
+#endif
+  }
+
+  command void IPAddress.getLLAddr(struct in6_addr *addr) {
+    __my_address.s6_addr16[7] = htons(TOS_NODE_ID);
+    memcpy(addr->s6_addr, linklocal_prefix, 8);
+    memcpy(&addr->s6_addr[8], &__my_address.s6_addr[8], 8);
+  }
+
+  command void IPAddress.getIPAddr(struct in6_addr *addr) {
+    __my_address.s6_addr16[7] = htons(TOS_NODE_ID);
+    memcpy(addr, &__my_address, 16);
+  }
+
+  command struct in6_addr *IPAddress.getPublicAddr() {
+    __my_address.s6_addr16[7] = htons(TOS_NODE_ID);
+    return &__my_address;
+  }
+
+  command void IPAddress.setPrefix(uint8_t *pfx) {
+    ip_memclr(__my_address.s6_addr, sizeof(struct in6_addr));
+    ip_memcpy(__my_address.s6_addr, pfx, 8);
+    globalPrefix = 1;
+  }
+
+  command bool IPAddress.haveAddress() {
+    return globalPrefix;
+  }
+
+  command void IPAddress.setSource(struct ip6_hdr *hdr) {
+    enum { LOCAL, GLOBAL } type = GLOBAL;
+      
+    if (hdr->ip6_dst.s6_addr[0] == 0xff) {
+      // link-local multicast sent from local address
+      if ((hdr->ip6_dst.s6_addr[1] & 0x0f) <= 0x2) {
+        type = LOCAL;
+      }
+    } else if (hdr->ip6_dst.s6_addr[0] == 0xfe) {
+      // link-local destinations sent from link-local
+      if ((hdr->ip6_dst.s6_addr[1] & 0xf0) <= 0x80) {
+        type = LOCAL;
+      }
+    }
+
+    if (type == GLOBAL && call IPAddress.haveAddress()) {
+      call IPAddress.getIPAddr(&hdr->ip6_src);
+    } else {
+      call IPAddress.getLLAddr(&hdr->ip6_src);
+    }
+
+  }
+
+
+#ifndef SIM
+  async event void ActiveMessageAddress.changed() {
+
+  }
+#endif
+
+}
diff --git a/tos/lib/net/blip/IPDispatch.h b/tos/lib/net/blip/IPDispatch.h
new file mode 100644 (file)
index 0000000..2435899
--- /dev/null
@@ -0,0 +1,243 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _IPDISPATCH_H_
+#define _IPDISPATCH_H_
+
+#include <message.h>
+#include <lib6lowpan.h>
+#include <Statistics.h>
+
+enum {
+  N_PARENTS = 3,
+  N_EPOCHS = 2,
+  N_EPOCHS_COUNTED = 1,
+  N_RECONSTRUCTIONS = 2,
+  N_FORWARD_ENT = IP_NUMBER_FRAGMENTS,
+};
+
+enum {
+  CONF_EVICT_THRESHOLD = 5, // Neighbor is 'mature'
+  CONF_PROM_THRESHOLD = 5, // Acceptable threshold for promotion
+  MAX_CONSEC_FAILURES = 11, // Max Failures before reroute is attempted
+  PATH_COST_DIFF_THRESH = 10, // Threshold for 'similar' path costs
+  LQI_DIFF_THRESH = 10, // Threshold for 'similar' LQI's
+  LINK_EVICT_THRESH = 50, // ETX * 10
+  RANDOM_ROUTE = 20, //Percentage of time to select random default route
+  LQI_ADMIT_THRESH = 0x200, 
+};
+
+/* chip-specific lqi values */
+uint16_t adjustLQI(uint8_t val);
+
+
+enum {
+  WITHIN_THRESH = 1,
+  ABOVE_THRESH = 2,
+  BELOW_THRESH = 3,
+};
+
+#ifndef LOW_POWER_LISTENING
+enum {
+  TGEN_BASE_TIME = 512,
+  TGEN_MAX_INTERVAL = 60L * 1024L * 5L,
+};
+#else
+enum {
+  TGEN_BASE_TIME = 16384L,
+  TGEN_MAX_INTERVAL = 60L * 1024L * 5L,
+};
+#endif
+
+
+struct epoch_stats {
+  uint16_t success;
+  uint16_t total;
+  uint16_t receptions;
+};
+
+struct report_stats {
+  uint8_t messages;
+  uint8_t transmissions;
+  uint8_t successes;
+};
+
+enum {
+  T_PIN_OFFSET    = 0,
+  T_PIN_MASK      = 1 << T_PIN_OFFSET,
+  T_VALID_OFFSET  = 2,
+  T_VALID_MASK    = 1 << T_VALID_OFFSET,
+  T_MARKED_OFFSET = 3,
+  T_MARKED_MASK   = 1 << T_MARKED_OFFSET,
+  T_MATURE_OFFSET = 4,
+  T_MATURE_MASK   = 1 << T_MATURE_OFFSET,
+  T_EVICT_OFFSET  = 5,
+  T_EVICT_MASK    = 1 << T_EVICT_OFFSET,
+};
+
+enum {
+  // store the top-k neighbors.  This could be a poor topology
+  // formation critera is very dense networks.  we may be able to
+  // really use the fact that the "base" has infinite memory.
+  N_NEIGH = 8,
+  N_LOW_NEIGH = 2,
+  N_FREE_NEIGH = (N_NEIGH - N_LOW_NEIGH),
+  N_FLOW_ENT = 6,
+  N_FLOW_CHOICES = 2,
+  N_PARENT_CHOICES = 3,
+  T_DEF_PARENT = 0xfffd,
+  T_DEF_PARENT_SLOT = 0,
+};
+
+typedef struct {
+  // The extra 2 is because one dest could be from source route, other
+  //  from the dest being a direct neighbor
+  ieee154_saddr_t dest[N_FLOW_CHOICES + N_PARENT_CHOICES + 2];
+  uint8_t   current:4;
+  uint8_t   nchoices:4;
+  uint8_t   retries;
+  uint8_t   actRetries;
+  uint16_t  delay;
+} send_policy_t;
+
+typedef struct {
+  send_policy_t policy;
+  uint8_t frags_sent;
+  bool failed;
+  uint8_t refcount;
+  uint8_t local_flow_label;
+} send_info_t;
+
+typedef struct {
+  send_info_t *info;
+  message_t  *msg;
+} send_entry_t;
+
+typedef struct {
+  uint8_t timeout;
+  ieee154_saddr_t l2_src;
+  uint16_t old_tag;
+  uint16_t new_tag;
+  send_info_t *s_info;
+} forward_entry_t;
+
+/* typedef struct { */
+/*   /\* how to dispatch this packet *\/ */
+/*   union { */
+/*     struct sockaddr_in6 sock; */
+/*     ip6_addr_t src; */
+/*   } address; */
+/*   /\* packet metadata *\/ */
+/*   union { */
+/*     uint16_t udp_port; */
+/*   } dispatch; */
+/*   struct ip_metadata metadata; */
+
+/*   /\* the lib6lowpan reconstruct structure *\/ */
+/*   reconstruct_t recon; */
+/* } ip_recon_t; */
+
+enum {
+  F_VALID_MASK = 0x01,
+  //F_TOTAL_VALID_ENTRY_MASK = 0x80, // For entire entry (not just specific choice)
+  F_FULL_PATH_OFFSET = 1,
+  F_FULL_PATH_MASK = 0x02,
+
+  MAX_PATH_LENGTH = 10,
+  N_FULL_PATH_ENTRIES = (N_FLOW_CHOICES * N_FLOW_ENT),
+};
+  
+struct flow_path {
+  uint8_t path_len;
+  cmpr_ip6_addr_t path[MAX_PATH_LENGTH];
+};
+
+struct f_entry {
+  uint8_t flags;
+  union {
+    struct flow_path *pathE;
+    cmpr_ip6_addr_t nextHop;
+  };
+};
+
+// Need to add another entry to avoid useless padding
+//  Or can make sure that the flow_table has an even
+//  number of entries.
+struct flow_entry {
+  uint8_t flags;
+  uint8_t count;
+  struct flow_match match;
+  struct f_entry entries[N_FLOW_CHOICES];
+};
+
+//#define IS_VALID_SLOT(f) (((f)->entries[0].flags & F_TOTAL_VALID_ENTRY_MASK) == F_TOTAL_VALID_ENTRY_MASK)
+#define IS_VALID_SLOT(f) (((f)->flags & F_VALID_MASK) == F_VALID_MASK)
+//#define SET_VALID_SLOT(f) (f)->entries[0].flags |= F_TOTAL_VALID_ENTRY_MASK
+#define SET_VALID_SLOT(f) (f)->flags |= F_VALID_MASK
+//#define SET_INVALID_SLOT(f) (f)->entries[0].flags &= ~F_TOTAL_VALID_ENTRY_MASK
+#define SET_INVALID_SLOT(f) (f)->flags &= ~F_VALID_MASK
+#define IS_VALID_ENTRY(e) (((e).flags & F_VALID_MASK) == F_VALID_MASK)
+#define SET_VALID_ENTRY(e) (e).flags |= F_VALID_MASK
+#define SET_INVALID_ENTRY(e) (e).flags &= ~F_VALID_MASK
+#define IS_FULL_TYPE(e) (((e).flags & F_FULL_PATH_MASK) == F_FULL_PATH_MASK)
+#define IS_HOP_TYPE(e) !IS_FULL_TYPE(e)
+#define SET_FULL_TYPE(e) ((e).flags |= F_FULL_PATH_MASK)
+#define SET_HOP_TYPE(e) ((e).flags &= ~F_FULL_PATH_MASK)
+  
+
+struct neigh_entry {
+  uint8_t flags;
+  uint8_t hops; // Put this before neighbor to remove potential padding issues
+  ieee154_saddr_t neighbor;
+  uint16_t costEstimate;
+  uint16_t linkEstimate;
+  struct epoch_stats stats[N_EPOCHS];
+}
+#ifdef MIG
+ __attribute__((packed));
+#else
+;
+#endif
+
+#define IS_NEIGH_VALID(e) (((e)->flags & T_VALID_MASK) == T_VALID_MASK)
+#define SET_NEIGH_VALID(e) ((e)->flags |= T_VALID_MASK)
+#define SET_NEIGH_INVALID(e) ((e)->flags &= ~T_VALID_MASK)
+#define PINNED(e) (((e)->flags & T_PIN_MASK) == T_PIN_MASK)
+#define REMOVABLE(e) (((e)->refCount == 0) && !(PINNED(e)))
+#define SET_PIN(e) (((e)->flags |= T_PIN_MASK))
+#define UNSET_PIN(e) (((e)->flags &= ~T_PIN_MASK))
+#define IS_MARKED(e) (((e)->flags & T_MARKED_MASK) == T_MARKED_MASK)
+#define SET_MARK(e) (((e)->flags |= T_MARKED_MASK))
+#define UNSET_MARK(e) (((e)->flags &= ~T_MARKED_MASK))
+#define IS_MATURE(e) (((e)->flags & T_MATURE_MASK) == T_MATURE_MASK)
+#define SET_MATURE(e) ((e)->flags |= T_MATURE_MASK)
+#define SET_EVICT(e) ((e).flags |= T_EVICT_MASK)
+#define UNSET_EVICT(e) ((e).flags &= ~T_EVICT_MASK)
+#define SHOULD_EVICT(e) ((e).flags & T_EVICT_MASK)
+
+
+typedef enum {
+  S_FORWARD,
+  S_REQ,
+} send_type_t;
+
+
+#endif
diff --git a/tos/lib/net/blip/IPDispatchC.nc b/tos/lib/net/blip/IPDispatchC.nc
new file mode 100644 (file)
index 0000000..6abcc5a
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/*
+ * Provides message dispatch based on the next header field of IP packets.
+ *
+ */
+#include "IPDispatch.h"
+
+configuration IPDispatchC {
+  provides {
+    interface SplitControl;
+    interface IPAddress;
+    interface IP[uint8_t nxt_hdr];
+
+    interface Statistics<ip_statistics_t> as IPStats;
+    interface Statistics<route_statistics_t> as RouteStats;
+    interface Statistics<icmp_statistics_t> as ICMPStats;
+
+  }
+} implementation {
+  
+  components Ieee154MessageC as MessageC; 
+  components MainC, IPDispatchP, IPAddressC, IPRoutingP; 
+  components NoLedsC as LedsC;
+  components RandomC;
+
+  SplitControl = IPDispatchP.SplitControl;
+  IPAddress = IPAddressC;
+  IP = IPDispatchP;
+
+  IPDispatchP.Boot -> MainC;
+
+#ifdef IEEE154FRAMES_ENABLED
+  IPDispatchP.Ieee154Send -> MessageC;
+#else
+  components ResourceSendP;
+  ResourceSendP.SubSend -> MessageC;
+  ResourceSendP.Resource -> MessageC.SendResource[unique(RADIO_SEND_RESOURCE)];
+  IPDispatchP.Ieee154Send -> ResourceSendP.Ieee154Send;
+#endif
+
+  IPDispatchP.Ieee154Receive -> MessageC.Ieee154Receive;
+  IPDispatchP.Packet -> MessageC.Packet;
+#ifdef LOW_POWER_LISTENING
+  IPDispatchP.LowPowerListening -> MessageC;
+#endif
+
+  components ReadLqiC;
+  IPDispatchP.Ieee154Packet -> MessageC;
+  IPDispatchP.PacketLink -> MessageC;
+  IPDispatchP.ReadLqi -> ReadLqiC;
+
+  IPDispatchP.Leds -> LedsC;
+
+  IPDispatchP.IPAddress -> IPAddressC;
+
+  components new TimerMilliC();
+  IPDispatchP.ExpireTimer -> TimerMilliC;
+
+  components new PoolC(message_t, IP_NUMBER_FRAGMENTS) as FragPool;
+
+  components new PoolC(send_entry_t, IP_NUMBER_FRAGMENTS) as SendEntryPool;
+  components new QueueC(send_entry_t *, IP_NUMBER_FRAGMENTS);
+
+  components new PoolC(send_info_t, N_FORWARD_ENT) as SendInfoPool;
+
+  IPDispatchP.FragPool -> FragPool;
+  IPDispatchP.SendEntryPool -> SendEntryPool;
+  IPDispatchP.SendInfoPool  -> SendInfoPool;
+  IPDispatchP.SendQueue -> QueueC;
+
+  components ICMPResponderC;
+  components new TimerMilliC() as TGenTimer;
+  IPDispatchP.ICMP -> ICMPResponderC;
+  IPRoutingP.ICMP  -> ICMPResponderC;
+  IPDispatchP.RadioControl -> MessageC;
+
+  components IPExtensionP;
+  MainC.SoftwareInit -> IPExtensionP.Init;
+  IPDispatchP.InternalIPExtension -> IPExtensionP;
+
+  IPDispatchP.IPRouting -> IPRoutingP;
+  IPRoutingP.Boot -> MainC;
+  IPRoutingP.Leds -> LedsC;
+  IPRoutingP.IPAddress -> IPAddressC;
+  IPRoutingP.Random -> RandomC;
+  IPRoutingP.TrafficGenTimer -> TGenTimer;
+  IPRoutingP.TGenSend -> IPDispatchP.IP[IPV6_NONEXT];
+
+  IPRoutingP.IPExtensions -> IPDispatchP;
+  IPRoutingP.DestinationExt -> IPExtensionP.DestinationExt[0];
+  
+
+  IPStats    = IPDispatchP;
+  RouteStats = IPRoutingP;
+  ICMPStats  = ICMPResponderC;
+
+  components new TimerMilliC() as RouteTimer;
+  IPRoutingP.SortTimer -> RouteTimer;
+
+#ifdef DELUGE
+  components NWProgC;
+#endif
+
+}
diff --git a/tos/lib/net/blip/IPDispatchP.nc b/tos/lib/net/blip/IPDispatchP.nc
new file mode 100644 (file)
index 0000000..746399e
--- /dev/null
@@ -0,0 +1,1073 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/*
+ * This file has the potential to be rather confusing, here are a few
+ * notes about what is happening.  There are several state machines in
+ * this file.  Together, they take care of packet forwarding and
+ * sending (which is accomplished by injecting new packets into the
+ * outgoing queue.)
+ *
+ * Messages enter from two places: either from the bottom (from the
+ * radio), or from the top (from the application).  Messages also
+ * leave from two places: either out over the radio, or up to an
+ * application.
+ *
+ *
+ *    IP.send          ---- - --->   IP.recvfrom
+ *                         \ /
+ *                          X
+ *                         / \
+ *    IEEE154.receive  ---- - --->   IEEE154.send
+ *
+ *
+ *  All of the queueing is done on the output; when each message
+ *  arrives, it is dispatched all the way to an output queue.
+ *
+ *  There are four paths through the system, so here they are:
+ *
+ *  IP.send -> IP.recvfrom       :  local delivery: not implemented
+ *  IP.send -> IEEE154.send      :  enqueue fragments on radio queue
+ *  IEEE154.receive -> IP.recv   :  deliver to this mote : reassemble and deliver
+ *  IEEE154.receive -> IEEE154.send : forwarding : enqueue fragments
+ *
+ *  the IP receive queue
+ *   data structures:  
+ *      recon_cache: holds state about packets which are to be consumed 
+ *               by this mote, and have fragments pending.
+ *
+ *  radio send queue
+ *   data structures:
+ *      send_info_t: packet metadata for a single packet flow through 
+ *                   the mote (could either come from a forwarded stream 
+ *                   or a local send.    
+ *      send_entry_t: the actual queue items, pointing to a fragment  
+ *                   and the packet metadata (send_info_t)
+ *
+ *  extra forwarding structures:
+ *    forward_cache: used to match up incoming fragments with their flow metadata,
+ *               stored in a send_info_t.
+ *    fragment pool: 
+ */
+#include <6lowpan.h>
+#include <lib6lowpan.h>
+#include <ip.h>
+#include <in_cksum.h>
+#include <ip_malloc.h>
+#include "IPDispatch.h"
+#include "table.h"
+#include "PrintfUART.h"
+
+/*
+ * Provides IP layer reception to applications on motes.
+ *
+ * @author Stephen Dawson-Haggerty <stevedh@cs.berkeley.edu>
+ */
+
+module IPDispatchP {
+  provides {
+    interface SplitControl;
+    // interface for protocols not requiring special hand-holding
+    interface IP[uint8_t nxt_hdr];
+
+    interface Statistics<ip_statistics_t>;
+
+    // IPv6 Extension headers are very useful, but somewhat tricky to
+    // handle in a pretty way.  This is my attempt.
+
+    // for inspecting/modifying extension headers on incomming packets
+    interface IPExtensions;
+
+  }
+  uses {
+    interface Boot;
+    interface SplitControl as RadioControl;
+
+    interface ReadLqi;
+    interface Packet;
+
+    interface Ieee154Send;
+    interface Ieee154Packet;
+    interface Receive as Ieee154Receive;
+
+    interface PacketLink;
+
+    // outgoing fragments
+    interface Pool<message_t> as FragPool;
+    interface Pool<send_info_t> as SendInfoPool;
+    interface Pool<send_entry_t> as SendEntryPool;
+    interface Queue<send_entry_t *> as SendQueue;
+
+    interface Timer<TMilli> as ExpireTimer;
+
+    interface IPRouting;
+    interface ICMP;
+
+    interface LowPowerListening;
+
+    interface Leds;
+    
+    interface IPAddress;
+
+    interface InternalIPExtension;
+  }
+} implementation {
+  
+#ifdef PRINTFUART_ENABLED
+#undef dbg
+#define dbg(X, fmt, args...)  printfUART(fmt, ## args)
+#endif
+
+  enum {
+    S_RUNNING,
+    S_STOPPED,
+    S_STOPPING,
+  };
+  uint8_t state = S_STOPPED;
+  bool radioBusy;
+  uint8_t current_local_label = 0;
+  ip_statistics_t stats;
+
+  // this in theory could be arbitrarily large; however, it needs to
+  // be large enough to hold all active reconstructions, and any tags
+  // which we are dropping.  It's important to keep dropped tags
+  // around for a while, or else there are pathological situations
+  // where you continually allocate buffers for packets which will
+  // never complete.
+
+  ////////////////////////////////////////
+  //
+  //
+
+  table_t recon_cache, forward_cache;
+
+
+  // table of packets we are currently receiving fragments from, that
+  // are destined to us
+  reconstruct_t recon_data[N_RECONSTRUCTIONS];
+
+  // table of fragmented flows who are going through us, so we must
+  // remember the next hop.
+  forward_entry_t forward_data[N_FORWARD_ENT];
+
+  //
+  //
+  ////////////////////////////////////////
+
+  task void sendTask();
+
+  void reconstruct_clear(void *ent) {
+    reconstruct_t *recon = (reconstruct_t *)ent;
+    ip_memclr((uint8_t *)&recon->metadata, sizeof(struct ip_metadata));
+    recon->timeout = T_UNUSED;
+    recon->buf = NULL;
+  }
+
+  void forward_clear(void *ent) {
+    forward_entry_t *fwd = (forward_entry_t *)ent;
+    fwd->timeout = T_UNUSED;
+  }
+
+  int forward_unused(void *ent) {
+    forward_entry_t *fwd = (forward_entry_t *)ent;
+    if (fwd->timeout == T_UNUSED) 
+      return 1;
+    return 0;
+  }
+
+  uint16_t forward_lookup_tag;
+  uint16_t forward_lookup_src;
+  int forward_lookup(void *ent) {
+    forward_entry_t *fwd = (forward_entry_t *)ent;
+    if (fwd->timeout > T_UNUSED && 
+        fwd->l2_src == forward_lookup_src &&
+        fwd->old_tag == forward_lookup_tag) {
+      fwd->timeout = T_ACTIVE;
+      return 1;
+    }
+    return 0;
+  }
+  
+
+  send_info_t *getSendInfo() {
+    send_info_t *ret = call SendInfoPool.get();
+    if (ret == NULL) return ret;
+    ret->refcount = 1;
+    ret->failed = FALSE;
+    ret->frags_sent = 0;
+    return ret;
+  }
+#define SENDINFO_INCR(X) ((X)->refcount)++
+#define SENDINFO_DECR(X) if (--((X)->refcount) == 0) call SendInfoPool.put(X)
+
+  command error_t SplitControl.start() {
+    return call RadioControl.start();
+  }
+
+  command error_t SplitControl.stop() {
+    if (!radioBusy) {
+      state = S_STOPPED;
+      return call RadioControl.stop();
+    } else {
+      // if there's a packet in the radio, wait for it to exit before
+      // stopping
+      state = S_STOPPING;
+      return SUCCESS;
+    }
+  }
+
+  event void RadioControl.startDone(error_t error) {
+#ifdef LPL_SLEEP_INTERVAL
+    call LowPowerListening.setLocalWakeupInterval(LPL_SLEEP_INTERVAL);
+#endif
+    if (error == SUCCESS) {
+      call ICMP.sendSolicitations();
+      state = S_RUNNING;
+    }
+    signal SplitControl.startDone(error);
+  }
+
+  event void RadioControl.stopDone(error_t error) {
+    signal SplitControl.stopDone(error);
+  }
+
+  event void Boot.booted() {
+    call Statistics.clear();
+
+    ip_malloc_init();
+
+    table_init(&recon_cache, recon_data, sizeof(reconstruct_t), N_RECONSTRUCTIONS);
+    table_init(&forward_cache, forward_data, sizeof(forward_entry_t), N_FORWARD_ENT);
+
+    table_map(&recon_cache, reconstruct_clear);
+    table_map(&forward_cache, forward_clear);
+
+    radioBusy = FALSE;
+
+    call ExpireTimer.startPeriodic(FRAG_EXPIRE_TIME);
+
+    call SplitControl.start();
+    return;
+  }
+
+  /*
+   *  Receive-side code.
+   */ 
+
+  /*
+   * Logic which must process every received IP datagram.
+   *
+   *  Each IP packet may be consumed and/or forwarded.
+   */
+  void signalDone(reconstruct_t *recon) {
+    struct ip6_hdr *iph = (struct ip6_hdr *)recon->buf;
+
+    signal IP.recv[recon->nxt_hdr](iph, recon->transport_hdr, &recon->metadata);
+    ip_free(recon->buf);
+    recon->timeout = T_UNUSED;
+    recon->buf = NULL;
+  }
+
+  /*
+   * Bulletproof recovery logic is very important to make sure we
+   * don't get wedged with no free buffers.
+   * 
+   * The table is managed as follows:
+   *  - unused entries are marked T_UNUSED
+   *  - entries which 
+   *     o have a buffer allocated
+   *     o have had a fragment reception before we fired
+   *     are marked T_ACTIVE
+   *  - entries which have not had a fragment reception during the last timer period
+   *     and were active are marked T_ZOMBIE
+   *  - zombie receptions are deleted: their buffer is freed and table entry marked unused.
+   *  - when a fragment is dropped, it is entered into the table as T_FAILED1.
+   *     no buffer is allocated
+   *  - when the timer fires, T_FAILED1 entries are aged to T_FAILED2.
+   * - T_FAILED2 entries are deleted.  Incomming fragments with tags
+   *     that are marked either FAILED1 or FAILED2 are dropped; this
+   *     prevents us from allocating a buffer for a packet which we
+   *     have already dropped fragments from.
+   *
+   */ 
+  void reconstruct_age(void *elt) {
+    reconstruct_t *recon = (reconstruct_t *)elt;
+    switch (recon->timeout) {
+    case T_ACTIVE:
+      recon->timeout = T_ZOMBIE; break; // age existing receptions
+    case T_FAILED1:
+      recon->timeout = T_FAILED2; break; // age existing receptions
+    case T_ZOMBIE:
+    case T_FAILED2:
+      // deallocate the space for reconstruction
+      if (recon->buf != NULL) {
+        ip_free(recon->buf);
+      }
+      recon->timeout = T_UNUSED;
+      recon->buf = NULL;
+      break;
+    }
+  }
+
+  void forward_age(void *elt) {
+    forward_entry_t *fwd = (forward_entry_t *)elt;
+    switch (fwd->timeout) {
+    case T_ACTIVE:
+      fwd->timeout = T_ZOMBIE; break; // age existing receptions
+    case T_FAILED1:
+      fwd->timeout = T_FAILED2; break; // age existing receptions
+    case T_ZOMBIE:
+    case T_FAILED2:
+      fwd->s_info->failed = TRUE;
+      SENDINFO_DECR(fwd->s_info);
+      fwd->timeout = T_UNUSED;
+      break;
+    }
+  }
+
+  void ip_print_heap() {
+#ifdef PRINTFUART_ENABLED
+    bndrt_t *cur = (bndrt_t *)heap;
+    while (((uint8_t *)cur)  - heap < IP_MALLOC_HEAP_SIZE) {
+      //printfUART ("heap region start: 0x%x length: %i used: %i\n", 
+                  //cur, (*cur & IP_MALLOC_LEN), (*cur & IP_MALLOC_INUSE) >> 15);
+      cur = (bndrt_t *)(((uint8_t *)cur) + ((*cur) & IP_MALLOC_LEN));
+    }
+#endif
+  }
+
+  event void ExpireTimer.fired() {
+    table_map(&recon_cache, reconstruct_age);
+    table_map(&forward_cache, forward_age);
+
+    /*
+    printfUART("Frag pool size: %i\n", call FragPool.size());
+    printfUART("SendInfo pool size: %i\n", call SendInfoPool.size());
+    printfUART("SendEntry pool size: %i\n", call SendEntryPool.size());
+    printfUART("Forward queue length: %i\n", call SendQueue.size());
+    */
+    ip_print_heap();
+  }
+
+  /*
+   * allocate a structure for recording information about incomming fragments.
+   */
+
+  reconstruct_t *get_reconstruct(ieee154_saddr_t src, uint16_t tag) {
+    reconstruct_t *ret = NULL;
+    int i;
+    for (i = 0; i < N_RECONSTRUCTIONS; i++) {
+      reconstruct_t *recon = (reconstruct_t *)&recon_data[i];
+      dbg("IPDispatch", " 0x%x 0x%x 0x%x\n",  recon->timeout, recon->metadata.sender, recon->tag);
+
+      if (recon->tag == tag &&
+          recon->metadata.sender == src) {
+
+        if (recon->timeout > T_UNUSED) {
+          
+          recon->timeout = T_ACTIVE;
+          return recon;
+
+        } else if (recon->timeout < T_UNUSED) {
+          // if we have already tried and failed to get a buffer, we
+          // need to drop remaining fragments.
+          return NULL;
+        }
+      }
+      if (recon->timeout == T_UNUSED) 
+        ret = recon;
+    }
+    return ret;
+  }
+  
+  /*
+   * This is called before a receive on packets with a source routing header.
+   *
+   * it updates the path stored in the header to remove our address
+   * and include our predicessor.
+   *
+   * However, if this is not a source record path and we are not in the current
+   *  spot, this means we are along the default path and so should invalidate this
+   *  source header.
+   */
+  void updateSourceRoute(ieee154_saddr_t prev_hop, struct ip6_route *sh) {
+    uint16_t my_address = call IPAddress.getShortAddr();
+    uint16_t target_hop = sh->hops[ROUTE_NENTRIES(sh) - sh->segs_remain];
+    if ((sh->type & ~IP6ROUTE_FLAG_MASK) == IP6ROUTE_TYPE_INVAL || sh->segs_remain == 0) return;
+
+    if (target_hop != htons(my_address)) {
+      printfUART("invalidating source route\n");
+
+      if (ROUTE_NENTRIES(sh) >= 2) {
+        sh->hops[0] = htons(prev_hop);
+        sh->hops[1] = target_hop;
+      }
+      sh->type = (sh->type & IP6ROUTE_FLAG_MASK) | IP6ROUTE_TYPE_INVAL;
+    } else {
+      sh->hops[ROUTE_NENTRIES(sh) - sh->segs_remain] = htons(prev_hop);
+      sh->segs_remain--;
+      printfUART("updating source route with prev: 0x%x remaining: %i\n",
+                 prev_hop, sh->segs_remain);
+    }
+  }
+
+  message_t *handle1stFrag(message_t *msg, packed_lowmsg_t *lowmsg) {
+    uint8_t *unpack_buf;
+    struct ip6_hdr *ip;
+
+    uint16_t real_payload_length;// , real_offset = sizeof(struct ip6_hdr);
+
+    unpack_info_t u_info;
+
+    unpack_buf = ip_malloc(LIB6LOWPAN_MAX_LEN + LOWPAN_LINK_MTU);
+    if (unpack_buf == NULL) return msg;
+
+    // unpack all the compressed headers.  this means the IP headers,
+    // and possibly also the UDP ones if there are no hop-by-hop
+    // options.
+    ip_memclr(unpack_buf, LIB6LOWPAN_MAX_LEN + LOWPAN_LINK_MTU);
+    if (unpackHeaders(lowmsg, &u_info,
+                      unpack_buf, LIB6LOWPAN_MAX_LEN) == NULL) {
+      ip_free(unpack_buf);
+      return msg;
+    }
+    
+    ip = (struct ip6_hdr *)unpack_buf;
+
+
+    if (u_info.hdr_route != NULL) {
+      // this updates the source route in the message_t, if it
+      // exists...
+      updateSourceRoute(call Ieee154Packet.source(msg),
+                        u_info.hdr_route);
+    }
+
+    // we handle the extension headers generically now
+    signal IPExtensions.handleExtensions(current_local_label++,
+                                         ip,
+                                         u_info.hdr_hop,
+                                         u_info.hdr_dest,
+                                         u_info.hdr_route,
+                                         u_info.nxt_hdr);
+    
+    // first check if we forward or consume it
+    if (call IPRouting.isForMe(ip)) {
+      struct ip_metadata metadata;
+      dbg("IPDispatch", "is for me!\n");
+      // consume it:
+      //   - get a buffer
+      //   - if fragmented, wait for remaining fragments
+      //   - if not, dispatch from here.
+
+      metadata.sender = call Ieee154Packet.source(msg);
+      metadata.lqi = call ReadLqi.read(msg);
+
+      real_payload_length = ntohs(ip->plen);
+      adjustPlen(ip, &u_info);
+
+      if (!hasFrag1Header(lowmsg)) {
+        uint16_t amount_here = lowmsg->len - (u_info.payload_start - lowmsg->data);
+
+#if 0
+        int i;
+        for (i = 0; i < 48; i++)
+          printfUART("0x%x ", ((uint8_t *)ip)[i]);
+        printfUART("\n");
+        for (i = 0; i < 8; i++)
+          printfUART("0x%x ", ((uint8_t *)u_info.payload_start)[i]);
+        printfUART("\n");
+#endif
+
+        // we can fill in the data and deliver the packet from here.
+        // this is the easy case...
+        // we malloc'ed a bit extra in this case so we don't have to
+        //  copy the IP header; we can just add the payload after the unpacked
+        //  buffers.
+        // if (rcv_buf == NULL) goto done;
+        ip_memcpy(u_info.header_end, u_info.payload_start, amount_here);
+
+        printfUART("IP.recv[%i] here: %i\n", amount_here);
+        signal IP.recv[u_info.nxt_hdr](ip, u_info.transport_ptr, &metadata);
+      } else {
+        // in this case, we need to set up a reconstruction
+        // structure so when the next packets come in, they can be
+        // filled in.
+        reconstruct_t *recon;
+        uint16_t tag, amount_here = lowmsg->len - (u_info.payload_start - lowmsg->data);
+        void *rcv_buf;
+
+        if (getFragDgramTag(lowmsg, &tag)) goto fail;
+        
+        dbg("IPDispatch", "looking up frag tag: 0x%x\n", tag);
+        recon = get_reconstruct(lowmsg->src, tag);
+        
+        // allocate a new struct for doing reassembly.
+        if (recon == NULL) {
+          goto fail;
+        }
+        
+        // the total size of the IP packet
+        rcv_buf = ip_malloc(real_payload_length + sizeof(struct ip6_hdr));
+
+        recon->metadata.sender = lowmsg->src;
+        recon->tag = tag;
+        recon->size = real_payload_length + sizeof(struct ip6_hdr);
+        recon->buf = rcv_buf;
+        recon->nxt_hdr = u_info.nxt_hdr;
+        recon->transport_hdr = ((uint8_t *)rcv_buf) + (u_info.transport_ptr - unpack_buf);
+        recon->bytes_rcvd = u_info.payload_offset + amount_here + sizeof(struct ip6_hdr);
+        recon->timeout = T_ACTIVE;
+
+        if (rcv_buf == NULL) {
+          // if we didn't get a buffer better not memcopy anything
+          recon->timeout = T_FAILED1;
+          recon->size = 0;
+          goto fail;
+        }
+        if (amount_here > recon->size - sizeof(struct ip6_hdr)) {
+          call Leds.led1Toggle();
+          recon->timeout = T_FAILED1;
+          recon->size = 0;
+          ip_free(rcv_buf);
+          recon->buf = NULL;
+          goto fail;
+        }
+
+        ip_memcpy(rcv_buf, unpack_buf, u_info.payload_offset + sizeof(struct ip6_hdr));
+        ip_memcpy(rcv_buf + u_info.payload_offset + sizeof(struct ip6_hdr), 
+                  u_info.payload_start, amount_here);
+        ip_memcpy(&recon->metadata, &metadata, sizeof(struct ip_metadata));
+
+        goto done;
+        // that's it, we just filled in the first piece of the fragment
+      } 
+    } else {
+      // otherwise set up forwarding information for the next
+      // fragments and enqueue this message_t on its merry way.
+      send_info_t *s_info;
+      send_entry_t *s_entry;
+      forward_entry_t *fwd;
+      message_t *msg_replacement;
+      
+      // this is a pointer to the hop-limit field in the packed fragment
+      *u_info.hlim = *u_info.hlim - 1;
+      if (*u_info.hlim == 0) {
+#ifndef NO_ICMP_TIME_EXCEEDED
+        uint16_t amount_here = lowmsg->len - (u_info.payload_start - lowmsg->data);
+        call ICMP.sendTimeExceeded(ip, &u_info, amount_here);
+#endif
+        // by bailing here and not setting up an entry in the
+        // forwarding cache, following fragments will be dropped like
+        // they should be.  we don't strictly follow the RFC that says
+        // we should return at least 64 bytes of payload.
+        ip_free(unpack_buf);
+        return msg;
+      }
+      s_info = getSendInfo();
+      s_entry = call SendEntryPool.get();
+      msg_replacement = call FragPool.get();
+      if (s_info == NULL || s_entry == NULL || msg_replacement == NULL) {
+        if (s_info != NULL) 
+          SENDINFO_DECR(s_info);
+        if (s_entry != NULL)
+          call SendEntryPool.put(s_entry);
+        if (msg_replacement != NULL) 
+          call FragPool.put(msg_replacement);
+        goto fail;
+      }
+
+      if (call IPRouting.getNextHop(ip, u_info.hdr_route, 
+                                    lowmsg->src, &s_info->policy) != SUCCESS)
+        goto fwd_fail;
+
+      dbg("IPDispatch", "next hop is: 0x%x\n", s_info->policy.dest[0]);
+
+      if (hasFrag1Header(lowmsg)) {
+        fwd = table_search(&forward_cache, forward_unused);
+        if (fwd == NULL) {
+          goto fwd_fail;
+        }
+
+        fwd->timeout = T_ACTIVE;
+        fwd->l2_src = call Ieee154Packet.source(msg);
+        getFragDgramTag(lowmsg, &fwd->old_tag);
+        fwd->new_tag = ++lib6lowpan_frag_tag;
+        // forward table gets a reference
+        SENDINFO_INCR(s_info);
+        fwd->s_info = s_info;
+        setFragDgramTag(lowmsg, lib6lowpan_frag_tag);
+      } 
+
+      // give a reference to the send_entry
+      SENDINFO_INCR(s_info);
+      s_info->local_flow_label = current_local_label - 1;
+      s_entry->msg = msg;
+      s_entry->info = s_info;
+
+      if (call SendQueue.enqueue(s_entry) != SUCCESS)
+        BLIP_STATS_INCR(stats.encfail);
+      post sendTask();
+
+      BLIP_STATS_INCR(stats.forwarded);
+
+      // s_info leaves lexical scope;
+      SENDINFO_DECR(s_info);
+      ip_free(unpack_buf);
+      return msg_replacement;
+
+    fwd_fail:
+      call FragPool.put(msg_replacement);
+      call SendInfoPool.put(s_info);
+      call SendEntryPool.put(s_entry);
+    }
+    
+   
+
+  fail:
+  done:
+    ip_free(unpack_buf);
+    return msg;
+  }
+
+  event message_t *Ieee154Receive.receive(message_t *msg, void *msg_payload, uint8_t len) {
+    packed_lowmsg_t lowmsg;
+
+    printfUART("p1: %p p2: %p\n", msg_payload, call Packet.getPayload(msg, 0));
+    // set up the ip message structaddFragment
+    lowmsg.data = msg_payload;
+    lowmsg.len  = len;
+    lowmsg.src  = call Ieee154Packet.source(msg);
+    lowmsg.dst  = call Ieee154Packet.destination(msg);
+
+    printfUART("receive(): %i\n", len);
+
+    BLIP_STATS_INCR(stats.rx_total);
+
+    call IPRouting.reportReception(call Ieee154Packet.source(msg),
+                                   call ReadLqi.read(msg));
+
+    lowmsg.headers = getHeaderBitmap(&lowmsg);
+    if (lowmsg.headers == LOWPAN_NALP_PATTERN) {
+      goto fail;
+    }
+
+    // consume it
+    if (!hasFragNHeader(&(lowmsg))) {
+      // in this case, we need to unpack the addressing information
+      // and either dispatch the packet locally or forward it.
+      msg = handle1stFrag(msg, &lowmsg);
+      goto done;
+    } else {
+      // otherwise, it's a fragN packet, and we just need to copy it
+      // into a buffer or forward it.
+      forward_entry_t *fwd;
+      reconstruct_t *recon;
+      uint8_t offset_cmpr;
+      uint16_t offset, amount_here, tag;
+      uint8_t *payload;
+
+      if (getFragDgramTag(&lowmsg, &tag)) goto fail;
+      if (getFragDgramOffset(&lowmsg, &offset_cmpr)) goto fail;
+
+      forward_lookup_tag = tag;
+      forward_lookup_src = call Ieee154Packet.source(msg);
+
+      fwd = table_search(&forward_cache, forward_lookup);
+      payload = getLowpanPayload(&lowmsg);
+      
+      recon = get_reconstruct(lowmsg.src, tag);
+      if (recon != NULL && recon->timeout > T_UNUSED && recon->buf != NULL) {
+        // for packets we are reconstructing.
+        
+        offset =  (offset_cmpr * 8); 
+        amount_here = lowmsg.len - (payload - lowmsg.data);
+        
+        if (offset + amount_here > recon->size) goto fail;
+        ip_memcpy(recon->buf + offset, payload, amount_here);
+        
+        recon->bytes_rcvd += amount_here;
+        
+        printfUART("sz: %i rcv: %i\n", recon->size, recon->bytes_rcvd);
+        if (recon->size == recon->bytes_rcvd) { 
+          // signal and free the recon.
+          signalDone(recon);
+        }
+      } else if (fwd != NULL && fwd->timeout > T_UNUSED) {
+        // this only catches if we've forwarded all the past framents
+        // successfully.
+        message_t *replacement = call FragPool.get();
+        send_entry_t *s_entry = call SendEntryPool.get();
+        uint16_t lowpan_size;
+        uint8_t lowpan_offset;
+
+        if (replacement == NULL || s_entry == NULL) {
+          // we have to drop the rest of the framents if we don't have
+          // a buffer...
+          if (replacement != NULL)
+            call FragPool.put(replacement);
+          if (s_entry != NULL)
+            call SendEntryPool.put(s_entry);
+
+          BLIP_STATS_INCR(stats.fw_drop);
+          fwd->timeout = T_FAILED1;
+          goto fail;
+        }
+        // keep a reference for ourself, and pass it off to the
+        // send_entry_t
+        SENDINFO_INCR(fwd->s_info);
+
+        getFragDgramOffset(&lowmsg, &lowpan_offset);
+        getFragDgramSize(&lowmsg, &lowpan_size);
+        if ((lowpan_offset * 8) + (lowmsg.len - (payload - lowmsg.data)) == lowpan_size) {
+          // this is the last fragment. since delivery is in-order,
+          // we want to free up that forwarding table entry.
+          // take back the reference the table had.
+          SENDINFO_DECR(fwd->s_info);
+          fwd->timeout = T_UNUSED;
+        }
+
+        setFragDgramTag(&lowmsg, fwd->new_tag);
+
+        s_entry->msg = msg;
+        s_entry->info = fwd->s_info;
+
+        dbg("IPDispatch", "forwarding: dest: 0x%x\n", 
+            fwd->s_info->policy.dest[s_entry->info->policy.current]);
+
+        if (call SendQueue.enqueue(s_entry) != SUCCESS) {
+          BLIP_STATS_INCR(stats.encfail);
+          dbg("Drops", "drops: receive enqueue failed\n");
+        }
+        post sendTask();
+        return replacement;
+
+      } else goto fail;
+      goto done;
+    }
+
+  fail:
+    dbg("Drops", "drops: receive()\n");;
+    BLIP_STATS_INCR(stats.rx_drop);
+  done:
+    return msg;
+  }
+
+
+  /*
+   * Send-side functionality
+   */
+
+
+
+  task void sendTask() {
+    send_entry_t *s_entry;
+    if (radioBusy || state != S_RUNNING) return;
+    if (call SendQueue.empty()) return;
+    // this does not dequeue
+    s_entry = call SendQueue.head();
+
+
+    call Ieee154Packet.setDestination(s_entry->msg, 
+                                      s_entry->info->policy.dest[s_entry->info->policy.current]);
+    call PacketLink.setRetries(s_entry->msg, s_entry->info->policy.retries);
+    call PacketLink.setRetryDelay(s_entry->msg, s_entry->info->policy.delay);
+#ifdef LPL_SLEEP_INTERVAL
+    call LowPowerListening.setRemoteWakeupInterval(s_entry->msg, 
+            call LowPowerListening.getLocalWakeupInterval());
+#endif
+
+    dbg("IPDispatch", "sendTask dest: 0x%x len: 0x%x \n", 
+        call Ieee154Packet.destination(s_entry->msg),
+        call Packet.payloadLength(s_entry->msg));
+    
+    if (s_entry->info->failed) {
+      dbg("Drops", "drops: sendTask: dropping failed fragment\n");
+      goto fail;
+    }
+          
+    if ((call Ieee154Send.send(call Ieee154Packet.destination(s_entry->msg),
+                               s_entry->msg,
+                               call Packet.payloadLength(s_entry->msg))) != SUCCESS) {
+      dbg("Drops", "drops: sendTask: send failed\n");
+      goto fail;
+    }
+    radioBusy = TRUE;
+    if (call SendQueue.empty()) return;
+    // this does not dequeue
+    s_entry = call SendQueue.head();
+
+    return;
+  fail:
+    post sendTask();
+    BLIP_STATS_INCR(stats.tx_drop);
+
+    // deallocate the memory associated with this request.
+    // other fragments associated with this packet will get dropped.
+    s_entry->info->failed = TRUE;
+    SENDINFO_DECR(s_entry->info);
+    call FragPool.put(s_entry->msg);
+    call SendEntryPool.put(s_entry);
+    call SendQueue.dequeue();
+  }
+  
+
+  /*
+   * this interface is only for grownups; it is also only called for
+   * local sends.
+   *
+   *  it will pack the message into the fragment pool and enqueue
+   *  those fragments for sending
+   *
+   * it will set
+   *  - payload length
+   *  - version, traffic class and flow label
+   *
+   * the source and destination IP addresses must be set by higher
+   * layers.
+   */
+  command error_t IP.send[uint8_t prot](struct split_ip_msg *msg) {
+    msg->hdr.nxt_hdr = prot;
+    return call IP.bareSend[prot](msg, NULL, 0);
+  }
+
+  command error_t IP.bareSend[uint8_t prot](struct split_ip_msg *msg, 
+                              struct ip6_route *route,
+                              int flags) {
+    uint16_t payload_length;
+
+    if (state != S_RUNNING) {
+      return EOFF;
+    }
+
+    if (msg->hdr.hlim != 0xff)
+      msg->hdr.hlim = call IPRouting.getHopLimit();
+
+    printfUART("sending...\n");
+
+    ip_memclr(msg->hdr.vlfc, 4);
+    msg->hdr.vlfc[0] = IPV6_VERSION << 4;
+
+    current_local_label++;
+    if (!(flags & IP_NOHEADERS)) {
+      call InternalIPExtension.addHeaders(msg, prot, current_local_label);
+
+      if (route == NULL)
+        route = call IPRouting.insertRoutingHeader(msg);
+    }
+                             
+    payload_length = msg->data_len;
+    {
+      struct generic_header *cur = msg->headers;
+      while (cur != NULL) {
+        payload_length += cur->len;
+        cur = cur->next;
+      }
+    }
+
+    msg->hdr.plen = htons(payload_length);
+    printfUART("sending: total length is: %i\n", payload_length);
+    
+    // okay, so we ought to have a fully setup chain of headers here,
+    // so we ought to be able to compress everything into fragments.
+    //
+
+    {
+      error_t rc = SUCCESS;
+      send_info_t  *s_info;
+      send_entry_t *s_entry;
+      uint8_t frag_len = 1;
+      message_t *outgoing;
+      fragment_t progress;
+      struct source_header *sh;
+      progress.offset = 0;
+
+      s_info = getSendInfo();
+      if (s_info == NULL) {
+        rc = ERETRY;
+        goto cleanup_outer;
+      }
+      s_info->local_flow_label = current_local_label;
+
+      // fill in destination information on outgoing fragments.
+      sh = (msg->headers != NULL) ? (struct source_header *)msg->headers->hdr.ext : NULL;
+      if (call IPRouting.getNextHop(&msg->hdr, route, 0x0,
+                                    &s_info->policy) != SUCCESS) {
+        dbg("Drops", "drops: IP send: getNextHop failed\n");
+        goto done;
+      }
+
+      //goto done;
+      while (frag_len > 0) {
+        s_entry  = call SendEntryPool.get();
+        outgoing = call FragPool.get();
+
+        if (s_entry == NULL || outgoing == NULL) {
+          if (s_entry != NULL)
+            call SendEntryPool.put(s_entry);
+          if (outgoing != NULL)
+            call FragPool.put(outgoing);
+          // this will cause any fragments we have already enqueued to
+          // be dropped by the send task.
+          s_info->failed = TRUE;
+          dbg("Drops", "drops: IP send: no fragments\n");
+          goto done;
+        }
+
+        // printfUART("getting frag... ");
+        // ip_dump_msg(msg);
+
+        frag_len = getNextFrag(msg, &progress, 
+                               call Packet.getPayload(outgoing, call Packet.maxPayloadLength()),
+                               call Packet.maxPayloadLength());
+        // printfUART("got frag: len: %i\n", frag_len);
+        if (frag_len == 0) {
+          call FragPool.put(outgoing);
+          call SendEntryPool.put(s_entry);
+          goto done;
+        }
+        call Packet.setPayloadLength(outgoing, frag_len);
+
+        s_entry->msg = outgoing;
+        s_entry->info = s_info;
+
+        if (call SendQueue.enqueue(s_entry) != SUCCESS) {
+          BLIP_STATS_INCR(stats.encfail);
+          dbg("Drops", "drops: IP send: enqueue failed\n");
+          goto done;
+        }
+
+        SENDINFO_INCR(s_info);
+//        printfUART("enqueue len 0x%x dest: 0x%x retries: 0x%x delay: 0x%x\n",frag_len,
+//                   s_info->policy.dest, s_info->policy.retries, s_info->policy.delay);
+      }
+    done:
+      BLIP_STATS_INCR(stats.sent);
+      SENDINFO_DECR(s_info);
+      post sendTask();
+    cleanup_outer:
+      call InternalIPExtension.free();
+
+      return rc;
+      
+    }
+  }
+
+  event void Ieee154Send.sendDone(message_t *msg, error_t error) {
+    send_entry_t *s_entry = call SendQueue.head();
+
+    radioBusy = FALSE;
+
+    if (state == S_STOPPING) {
+      call RadioControl.stop();
+      state = S_STOPPED;
+      goto fail;
+    }
+
+
+    if (!call PacketLink.wasDelivered(msg)) {
+
+      // if we haven't sent out any fragments yet, we can try rerouting
+      if (s_entry->info->frags_sent == 0) {
+        // SDH : TODO : if sending a fragment fails, abandon the rest of
+        // the fragments
+        s_entry->info->policy.current++;
+        if (s_entry->info->policy.current < s_entry->info->policy.nchoices) {
+          // this is the retry case; we don't need to change anything.
+          post sendTask();
+          return;
+        }
+        // no more next hops to try, so free the buffers and move on
+      }    
+      // a fragment failed, and it wasn't the first.  we drop all
+      // remaining fragments.
+      goto fail;
+    } else {
+      // the fragment was successfully sent.
+      s_entry->info->frags_sent++;
+      goto done;
+    }
+    goto done;
+    
+  fail:
+    s_entry->info->failed = TRUE;
+    if (s_entry->info->policy.dest[0] != 0xffff)
+      dbg("Drops", "drops: sendDone: frag was not delivered\n");
+    BLIP_STATS_INCR(stats.tx_drop);
+
+  done:
+    s_entry->info->policy.actRetries = call PacketLink.getRetries(msg);
+    signal IPExtensions.reportTransmission(s_entry->info->local_flow_label, &s_entry->info->policy);
+    // kill off any pending fragments
+    SENDINFO_DECR(s_entry->info);
+    call FragPool.put(s_entry->msg);
+    call SendEntryPool.put(s_entry);
+    call SendQueue.dequeue();
+
+    post sendTask();
+  }
+
+  command struct tlv_hdr *IPExtensions.findTlv(struct ip6_ext *ext, uint8_t tlv_val) {
+    int len = ext->len - sizeof(struct ip6_ext);
+    struct tlv_hdr *tlv = (struct tlv_hdr *)(ext + 1);
+    while (len > 0) {
+      if (tlv->type == tlv_val) return tlv;
+      if (tlv->len == 0) return NULL;
+      tlv = (struct tlv_hdr *)(((uint8_t *)tlv) + tlv->len);
+      len -= tlv->len;
+    }
+    return NULL;
+  }
+
+  event void ICMP.solicitationDone() {
+
+  }
+
+  /*
+   * Statistics interface
+   */
+  command void Statistics.get(ip_statistics_t *statistics) {
+#ifdef BLIP_STATS_IP_MEM
+    stats.fragpool = call FragPool.size();
+    stats.sendinfo = call SendInfoPool.size();
+    stats.sendentry= call SendEntryPool.size();
+    stats.sndqueue = call SendQueue.size();
+    stats.heapfree = ip_malloc_freespace();
+    printfUART("frag: %i sendinfo: %i sendentry: %i sendqueue: %i heap: %i\n",
+               stats.fragpool,
+               stats.sendinfo,
+               stats.sendentry,
+               stats.sndqueue,
+               stats.heapfree);
+#endif
+    ip_memcpy(statistics, &stats, sizeof(ip_statistics_t));
+
+  }
+
+  command void Statistics.clear() {
+    ip_memclr((uint8_t *)&stats, sizeof(ip_statistics_t));
+  }
+
+  default event void IP.recv[uint8_t nxt_hdr](struct ip6_hdr *iph,
+                                              void *payload,
+                                              struct ip_metadata *meta) {
+  }
+}
diff --git a/tos/lib/net/blip/IPExtensionP.nc b/tos/lib/net/blip/IPExtensionP.nc
new file mode 100644 (file)
index 0000000..415e868
--- /dev/null
@@ -0,0 +1,144 @@
+
+/* 
+ * Provides various functions for dealing with IP extension header
+ * processing
+
+ *
+ */
+
+#include <ip_malloc.h>
+
+module IPExtensionP {
+  provides {
+    // for inserting destination and hop-by-hop headers on outgoing packets.
+    // routing headers are handled through the IPRouting interface
+    interface Init;
+    interface TLVHeader as HopByHopExt[uint8_t client];
+    interface TLVHeader as DestinationExt[uint8_t client];
+    interface InternalIPExtension;
+  }
+} implementation {
+
+  struct generic_header *ext_dest, *ext_hop;
+
+  command error_t Init.init() {
+    ext_hop = ext_dest = NULL;
+    return SUCCESS;
+  }
+
+  struct tlv_hdr *destopt_get(int i, int nxt_hdr, struct ip6_hdr *iph) {
+    return signal DestinationExt.getHeader[i](0, nxt_hdr, iph);
+  }
+  struct tlv_hdr *hopopt_get(struct ip6_hdr *iph, int i) { //, uint8_t nxt_hdr) {
+    // return signal HopByHopExt.getHeader[i](label, iph, nxt_hdr);
+    return NULL;
+  }
+
+  /* build up a sequence of TLV headers for hop-by-hop or
+     destination only extension headers */
+  struct generic_header *buildTLVHdr(struct split_ip_msg *msg,
+                                     int which, 
+                                     int n, int nxt_hdr) {
+    // allocate generic headers for all the possible TLV-encoded
+    // headers we might get
+    int i;
+    uint8_t *buf = ip_malloc(sizeof(struct ip6_ext) + (sizeof(struct generic_header) * (n + 1)));
+    struct ip6_ext *real_hdr;
+    struct generic_header *ghdrs;
+    if (buf == NULL) return NULL;
+    ghdrs = (struct generic_header *)buf;
+    real_hdr = (struct ip6_ext *)(ghdrs + (n + 1));
+
+
+    real_hdr->len = sizeof(struct ip6_ext);
+
+    ghdrs[0].len = sizeof(struct ip6_ext);
+    ghdrs[0].hdr.data = (uint8_t *)real_hdr;
+    ghdrs[0].next = msg->headers;
+
+    for (i = 0; i < n; i++) {
+      struct tlv_hdr *this_hdr;
+      if (which == 0) {
+        printfUART("adding destination idx %i\n", i);
+        this_hdr = signal DestinationExt.getHeader[i](0, nxt_hdr, &msg->hdr);
+      } else {
+        this_hdr = signal HopByHopExt.getHeader[i](0, nxt_hdr, &msg->hdr);
+      }
+
+      printfUART("buildTLV: got %p\n", this_hdr);
+      if (this_hdr == NULL) continue;
+
+      real_hdr->len += this_hdr->len;
+      ghdrs[i+1].len = this_hdr->len;
+      ghdrs[i+1].hdr.data = (uint8_t *)this_hdr;
+      ghdrs[i].next = &ghdrs[i+1];
+      ghdrs[i+1].next = msg->headers;
+    }
+    if (real_hdr->len == sizeof(struct ip6_ext)) {
+      ip_free(buf);
+      return NULL;
+    } else {
+      real_hdr->nxt_hdr = msg->hdr.nxt_hdr;
+      msg->headers = ghdrs;
+      return ghdrs;
+    }
+  }
+
+  command void InternalIPExtension.addHeaders(struct split_ip_msg *msg, 
+                                              uint8_t nxt_hdr,
+                                              uint16_t label) {
+
+    ext_dest = ext_hop = NULL;
+    msg->hdr.nxt_hdr = nxt_hdr;
+    ext_dest = buildTLVHdr(msg, 0, 1, nxt_hdr);
+    if (ext_dest != NULL) msg->hdr.nxt_hdr = IPV6_DEST;
+
+    ext_hop = buildTLVHdr(msg, 1, 1, msg->hdr.nxt_hdr);
+    if (ext_hop != NULL) msg->hdr.nxt_hdr = IPV6_HOP;
+  }
+
+  command void InternalIPExtension.free() {
+    if (ext_dest != NULL) ip_free(ext_dest);
+    if (ext_hop  != NULL) ip_free(ext_hop);
+    ext_dest = ext_hop = NULL;
+    // signal HopByHopExt.free[0]();
+    // signal DestinationExt.free[0]();
+  }
+
+#if 0
+  void ip_dump_msg(struct split_ip_msg *msg) {
+    struct generic_header *cur = msg->headers;
+    int i;
+    printfUART("DUMPING IP PACKET\n ");
+    for (i = 0; i < sizeof(struct ip6_hdr); i++)
+      printfUART("0x%x ", ((uint8_t *)&msg->hdr)[i]);
+    printfUART("\n");
+
+    while (cur != NULL) {
+      printfUART(" header [%i]: ", cur->len);
+      for (i = 0; i < cur->len; i++) 
+        printfUART("0x%x ", cur->hdr.data[i]);
+      printfUART("\n");
+      cur = cur->next;
+    }
+
+    printfUART("data [%i]: ", msg->data_len);
+    for (i = 0; i < msg->data_len; i++) 
+      printfUART("0x%x ", ((uint8_t *)msg->data)[i]);
+    printfUART("\n\n");
+  }
+#endif
+
+  default event struct tlv_hdr *DestinationExt.getHeader[uint8_t i](int label,int nxt_hdr,
+                                                                   struct ip6_hdr *msg) {
+    printfUART("default dest handler?\n");
+    return NULL;
+  }
+
+  default event struct tlv_hdr *HopByHopExt.getHeader[uint8_t i](int label,int nxt_hdr,
+                                                                   struct ip6_hdr *msg) {
+    return NULL;
+  }
+
+
+}
diff --git a/tos/lib/net/blip/IPExtensionsP.nc b/tos/lib/net/blip/IPExtensionsP.nc
new file mode 100644 (file)
index 0000000..d82322c
--- /dev/null
@@ -0,0 +1,33 @@
+
+module IPExtensionsP {
+  provides interface IPExtensions[uint8_t client];
+  uses interface IPExtensions;
+} implementation {
+
+
+
+
+  command struct tlv_hdr *findTlv(struct ip6_ext *ext, uint8_t tlv) {
+
+  }
+
+  event void handleExtensions(uint8_t label,
+                              struct ip6_hdr *iph,
+                              struct ip6_ext *hop,
+                              struct ip6_ext *dst,
+                              struct ip6_route *route,
+                              uint8_t nxt_hdr) {
+
+  }
+
+
+
+
+  /*
+   * will be called once for each fragment when sending or forwarding
+   */
+  event void reportTransmission(uint8_t label, send_policy_t *send) {
+
+  }
+
+}
diff --git a/tos/lib/net/blip/IPRoutingP.nc b/tos/lib/net/blip/IPRoutingP.nc
new file mode 100644 (file)
index 0000000..4a50978
--- /dev/null
@@ -0,0 +1,1421 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include "IPDispatch.h"
+#include "PrintfUART.h"
+
+module IPRoutingP {
+  provides interface IPRouting;
+  provides interface Statistics<route_statistics_t>;
+
+  uses interface IPExtensions;
+  uses interface TLVHeader as DestinationExt;
+  uses interface ICMP;
+  uses interface Boot;
+  uses interface IPAddress;
+  uses interface Random;
+
+  uses interface Timer<TMilli> as SortTimer;
+
+  uses interface IP as TGenSend;
+  uses interface Timer<TMilli> as TrafficGenTimer;
+
+  uses interface Leds;
+
+} implementation {
+
+#ifdef PRINTFUART_ENABLED
+// #undef dbg
+// #define dbg(X, fmt, args...)  printfUART(fmt, ## args)
+#endif
+
+  enum {
+    SHORT_EPOCH = 0,
+    LONG_EPOCH = 1,
+  };
+
+  //uint16_t current_epoch;
+  //route_statistics_t stats;
+  uint16_t last_qual;
+  uint8_t last_hops;
+  uint16_t reportSeqno;
+
+  bool soliciting;
+
+  // pointer into the neighbor table of the current entry that is our
+  // first choice.
+  struct neigh_entry *default_route;
+  uint16_t default_route_failures;
+
+  uint32_t traffic_interval;
+  bool traffic_sent;
+
+#ifdef CENTRALIZED_ROUTING
+  // this is the routing table (k parents);
+  struct flow_path full_path_entries[N_FULL_PATH_ENTRIES];
+  struct flow_entry flow_table[N_FLOW_ENT];
+#endif
+  struct neigh_entry neigh_table[N_NEIGH];
+
+  void printTable();
+  error_t freeFullPath(struct flow_path* path);
+  void updateFlowCounts(struct flow_entry *target);
+  void updateRankings();
+  void swapNodes(struct neigh_entry *highNode, struct neigh_entry *lowNode);
+  uint8_t checkThresh(uint32_t firstVal, uint32_t secondVal, uint16_t thresh);
+  void evictNeighbor(struct neigh_entry *neigh);
+  uint16_t getMetric(struct neigh_entry *neigh);
+
+  void clearStats(struct neigh_entry *r) {
+    ip_memclr((uint8_t *)r->stats, sizeof(struct epoch_stats) * N_EPOCHS);
+#if 0
+    int j;
+    for (j = 0; j < N_EPOCHS; j++) {
+      r->stats[j].total   = 0;
+      r->stats[j].success = 0;
+      r->stats[j].receptions = 0;
+    }
+#endif
+  }
+
+  void clearEpoch(uint8_t target_epoch) {
+    int i;
+    for (i = 0; i < N_NEIGH; i++) {
+      neigh_table[i].stats[target_epoch].total = 0;
+      neigh_table[i].stats[target_epoch].success = 0;
+      neigh_table[i].stats[target_epoch].receptions = 0;
+    }
+  }
+
+  void restartTrafficGen() {
+    traffic_interval = TGEN_BASE_TIME;
+    // jitter the period by 10% to prevent synchronization
+    traffic_interval += (call Random.rand16()) % (TGEN_BASE_TIME);
+    if (call TrafficGenTimer.isRunning())
+      call TrafficGenTimer.stop();
+    traffic_sent = FALSE;
+
+    call TrafficGenTimer.startOneShot(traffic_interval);
+  }
+
+  event void TrafficGenTimer.fired() {
+    struct split_ip_msg *msg;
+    if (traffic_sent) goto done;
+    msg = (struct split_ip_msg *)ip_malloc(sizeof(struct split_ip_msg));
+    if (msg == NULL) {
+      printfUART("malloc fail\n");
+      goto done;
+    }
+    traffic_sent = FALSE;
+
+    ip_memclr((uint8_t *)&msg->hdr, sizeof(struct ip6_hdr));
+    inet_pton6("ff05::1", &msg->hdr.ip6_dst);
+    call IPAddress.getIPAddr(&msg->hdr.ip6_src);
+    msg->data = NULL;
+    msg->data_len = 0;
+    msg->headers = NULL;
+
+    dbg("IPRouting", "Sending generated message\n");
+    call TGenSend.send(msg);
+    ip_free(msg);
+  done:
+    // restart timer
+    dbg("IPRouting", "Done checking for tgen\n");
+    traffic_sent = FALSE;
+    traffic_interval *= 2;
+    if (traffic_interval > TGEN_MAX_INTERVAL)
+      traffic_interval = TGEN_MAX_INTERVAL;
+    call TrafficGenTimer.startOneShot(traffic_interval);
+  }
+
+  event void TGenSend.recv(struct ip6_hdr *iph,
+                           void *payload, 
+                           struct ip_metadata *meta) {
+
+  }
+
+  command void IPRouting.reset() {
+    int i;
+
+    for (i = 0; i < N_NEIGH; i++) {
+      neigh_table[i].flags = 0;
+      clearStats(&neigh_table[i]);
+    }
+
+#ifdef CENTRALIZED_ROUTING
+    call IPRouting.clearFlows();
+    for (i = 0; i < N_FULL_PATH_ENTRIES; i++) {
+      full_path_entries[i].path_len = 0;
+    }
+#endif
+
+    // current_epoch = 0;
+    if (!soliciting) {
+      call ICMP.sendSolicitations();
+      soliciting = TRUE;
+    }
+    //reRouting = FALSE;
+    default_route_failures = 0;
+    default_route = &neigh_table[0];
+    // boot with this true so the router will invalidate any state
+    // associated from us when it gets the first packet.
+    last_qual = 0xffff;
+    last_hops = 0xff;
+
+    traffic_sent = FALSE;
+    restartTrafficGen();
+  }
+
+  event void Boot.booted() {
+    call IPRouting.reset();
+    reportSeqno = call Random.rand16();
+
+    call Statistics.clear();
+    call SortTimer.startPeriodic(1024L * 60);
+
+  }
+  
+  command bool IPRouting.isForMe(struct ip6_hdr *hdr) {
+    // the destination prefix is either link-local or global, or
+    // multicast (we accept all multicast packets), and the suffix is
+    // me.
+    struct in6_addr *my_address = call IPAddress.getPublicAddr();
+    return (((cmpPfx(my_address->s6_addr, hdr->ip6_dst.s6_addr) || 
+              cmpPfx(linklocal_prefix, hdr->ip6_dst.s6_addr)) &&
+             cmpPfx(&my_address->s6_addr[8], &hdr->ip6_dst.s6_addr[8])) ||
+            (hdr->ip6_dst.s6_addr[0] == 0xff && 
+             (hdr->ip6_dst.s6_addr[1] & 0x0f) <= 3))
+;
+  }
+
+#ifdef CENTRALIZED_ROUTING
+  void print_rinstall(struct rinstall_header *rih) {
+    uint8_t i;
+    dbg("Install", "rinstall header:\n");
+    dbg_clear("Install", "\tnxt_header\t0x%x\n", rih->ext.nxt_hdr);
+    dbg_clear("Install", "\tlen\t0x%x\n", rih->ext.len);
+    dbg_clear("Install", "\tflags\t0x%x\n", rih->flags);
+    dbg_clear("Install", "\tmatch_src\t0x%x\n", ntohs(rih->match.src));
+    dbg_clear("Install", "\tmatch_prev\t0x%x\n", ntohs(rih->match.prev_hop));
+    dbg_clear("Install", "\tmatch_dest\t0x%x\n", ntohs(rih->match.dest));
+    dbg_clear("Install", "\tpath_len\t0x%x\n", rih->path_len);
+    dbg_clear("Install", "\tcurrent\t0x%x\n", rih->current);
+    for(i = 0; i < rih->path_len; i++)
+      dbg_clear("Install", "\thop[%u]\t0x%x\n", i, ntohs(rih->path[i]));
+  }
+
+  struct flow_entry *getFlowEntry(cmpr_ip6_addr_t a) {
+    int i;
+    dbg("IPRouting", "getFlowEntry called for 0x%x\n", a);
+    for (i = 0; i < N_FLOW_ENT; i++) {
+      if (IS_VALID_SLOT(&flow_table[i]) && flow_table[i].match.dest == a) {
+        dbg("IPRouting", "Match found in slot [%u]\n", i);
+        return &(flow_table[i]);
+      }
+    }
+    return NULL;
+  }
+
+  //  Add this extra layer of indirection to allow us to do
+  //   more extensive 5-tuple lookups.
+  struct flow_entry *getFlowEntry_Header(struct ip6_hdr* hdr) {
+   if (hdr == NULL)
+     //return &flow_table[T_DEF_PARENT_SLOT]; 
+     return NULL;
+   return getFlowEntry(ntohs(hdr->ip6_dst.s6_addr16[7]));
+  }
+
+  struct flow_entry *getFlowEntry_Match(struct flow_match *match) {
+    dbg("IPRouting", "getFlowEntry_Match called for 0x%x\n", ntohs(match->dest));
+    return getFlowEntry(ntohs(match->dest));
+  }
+
+  struct flow_entry *getNewEntry(struct flow_match *match) {
+    uint8_t i;
+    uint8_t place = N_FLOW_ENT;
+    for (i = 0; i < N_FLOW_ENT; i++) {
+      if (!IS_VALID_SLOT(&(flow_table[i]))) {
+        flow_table[i].match.src = ntohs(match->src);
+        flow_table[i].match.dest = ntohs(match->dest);
+
+        dbg("IPRouting", "New flow entry slot provided in slot [%u]\n", i);
+        return &(flow_table[i]);
+      }
+      if (flow_table[i].count == (N_FLOW_ENT - 1))
+        place = i;
+    }
+    if (place == N_FLOW_ENT) {
+      dbg("IPRouting", "The correct value of place doesn't exist!!\n");
+      return NULL;
+    }
+
+    dbg("IPRouting", "Conflicted flow entry slot. Dest: 0x%x, slot 0x%x\n", flow_table[place].match.dest, place);
+    for (i = 0; i < N_FLOW_CHOICES; i++) {
+      if(IS_VALID_ENTRY(flow_table[place].entries[i])) {
+        SET_INVALID_ENTRY(flow_table[place].entries[i]);
+        if (IS_FULL_TYPE(flow_table[place].entries[i]))
+          freeFullPath(flow_table[place].entries[i].pathE);
+      }
+    }
+    SET_INVALID_SLOT(&(flow_table[place]));
+    updateFlowCounts(&(flow_table[place]));
+    ip_memclr((uint8_t *)(&(flow_table[place])), sizeof(struct flow_entry));
+    return &(flow_table[place]);
+  }
+#endif
+
+  struct neigh_entry *getNeighEntry(cmpr_ip6_addr_t a) {
+    int i;
+    for (i = 0; i < N_NEIGH; i++) {
+      if (neigh_table[i].neighbor == a)
+        return &(neigh_table[i]);
+    }
+    return NULL;
+  }
+
+#ifdef CENTRALIZED_ROUTING
+  cmpr_ip6_addr_t nextHop_Flow(struct f_entry *fEntry) {
+    if (IS_VALID_ENTRY(*fEntry)) {
+      if (IS_HOP_TYPE(*fEntry)) return fEntry->nextHop;
+      return fEntry->pathE->path[0];
+    }
+    return T_INVAL_NEIGH;
+  }
+
+  struct flow_path *getNewFlowPath() {
+    uint8_t i;
+    for (i = 0; i < N_FULL_PATH_ENTRIES; i++) {
+      if (full_path_entries[i].path_len == 0)
+        return &(full_path_entries[i]);
+    }
+    return NULL;
+  }
+  
+  error_t freeFullPath(struct flow_path* path) {
+    path->path_len = 0;
+    return SUCCESS;
+  }
+
+  void reverseFlowMatch(struct rinstall_header *orig, 
+                        struct flow_match *reverse,
+                        struct ip6_hdr *iph) {
+
+    printfUART("reverseFlowMatch: %i %i\n", ntohs(iph->ip6_dst.s6_addr16[7]),
+               ntohs(iph->ip6_src.s6_addr16[7]));
+
+    if (orig->match.src == htons(T_INVAL_NEIGH))
+      reverse->src = htons(T_INVAL_NEIGH);
+    else
+      reverse->src = iph->ip6_src.s6_addr16[7];
+
+    if (orig->match.dest == htons(T_INVAL_NEIGH)) // Shouldn't happen
+      reverse->dest = htons(T_INVAL_NEIGH);
+    else
+      reverse->dest = iph->ip6_dst.s6_addr16[7];
+  }  
+  
+  /*
+   * Function takes the set of choices within a single flow_entry slot and arranges
+   *  them in order of addition/modification.
+   *
+   * @entry_index - The index of the entry that is being uninstalled, or moved to
+   *  the top of the stack. (Set this to N_FLOW_CHOICES to indicate that a new
+   *  entry is being installed).
+   * @install - Whether an entry is being installed or moved to the top of the stack
+   *
+   * TODO: Implement explicit flow entry removal
+   */
+  void sortFlowEntries(struct flow_entry *target, uint8_t entry_index, bool install) {
+    struct f_entry f_temp;
+    uint8_t i;
+   
+    dbg("IPRouting", "sortFlowEntries: Index: 0x%x, Install: 0x%x\n", entry_index, install);
+
+    if (install && (entry_index < N_FLOW_CHOICES)) {
+      ip_memcpy(&f_temp, &(target->entries[entry_index]), sizeof(struct f_entry));
+    }
+
+    for (i = ((entry_index < N_FLOW_CHOICES)? (entry_index):(N_FLOW_CHOICES - 1)); i > 0; i--) {
+      ip_memcpy(&(target->entries[i]), &(target->entries[i-1]), sizeof(struct f_entry));
+    }
+
+    if (install && (entry_index < N_FLOW_CHOICES))
+      ip_memcpy(&(target->entries[0]), &f_temp, sizeof(struct f_entry));
+    else
+      ip_memclr((uint8_t *)(&(target->entries[0])), sizeof(struct f_entry));
+  }
+
+  void updateFlowCounts(struct flow_entry *target) {
+    uint8_t i;
+    if (target == NULL) return;
+    dbg("IPRouting", "updateFlowCounts\n");
+    
+    // Just used or installed something
+    if (IS_VALID_SLOT(target)) {
+      for(i = 0; i < N_FLOW_ENT; i++) {
+        if (!(IS_VALID_SLOT(&(flow_table[i])))) continue;
+        if (flow_table[i].count < target->count) flow_table[i].count++;
+      }
+      target->count = 0;
+    } else {
+      for (i = 0; i < N_FLOW_ENT; i++) {
+        if (!(IS_VALID_SLOT(&(flow_table[i])))) continue;
+        if (flow_table[i].count > target->count) flow_table[i].count--;
+      }
+      target->count = N_FLOW_ENT;
+    }
+  }
+
+  // Helper Functions
+  error_t installEntry(struct ip6_hdr *iph, struct rinstall_header *rih, struct ip6_route *route) {
+    struct flow_entry *entry;
+    struct flow_match reverse_match;
+    uint16_t current, path_len, 
+      reverse = 0,
+      fullPath = (rih->flags & HYDRO_INSTALL_METHOD_MASK) == HYDRO_METHOD_SOURCE;
+    cmpr_ip6_addr_t *path;
+    uint8_t i;
+
+    // if this is a METHOD_SOURCE install, and the path is carried in
+    // the routing header we must be on the far end of the install,
+    // and so need to reverse everything.
+
+
+    if (fullPath && rih->path_len == 0) reverse = 1;
+    if (!fullPath) {
+      printfUART("not fp, route: %p  rip: %i\n", route, rih->path_len);
+      reverse = rih->flags & HYDRO_INSTALL_REVERSE;
+      if (!reverse && route && route->segs_remain == 0 && rih->path_len == 0) return SUCCESS;
+      if (reverse && rih->path_len > 0) return SUCCESS;
+    }
+
+    printfUART("install rev: %i fp: %i\n", reverse, fullPath)
+
+    if (rih->path_len == 0) {
+      if (route == NULL) return FAIL;
+      current = ROUTE_NENTRIES(route) - route->segs_remain;
+      path = route->hops;
+      path_len = ROUTE_NENTRIES(route);
+    } else {
+      current = reverse ? rih->path_len - 1 : 0;
+      path = rih->path;
+      path_len = rih->path_len;
+    }
+    
+    dbg("Install", "installEntry: flags: 0x%x\n", rih->flags);
+    
+    if (!reverse && 
+        ((entry = getFlowEntry_Match(&(rih->match))) == NULL) && 
+        ((entry = getNewEntry(&(rih->match))) == NULL)) {
+      dbg("Install", "installEntry: forward path has no match and no room in flow table\n");
+      return FAIL;
+    } else if (reverse) {
+      reverseFlowMatch(rih, &reverse_match, iph);
+      if (((entry = getFlowEntry_Match(&(reverse_match))) == NULL) && 
+          ((entry = getNewEntry(&(reverse_match))) == NULL)) {
+        dbg("Install", "installEntry: reverse path has no match and no room in flow table\n");
+        return FAIL;
+       }
+    }
+
+    //Inefficient duplicate detection
+    for (i = 0; i < N_FLOW_CHOICES; i++) {
+      printfUART("checking dup %i %i\n", nextHop_Flow(&entry->entries[i]),
+                 ntohs(path[reverse ? (current - 1) : current]));
+      if (IS_VALID_ENTRY(entry->entries[i]) && 
+          (nextHop_Flow(&entry->entries[i]) == 
+           ntohs(path[reverse ? (current - 1) : current])) && 
+          !fullPath) { 
+        dbg("Install", "This choice already exists in flow table!\n");
+        // Since order indicates order of arrival, need to move this one up higher
+        if (i != 0) {
+          sortFlowEntries(entry, i, TRUE);
+        }
+        return SUCCESS;
+      }
+      if (IS_VALID_ENTRY(entry->entries[i]) && IS_FULL_TYPE(entry->entries[i])) {
+        dbg("Install", "Removing exiting source choice\n");
+        entry->entries[0].pathE->path_len = 0;
+        SET_INVALID_ENTRY(entry->entries[0]);        
+      }
+    }
+    
+
+    if (IS_VALID_ENTRY(entry->entries[0]))
+      sortFlowEntries(entry, N_FLOW_CHOICES, TRUE);
+    if (fullPath) {
+      if ((entry->entries[0].pathE = getNewFlowPath()) == NULL) {
+        dbg("Install", "No room available for new full path entry\n");
+        return FAIL;
+      }
+      for (i = 0; i < path_len; i++) {
+        entry->entries[0].pathE->path[i] = ntohs(path[(reverse ? (path_len - i - 1): i)]);
+        dbg("Install", "Put node 0x%x as hop [%u]\n", entry->entries[0].pathE->path[i], (i));
+      }
+      entry->entries[0].pathE->path_len = path_len;
+    } else {
+      entry->entries[0].nextHop = ntohs(path[(reverse? (current - 1) : current)]);
+      dbg("Install", "Put node 0x%x as next hop\n", entry->entries[0].nextHop);
+    }
+    SET_VALID_ENTRY((entry->entries[0]));
+    SET_VALID_SLOT(entry);
+    (fullPath? (SET_FULL_TYPE(entry->entries[0])) : (SET_HOP_TYPE(entry->entries[0])));
+   
+    updateFlowCounts(entry); 
+    printTable();
+    return SUCCESS;
+  }
+
+  error_t uninstallEntry(struct rinstall_header *rih) {
+    struct flow_entry *entry;
+    //struct neigh_entry *neigh;
+    uint8_t i;
+
+    // don't support reverse install
+    if (rih->flags & HYDRO_INSTALL_REVERSE) return FAIL;
+    // only work for source installs
+    if ((rih->flags & HYDRO_INSTALL_METHOD_MASK) != HYDRO_METHOD_SOURCE) return FAIL;
+    if ((entry = getFlowEntry_Match(&(rih->match))) == NULL)
+      return FAIL;
+    
+    for (i = 0; i < N_FLOW_CHOICES; i++) {
+      if (IS_VALID_ENTRY(entry->entries[i])) {
+        SET_INVALID_ENTRY(entry->entries[i]);
+        SET_INVALID_SLOT(entry);
+        freeFullPath(entry->entries[i].pathE);
+      }
+    }
+    return SUCCESS;
+  }
+#endif
+
+
+  event void IPExtensions.handleExtensions(uint8_t label,
+                                           struct ip6_hdr *iph,
+                                           struct ip6_ext *hop,
+                                           struct ip6_ext *dst,
+                                           struct ip6_route *route,
+                                           uint8_t nxt_hdr) {
+#ifdef CENTRALIZED_ROUTING
+    struct tlv_hdr *tlv = NULL;
+    struct rinstall_header *rih;
+    uint8_t method;
+    bool forMe = call IPRouting.isForMe(iph), isHop = FALSE;
+
+    printfUART("handling extension header!\n");
+
+    if (dst != NULL) tlv = call IPExtensions.findTlv(dst, TLV_TYPE_INSTALL);
+    if (tlv == NULL && hop != NULL) { tlv = call IPExtensions.findTlv(hop, TLV_TYPE_INSTALL); isHop = TRUE; }
+    if (tlv == NULL) return;
+    rih = (struct rinstall_header *)(tlv + 1);
+    // first, install the entry if it's for me
+    method = (rih->flags & HYDRO_INSTALL_METHOD_MASK);
+
+
+    if (!forMe) {
+      if (method == HYDRO_METHOD_HOP    && !isHop) return;
+      if (method == HYDRO_METHOD_SOURCE) return;
+    }
+    if (!(rih->flags & HYDRO_INSTALL_UNINSTALL_MASK)) {
+      installEntry(iph, rih, route);
+    } else {
+      // uninstall only returns
+      uninstallEntry(rih);
+      return;
+    }
+
+    if (method == HYDRO_METHOD_HOP && (rih->flags & HYDRO_INSTALL_REVERSE)) {
+      // a little clunky, perhaps, but this is sort of how
+      // installEntry expects things to work.
+      rih->flags &= ~HYDRO_INSTALL_REVERSE;
+      installEntry(iph, rih, route);
+      rih->flags |= HYDRO_INSTALL_REVERSE;
+    }
+
+    if ( (forMe && rih->path_len > 0 && rih->path_len < 10) && 
+
+         // if it's a source install, we don't need to generate a new
+         // message unless the command is for us to also install the reverse path.
+         ((method == HYDRO_METHOD_SOURCE &&
+           rih->flags & HYDRO_INSTALL_REVERSE) ||
+          // if it's a hop-by-hop install, we always need to generate a
+          // new message to do the install.  however, only want this to
+          // happen once, and since along the path the route install will be
+          // carried as a hop-by-hop options, this check is sufficient.
+          (method == HYDRO_METHOD_HOP && !isHop))) {
+      
+      // in either case the actual route to install must be in the
+      // route install header
+      uint16_t plen = sizeof(struct ip6_route) + (sizeof(cmpr_ip6_addr_t) * rih->path_len) +
+        sizeof(struct ip6_ext) + sizeof(struct tlv_hdr) + 
+        sizeof(struct rinstall_header);
+      struct uint8_t *buf = ip_malloc(sizeof(struct split_ip_msg) + plen);
+      struct split_ip_msg *ipmsg;
+      struct ip6_ext   *newext;
+      struct tlv_hdr   *newtlv;
+      struct rinstall_header *newrih;
+      struct ip6_route *iproute;
+      printfUART("installing reverse path to 0x%x\n", rih->match.dest);
+
+      if (buf == NULL) return;
+      ip_memclr((void *)buf, sizeof(struct split_ip_msg) + plen);
+
+      ipmsg = (struct split_ip_msg *)buf;
+      newext = (struct ip6_ext *)(ipmsg + 1);
+      newtlv = (struct tlv_hdr *)(newext + 1);
+      newrih = (struct rinstall_header *)(newtlv + 1);
+      iproute = (struct ip6_route *)(newrih + 1);
+      
+      ipmsg->hdr.nxt_hdr = (method == HYDRO_METHOD_SOURCE) ? IPV6_DEST : IPV6_HOP;
+      ipmsg->hdr.plen = htons(plen);
+      ipmsg->data = (uint8_t *)(ipmsg  + 1);
+      ipmsg->data_len = plen;
+      ipmsg->headers = NULL;
+      call IPAddress.getIPAddr(&ipmsg->hdr.ip6_src);
+      call IPAddress.getIPAddr(&ipmsg->hdr.ip6_dst);
+      ipmsg->hdr.ip6_src.s6_addr16[7] = rih->match.dest;
+
+      newext->nxt_hdr = IPV6_ROUTING;
+      newext->len = sizeof(struct ip6_ext) + sizeof(struct tlv_hdr) + 
+        sizeof(struct rinstall_header);
+      newtlv->type = TLV_TYPE_INSTALL;
+      newtlv->len = sizeof(struct tlv_hdr) + sizeof(struct rinstall_header);
+
+      ip_memcpy(&newrih->match, &rih->match, sizeof(struct flow_match));
+      newrih->flags = rih->flags;
+      newrih->path_len = 0;
+
+      iproute->nxt_hdr = IPV6_NONEXT;
+      iproute->len = sizeof(struct ip6_route) + (sizeof(cmpr_ip6_addr_t) * rih->path_len);
+      iproute->type = IP6ROUTE_TYPE_SOURCE;
+      iproute->segs_remain = rih->path_len;
+      ip_memcpy(iproute->hops, rih->path, sizeof(cmpr_ip6_addr_t) * rih->path_len);
+      
+      call TGenSend.bareSend(ipmsg, iproute, IP_NOHEADERS);
+      ip_free(buf);
+      // we should be all set up now.  
+    }
+#endif
+  }
+
+  
+  uint16_t getConfidence(struct neigh_entry *neigh) {
+    //uint8_t i;
+    uint16_t conf = 0;
+    if (neigh != NULL && IS_NEIGH_VALID(neigh)) {
+      //for (i = 0; i < N_EPOCHS_COUNTED; i++) {
+      //conf += neigh->stats[(current_epoch + N_EPOCHS - i) % N_EPOCHS].total;
+        //}
+      conf = neigh->stats[LONG_EPOCH].total;
+    }
+    return conf;
+  }
+
+  uint16_t getReceptions(struct neigh_entry *neigh) {
+    //uint8_t i;
+    uint16_t receptions = 0;
+    if ((neigh != NULL) && (IS_NEIGH_VALID(neigh))) {
+      //for (i = 0; i < N_EPOCHS_COUNTED; i++) {
+      //receptions += neigh->stats[(current_epoch + N_EPOCHS - i) % N_EPOCHS].receptions;
+        //}
+      receptions += neigh->stats[receptions].receptions;
+    }
+    return receptions;
+  }
+
+  uint16_t getSuccess(struct neigh_entry *neigh) {
+    //uint8_t i;
+    uint16_t succ = 0;
+    if ((neigh != NULL) && (IS_NEIGH_VALID(neigh))) {
+      //for (i = 0; i < N_EPOCHS_COUNTED; i++) {
+      //succ += neigh->stats[(current_epoch + N_EPOCHS - i) % N_EPOCHS].success;
+      //}
+      succ += neigh->stats[LONG_EPOCH].success;
+    }
+    return succ;
+  }
+
+  uint16_t getLinkCost(struct neigh_entry *neigh) {
+    uint16_t conf, succ;
+    conf = getConfidence(neigh);
+    succ = getSuccess(neigh);
+    // we can return a real confidence if we have enough data
+    if (succ == 0 || conf == 0) return 0xff;
+    return ((conf * 10) / succ);
+  }
+        
+
+  void printTable() {
+#ifdef PRINTFUART_ENABLED
+    uint8_t i;
+#ifdef CENTRALIZED_ROUTING
+    uint8_t j, k;
+#endif
+    dbg("Table", "----------------------------------------___\n");
+    dbg("Table", "ind\tvalid\tmature\tneigh\thops\tconf\trecep\tcost\tetx\tlqi\tmetric\n");
+    for (i = 0; i < N_NEIGH; i++) {
+      if (&neigh_table[i] == default_route)
+        dbg("Table", "-- default --\n");
+      dbg("Table", "0x%x\t0x%x\t0x%x\t0x%x\t0x%x\t0x%x\t0x%x\t0x%x\t0x%x\t0x%x\t0x%x\n", i, 
+          (neigh_table[i].flags & T_VALID_MASK), (IS_MATURE(&(neigh_table[i]))),
+          neigh_table[i].neighbor, neigh_table[i].hops, getConfidence(&(neigh_table[i])), 
+          getReceptions(&(neigh_table[i])), neigh_table[i].costEstimate, 
+          getLinkCost(&(neigh_table[i])), neigh_table[i].linkEstimate, 
+          getMetric(&(neigh_table[i])));
+    }
+#ifdef CENTRALIZED_ROUTING
+    dbg("Table", "------ Valid Flow Tables -------\n");
+    dbg("Table", "valid\ttype\tnext\n");
+    for (j = 0; j < N_FLOW_ENT; j++) {
+      if (!(IS_VALID_SLOT(&(flow_table[j])))) continue;
+      dbg("Table", "\n -- Flow Table Slot [%u] , Dest: [0x%x] , Count: [0x%x] --\n", 
+          j, flow_table[j].match.dest, flow_table[j].count);
+      for (i = 0; i < N_FLOW_CHOICES; i++) {
+        if (IS_VALID_ENTRY(flow_table[j].entries[i]) && 
+            IS_FULL_TYPE(flow_table[j].entries[i])) {
+          dbg("Table", "0x%x\t0x%x\t", 
+              IS_VALID_ENTRY(flow_table[j].entries[i]), 
+              IS_FULL_TYPE(flow_table[j].entries[i]));
+          for (k = 0; k < flow_table[j].entries[i].pathE->path_len; k++)
+            dbg("Table", "0x%x\t", 
+                flow_table[j].entries[i].pathE->path[k]);
+          dbg("Table", "\n");
+        } else {
+          dbg("Table", "0x%x\t0x%x\t0x%x\n", 
+              IS_VALID_ENTRY(flow_table[j].entries[i]), 
+              IS_FULL_TYPE(flow_table[j].entries[i]),
+              nextHop_Flow(&(flow_table[j].entries[i])));
+        }
+      }
+    }
+#endif
+    dbg("Table", "----------------------------------------\n");
+#endif
+  }
+
+  uint16_t getMetric(struct neigh_entry *r) {
+    return (((r == NULL) || (!(IS_NEIGH_VALID(r)))) ? 
+            0xffff : (r->costEstimate + getLinkCost(r)));
+  }
+
+  // Selects a potential neighbor that is not the current default route
+  void chooseNewRandomDefault(bool force) {
+    uint8_t i;
+    uint8_t numNeigh = 0;
+    uint8_t chosenNeigh;
+    bool useHops = TRUE;
+
+    dbg("IPRouting", "Looking for a new default route\n");
+  retry:
+    for (i = 1; i < N_NEIGH; i++) {
+      if (!(IS_NEIGH_VALID(&(neigh_table[i])))) break;
+      if (&neigh_table[i] == default_route) continue;
+      if ((useHops && neigh_table[i].hops < neigh_table[0].hops) ||
+          (!useHops && neigh_table[i].costEstimate < neigh_table[0].costEstimate)) {
+        numNeigh++;
+      }
+    }
+
+    // There exist other neighbors with respectable hop counts
+    if (numNeigh) {
+      chosenNeigh = (call Random.rand16()) % numNeigh;
+      for (i = 1; i < N_NEIGH; i++) {
+        if (&neigh_table[i] == default_route) continue;
+        if ((useHops && neigh_table[i].hops < neigh_table[0].hops)
+            || (!useHops && neigh_table[i].costEstimate < neigh_table[0].costEstimate)) {
+          if (chosenNeigh) {
+            chosenNeigh--;
+          } else {
+            default_route = &neigh_table[i];
+            default_route_failures = 0;
+            return;
+          }
+        }
+      }
+    }
+
+    if (!force || !useHops) goto done;
+    numNeigh = 0;
+    useHops = FALSE;
+  goto retry;
+
+  done:
+    dbg("IPRouting", "No random route found\n");
+    default_route = &neigh_table[0];
+    default_route_failures = 0;
+  }
+  /*
+   * return: a send policy for a given attempt, including destination and one-hop neighbor.
+   *        if no default route is available, returns FAIL unless the
+   *        packet is destined to a link-local address, or a
+   *        all-node/all-routers local multicast group.
+   *
+   */
+  command error_t IPRouting.getNextHop(struct ip6_hdr   *hdr, 
+                                       struct ip6_route *sh,
+                                       ieee154_saddr_t prev_hop,
+                                       send_policy_t *ret) {
+    
+    int i;
+#ifdef CENTRALIZED_ROUTING
+    struct flow_entry *r = getFlowEntry_Header(hdr);
+#endif
+    prev_hop = 0;
+    ret->retries = BLIP_L2_RETRIES;
+    ret->delay = (BLIP_L2_DELAY % (call Random.rand16())) + BLIP_L2_DELAY;
+    ret->current = 0;
+    ret->nchoices = 0;
+/*     printfUART("determining next hop for message bound to: 0x%x (sh: %p)\n",  */
+/*                ntohs(hdr->ip6_dst.s6_addr16[7]), sh); */
+
+    if (sh != NULL) {
+      printfUART(" type: 0x%x, next hop: 0x%x, remain: 0x%x\n",
+          sh->type, ntohs(sh->hops[ROUTE_NENTRIES(sh) - sh->segs_remain]), sh->segs_remain);
+    }
+
+
+    // we only use the address in the source header if the record option is not used
+    // otherwise, we use normal routing.
+    if (sh != NULL && ((sh->type & ~IP6ROUTE_FLAG_MASK) == IP6ROUTE_TYPE_SOURCE)) {
+      // if it's source routed, grab the next address out of the header.
+
+
+      if (sh->segs_remain == 0) return FAIL;
+
+      ret->dest[0] = ntohs(sh->hops[ROUTE_NENTRIES(sh) - sh->segs_remain]);
+      ret->nchoices = 1;
+
+    } else if (hdr->ip6_dst.s6_addr[0] == 0xff &&
+               (hdr->ip6_dst.s6_addr[1] & 0xf) <= 0x03) {
+      //hdr->dst_addr[0] == 0xff && (hdr->dst_addr[1] & 0xf) == 0x2) {
+      // if it's multicast, for now, we send it to the local broadcast
+      ret->dest[0] = 0xffff;
+      ret->nchoices = 1;
+      ret->retries = 0;
+      ret->delay = 0;
+      return SUCCESS;
+    } else if (cmpPfx(hdr->ip6_dst.s6_addr, linklocal_prefix)) {
+      ret->dest[0] = ntohs(hdr->ip6_dst.s6_addr16[7]); //  (hdr->dst_addr[14] << 8) | hdr->dst_addr[15];
+      ret->nchoices = 1;
+      return SUCCESS; // Currently only want one choice for broadcast
+    } 
+
+    if (getNeighEntry(ntohs(hdr->ip6_dst.s6_addr16[7])) != NULL) {
+        dbg("IPRouting", "Directly adding next hop of dest: 0x%x\n", ntohs(hdr->ip6_dst.s6_addr16[7]));
+        ret->dest[ret->nchoices++] = ntohs(hdr->ip6_dst.s6_addr16[7]);
+    }
+    
+#ifdef CENTRALIZED_ROUTING
+    if (r != NULL)
+      updateFlowCounts(r);
+     
+    for (i = 0; i < N_FLOW_CHOICES; i++) {
+      ieee154_saddr_t next_choice;
+      if (r == NULL || 
+          !IS_VALID_ENTRY(r->entries[i]) || 
+          (IS_FULL_TYPE(r->entries[i]) && 
+           r->entries[i].pathE->path_len > 1)) break;
+      next_choice = nextHop_Flow(&(r->entries[i]));
+      if (next_choice != prev_hop) {
+        ret->dest[ret->nchoices++] = next_choice;
+        dbg("Install", "Match: Neighbor 0x%x provided as choice 0x%x\n", 
+            ret->dest[i], ret->nchoices - 1);
+      }
+    }
+#endif
+
+    //dbg("IPRouting", "flags: 0x%x neigh: 0x%x\n", r->flags, r->neighbor);
+    if (IS_NEIGH_VALID(default_route) && prev_hop != default_route->neighbor) {
+      ret->dest[ret->nchoices++] = default_route->neighbor;
+    } else {
+      dbg("IPRouting", "Invalid default route... quitting\n");
+      /*
+       * if we failed because the default route is invalid, we want to
+       * trigger a routing update whenever we manage to reattach.
+       */
+      traffic_sent = FALSE;
+      return FAIL;
+    }
+    i = 0;
+    while (ret->nchoices < N_PARENT_CHOICES && i < N_NEIGH) {
+      if (IS_NEIGH_VALID(&neigh_table[i]) &&
+          &neigh_table[i] != default_route &&
+          neigh_table[i].neighbor != prev_hop) {
+        ret->dest[ret->nchoices++] = neigh_table[i].neighbor;
+      }
+      i++;
+    }
+    
+    if (ret->nchoices == 0)
+      return FAIL;
+    
+    dbg("IPRouting", "getNextHop: nchoices: 0x%x\n", ret->nchoices);
+    
+    return SUCCESS;
+  }
+
+  command uint8_t IPRouting.getHopLimit() {
+    // advertise our best path to the root
+    if (IS_NEIGH_VALID(&(neigh_table[0])))// && IS_MATURE(&neigh_table[0]))
+      return neigh_table[0].hops + 1;
+    else return 0xf0;
+  }
+
+  command uint16_t IPRouting.getQuality() {
+    if (IS_NEIGH_VALID(&(neigh_table[0])))
+      return getMetric(&(neigh_table[0]));
+    else return 0xffff;
+  }
+
+  
+  /*
+   * An advertisement was received from a neighboring node
+   *
+   * Processing steps:
+   * 1) First must check to see if the neighbor already exists in the table
+   *  a) If so, we are just updating its information
+   * 2) If not in table, check to make sure that the lqi passes the low-filter bar.
+   *  a) If not, return
+   * 3) If there is an empty space
+   *  a) Insert it in the open space
+   *  b) (Do we then want to move it up to where it belongs based on total path cost?)
+   * 4) If there is no open space
+   *  a) If the last entry doesn't meet the confidence threshold (CONF_EVICT_THRESHOLD), do nothing
+   *  b) Otherwise, replace last entry if:
+   *    i) Advertised Path Cost difference is greater than PATH_COST_DIFF_THRESH
+   *    ii) Advertised Path Cost difference is within PATH_COST_DIFF_THRESH, 
+   *         and Link estimate is lower by at least LQI_DIFF_THRESH
+   * 5) Make sure to update the receptions statistic
+   */ 
+  command void IPRouting.reportAdvertisement(ieee154_saddr_t neigh, uint8_t hops, 
+                                             uint8_t lqi, uint16_t cost) {
+    //int i, place = N_NEIGH;
+    //bool mustInsert = FALSE, exists = FALSE;
+    //uint8_t maxCost = 0;
+    //bool recount = FALSE;
+    struct neigh_entry *neigh_slot =  NULL;
+    dbg("IPRouting", "report adv: 0x%x 0x%x 0x%x 0x%x\n", neigh, hops, lqi, cost);
+    dbg("IPRouting", "my Cost: 0x%x\n", getMetric(&(neigh_table[0])));
+   
+    // If neighbor does not exist in table 
+    if ((neigh_slot = getNeighEntry(neigh)) == NULL) {
+      dbg("IPRouting", "Advertisement from new neighbor 0x%x!\n", neigh);
+      if (adjustLQI(lqi) > LQI_ADMIT_THRESH || cost == 0xffff) {
+        dbg("IPRouting", "Poor Link.  Rejecting\n");
+        return;
+      }
+      // free spots in the table.
+      if(!(IS_NEIGH_VALID(&(neigh_table[N_NEIGH - 1])))) {
+        
+        dbg("IPRouting", "Neighbor being inserted in empty slot: 0x%x\n", N_NEIGH - 1);
+        for (neigh_slot = &(neigh_table[N_NEIGH - 1]); 
+             neigh_slot > &(neigh_table[0]); neigh_slot--) {
+          // we might go ahead of other neighbors if we haven't heard
+          // from them either and our cost is better.
+          if (IS_NEIGH_VALID(neigh_slot - 1) &&
+              getConfidence(neigh_slot - 1) == 0 &&
+              (((struct neigh_entry *)(neigh_slot - 1))->costEstimate > cost)) {
+            swapNodes((neigh_slot - 1), neigh_slot);
+          } else if (IS_NEIGH_VALID(neigh_slot - 1)) {
+            // if we didn't catch on the first check and the next
+            // highest guy in the table is valid, we'll just go at the
+            // end.  If this never catches, the loop will terminate
+            // with neigh_slot == &neigh_table[0].
+            break;
+          }
+        }
+        ip_memclr((void *)neigh_slot, sizeof(struct neigh_entry));
+      } else {
+        // evict the bottom guy?
+        dbg("IPRouting", "No empty slots...looking to replace bottom entry\n");
+        //if (getConfidence(&(neigh_table[N_NEIGH - 1])) >= CONF_EVICT_THRESHOLD) {
+        if (IS_MATURE(&(neigh_table[N_NEIGH - 1])) ||
+            hops <= neigh_table[N_NEIGH - 1].hops) {
+          dbg("IPRouting", "Bottom entry evictable\n");
+          // we're a lot better,
+          if ((checkThresh(neigh_table[N_NEIGH - 1].costEstimate, cost, 
+                           PATH_COST_DIFF_THRESH) == BELOW_THRESH) || 
+              // or we're about equal and the link estimate is better
+              ((checkThresh(neigh_table[N_NEIGH - 1].costEstimate, cost, 
+                            PATH_COST_DIFF_THRESH) == WITHIN_THRESH) && 
+               (checkThresh(neigh_table[N_NEIGH - 1].linkEstimate, adjustLQI(lqi), 
+                            LQI_DIFF_THRESH) == BELOW_THRESH))) {
+            dbg("Evictions", "evict: bottom entry\n");
+
+            // use evict to correctly handle the case when we evict
+            // the default route.
+            evictNeighbor(&neigh_table[N_NEIGH - 1]);
+            neigh_slot = &(neigh_table[N_NEIGH - 1]);
+          }
+        }
+      }
+    } else {
+      if (cost == 0xffff) {
+        dbg("Evictions", "evict with cost 0xffff\n");
+        evictNeighbor(neigh_slot);
+        return;
+      }
+      // Do this to prevent double counting because of reportReception
+      neigh_slot->stats[SHORT_EPOCH].receptions--; 
+    }
+      
+    if (neigh_slot != NULL) {
+      SET_NEIGH_VALID(neigh_slot);
+      neigh_slot->neighbor = neigh;
+      neigh_slot->hops = hops;
+      neigh_slot->costEstimate = cost;
+      neigh_slot->linkEstimate = adjustLQI(lqi);
+      neigh_slot->stats[SHORT_EPOCH].receptions++;
+      dbg("IPRouting", "currentEpoch: 0x%x, Receptions in epoch: 0x%x, Total Receptions: 0x%x\n", 
+                 SHORT_EPOCH, neigh_slot->stats[SHORT_EPOCH].receptions, getReceptions(neigh_slot));
+    }
+    printTable();
+  }
+
+  /*
+   * Reports packet reception
+   *
+   * Updates the link estimate, as well as the number of receptions
+   */
+  command void IPRouting.reportReception(ieee154_saddr_t neigh, uint8_t lqi) {
+    struct neigh_entry *e = getNeighEntry(neigh);
+    dbg("IPRouting", "Packet received from 0x%x lqi: %u\n", neigh, lqi);
+    //if (e == NULL) e = addNeighEntry(neigh);
+    if (e != NULL) {
+      e->linkEstimate = adjustLQI(lqi);
+      // e->stats[current_epoch].receptions++;
+      //if (e == &(neigh_table[0]))
+        //resetNeighLow();
+      //else if (getMetric(e) < getMetric(&(neigh_table[0]))) {
+        //sortFlowTable();
+        //resetNeighLow();
+      //}
+    }
+  }
+
+  // Updates success (and failure) statistics
+  // Also needs to reroute if the number of failures hits the threshold 
+  event void IPExtensions.reportTransmission(uint8_t label, send_policy_t *policy) {
+    int i;
+    struct neigh_entry *e = NULL;
+    
+    // If not a broadcast address:
+    //  1. If none of the provided addresses worked, then we should send out a solicitation
+    //  2. All the failed nodes should have their totals increased by the max number of retries
+    //  3. The successful node should update both its total and success by one
+    //  4. If the successful node meets one of the following two conditions, it should be moved up one spot:
+    //   a) It has a lower path cost and higher confidence than the above entry
+    //   b) It has a similar path cost and confidence above a threshold (CONF_PROM_THRESHOLD)
+    //  5. If we have had too many consecutive losses (MAX_CONSEC_FAILURES) toggle ReRouting
+    if (policy->dest[0] != IEEE154_BROADCAST_ADDR) {
+      // BLIP_STATS_INCR(stats.messages);
+      dbg("IPRouting", "reportTransmission: current: 0x%x, nchoices: 0x%x, retries: 0x%x\n", 
+                 policy->current, policy->nchoices, policy->actRetries); 
+
+      // update the failed neighbor statistics
+      for (i = 0; i < policy->current; i++) {
+        e = getNeighEntry(policy->dest[i]);
+        if (e != NULL) {
+          // SDH : presumably retries == actRetries
+          e->stats[SHORT_EPOCH].total += policy->retries;
+          
+          if (e == default_route) {
+            default_route_failures++;
+          }
+
+          dbg("IPRouting", "reportTransmissions: 0x%x failed\n", e->neighbor);
+
+          // stats.transmissions += policy->retries;
+        }
+      }
+
+      if (default_route_failures > MAX_CONSEC_FAILURES) {
+        dbg("IPRouting", "Too many consecutive failures!\n");
+        chooseNewRandomDefault(TRUE);
+      }
+      
+      // if we succeeded sending the packet, increment the success on that one.
+      e = getNeighEntry(policy->dest[policy->current]);
+      if ((policy->current < policy->nchoices) && e != NULL) {
+        e->stats[SHORT_EPOCH].success += 1;
+        e->stats[SHORT_EPOCH].total += policy->actRetries;
+
+        dbg("IPRouting", "Success: 0x%x, Total: 0x%x, ETX: 0x%x (addr 0x%x)\n", 
+                   getSuccess(e), getConfidence(e), getLinkCost(e), e->neighbor);
+        dbg("IPRouting", "Actual attempts was 0x%x\n", policy->actRetries);
+
+        if (e == default_route)
+          default_route_failures++;
+
+
+        if ((e != &(neigh_table[0])) && 
+            // we have higher confidence and lower cost
+            (((getConfidence(e) > CONF_PROM_THRESHOLD) && // getConfidence(e - 1)) && 
+              (checkThresh(getMetric(e), getMetric(e-1), PATH_COST_DIFF_THRESH) == BELOW_THRESH)) || 
+             // we have similar cost and sufficient confidenceIP
+             ((checkThresh(getMetric(e), getMetric(e-1), PATH_COST_DIFF_THRESH) == WITHIN_THRESH) && 
+              (getConfidence(e) > CONF_PROM_THRESHOLD)))) {
+
+          dbg("IPRouting", "Promoting node 0x%x over node 0x%x\n", e->neighbor, (e-1)->neighbor);
+          swapNodes((e - 1), e);
+        }
+
+        // stats.successes += 1;
+        // stats.transmissions += policy->actRetries;
+      } else {
+        dbg("IPRouting", "FAILURE!!!!!\n");
+      }
+    }
+  }
+
+  /*
+   * @returns TRUE if the routing engine has established a default route.
+   */
+  command bool IPRouting.hasRoute() {    
+    return (IS_NEIGH_VALID(&(neigh_table[0])));
+  }
+
+  struct ip6_route *insertSourceHeader(struct split_ip_msg *msg, struct flow_entry *entry) {
+    // these actually need to be static
+    static uint8_t source_buf[sizeof(struct ip6_route) + MAX_PATH_LENGTH * sizeof(uint16_t)];
+    static struct generic_header g_sh;
+    struct ip6_route *sh = (struct ip6_route *)source_buf;
+    uint8_t i;
+
+    sh->nxt_hdr = msg->hdr.nxt_hdr;
+    msg->hdr.nxt_hdr = IPV6_ROUTING;
+
+    sh->len = sizeof(struct ip6_route) + entry->entries[0].pathE->path_len * sizeof(uint16_t);
+    sh->type = IP6ROUTE_TYPE_SOURCE;
+    sh->segs_remain = entry->entries[0].pathE->path_len;
+
+    g_sh.hdr.ext = (struct ip6_ext *)sh;
+    g_sh.len = sh->len;
+    g_sh.next = msg->headers;
+    msg->headers = &g_sh;
+
+    dbg("Install", "Inserted source header with length 0x%x and next hop: 0x%x\n", 
+        entry->entries[0].pathE->path_len, entry->entries[0].pathE->path[0]);
+
+    for (i = 0; i < entry->entries[0].pathE->path_len; i++) {
+      sh->hops[i] = ntohs(entry->entries[0].pathE->path[i]);
+    }
+    return sh;
+  }
+
+#ifdef CENTRALIZED_ROUTING
+  command void IPRouting.clearFlows() {
+    int i, j;
+    for (i = 0; i < N_FLOW_ENT; i++) {
+      SET_INVALID_SLOT((&(flow_table[i])));
+      flow_table[i].count = N_FLOW_ENT;
+      for (j = 0; j < N_FLOW_CHOICES; j++) {
+        SET_INVALID_ENTRY(flow_table[i].entries[j]);
+      }
+    }
+
+    for (i = 0; i < N_FULL_PATH_ENTRIES; i++) {
+      full_path_entries[i].path_len = 0;
+    }
+  }
+#endif
+
+#define convertTo8(X)  ((X) > 0xff ? 0xff : (X))
+
+  /*
+   * Inserts all necessary routing headers for the packet
+   * 
+   * If packet is going to the root, inserts a topology information
+   *  collection header
+   *  XXX : SDH : the detection of weather it's going to the root is 
+   *              very broken...
+   *
+   */
+
+  event struct tlv_hdr *DestinationExt.getHeader(int label,int nxt_hdr,
+                                                 struct ip6_hdr *iph) {
+    static uint8_t sh_buf[sizeof(struct tlv_hdr) + 
+                          sizeof(struct topology_header) +
+                          (sizeof(struct topology_entry) * N_NEIGH)];
+    struct tlv_hdr *tlv =    (struct tlv_hdr *)sh_buf;
+    struct topology_header *th = (struct topology_header *)(tlv + 1);
+
+    tlv->len = sizeof(struct tlv_hdr) + sizeof(struct topology_header);
+    tlv->type = TLV_TYPE_TOPOLOGY;
+
+    if (iph->ip6_dst.s6_addr[0] == 0xff &&
+        (iph->ip6_dst.s6_addr[1] & 0xf) <= 3) {
+      return NULL;
+    }
+
+    printfUART("inserting destination options header\n");
+
+    // AT: We theoretically only want to attach this topology header if we're
+    //  sending this message to a controller.  Isn't it easier to just check
+    //  to see if the dest address matches that of the sink?
+    // SDH: how do you know what the address of the sink is?  
+    // some how we need to check if we're using a default route and
+    // only attach the topology information if we are.  This still isn't
+    // perfect since somebody further down the tree may have a route and the
+    // packet might not get to the controller.
+    if (iph->nxt_hdr == IANA_UDP || 
+        iph->nxt_hdr == IPV6_NONEXT) {
+      int i,j = 0;
+      if (iph->ip6_dst.s6_addr16[0] == htons(0xff02)) return NULL;
+      if (traffic_sent) return NULL;
+      
+      traffic_sent = TRUE;
+
+      // only add topology information directly behind actual payload
+      // headers.
+      // SDH : TODO : check that this will not fragment the packet...
+      // AT: Why do we care about the number of hops? Debugging purposes?
+      th->seqno = reportSeqno++;
+      th->seqno = htons(th->seqno);
+
+      // For all these 16-bit values, we're only using 8 bit values
+      for (i = 0; i < N_NEIGH; i++) {
+        if (IS_NEIGH_VALID(&neigh_table[i]) && j < 4 && 
+            (IS_MATURE(&neigh_table[i]) || default_route == &neigh_table[i])) {
+          th->topo[j].etx = convertTo8(getLinkCost(&neigh_table[i]));
+          th->topo[j].conf = convertTo8(getConfidence(&neigh_table[i]));
+          th->topo[j].hwaddr = htons(neigh_table[i].neighbor);
+          j++;
+          tlv->len += sizeof(struct topology_entry);
+          dbg("Lqi", "link est: 0x%x hops: 0x%x\n", 
+              neigh_table[i].linkEstimate, neigh_table[i].hops);
+        }
+      }
+      if (j > 0) {
+        return tlv;
+      }
+    }
+    return NULL;
+  }
+
+  event void DestinationExt.free() {
+
+  }
+
+  command struct ip6_route *IPRouting.insertRoutingHeader(struct split_ip_msg *msg) {
+    // these actually need to be static
+#ifdef CENTRALIZED_ROUTING
+    struct flow_entry *entry;
+
+    // Need to source route this packet
+    //  Put this last because theoretically we could have a source
+    //  routed packet to the root, in which case it would have a topo
+    //  header, but the source header must always be the first in the
+    //  header list
+    if (((entry = getFlowEntry_Header(&msg->hdr)) != NULL) &&
+        IS_FULL_TYPE(entry->entries[0]) &&
+        entry->entries[0].pathE->path_len > 1) {
+      dbg("IPRouting", "Inserting a source routing header for a full path!\n");
+      updateFlowCounts(entry);
+      return insertSourceHeader(msg, entry);
+    }
+
+#endif
+    return NULL;
+  }
+
+  /*
+   * Sort timer will no longer be used only for sorting, but rather to expire an epoch and
+   *  change entry statistics
+   */
+  event void SortTimer.fired() {
+    dbg("IPRouting", "Epoch ended!\n");
+    printTable();
+
+    if (!call IPRouting.hasRoute() && !soliciting) {
+      call ICMP.sendSolicitations();
+      soliciting = TRUE;
+    }
+
+    if (checkThresh(call IPRouting.getQuality(), last_qual, 5) != WITHIN_THRESH ||
+        last_hops != call IPRouting.getHopLimit()) {
+      call ICMP.sendAdvertisements();
+      last_qual = call IPRouting.getQuality();
+      last_hops = call IPRouting.getHopLimit();
+    }
+
+    updateRankings();
+
+    if (call Random.rand16() % 32 < 8) {
+      dbg("IPRouting", "Attemting exploration\n");
+      chooseNewRandomDefault(FALSE);
+    } else {
+      // default_route = &neigh_table[0];
+      default_route_failures = 0;
+    }
+  }
+
+  
+  /*
+   * This is called when the ICMP engine finishes sending out router solicitations.
+   *
+   * We will keep sending solicitations so long as we have not
+   * established a default route.
+   *
+   */
+  event void ICMP.solicitationDone() {
+    //int i;
+
+    dbg("IPRouting", "done soliciting\n");
+
+    soliciting = FALSE;
+
+    if (!call IPRouting.hasRoute()) {
+      call ICMP.sendSolicitations();
+      soliciting = TRUE;
+    }
+  }
+
+  command void Statistics.get(route_statistics_t *statistics) {
+    //struct neigh_entry *p = getNeighEntry((getFlowEntry_Header(NULL))->entries[0].nextHop);
+    // struct neigh_entry *p = &(neigh_table[0]);
+    // stats.hop_limit = call IPRouting.getHopLimit();
+//    if (p != NULL) {
+//      ip_memcpy(&stats.parent, p, sizeof(struct neigh_entry));
+      // stats.parentmetric = getMetric(p);
+//    }
+    statistics->hop_limit = call IPRouting.getHopLimit();
+    statistics->parent = (uint16_t) default_route->neighbor; 
+    statistics->parent_metric = call IPRouting.getQuality(); 
+    statistics->parent_etx = getMetric(default_route);
+  }
+
+  command void Statistics.clear() {
+    // ip_memclr((uint8_t *)&stats, sizeof(route_statistics_t));
+  }
+
+  void evictNeighbor(struct neigh_entry *neigh) {
+    struct neigh_entry *iterator;
+    bool reset_default = FALSE;
+
+    dbg("IPRouting", "Evicting neighbor 0x%x\n", neigh->neighbor);
+    dbg("Evictions", "evict: 0x%x\n", neigh->neighbor);
+
+    SET_NEIGH_INVALID(neigh);
+
+    if (neigh == default_route) {
+      reset_default = TRUE;
+    }
+
+    ip_memclr((uint8_t *)(neigh), sizeof(struct neigh_entry));
+    for (iterator = neigh; iterator < &(neigh_table[N_NEIGH - 1]); iterator++) {
+      if (!IS_NEIGH_VALID(iterator + 1)) break;
+      swapNodes(iterator, iterator + 1);
+    }
+
+    if (reset_default) {
+      // send new topology updates quickly to let an edge router know
+      // that something happened.
+      restartTrafficGen();
+      default_route = &neigh_table[0];
+      default_route_failures = 0;
+    }
+
+    printTable();
+  }
+
+  // Typically called after an epoch change
+  void updateRankings() {
+    uint8_t i;
+    bool evicted = FALSE;
+
+    for (i = 0; i < N_NEIGH; i++) {
+      UNSET_EVICT(neigh_table[i]);
+      if (!IS_NEIGH_VALID(&neigh_table[i])) continue;
+      neigh_table[i].stats[LONG_EPOCH].total += neigh_table[i].stats[SHORT_EPOCH].total;
+      neigh_table[i].stats[LONG_EPOCH].receptions += neigh_table[i].stats[SHORT_EPOCH].receptions;
+      neigh_table[i].stats[LONG_EPOCH].success += neigh_table[i].stats[SHORT_EPOCH].success;
+      
+      if (neigh_table[i].stats[LONG_EPOCH].total & (0xf000)) {
+        // if we're this big, the etx computation might overflow.
+        // Make it smaller by dividing top and bottom by 2.
+        neigh_table[i].stats[LONG_EPOCH].total >>= 1;
+        neigh_table[i].stats[LONG_EPOCH].success >>= 1;
+      }
+      
+      if (neigh_table[i].stats[LONG_EPOCH].total > CONF_EVICT_THRESHOLD) 
+        SET_MATURE(&neigh_table[i]);
+
+      if (IS_MATURE(&(neigh_table[i]))) {
+        uint16_t cost;
+        // if we didn't try the link, don't evict it            
+        if (neigh_table[i].stats[SHORT_EPOCH].total == 0) goto done_iter;
+        if (neigh_table[i].stats[SHORT_EPOCH].success == 0) {
+          cost = 0xff;
+        } else {
+          cost = (10 * neigh_table[i].stats[SHORT_EPOCH].total) / 
+            neigh_table[i].stats[SHORT_EPOCH].success;
+        }
+        if (cost > LINK_EVICT_THRESH) {
+          dbg("Evictions", "cost: 0x%x, slot %i\n", cost, i);
+          SET_EVICT(neigh_table[i]);
+        }
+      }
+    done_iter:
+      neigh_table[i].stats[SHORT_EPOCH].total = 0;
+      neigh_table[i].stats[SHORT_EPOCH].receptions = 0;
+      neigh_table[i].stats[SHORT_EPOCH].success = 0;
+    }
+    for (i = 0; i < N_NEIGH; i++) {
+      if (IS_NEIGH_VALID(&neigh_table[i]) &&
+          SHOULD_EVICT(neigh_table[i])) {
+// #if 0
+        // SDH : because of the overflow bug, this was never being
+        // triggered.  I'm not sure it's actually a good idea because
+        // it seems to increase path lengths for heavily used routes.
+        // Let's disable it for now.
+        dbg("Evictions", "performing evict: %i\n", i);
+        evictNeighbor(&neigh_table[i]);
+        i --;
+// #endif
+        evicted = TRUE;
+      }
+    }
+    if (evicted)
+      call ICMP.sendSolicitations();
+  }
+
+  void swapNodes(struct neigh_entry *highNode, struct neigh_entry *lowNode) {
+    struct neigh_entry tempNode;
+    if (highNode == NULL || lowNode == NULL) return;
+    ip_memcpy(&tempNode, highNode, sizeof(struct neigh_entry));
+    ip_memcpy(highNode, lowNode, sizeof(struct neigh_entry));
+    ip_memcpy(lowNode, &tempNode, sizeof(struct neigh_entry));
+
+    if (highNode == default_route) default_route = lowNode;
+    else if (lowNode == default_route) default_route = highNode;
+  }
+
+  uint8_t checkThresh(uint32_t firstVal, uint32_t secondVal, uint16_t thresh) {
+    if (((firstVal > secondVal) && ((firstVal - secondVal) <= thresh)) || 
+        ((secondVal >= firstVal) && (secondVal - firstVal) <= thresh)) return WITHIN_THRESH;
+    if (((firstVal > secondVal) && ((firstVal - secondVal) > thresh))) return ABOVE_THRESH;
+    return BELOW_THRESH;
+  }
+}
diff --git a/tos/lib/net/blip/PrintfUART.h b/tos/lib/net/blip/PrintfUART.h
new file mode 100644 (file)
index 0000000..2d7e39f
--- /dev/null
@@ -0,0 +1,368 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/*                          
+ * Copyright (c) 2005
+ *     The President and Fellows of Harvard College.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* 
+ * Writes printf like output to the UART.  
+ * This works only on the AVR and MSP430 Microcontrollers!
+ * <p>
+ * Note: For AVR we explicitly place the print statements in ROM; for
+ * MSP430 this is done by default!  For AVR, if we don't place it
+ * explicitely in ROM, the statements will go in RAM, which will
+ * quickly cause a descent size program to run out of RAM.  By default
+ * it doesn't disable the interupts; disabling the interupts when
+ * writing to the UART, slows down/makes the mote quite unresponsive,
+ * and can lead to problems!  If you wish to disable all printfs to
+ * the UART, then comment the flag: <code>PRINTFUART_ENABLED</code>.
+
+ * <p> <pre>
+ * How to use:
+ *   // (0) In your Makefile, define PRINTFUART_ENABLED
+ *   CFLAGS += -DPRINTFUART_ENABLED
+ *   // (1) Call printfUART_init() from your initialization function 
+ *   //     to initialize the UART
+ *   printfUART_init();
+ *   // (2) Set your UART client to the correct baud rate.  Look at 
+ *   //     the comments in printfUART_init(), to figure out what 
+ *   //     baud to use for your particular mote
+ *
+ *   // (3) Send printf statements like this:
+ *   printfUART("Hello World, we are in year= %u\n", 2004);
+ *   printfUART("Printing uint32_t variable, value= %lu\n", 4294967295);
+ *
+ * Examples and caveats:
+ *   // (1) - Must use curly braces in single section statements.  
+ *            (Look in the app.c to see why -- hint: it's a macro)
+ *   if (x < 3)
+ *       {printfUART("The value of x is %i\n", x);}
+ *   // (2) - Otherwise it more or less works like regular printf
+ *   printfUART("\nThe value of x=%u, and y=%u\n", x, y); 
+ * </pre>
+ * <pre>URL: http://www.eecs.harvard.edu/~konrad/projects/motetrack</pre>
+ * @author Konrad Lorincz
+ * @version 2.0, January 5, 2005
+ */
+#ifndef PRINTFUART_H
+#define PRINTFUART_H
+#include <stdarg.h>
+#include <stdio.h>
+
+// -------------------------------------------------------------------
+#ifdef PRINTFUART_ENABLED
+    #define DEBUGBUF_SIZE 256
+    char debugbuf[DEBUGBUF_SIZE];
+    char debugbufROMtoRAM[DEBUGBUF_SIZE];
+
+    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
+        #define printfUART(__format...) {                          \
+            static const char strROM[] PROGMEM = __format;         \
+            strcpy_P((char*) &debugbufROMtoRAM, (PGM_P) &strROM);  \
+            sprintf(debugbuf, debugbufROMtoRAM);                   \
+            writedebug();                                          \
+        }   
+    #else  // assume MSP430 architecture (e.g. TelosA, TelosB, etc.)
+        #define printfUART(__format...) {      \
+            sprintf(debugbuf, __format);       \
+            writedebug();                      \
+        }  
+    #endif
+#else
+    #define printfUART(X, args...) dbg("printf", X, ## args)
+// #define printfUART(__format...) {}
+    void printfUART_init() {}
+#endif
+
+#define NOprintfUART(__format...)
+
+
+// -------------------------------------------------------------------
+#ifdef PRINTFUART_ENABLED
+
+/**
+ * Initialize the UART port.  Call this from your startup routine.
+ */
+#define printfUART_init() {atomic printfUART_init_private();}
+void printfUART_init_private()
+{
+    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2)
+        // 56K baud
+        outp(0,UBRR0H);
+        outp(15, UBRR0L);                              //set baud rate
+        outp((1<<U2X),UCSR0A);                         // Set UART double speed
+        outp(((1 << UCSZ1) | (1 << UCSZ0)) , UCSR0C);  // Set frame format: 8 data-bits, 1 stop-bit
+        inp(UDR0);
+        outp((1 << TXEN) ,UCSR0B);   // Enable uart reciever and transmitter
+
+    #else
+    #if defined(PLATFORM_MICA2DOT)  
+        // 19.2K baud
+        outp(0,UBRR0H);            // Set baudrate to 19.2 KBps
+        outp(12, UBRR0L);
+        outp(0,UCSR0A);            // Disable U2X and MPCM
+        outp(((1 << UCSZ1) | (1 << UCSZ0)) , UCSR0C);
+        inp(UDR0);
+        outp((1 << TXEN) ,UCSR0B);
+  
+    #else
+    #if defined(PLATFORM_IMOTE2)
+      //async command result_t UART.init() {
+        
+        /*** 
+           need to configure the ST UART pins for the correct functionality
+           
+           GPIO<46> = STDRXD = ALT2(in)
+           GPIO<47> = STDTXD = ALT1(out)
+        *********/
+        //atomic{
+          
+        //configure the GPIO Alt functions and directions
+        _GPIO_setaltfn(46,2);   // STD_RXD
+        _GPIO_setaltfn(47,1);   // STD_TXD
+        
+        _GPDR(46) &= ~_GPIO_bit(46);  // input
+        _GPDR(47) |= _GPIO_bit(47);   // output
+        
+        STLCR |=LCR_DLAB; //turn on DLAB so we can change the divisor
+        STDLL = 8;  //configure to 115200;
+        STDLH = 0;
+        STLCR &= ~(LCR_DLAB);  //turn off DLAB
+        
+        STLCR |= 0x3; //configure to 8 bits
+        
+        STMCR &= ~MCR_LOOP;
+        STMCR |= MCR_OUT2;
+        STIER |= IER_RAVIE;
+        STIER |= IER_TIE;
+        STIER |= IER_UUE; //enable the UART
+        
+        //STMCR |= MCR_AFE; //Auto flow control enabled;
+        //STMCR |= MCR_RTS;
+        
+        STFCR |= FCR_TRFIFOE; //enable the fifos
+        
+//        call Interrupt.allocate();
+//        call Interrupt.enable();
+        //configure all the interrupt stuff
+        //make sure that the interrupt causes an IRQ not an FIQ
+        // __REG(0x40D00008) &= ~(1<<21);
+        //configure the priority as IPR1
+        //__REG(0x40D00020) = (1<<31 | 21);
+        //unmask the interrupt
+        //__REG(0x40D00004) |= (1<<21);
+        
+        CKEN |= CKEN5_STUART; //enable the UART's clk    
+
+
+    #else  // assume TelosA, TelosB, etc.
+        // Variabel baud 
+        // To change the baud rate, see /tos/platform/msp430/msp430baudrates.h
+        uint8_t source = SSEL_SMCLK;
+        uint16_t baudrate = 0x0012; // UBR_SMCLK_57600=0x0012
+        uint8_t mctl = 0x84;        // UMCTL_SMCLK_57600=0x84
+        //uint16_t baudrate = 0x0009; // UBR_SMCLK_115200=0x0009
+        //uint8_t mctl = 0x10;        // UMCTL_SMCLK_115200=0x10
+
+
+        uint16_t l_br = 0;
+        uint8_t l_mctl = 0;
+        uint8_t l_ssel = 0;
+
+        TOSH_SEL_UTXD1_MODFUNC();
+        TOSH_SEL_URXD1_MODFUNC();
+
+
+        UCTL1 = SWRST;  
+        UCTL1 |= CHAR;  // 8-bit char, UART-mode
+    
+        U1RCTL &= ~URXEIE;  // even erroneous characters trigger interrupts
+
+        UCTL1 = SWRST;
+        UCTL1 |= CHAR;  // 8-bit char, UART-mode
+
+        if (l_ssel & 0x80) {
+            U1TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
+            U1TCTL |= (l_ssel & 0x7F); 
+        }
+        else {
+            U1TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
+            U1TCTL |= SSEL_ACLK; // use ACLK, assuming 32khz
+        }
+
+        if ((l_mctl != 0) || (l_br != 0)) {
+            U1BR0 = l_br & 0x0FF;
+            U1BR1 = (l_br >> 8) & 0x0FF;
+            U1MCTL = l_mctl;
+        }
+        else {
+            U1BR0 = 0x03;   // 9600 baud
+            U1BR1 = 0x00;
+            U1MCTL = 0x4A;
+        }
+      
+        ME2 &= ~USPIE1;   // USART1 SPI module disable
+        ME2 |= (UTXE1 | URXE1);   // USART1 UART module enable
+      
+        U1CTL &= ~SWRST;
+    
+        IFG2 &= ~(UTXIFG1 | URXIFG1);
+        IE2 &= ~(UTXIE1 | URXIE1);  // interrupt disabled
+
+   
+
+        //async command void USARTControl.setClockSource(uint8_t source) {
+        //    atomic {
+                l_ssel = source | 0x80;
+                U1TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
+                U1TCTL |= (l_ssel & 0x7F); 
+                //    }
+                //}
+                //async command void USARTControl.setClockRate(uint16_t baudrate, uint8_t mctl) {
+                //atomic {
+                l_br = baudrate;
+                l_mctl = mctl;
+                U1BR0 = baudrate & 0x0FF;
+                U1BR1 = (baudrate >> 8) & 0x0FF;
+                U1MCTL = mctl;
+                //}
+                //}
+
+                //async command result_t USARTControl.enableRxIntr(){
+                //atomic {
+                IFG2 &= ~URXIFG1;
+                IE2 |= URXIE1;
+                //}
+                //return SUCCESS;
+                //}
+
+                //async command result_t USARTControl.enableTxIntr(){
+                //atomic {
+                IFG2 &= ~UTXIFG1;
+                IE2 |= UTXIE1;
+                //}
+                //return SUCCESS;
+                //}     
+
+    #endif
+    #endif
+    #endif
+}
+
+#if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
+#else
+#if defined(PLATFORM_IMOTE2)
+#else // assume AVR architecture (e.g. TelosA, TelosB)
+    bool isTxIntrPending()
+    {
+        if (U1TCTL & TXEPT) {
+            return TRUE;
+        }
+        return FALSE;
+    }
+#endif
+#endif
+
+/**
+ * Outputs a char to the UART.
+ */
+void UARTPutChar(char c)
+{
+    if (c == '\n')
+        UARTPutChar('\r');
+
+
+    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
+        loop_until_bit_is_set(UCSR0A, UDRE);
+        outb(UDR0,c);
+
+    #else
+    #if defined(PLATFORM_IMOTE2)
+        STTHR = c;    
+
+    #else // assume AVR architecture (e.g. TelosA, TelosB)
+        U1TXBUF = c;  
+        while( !isTxIntrPending() )  
+            continue;
+    #endif
+    #endif
+}
+
+/**
+ * Outputs the entire debugbuf to the UART, or until it encounters '\0'.
+ */
+void writedebug()
+{
+    uint16_t i = 0;
+    
+    while (debugbuf[i] != '\0' && i < DEBUGBUF_SIZE)
+        UARTPutChar(debugbuf[i++]);
+}
+
+#endif  // PRINTFUART_ENABLED
+// -------------------------------------------------------------------
+
+#if 0
+// --------------------------------------------------------------
+#define assertUART(x) if (!(x)) { __assertUART(__FILE__, __LINE__); }
+void __assertUART(const char* file, int line)
+{
+    printfUART("ASSERT FAILED: file= %s, lineNbr= %i\n", file, line);
+    // for some reason, CLR means on
+    TOSH_MAKE_RED_LED_OUTPUT();
+    TOSH_MAKE_YELLOW_LED_OUTPUT();
+    TOSH_MAKE_GREEN_LED_OUTPUT();
+    TOSH_CLR_RED_LED_PIN();
+    TOSH_CLR_YELLOW_LED_PIN();
+    TOSH_CLR_GREEN_LED_PIN();
+    exit(1);
+}
+// --------------------------------------------------------------
+#endif
+
+#endif  // PRINTFUART_H
+
diff --git a/tos/lib/net/blip/ReadLqiC.nc b/tos/lib/net/blip/ReadLqiC.nc
new file mode 100644 (file)
index 0000000..7debe7d
--- /dev/null
@@ -0,0 +1,30 @@
+
+/*
+ * Different platforms have different ways of getting in touch with
+ * the LQI reading the radio provides.  This module wraps the
+ * different ways in platform-independent logic.
+ *
+ * 
+ * @author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
+ */
+
+configuration ReadLqiC {
+  provides interface ReadLqi;
+} implementation {
+  
+#if defined(PLATFORM_MICAZ) || defined(PLATFORM_TELOSB)  || \
+    defined(PLATFORM_EPIC)  || defined(PLATFORM_SHIMMER) || \
+    defined(PLATFORM_SHIMMER2) || defined(PLATFORM_INTELMOTE2)
+  // cc2420 platforms
+  components CC2420ReadLqiC, CC2420PacketC;
+  ReadLqi = CC2420ReadLqiC;
+  CC2420ReadLqiC.CC2420Packet -> CC2420PacketC;
+#elif defined(PLATFORM_IRIS) 
+  components RF230ReadLqiC, RF230Ieee154MessageC;
+  ReadLqi = RF230ReadLqiC;
+  RF230ReadLqiC.SubLqi -> RF230Ieee154MessageC.PacketLinkQuality;
+#else
+#error "No radio support is available for your platform"
+#endif
+
+}
diff --git a/tos/lib/net/blip/ResourceSendP.nc b/tos/lib/net/blip/ResourceSendP.nc
new file mode 100644 (file)
index 0000000..31f6ff0
--- /dev/null
@@ -0,0 +1,62 @@
+
+#include <Ieee154.h>
+
+#include "PrintfUART.h"
+
+module ResourceSendP {
+  provides interface Ieee154Send;
+  uses interface Resource;
+  uses interface Ieee154Send as SubSend;
+} implementation {
+  ieee154_saddr_t m_addr;
+  message_t      *m_msg = NULL;
+  uint8_t         m_len;
+  
+  command error_t Ieee154Send.send(ieee154_saddr_t addr,
+                                   message_t* msg,
+                                   uint8_t len) {
+    if (m_msg != NULL) return EBUSY;
+
+    m_addr = addr;
+    m_msg = msg;
+    m_len = len;
+
+    call Resource.request();
+    return SUCCESS;
+  }
+
+  event void SubSend.sendDone(message_t* msg, error_t result) {
+    call Resource.release();
+    signal Ieee154Send.sendDone(msg, result);
+    m_msg = NULL;
+  }
+
+  event void Resource.granted() {
+    error_t rc;
+    if ((rc = (call SubSend.send(m_addr, m_msg, m_len))) != SUCCESS) {
+      signal Ieee154Send.sendDone(m_msg, rc);
+      m_msg = NULL;
+      call Resource.release();
+    }
+  }
+
+  command error_t Ieee154Send.cancel(message_t* msg) {
+    if (m_msg != NULL) {
+      call Resource.release();
+      m_msg = NULL;
+      return call SubSend.cancel(msg);
+    } else {
+      return FAIL;
+    }
+  }
+
+  command uint8_t Ieee154Send.maxPayloadLength() {
+    return call SubSend.maxPayloadLength();
+  }
+
+  command void* Ieee154Send.getPayload(message_t* m, uint8_t len) {
+    return call SubSend.getPayload(m, len);
+  }
+
+
+}
diff --git a/tos/lib/net/blip/Statistics.h b/tos/lib/net/blip/Statistics.h
new file mode 100644 (file)
index 0000000..6f5a5fb
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _BLIP_STATISTICS_H_
+#define _BLIP_STATISTICS_H_
+
+/* Different IP components provide statistics about their operation. 
+ *
+ * Structures with this information is available here.
+ */
+
+#ifdef BLIP_STATS
+// if we get rid of the increments the compiler can optimize out the
+// statistics data structures when we don't use them.
+#define BLIP_STATS_INCR(X) X++
+#else
+#define BLIP_STATS_INCR(X)
+#endif
+
+
+/* Statistics from the core 6lowpan/IPv6 fragmentation and forwarding engine */
+typedef nx_struct {
+  nx_uint16_t sent;       // total IP datagrams sent
+  nx_uint16_t forwarded;  // total IP datagrams forwarded
+  nx_uint8_t rx_drop;     // L2 frags dropped due to 6lowpan failure
+  nx_uint8_t tx_drop;     // L2 frags dropped due to link failures
+  nx_uint8_t fw_drop;     // L2 frags dropped when forwarding due to queue overflow
+  nx_uint8_t rx_total;    // L2 frags received
+  nx_uint8_t encfail;     // frags dropped due to send queue
+
+#ifdef BLIP_STATS_IP_MEM
+  // statistics about free memory
+  // mostly useful for looking for memory leaks, or looking at
+  // forwarding queue depth.
+  nx_uint8_t fragpool;    // free fragments in pool
+  nx_uint8_t sendinfo;    // free sendinfo structures
+  nx_uint8_t sendentry;   // free send entryies
+  nx_uint8_t sndqueue;    // free send queue entries
+  nx_uint16_t heapfree;   // available free space in the heap
+#endif
+} ip_statistics_t;
+
+
+typedef nx_struct {
+  nx_uint8_t hop_limit;
+  nx_uint16_t parent;
+  nx_uint16_t parent_metric;
+  nx_uint16_t parent_etx;
+} route_statistics_t;
+
+typedef nx_struct {
+  nx_uint8_t sol_rx;
+  nx_uint8_t sol_tx;
+  nx_uint8_t adv_rx;
+  nx_uint8_t adv_tx;
+  nx_uint8_t echo_rx;
+  nx_uint8_t echo_tx;
+  nx_uint8_t unk_rx;
+  nx_uint16_t rx;
+} icmp_statistics_t;
+
+/* Statistics from the UDP transport protocol  */
+typedef nx_struct {
+  nx_uint16_t sent;  // UDP datagrams sent from app
+  nx_uint16_t rcvd;  // UDP datagrams delivered to apps
+  nx_uint16_t cksum; // UDP datagrams dropped due to checksum error
+} udp_statistics_t;
+
+
+#endif
diff --git a/tos/lib/net/blip/TcpC.nc b/tos/lib/net/blip/TcpC.nc
new file mode 100644 (file)
index 0000000..87a2167
--- /dev/null
@@ -0,0 +1,17 @@
+
+configuration TcpC {
+  provides interface Tcp[uint8_t client];
+} implementation {
+
+  components MainC, IPDispatchC, TcpP, IPAddressC;
+  components new TimerMilliC();
+
+  Tcp = TcpP;
+
+  MainC -> TcpP.Init;
+  TcpP.Boot -> MainC;
+  TcpP.IP -> IPDispatchC.IP[IANA_TCP];
+
+  TcpP.Timer -> TimerMilliC;
+  TcpP.IPAddress -> IPAddressC;
+}
diff --git a/tos/lib/net/blip/TcpP.nc b/tos/lib/net/blip/TcpP.nc
new file mode 100644 (file)
index 0000000..23d6cd6
--- /dev/null
@@ -0,0 +1,154 @@
+
+#include <table.h>
+#include <ip.h>
+
+module TcpP {
+  provides interface Tcp[uint8_t client];
+  provides interface Init;
+  uses {
+    interface Boot;
+
+    interface IP;    
+    interface Timer<TMilli>;
+    interface IPAddress;
+  }
+} implementation {
+
+  enum {
+    N_CLIENTS = uniqueCount("TCP_CLIENT"),
+  };
+
+#include <tcplib.h>
+  struct tcplib_sock socks[N_CLIENTS];
+
+  int find_client(struct tcplib_sock *conn) {
+    int i;
+    for (i = 0; i < N_CLIENTS; i++)
+      if (&socks[i] == conn) break;
+
+    return i;
+  }
+
+  void tcplib_extern_connectdone(struct tcplib_sock *sock, int error) {
+    int cid = find_client(sock);
+    if (cid < N_CLIENTS)
+      signal Tcp.connectDone[cid](error == 0);
+  }
+
+  void tcplib_extern_recv(struct tcplib_sock *sock, void *data, int len) {
+    int cid = find_client(sock);
+    if (cid < N_CLIENTS)
+      signal Tcp.recv[cid](data, len);
+  }
+
+  void tcplib_extern_closed(struct tcplib_sock *sock) {
+    tcplib_close(sock);
+  }
+
+  void tcplib_extern_closedone(struct tcplib_sock *sock) {
+    int cid = find_client(sock);
+    tcplib_init_sock(sock);
+    if (cid < N_CLIENTS)
+      signal Tcp.closed[cid](0);
+  }
+
+  void tcplib_extern_acked(struct tcplib_sock *sock) {
+    int cid = find_client(sock);
+    if (cid < N_CLIENTS)
+      signal Tcp.acked[cid]();
+  }
+#include "circ.c"
+#include "tcplib.c"
+
+  struct tcplib_sock socks[uniqueCount("TCP_CLIENT")];
+
+  struct tcplib_sock *tcplib_accept(struct tcplib_sock *conn,
+                                    struct sockaddr_in6 *from) {
+    int cid = find_client(conn);
+    int buf_len;
+
+    printfUART("tcplib_accept: cid: %i\n", cid);
+
+    if (cid == N_CLIENTS) return NULL;
+    if (signal Tcp.accept[cid](from, &conn->tx_buf, &buf_len)) {
+      if (conn->tx_buf == NULL) return NULL;
+      conn->tx_buf_len = buf_len;
+      return conn;
+    }
+    return NULL;
+  }
+
+  void tcplib_send_out(struct split_ip_msg *msg, struct tcp_hdr *tcph) {
+    printfUART("tcp output\n");
+    call IPAddress.setSource(&msg->hdr);
+    tcph->chksum = htons(msg_cksum(msg, IANA_TCP));
+    call IP.send(msg);
+  }
+
+  command error_t Init.init() {
+    int i;
+    for (i = 0; i < uniqueCount("TCP_CLIENT"); i++) {
+      tcplib_init_sock(&socks[i]);
+    }
+    return SUCCESS;
+  }
+
+  event void Boot.booted() {
+    call Timer.startPeriodic(512);
+  }
+
+  event void Timer.fired() {
+    tcplib_timer_process();
+  }
+
+  event void IP.recv(struct ip6_hdr *iph, 
+                     void *payload, 
+                     struct ip_metadata *meta) {
+    
+    printfUART("tcp packet received\n");
+    tcplib_process(iph, payload);
+  }
+
+
+  command error_t Tcp.bind[uint8_t client](uint16_t port) {
+    struct sockaddr_in6 addr;
+    ip_memclr(addr.sin6_addr.s6_addr, 16);
+    addr.sin6_port = htons(port);
+    tcplib_bind(&socks[client], &addr);
+    return SUCCESS;
+  }
+
+  command error_t Tcp.connect[uint8_t client](struct sockaddr_in6 *dest,
+                                              void *tx_buf, int tx_buf_len) {
+    socks[client].tx_buf = tx_buf;
+    socks[client].tx_buf_len = tx_buf_len;
+    tcplib_connect(&socks[client], dest);
+  }
+
+  command error_t Tcp.send[uint8_t client](void *payload, uint16_t len) {
+    if (tcplib_send(&socks[client], payload, len) < 0) return FAIL;
+    return SUCCESS;
+  }
+  
+  command error_t Tcp.close[uint8_t client]() {
+    if (!tcplib_close(&socks[client]))
+      return SUCCESS;
+    return FAIL;
+  }
+
+  command error_t Tcp.abort[uint8_t client]() {
+    if (tcplib_abort(&socks[client]) < 0) return FAIL;
+    return SUCCESS;
+  }
+
+  default event bool Tcp.accept[uint8_t cid](struct sockaddr_in6 *from, 
+                                             void **tx_buf, int *tx_buf_len) {
+    return FALSE;
+  }
+
+ default event void Tcp.connectDone[uint8_t cid](error_t e) {}
+ default event void Tcp.recv[uint8_t cid](void *payload, uint16_t len) {  }
+ default event void Tcp.closed[uint8_t cid](error_t e) { }
+ default event void Tcp.acked[uint8_t cid]() { }
+}
diff --git a/tos/lib/net/blip/TcpSocketC.nc b/tos/lib/net/blip/TcpSocketC.nc
new file mode 100644 (file)
index 0000000..1c832f1
--- /dev/null
@@ -0,0 +1,11 @@
+
+
+generic configuration TcpSocketC() {
+  provides interface Tcp;
+} implementation {
+
+  components TcpC;
+
+  Tcp = TcpC.Tcp[unique("TCP_CLIENT")];
+  
+}
diff --git a/tos/lib/net/blip/TrackFlowsC.nc b/tos/lib/net/blip/TrackFlowsC.nc
new file mode 100644 (file)
index 0000000..729d935
--- /dev/null
@@ -0,0 +1,16 @@
+
+configuration TrackFlowsC {
+
+} implementation {
+  
+  components MainC, TrackFlowsP, IPDispatchP;
+  components SerialActiveMessageC as Serial;
+
+  TrackFlowsP.Boot -> MainC;
+  TrackFlowsP.SerialControl -> Serial;
+  TrackFlowsP.IPExtensions -> IPDispatchP.IPExtensions;
+  TrackFlowsP.Headers -> IPDispatchP.HopByHopExt;
+
+  TrackFlowsP.FlowSend -> Serial.AMSend[AM_FLOW_ID_MSG];
+  
+}
diff --git a/tos/lib/net/blip/TrackFlowsP.nc b/tos/lib/net/blip/TrackFlowsP.nc
new file mode 100644 (file)
index 0000000..f06bcae
--- /dev/null
@@ -0,0 +1,140 @@
+
+#include "TrackFlows.h"
+
+module TrackFlowsP {
+  uses {
+    interface Boot;
+    interface SplitControl as SerialControl;
+    interface IPExtensions;
+    interface TLVHeader as Headers;
+    interface AMSend as FlowSend;
+  }
+} implementation {
+  
+
+  bool flow_send_busy = FALSE;
+  uint16_t current_flowid = 0;
+  message_t flow_send;
+
+  int send_flow_idx = -1, cur_idx = 0;
+  nx_struct {
+    nx_uint8_t flags;
+    nx_uint8_t label;
+    nx_struct flow_id_msg flow;
+  } flow_cache[N_FORWARD_ENT * 3];
+
+  int get_entry() {
+    cur_idx = (cur_idx + 1) % (N_FORWARD_ENT * 3);
+    return cur_idx;
+  }
+  int lookup_entry(uint8_t label) {
+    int i;
+    for (i = 0; i < N_FORWARD_ENT * 3; i++) {
+      if (flow_cache[i].flags == 1 && flow_cache[i].label == label)
+        return i;
+    } 
+    return -1;
+  }
+  
+  event void Boot.booted() {
+    call SerialControl.start();
+    flow_send_busy = FALSE;
+    ip_memclr((void *)flow_cache, sizeof(flow_cache));
+  }
+
+  event void FlowSend.sendDone(message_t *msg, error_t error) {
+    flow_send_busy = FALSE;
+    flow_cache[send_flow_idx].flags = 0;
+  }
+
+  void update_msg(struct ip6_hdr *iph, nx_struct flow_id *flow, uint8_t label, uint8_t nxt_hdr) {
+    nx_struct flow_id_msg *payload;
+    int i = get_entry();
+    if (i < 0) return;
+    flow_cache[i].flags = 1;
+    flow_cache[i].label = label;
+    payload = &flow_cache[i].flow;
+
+    memcpy(&payload->flow, flow, sizeof(nx_struct flow_id));
+    payload->src = ntohs(iph->ip6_src.s6_addr16[7]);
+    payload->dst = ntohs(iph->ip6_dst.s6_addr16[7]);
+    payload->local_address = TOS_NODE_ID;
+    payload->nxt_hdr = nxt_hdr;
+  }
+
+  event void IPExtensions.handleExtensions(uint8_t label,
+                                           struct ip6_hdr *iph,
+                                           struct ip6_ext *hop,
+                                           struct ip6_ext *dst,
+                                           struct ip6_route *route,
+                                           uint8_t nxt_hdr) {
+    if (hop != NULL) {
+      struct tlv_hdr *tlv = call IPExtensions.findTlv(hop, TLV_TYPE_FLOW);
+      if (tlv != NULL && tlv->len == sizeof(struct tlv_hdr) + sizeof(nx_struct flow_id)) {
+        update_msg(iph, (nx_struct flow_id *)(tlv + 1), label, nxt_hdr);
+      }
+    }
+  }
+
+  event void IPExtensions.reportTransmission(uint8_t label, send_policy_t *send) {
+    int i, flow_idx = lookup_entry(label);
+    nx_struct flow_id_msg *payload =
+      (nx_struct flow_id_msg *)call FlowSend.getPayload(&flow_send, sizeof(nx_struct flow_id_msg));
+
+    
+    if (flow_idx < 0) return;
+    memcpy(payload, &flow_cache[flow_idx].flow, sizeof(nx_struct flow_id_msg));
+
+
+    payload->n_attempts = 0;
+    for (i = 0; i < send->current && i < 3; i++) {
+      // if (send->dest[i] == IEEE154_BROADCAST_ADDR) return;
+      
+      payload->attempts[i].next_hop = send->dest[i];
+      payload->attempts[i].tx = send->retries;
+    }
+    if (i < 3) {
+      payload->attempts[i].next_hop = send->dest[i];
+      payload->attempts[i].tx = send->actRetries;
+      i++;
+    }
+    payload->n_attempts = i;
+    
+    if (!flow_send_busy) {
+      if (call FlowSend.send(0xffff, &flow_send, sizeof(nx_struct flow_id_msg)) == SUCCESS) {
+        flow_send_busy = TRUE;
+        send_flow_idx = flow_idx;
+        return;
+      } 
+      // otherwise fall through and invalidate the cache
+    }
+    flow_cache[flow_idx].flags = 0;
+  }
+
+  event struct tlv_hdr *Headers.getHeader(uint8_t label,
+                                          struct ip6_hdr *msg,
+                                          uint8_t nxt_hdr) {
+    static uint8_t buf[sizeof(struct tlv_hdr) + sizeof(nx_struct flow_id)];
+    struct tlv_hdr *tlv;
+    nx_struct flow_id *flow;
+    tlv = (struct tlv_hdr *)buf;
+    flow = (nx_struct flow_id *)(tlv + 1);
+
+    tlv->type = TLV_TYPE_FLOW;
+    tlv->len = sizeof(struct tlv_hdr) + sizeof(nx_struct flow_id);
+
+/*     if (msg->ip6_dst.s6_addr[0] != 0xff ||  */
+/*         (msg->ip6_dst.s6_addr[0] == 0xff &&  */
+/*          (msg->ip6_dst.s6_addr[1] & 0x0f) > 2)) { */
+      flow->id  = current_flowid++;
+
+      update_msg(msg, flow, label, nxt_hdr);
+      return tlv;
+/*     } */
+/*     return NULL; */
+  }
+
+  event void SerialControl.startDone(error_t e) { }
+  event void SerialControl.stopDone(error_t e) { }
+
+}
diff --git a/tos/lib/net/blip/UdpC.nc b/tos/lib/net/blip/UdpC.nc
new file mode 100644 (file)
index 0000000..eda9c23
--- /dev/null
@@ -0,0 +1,16 @@
+
+#include <Statistics.h>
+
+configuration UdpC {
+  provides interface UDP[uint8_t clnt];
+  provides interface Statistics<udp_statistics_t>;
+} implementation {
+
+  components MainC, IPDispatchC, UdpP, IPAddressC;
+  UDP = UdpP;
+  Statistics = UdpP;
+
+  MainC -> UdpP.Init;
+  UdpP.IP -> IPDispatchC.IP[IANA_UDP];
+  UdpP.IPAddress -> IPAddressC;
+}
diff --git a/tos/lib/net/blip/UdpP.nc b/tos/lib/net/blip/UdpP.nc
new file mode 100644 (file)
index 0000000..99c47c4
--- /dev/null
@@ -0,0 +1,199 @@
+
+#include <ip_malloc.h>
+#include <in_cksum.h>
+#include <Statistics.h>
+
+module UdpP {
+  provides interface UDP[uint8_t clnt];
+  provides interface Init;
+  provides interface Statistics<udp_statistics_t>;
+  uses interface IP;
+  uses interface IPAddress;
+} implementation {
+
+#ifdef PRINTFUART_ENABLED
+#undef dbg
+#define dbg(X,fmt, args...) printfUART(fmt, ##args)
+#endif
+
+  enum {
+    N_CLIENTS = uniqueCount("UDP_CLIENT"),
+  };
+
+  udp_statistics_t stats;
+  uint16_t local_ports[N_CLIENTS];
+
+  enum {
+    LOCAL_PORT_START = 51024U,
+    LOCAL_PORT_STOP  = 54999U,
+  };
+  uint16_t last_localport = LOCAL_PORT_START;
+
+  uint16_t alloc_lport(uint8_t clnt) {
+    int i, done = 0;
+    uint16_t compare = htons(last_localport);
+    last_localport = (last_localport < LOCAL_PORT_START) ? last_localport + 1 : LOCAL_PORT_START;
+    while (!done) {
+      done = 1;
+      for (i = 0; i < N_CLIENTS; i++) {
+        if (local_ports[i] == compare) {
+          last_localport = (last_localport < LOCAL_PORT_START) ? last_localport + 1 : LOCAL_PORT_START;
+          compare = htons(last_localport);
+          done = 0;
+          break;
+        }
+      }
+    }
+    return last_localport;
+  }
+
+  command error_t Init.init() {
+    call Statistics.clear();
+    ip_memclr((uint8_t *)local_ports, sizeof(uint16_t) * N_CLIENTS);
+    return SUCCESS;
+  }
+
+  command error_t UDP.bind[uint8_t clnt](uint16_t port) {
+    int i;
+    port = htons(port);
+    if (port > 0) {
+      for (i = 0; i < N_CLIENTS; i++)
+        if (i != clnt && local_ports[i] == port)
+          return FAIL;
+    }
+    local_ports[clnt] = port;
+    return SUCCESS;
+  }
+
+  event void IP.recv(struct ip6_hdr *iph,
+                     void *payload,
+                     struct ip_metadata *meta) {
+    int i;
+    struct sockaddr_in6 addr;
+    struct udp_hdr *udph = (struct udp_hdr *)payload;
+
+    dbg("UDP", "UDP - IP.recv: len: %i srcport: %i dstport: %i\n",
+        ntohs(iph->plen), ntohs(udph->srcport), ntohs(udph->dstport));
+
+    for (i = 0; i < N_CLIENTS; i++)
+      if (local_ports[i] == udph->dstport)
+        break;
+
+    if (i == N_CLIENTS) {
+      // TODO : send ICMP port closed message here.
+      return;
+    }
+    ip_memcpy(&addr.sin6_addr, &iph->ip6_src, 16);
+    addr.sin6_port = udph->srcport;
+
+
+    { 
+      uint16_t rx_cksum = ntohs(udph->chksum), my_cksum;
+      vec_t cksum_vec[4];
+      uint32_t hdr[2];
+
+      udph->chksum = 0;
+
+      cksum_vec[0].ptr = (uint8_t *)(iph->ip6_src.s6_addr);
+      cksum_vec[0].len = 16;
+      cksum_vec[1].ptr = (uint8_t *)(iph->ip6_dst.s6_addr);
+      cksum_vec[1].len = 16;
+      cksum_vec[2].ptr = (uint8_t *)hdr;
+      cksum_vec[2].len = 8;
+      hdr[0] = iph->plen;
+      hdr[1] = htonl(IANA_UDP);
+      cksum_vec[3].ptr = payload;
+      cksum_vec[3].len = ntohs(iph->plen);
+
+      my_cksum = in_cksum(cksum_vec, 4);
+      printfUART("rx cksum: %x calc: %x\n", rx_cksum, my_cksum);
+      if (rx_cksum != my_cksum) {
+        BLIP_STATS_INCR(stats.cksum);
+        // return;
+      }
+    }
+
+    BLIP_STATS_INCR(stats.rcvd);
+    signal UDP.recvfrom[i](&addr, (void *)(udph + 1), ntohs(iph->plen) - sizeof(struct udp_hdr), meta);
+  }
+
+  /*
+   * Injection point of IP datagrams.  This is only called for packets
+   * being sent from this mote; packets which are being forwarded
+   * never lave the stack and so never use this entry point.
+   *
+   * @msg an IP datagram with header fields (except for length)
+   * @plen the length of the data payload added after the headers.
+   */
+  command error_t UDP.sendto[uint8_t clnt](struct sockaddr_in6 *dest, void *payload, 
+                                           uint16_t len) {
+    struct split_ip_msg *msg;
+    struct udp_hdr *udp;
+    struct generic_header *g_udp;
+    error_t rc;
+
+    // todo check + alloc local port
+
+    msg = (struct split_ip_msg *)ip_malloc(sizeof(struct split_ip_msg) +
+                                        sizeof(struct udp_hdr) +
+                                        sizeof(struct generic_header));
+
+    if (msg == NULL) {
+      dbg("Drops", "drops: UDP send: malloc failure\n");
+      return ERETRY;
+    }
+    udp = (struct udp_hdr *)(msg + 1);
+    g_udp = (struct generic_header *)(udp + 1);
+
+    // fill in all the packet fields
+    ip_memclr((uint8_t *)msg, sizeof(struct split_ip_msg));
+    ip_memclr((uint8_t *)udp, sizeof(struct udp_hdr));
+    
+    memcpy(&msg->hdr.ip6_dst, dest->sin6_addr.s6_addr, 16);
+    call IPAddress.setSource(&msg->hdr);
+    
+    if (local_ports[clnt] == 0 && (local_ports[clnt] = alloc_lport(clnt)) == 0) {
+      ip_free(msg);
+      return FAIL;
+    }
+    udp->srcport = local_ports[clnt];
+    udp->dstport = dest->sin6_port;
+    udp->len = htons(len + sizeof(struct udp_hdr));
+    udp->chksum = 0;
+
+    // set up the pointers
+    g_udp->len = sizeof(struct udp_hdr);
+    g_udp->hdr.udp = udp;
+    g_udp->next = NULL;
+    msg->headers = g_udp;
+    msg->data_len = len;
+    msg->data = payload;
+    msg->hdr.plen = udp->len;
+
+    udp->chksum = htons(msg_cksum(msg, IANA_UDP)); 
+
+    rc = call IP.send(msg);
+    BLIP_STATS_INCR(stats.sent);
+
+    ip_free(msg);
+    return rc;
+
+  }
+
+  command void Statistics.clear() {
+#ifdef BLIP_STATS
+    ip_memclr((uint8_t *)&stats, sizeof(udp_statistics_t));
+#endif
+  }
+
+  command void Statistics.get(udp_statistics_t *buf) {
+#ifdef BLIP_STATS
+    ip_memcpy(buf, &stats, sizeof(udp_statistics_t));
+#endif
+  }
+
+  default event void UDP.recvfrom[uint8_t clnt](struct sockaddr_in6 *from, void *payload,
+                                               uint16_t len, struct ip_metadata *meta) {
+
+ }
+}
diff --git a/tos/lib/net/blip/UdpSocketC.nc b/tos/lib/net/blip/UdpSocketC.nc
new file mode 100644 (file)
index 0000000..e4323b7
--- /dev/null
@@ -0,0 +1,9 @@
+
+generic configuration UdpSocketC() {
+  provides interface UDP;
+} implementation {
+  
+  components UdpC;
+
+  UDP = UdpC.UDP[unique("UDP_CLIENT")];
+}
diff --git a/tos/lib/net/blip/doc/README b/tos/lib/net/blip/doc/README
new file mode 100644 (file)
index 0000000..8ae52d2
--- /dev/null
@@ -0,0 +1,94 @@
+
+ @title blip documentation
+ @author Stephen Dawson-Haggerty stevedh@eecs.berkeley.edu
+ @release public
+---------------------------------------------------------------------
+
+ 1. Installation
+
+ - This is only going to work on linux.
+
+ - The recommended version of TinyOS is a recent CVS checkout.  This
+   is necessary for appropriate radio stack support.
+
+ - Make sure the c serial tools are built in
+   $TOSROOT/support/sdk/c/sf.  You may need to run ./bootstrap,
+   ./configure, and make in that folder to generate libmote.a.
+
+ 2. Building
+
+ - Build a test app:
+      * cd to $TOSROOT/apps/UDPEcho/ and try typing `make <platform> blip`
+ - Build the Ieee802.15.4 bridge to your computer
+      * cd to $TOSROOT/apps/IPBaseStation/ and `make <platform> blip`
+ - Build the driver 
+      * cd to $TOSROOT/support/sdk/c/blip
+      * run ./bootstrap
+      * run ./configure
+      * run make
+
+ 3. Running
+
+ - Install IPBaseStation on a mote.  This will be your
+       computer's interface to the world of low-power radio.  Setting
+       the node id and channel is not important-- these settings will be
+       overwritten.
+
+ - Start the driver (once you've built it)
+      * cd $TOSROOT/support/sdk/c/blip
+      * edit the config file $TOSROOT/support/sdk/c/blip/serial_tun.conf
+         * set 'addr' you would like your computer's interface to use on the PAN
+         * leave 'proxy' set to 'lo'
+      * sudo driver/ip-driver /dev/ttyUSB0 telosb
+           (replace the device and baud with whatever you're using)
+   The config file is assumed to be in the CWD when ip-driver starts;
+       if this is not the case it may be specified using '-c <config file>'
+
+ - The driver registers itself on the fec0::/64
+       subnet (or whatever you have specified in the config file).
+
+ - If you program a few motes with UDPEcho, their addresses are formed
+       with octets 15 and 16 of the IPv6 address comming from the
+       802.15.4 short address you programmed them with.  Octets 9-14
+       are zero, so the address formed is:
+
+       +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
+       |  network prefix       |     zero        | id  | 
+       +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
+
+       ICMPv6 DAD is not performed.
+
+ - For instance, if you program a mote with ID 101 (0x65), you can try
+       ping6 fec0::65
+       tracert6 fec0::65
+       nc6 -u fec0::65 7
+       nc6 -u fec0::65 2000
+       
+       UDPEcho runs an echo service on port 7, and a simple shell on
+       port 2000; type 'help' for a list of commands.
+
+ - The motes can also report back statistics every 15 seconds over
+       UDP.  They will send these reports to an address specified in the
+       application make file; however these reports are disabled by default.
+       You can observe these statistics using the Listener.py
+       script in $TOSROOT/apps/UDPEcho/: `python Listener.py`.
+
+ - The driver provides a simple console when running, which allows you
+       to inspect and manipulates routes, and view statistics.  The
+       console runs as a telnet service on port 6106.
+
+ - A good way of understanding what is happening is to start wireshark
+       on tun0; you should be able to observe the neighbor discovery
+       process as motes boot.  You may also notice messages sent to
+       ff05::1; these are routing updates.  They are sent from a
+       binary exponential timer with a maximum period of 5 minutes to
+       inform the router of mote's presence; however, they are
+       suppressed by data traffic since the routing updates will be
+       piggybacked on it.
+
+ - Further reading: doc/ contains a numbers of README's related to
+       pieces of blip such as the socket interface, the shell, and
+       network programming support.  For more technical details on
+       IPv6, please see any reference on the subject.  Many of the
+       documents produced by the IETF ROLL and 6lowpan working groups
+       are relevent to this design space.  
diff --git a/tos/lib/net/blip/doc/README-IP b/tos/lib/net/blip/doc/README-IP
new file mode 100644 (file)
index 0000000..a73fbf9
--- /dev/null
@@ -0,0 +1,56 @@
+
+ @title IP data-structure documentation
+ @author Stephen Dawson-Haggerty
+ @release public
+----------------------------------------------------------------------
+
+The ip-stack provides a bare IP datagram interface to the network
+layer; this is documented in comments in the code.
+
+For the purposes of socket programming, two data structures are most
+important.  The 'struct sockaddr_in6' and the 'struct in6_addr'.  They
+are substantially shared with the linux/bsd versions, and reproduced
+below.
+
+struct in6_addr
+  {
+    union
+      {
+       uint8_t u6_addr8[16];
+       uint16_t u6_addr16[8];
+       uint32_t u6_addr32[4];
+      } in6_u;
+#define s6_addr                        in6_u.u6_addr8
+#define s6_addr16              in6_u.u6_addr16
+#define s6_addr32              in6_u.u6_addr32
+  };
+
+struct sockaddr_in6 {
+  uint16_t sin6_port;
+  struct in6_addr sin6_addr;
+};
+
+void inet_pton6(char *addr, struct in6_addr *dest);
+
+Usage
+----------------------------------------------------------------------
+
+ Example 1: Suppose we want to setup a sockaddr_in6 to point to ff02::5, port 10000:
+ {
+   struct sockaddr_in6 sa6;
+   inet_pton6("ff02::5", &sa6.sin6_addr);
+   sa6.sin6_port = htons(10000);
+ }
+
+ Example 2: Do the same thing, but without the overhead of storing and
+  parsing the string address representation.
+ {
+   struct sockaddr_in6 sa6;
+   memset(&sa6, 0, sizeof(struct sockaddr_in6));
+   sa6.sin6_addr.s6_addr16[0] = htons(0xff02);
+   sa6.sin6_addr.s6_addr[15] = 5;
+   sa6.sin6_port = htons(10000);
+ }
+
+ This code is very unix-y; the second example will work on *nix's.
+
diff --git a/tos/lib/net/blip/doc/README-MERAKI b/tos/lib/net/blip/doc/README-MERAKI
new file mode 100644 (file)
index 0000000..ab9514b
--- /dev/null
@@ -0,0 +1,53 @@
+
+ @title Meraki Documentation
+ @author Stephen Dawson-Haggerty stevedh@eecs.berkeley.edu
+ @release internal
+---------------------------------------------------------------------
+
+This README explains how to use a Meraki Mini programmed with
+OpenWRT/kamikaze as a border router.  This document and the code make
+the following assumptions:
+
+ - The Meraki has a public IP address or is in a DMZ such that the
+        6over4 tunneling protocol will work.
+ - The Meraki is the sole router for a prefix
+
+Background
+---------------------------------------------------------------------
+
+To ease configuration, the important parameters are stored in a
+database.  When the meraki waits up, it hits the database and
+downloads a few config files which it then uses.  To grab new
+configuration, you can either log in and manually restart the router
+daemon, or just reboot.  The parameters stored are:
+ prefix : the one received from the hurricane electric tunnel broker
+ short addr : the address of this device on the network
+ channel : which channel to use
+
+Install
+---------------------------------------------------------------------
+
+ 1. Install the router daemon on the meraki using either the provided
+ipkg, or your own if you've built a version.  Building the package is
+very easy but not covered here.
+   'ipkg update'
+   'ipkg install lowpan-bridge_1.2-855_mips.ipk' 
+In order for the dependancies to be automatically installed, you must
+do the update first so that the package system downloads the directory
+with the necessary packages.
+ 2. Set up the configuration parameters in the database.  The key used
+is the hostname; precisely, whatever 'uname -n' prints.  If no key is
+found in the database the meraki will just use defaults.
+ 3. Start the daemon with '/etc/init.d/lowpan-bridge start' This will
+run automatically when the meraki boots.
+
+... I think that's it.  Pretty easy!
+
+Bugs/Notes
+---------------------------------------------------------------------
+
+There seems to be an issue with the serial port on the meraki.  The
+effect is that packets are dropped when you send too quickly.  This
+mostly effects fragmentation.  As a stopgap, I've inserted a timeout
+between fragments, but this means the performance is somewhat worse
+then on a PC and a micaz.
diff --git a/tos/lib/net/blip/doc/README-NWPROG b/tos/lib/net/blip/doc/README-NWPROG
new file mode 100644 (file)
index 0000000..ef59590
--- /dev/null
@@ -0,0 +1,70 @@
+
+ @title Meraki Documentation
+ @author Stephen Dawson-Haggerty stevedh@eecs.berkeley.edu
+ @release public
+---------------------------------------------------------------------
+
+What is it?
+---------------------------------------------------------------------
+nwprog is a method of over-the-air programming.  It uses much of the
+machinery Deluge has developed, like the boot loader and flash layout,
+but substitutes a simpler transport using UDP for Deluge's
+dissemination algorithm.  This means that it is point-to-point, and
+not incredibly appropriate for reprogramming an entire network all at
+once.
+
+How do I get it?
+---------------------------------------------------------------------
+It is included with the b6lowpan stack.  It reuses much of the Deluge
+code directly from the TinyOS tree without shadowing the files.
+
+Differences from Deluge?
+---------------------------------------------------------------------
+ - no dissemination 
+ - no base station or serial port for injection
+
+ The application is very simple: flash is formatted into several
+volumes (a golden image and three application volumes), which are used
+to store application images.  Flash management, boot loading, and
+image formatting are all provided by Deluge.
+
+How to use it?
+---------------------------------------------------------------------
+Build your application with support by include a line in your
+application Makefile, and include the IPDispatchC component.
+== application makefile ==
+BOOTLOADER=tosboot
+== </snip> == 
+Also, it is necessary to include a volumes xml file for your flash
+chip; examples for the stm25p and at45db are present in apps/UDPEcho.
+
+First built the tosboot bootloader for your platform by going to
+tinyos-2.x/tos/lib/tosboot and typing `make <platform>`.
+
+Then just build and install your application like usual.  If
+networking is working, you should have no problem following the rest
+of the instructions.
+
+Interactions with the motes happen using the 'nwprog' tool in a shell.
+Connect the shell with `nc6 -u 2001:470:1f04:56d::65 2000`.
+It has three commands:
+ `nwprog list`: examine the flash and print out information on volumes
+        containing images believed to be valid
+ `nwprog reboot`: reboot into the same image
+ `nwprog boot N`: reboot, and flash the mote with the binary stored in
+        volume N
+
+In order to upload new images, use the tos-nwprog tool, located in
+$LOWPAN_ROOT/tools/tinyos/misc.  This tool provides minimal
+functionality; only erasing and uploading are supported.
+
+ `./tos-nwprog 2001:470:1f04:56d::65 -e 0`: erase image 0 from the
+        mote at the given IP address.
+ `./tos-nwprog 2001:470:1f04:56d::65 -u 0 tos_image.xml`: upload the
+        image in tos_image.xml to volume 0 on the mote at the IP
+        address.  This will erase the volume before uploading it.
+
+To integrate with your own application, there are several internal
+interfaces which can be used to examine the flash.  Looking at the
+example code in UDPShellP component is the best way of finding out
+about these.
diff --git a/tos/lib/net/blip/doc/README-SHELL b/tos/lib/net/blip/doc/README-SHELL
new file mode 100644 (file)
index 0000000..dd09536
--- /dev/null
@@ -0,0 +1,55 @@
+ @title UDPShell Documentation
+ @author Stephen Dawson-Haggerty
+ @release public
+----------------------------------------------------------------------
+
+UDPShell is a simple text-based command processor which comes with the
+ip-stack.  It is an optional, although convenient way of
+implementating debugging commands on a mote.
+
+Usage
+----------------------------------------------------------------------
+
+By default, the shell contains only a few simple commands: help, echo,
+uptime, ping, and ident.  It is designed to be very easy to extend by
+adding your own commands.
+
+To include just the basic shell, include the UDPShellC component in
+your application.  To augment the shell with a new shell command, use
+the generic component ShellCommandC.
+
+Example
+----------------------------------------------------------------------
+
+Suppose we want to implement `expr`, a simple arithmetic evaluator.
+First, bind the 'expr' command string in your application configuration.
+
+configuration App {} implementation {
+  components AppImplP;
+  components new ShellCommandC("expr") as Expr;
+  AppImplP.Expr -> Expr;
+}
+
+Within AppImplP, you must implement the ShellCommand interface.  The
+interface has only one event, 'eval' which has the same prototype as
+main() in a typical c program.
+
+event char *Expr.eval(int argc, char **argv) {
+  static char ret[10];
+  return ret;
+}
+
+If expr returns a non-null value, it is assumed to be a
+null-terminated string which will be echoed back to a connected
+client.  The buffer returned must obviously not be allocated on the
+stack.  The shell does maintain a single buffer which components can
+use to print their reply to; it can be requested with a call to
+Expr.getBuffer(uint16_t len).
+
+More running code
+----------------------------------------------------------------------
+
+Fully fleshed out examples of code using this interface are available
+within the stack; see tos/lib/net/b6lowpan/shell/FlashShell[CP].nc and
+tos/lib/net/b6lowpan/nwprog/NWProg[CP].nc
\ No newline at end of file
diff --git a/tos/lib/net/blip/doc/README-SIM b/tos/lib/net/blip/doc/README-SIM
new file mode 100644 (file)
index 0000000..5461d94
--- /dev/null
@@ -0,0 +1,43 @@
+
+ @title blip + TOSSIM documentation
+ @author Stephen Dawson-Haggerty stevedh@eecs.berkeley.edu
+ @release internal
+---------------------------------------------------------------------
+
+The state of blip + TOSSIM
+---------------------------------------------------------------------
+
+TOSSIM and blip have worked reliably together in the not-so-distant
+past.  However, blip makes several assumptions about the radio stack
+which are not (yet) reflected in TOSSIM-cvs.  It expects a PacketLink
+and Unique layer a la the cc2420 stack in order to provide reliable
+transmissions with link duplicate suppression.  Performance without
+these is very poor.  There are also several other minor changes which
+deal with the deliver of serial packets.
+
+Ported versions of those components exist and are present in the blip
+distribution.  However, they require patching an existing tinyos
+stack, so it is probably a good idea to do a sideways checkout of
+tinyos for experimenting on.
+
+Instructions for using TOSSIM with UDPEcho
+---------------------------------------------------------------------
+
+This is completely unsupported right now.  If you really want TOSSIM +
+blip, it ought to work, but there are definitly NO GUARANTEES and NO
+SUPPORT.  It's just too much of a hack at the moment.
+
+ - patch your tossim installation.  The patch is in $LOWPAN_ROOT/tos/lib/tossim.patch, so apply that using
+    * `cd $TOSDIR/tos/lib`
+    * `patch -p0 < $LOWPAN_ROOT/tos/lib/tossim.patch`
+   Then copy $LOWPAN_ROOT/tos/lib/tossim/Packet* to $TOSDIR/tos/lib/tossim
+
+ - I think you should then be able to cd to apps/UDPEcho/sim and type `make`
+    * make sure you have python2.5 and python2.5-dev installed
+ - run `./Sim.py` (or `python2.5 ./Sim.py` if 2.4 is default)
+ - build the driver in support/sdh/c/lib6lowpan/tunnel using `make
+     sim` (probably doing make clean first)
+ - you can then run the driver as usually, except using `./serial_tun
+     localhost 9001` to point it at the serialforwarder running in the simulator.
+
+
diff --git a/tos/lib/net/blip/doc/README-TCP b/tos/lib/net/blip/doc/README-TCP
new file mode 100644 (file)
index 0000000..d20e4e6
--- /dev/null
@@ -0,0 +1,101 @@
+
+ @title TCP Socket Documentation
+ @author Stephen Dawson-Haggerty
+ @release internal
+ @target 2.1.1
+----------------------------------------------------------------------
+
+TCP is the standard  Internet protocol for reliable, in-order delivery
+of data across the  network.  Although inefficient, its ubiquity makes
+it impossible to ignore; thus, blip provides a very simple TCP stack.
+TCP is considerably more complicated then UDP, and requires careful
+use in the embedded setting to prevent resource exhaustion.  It is
+essential that one understand the BSD sockets API; this brief README
+does not cover many details.
+
+For memory-constrained operation, blip's TCP does not do any
+receive-side buffering.  Instead, it will immediately dispatch
+new, in-order data to the application and otherwise drop the segment.
+Blip does provide send-buffering so that it can automatically
+retransmit missing segments; this buffer may be of any size and is
+provided by the application.  
+
+Important parameters:
+
+MSS: Maximum Segment Size: the maximum amount of data that a TCP packet
+will contain.  Since blip immediately delivers new data, this is also
+greater then or equal to the maximum amount of data which will ever be
+delivered in a recv() call.
+
+Window: TCP keeps the other side informed about how much buffer is
+available for new data.  Since blip does not have a receive buffer,
+this parameter is not adjusted by blip; only set to a reasonable
+value.  Applications using TCP may wish to dynamically control this
+value for various reasons.
+
+Notes
+----------------------------------------------------------------------
+
+The TCP interface is located in
+$LOWPAN_ROOT/tos/lib/net/blip/interfaces/Tcp.nc.  For the most part,
+it should be familier.
+
+Since the application is responsible for buffering, both accept() and
+connect() require the implementer to include a buffer for the stack's
+use.  Once passed to the stack, the buffer is reserved until a
+closed() event is signaled on that socket.
+
+A few of the most important caveats/brokeness:
+
+ - there is no listen().  calling bind() on a socket also begins to listen.
+
+ - there is no way to accept() multiple sockets like you can in Unix.
+   More precisely, all the code would support it but then there is
+   dynamic allocation since you have to allocate a new socket struct
+   on the fly.
+
+ - (sort of) as a result of these, if the socket is closed, you have
+   to call bind() if you want to continue listening.
+
+ - you'll need to carefully manage buffer and window sized by hand if
+   you want to be sure of correct operation.  Make sure you check
+   return codes from send() since it will fail if there is not enough
+   local buffer for the entire request.
+
+
+Example
+----------------------------------------------------------------------
+
+
+configuration {
+  components new TcpSocketC() as TcpEcho;
+  TCPEchoP.TcpEcho -> TcpEcho;
+}
+
+module {} implementation {
+  // allocate a send buffer
+  char tcp_buf[150];
+
+  // accept connections from anyone.  no need to save the endpoint,
+  // but this is the only time its available (add an API call?)
+  event bool TcpEcho.accept(struct sockaddr_in6 *from, 
+                            void **tx_buf, int *tx_buf_len) {
+    *tx_buf = tcp_buf;
+    *tx_buf_len = 150;
+    // indicates we are accepting the connection
+    return TRUE;
+  }
+  // potentially useful?
+  event void TcpEcho.connectDone(error_t e) {}
+
+  // just echo the data back.
+  event void TcpEcho.recv(void *payload, uint16_t len) {
+    call TcpEcho.send(payload,len);
+  }
+
+  // rebind to accept other connections.
+  event void TcpEcho.closed(error_t e) {
+    call Leds.led0Toggle();
+    call TcpEcho.bind(7);
+  }
+}
\ No newline at end of file
diff --git a/tos/lib/net/blip/doc/README-UDP b/tos/lib/net/blip/doc/README-UDP
new file mode 100644 (file)
index 0000000..e85e793
--- /dev/null
@@ -0,0 +1,70 @@
+
+ @title UDP Socket Documentation
+ @author Stephen Dawson-Haggerty
+ @release public
+----------------------------------------------------------------------
+
+ip-stack provides a UDP sockets layer as a basic application transport
+service.  The UDP interface is located in
+tos/lib/net/b6lowpan/interfaces/UDP.nc and is simple:
+
+interface UDP {
+
+  /*
+   * bind a local address.  to cut down memory requirements and handle the 
+   * common case well, you can only bind a port; all local interfaces are 
+   * implicitly bound.  the port should be passed in host byte-order (is 
+   * this confusing?
+   */
+  command error_t bind(uint16_t port);
+
+  /*
+   * send a payload to the socket address indicated
+   * once the call returns, the stack has no claim on the buffer pointed to
+   */ 
+  command error_t sendto(struct sockaddr_in6 *dest, void *payload, 
+                         uint16_t len);
+
+  /*
+   * indicate that the stack has finished writing data into the
+   * receive buffer.  if error is not SUCCESS, the payload does not
+   * contain valid data and the src pointer should not be used.
+   */
+  event void recvfrom(struct sockaddr_in6 *src, void *payload, 
+                      uint16_t len, struct ip_metadata *meta);
+
+}
+
+Usage
+----------------------------------------------------------------------
+
+Each socket must be allocated using the generic component UdpSocketC.
+
+For clients, no initialization is necessary; they may send to a
+destination without calling bind.  The stack will allocate a unique
+ephemeral port number and send out the datagram.
+
+Servers wishing to provide a service using a well-known port should
+call bind() on that port number before generating datagrams.
+
+Example
+----------------------------------------------------------------------
+
+The simplest server is an echo service running on port 7.
+
+Because of the buffer semantics, it is safe to call send directly from
+a receive event handler.
+
+  event void Boot.booted() {
+    call Echo.bind(7);
+  }
+
+  event void Echo.recvfrom(struct sockaddr_in6 *from, void *data,
+                           uint16_t len, struct ip_metadata *meta) {
+    call Echo.sendto(from, data, len);
+  }
+
+The wiring is as follows. 
+
+  components new UdpSocketC();
+  UDPEchoP.Echo -> UdpSocketC;
diff --git a/tos/lib/net/blip/interfaces/ICMP.nc b/tos/lib/net/blip/interfaces/ICMP.nc
new file mode 100644 (file)
index 0000000..c1de09f
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+interface ICMP {
+
+  command uint16_t cksum(struct split_ip_msg *msg, uint8_t nxt_hdr);
+
+  // called to start sending router solicitations
+  command void sendSolicitations();
+
+  // called when we are done sending router solicitations
+  event void solicitationDone();
+
+  command void sendAdvertisements();
+
+  command void sendTimeExceeded(struct ip6_hdr *hdr, unpack_info_t *u_info, uint16_t amount_here);
+
+}
diff --git a/tos/lib/net/blip/interfaces/ICMPPing.nc b/tos/lib/net/blip/interfaces/ICMPPing.nc
new file mode 100644 (file)
index 0000000..24fc1ec
--- /dev/null
@@ -0,0 +1,12 @@
+
+#include <ICMP.h>
+
+interface ICMPPing {
+
+  command error_t ping(struct in6_addr *target, uint16_t period, uint16_t n);
+
+  event void pingReply(struct in6_addr *source, struct icmp_stats *stats);
+
+  event void pingDone(uint16_t ping_rcv, uint16_t ping_n);
+
+}
diff --git a/tos/lib/net/blip/interfaces/IP.nc b/tos/lib/net/blip/interfaces/IP.nc
new file mode 100644 (file)
index 0000000..2b74bc9
--- /dev/null
@@ -0,0 +1,27 @@
+
+interface IP {
+
+  /*
+   * sends the message with the headers and payload given.  Things
+   * which we know how to compress should be part of the data passed
+   * in as headers; things which we cannot compress must be passed as
+   * payload.
+
+   * the interface is this way so that the stack may insert extra
+   * (routing, snooping) headers between the two sections.
+   * once the call returns, the stack has no claim on the buffer
+   * pointed to
+   */ 
+  command error_t send(struct split_ip_msg *msg);
+
+  command error_t bareSend(struct split_ip_msg *msg, 
+                           struct ip6_route *route,
+                           int flags);
+
+  /*
+   * indicate that the stack has finished writing data into the
+   * receive buffer. 
+   */
+  event void recv(struct ip6_hdr *iph, void *payload, struct ip_metadata *meta);
+
+}
diff --git a/tos/lib/net/blip/interfaces/IPAddress.nc b/tos/lib/net/blip/interfaces/IPAddress.nc
new file mode 100644 (file)
index 0000000..d4a5c21
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#include <6lowpan.h>
+
+interface IPAddress {
+  command ieee154_saddr_t getShortAddr();
+  command void setShortAddr(ieee154_saddr_t newaddr);
+
+  command struct in6_addr *getPublicAddr();
+  command void getLLAddr(struct in6_addr *addr);
+  command void getIPAddr(struct in6_addr *addr);
+
+  command void setSource(struct ip6_hdr *hdr);
+
+  command void setPrefix(uint8_t *prefix);
+
+  command bool haveAddress();
+}
diff --git a/tos/lib/net/blip/interfaces/IPExtensions.nc b/tos/lib/net/blip/interfaces/IPExtensions.nc
new file mode 100644 (file)
index 0000000..eb6f5c3
--- /dev/null
@@ -0,0 +1,19 @@
+
+interface IPExtensions {
+
+  command struct tlv_hdr *findTlv(struct ip6_ext *ext, uint8_t tlv);
+
+  event void handleExtensions(uint8_t label,
+                              struct ip6_hdr *iph,
+                              struct ip6_ext *hop,
+                              struct ip6_ext *dst,
+                              struct ip6_route *route,
+                              uint8_t nxt_hdr);
+
+
+  /*
+   * will be called once for each fragment when sending or forwarding
+   */
+  event void reportTransmission(uint8_t label, send_policy_t *send);
+
+}
diff --git a/tos/lib/net/blip/interfaces/IPRouting.nc b/tos/lib/net/blip/interfaces/IPRouting.nc
new file mode 100644 (file)
index 0000000..e352ab1
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/*
+ *  This interface presents the interface to the IP routing engine.
+ *  Related interfaces are the forwarding engine, which implements
+ *     the routing decision whare are communicated by this interface, 
+ *     and the ICMP interface, which deals with sending and receiving 
+ *     ICMP traffic.
+ *
+ */
+
+#include "IPDispatch.h"
+
+interface IPRouting {
+  /*
+   * returns weather or not the node should consume a packet addressed
+   * to a given address.  Interprets link-local and global addresses,
+   * and manages multicast group membership.
+   */
+  command bool isForMe(struct ip6_hdr *a);
+
+  /*
+   * returns a policy for sending this message to someone else.
+   *   the send policy includes the layer 2 address, number of retransmissions,
+   *     and spacing between them.
+   *
+   */ 
+  command error_t getNextHop(struct ip6_hdr   *hdr, 
+                             struct ip6_route *routing_hdr,
+                             ieee154_saddr_t prev_hop,
+                             send_policy_t *ret);
+
+
+  /*
+   * returns the currently configured default IP hop limit.
+   *
+   */
+  command uint8_t getHopLimit();
+
+  command uint16_t getQuality();
+
+  /*
+   * 
+   *
+   */
+  command void reportAdvertisement(ieee154_saddr_t neigh, uint8_t hops, 
+                                             uint8_t lqi, uint16_t cost);
+
+  /*
+   * informs the router of a reception from a neighbor, along with the 
+   *  the rssi of the received packet.
+   *
+   */
+  command void reportReception(ieee154_saddr_t neigh, uint8_t lqi);
+
+  /*
+   * @returns TRUE if the routing engine has established a default route.
+   */
+  command bool hasRoute();
+
+  command struct ip6_route *insertRoutingHeader(struct split_ip_msg *msg);
+  
+  command void reset();
+
+#ifdef CENTRALIZED_ROUTING
+  // command error_t installFlowEntry(struct rinstall_header* rih, bool isMine);
+
+  command void clearFlows();
+#endif
+
+}
diff --git a/tos/lib/net/blip/interfaces/InternalIPExtension.nc b/tos/lib/net/blip/interfaces/InternalIPExtension.nc
new file mode 100644 (file)
index 0000000..e6f6958
--- /dev/null
@@ -0,0 +1,8 @@
+
+interface InternalIPExtension {
+
+  command void addHeaders(struct split_ip_msg *msg, uint8_t nxt_hdr, uint16_t label);
+
+  command void free();
+
+}
diff --git a/tos/lib/net/blip/interfaces/ReadLqi.nc b/tos/lib/net/blip/interfaces/ReadLqi.nc
new file mode 100644 (file)
index 0000000..0d874f7
--- /dev/null
@@ -0,0 +1,4 @@
+
+interface ReadLqi {
+  command uint8_t read(message_t *msg);
+}
diff --git a/tos/lib/net/blip/interfaces/Statistics.nc b/tos/lib/net/blip/interfaces/Statistics.nc
new file mode 100644 (file)
index 0000000..230a6be
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+
+interface Statistics <stat_str> {
+  
+  /*
+   * Fills the given structure with the requested statistics.
+   */
+  command void get(stat_str *stats);
+
+  /*
+   * Reset whatever statistics are being collected.
+   */
+  command void clear();
+
+}
diff --git a/tos/lib/net/blip/interfaces/TLVHeader.nc b/tos/lib/net/blip/interfaces/TLVHeader.nc
new file mode 100644 (file)
index 0000000..faeb368
--- /dev/null
@@ -0,0 +1,9 @@
+
+#include <ip.h>
+
+interface TLVHeader {
+  event struct tlv_hdr *getHeader(int label,int nxt_hdr,
+                                  struct ip6_hdr *msg);
+
+  event void free();
+}
diff --git a/tos/lib/net/blip/interfaces/Tcp.nc b/tos/lib/net/blip/interfaces/Tcp.nc
new file mode 100644 (file)
index 0000000..a87bb01
--- /dev/null
@@ -0,0 +1,55 @@
+
+
+interface Tcp { 
+
+  /*
+   * Bind the socket to a local address
+   * 
+   */
+  command error_t bind(uint16_t port);
+
+  /*
+   * Accept an incomming connection.
+   *
+   * the app should return FALSE to reject the connection attempt
+   */
+  event bool accept(struct sockaddr_in6 *from, 
+                    void **tx_buf, int *tx_buf_len);
+
+  /*
+   * Split-phase connect: connect to a remote endpoint.
+   *
+   * The socket should not be used until connectDone is signaled.
+   */
+  command error_t connect(struct sockaddr_in6 *dest,
+                          void *tx_buf, int tx_buf_len);
+  event void connectDone(error_t e);
+
+  /*
+   * Send and receive data on a socket.  The socket must be CONNECTed
+   * for these to succeed.
+   */
+  command error_t send(void *payload, uint16_t len);
+
+  event void recv(void *payload, uint16_t len);
+
+  /*
+   * terminate a connection.
+   */
+  command error_t close();
+  command error_t abort();
+
+  /*
+   * notify the app that the socket connection has been closed or
+   * reset by the other end, or else a timeout has occured and the
+   * local side has given up.
+   */
+  event void closed(error_t e);
+
+  /* 
+   * returns TRUE if all previously sent data has been ACKed
+   */
+  event void acked();
+
+
+}
diff --git a/tos/lib/net/blip/interfaces/UDP.nc b/tos/lib/net/blip/interfaces/UDP.nc
new file mode 100644 (file)
index 0000000..a2db7cf
--- /dev/null
@@ -0,0 +1,27 @@
+
+interface UDP {
+  /*
+   * bind a local address.  to cut down memory requirements and handle the
+   * common case well, you can only bind a port; all local interfaces are
+   * implicitly bound.  the port should be passed in host byte-order (is 
+   * this confusing?  
+   */       
+
+  command error_t bind(uint16_t port);
+
+  /*
+   * send a payload to the socket address indicated
+   * once the call returns, the stack has no claim on the buffer pointed to
+   */ 
+  command error_t sendto(struct sockaddr_in6 *dest, void *payload, 
+                         uint16_t len);
+
+  /*
+   * indicate that the stack has finished writing data into the
+   * receive buffer.  if error is not SUCCESS, the payload does not
+   * contain valid data and the src pointer should not be used.
+   */
+  event void recvfrom(struct sockaddr_in6 *src, void *payload, 
+                      uint16_t len, struct ip_metadata *meta);
+
+}
diff --git a/tos/lib/net/blip/nwprog/BootImage.nc b/tos/lib/net/blip/nwprog/BootImage.nc
new file mode 100644 (file)
index 0000000..034d1b0
--- /dev/null
@@ -0,0 +1,8 @@
+
+interface BootImage {
+  command void reboot();
+  command error_t boot(uint8_t img_num);
+  
+  // Added by Jaein Jeong
+  command error_t erase(uint8_t img_num);
+}
diff --git a/tos/lib/net/blip/nwprog/Deluge.h b/tos/lib/net/blip/nwprog/Deluge.h
new file mode 100644 (file)
index 0000000..58489f2
--- /dev/null
@@ -0,0 +1,126 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ */
+
+#ifndef __DELUGE_H__
+#define __DELUGE_H__
+
+typedef nx_struct DelugeIdent {
+  nx_uint32_t  uidhash;        // unique id of the image
+  nx_uint32_t  size;           // size of the whole image (ident + CRCs + binary)
+  nx_uint8_t   numPgs;         // number of pages of complete image
+  nx_uint8_t   reserved;
+  nx_uint16_t  crc;            // crc over the above 4 fields
+  nx_uint8_t   appname[16];
+  nx_uint8_t   username[16];
+  nx_uint8_t   hostname[16];
+  nx_uint8_t   platform[16];
+  nx_uint32_t  timestamp;
+  nx_uint32_t  userhash;
+} DelugeIdent;
+
+typedef nx_struct DelugePatchCmd {
+  nx_uint16_t linenum;      // sequence number of patches, starting from 0
+  nx_uint8_t  cmd;          // patch cmd: 16 for upload, 17 for copy
+  nx_uint16_t dst_offset;
+  nx_uint16_t data_length;  // byte length of the data
+  nx_uint16_t src_offset;
+  nx_uint8_t  reserved[7];
+  nx_uint8_t  data[0];      // data for the upload command
+} DelugePatchCmd;
+
+enum {
+  DELUGE_INVALID_UID = 0xffffffff,
+  DELUGE_NUM_VOLUMES = 4, 
+  DELUGE_IDENT_SIZE                 = 128,
+  DELUGE_MAX_PAGES                  = 128,
+  DELUGE_CRC_SIZE                   = sizeof(uint16_t),
+  DELUGE_CRC_BLOCK_SIZE             = DELUGE_MAX_PAGES * DELUGE_CRC_SIZE,
+  DELUGE_BYTES_PER_PAGE             = 23 * 48,
+};
+
+enum {
+  MAX_PATCH_DATA_SIZE = 512,
+  PATCH_LINE_SIZE = 16,
+};
+
+#define UQ_DELUGE_METADATA "DelugeMetadata.client"
+#define UQ_DELUGE_VOLUME_MANAGER "DelugeVolumeManager.client"
+#define UQ_DELUGE_VERIFY "DelugeVerify.client"
+#define UQ_DELUGE_PATCH "DelugePatch.client"
+#define UQ_DELUGE_READ_IDENT "DelugeReadIdent.client"
+
+typedef struct BootArgs {
+  uint16_t  address;
+  uint32_t imageAddr;
+  uint8_t  gestureCount;
+  bool     noReprogram;
+} BootArgs;
+
+enum {
+  NWPROG_CMD_ERASE = 1,
+  NWPROG_CMD_WRITE = 2,
+  NWPROG_CMD_READ  = 3,
+  NWPROG_CMD_LIST  = 4,
+  NWPROG_CMD_BOOT  = 5,
+  NWPROG_CMD_REBOOT= 6,
+  NWPROG_CMD_READDONE = 7,
+  NWPROG_CMD_IMAGEIFO = 8,
+};
+
+enum {
+  NWPROG_ERROR_OK = 0,
+};
+
+enum{
+  PATCH_CMD_UPLOAD = 16,
+  PATCH_CMD_COPY   = 17,
+};
+
+nx_struct ShortDelugeIdent {
+  nx_uint8_t   appname[16];
+  nx_uint8_t   username[16];
+  nx_uint8_t   hostname[16];
+  nx_uint32_t  timestamp;
+};
+
+typedef nx_struct prog_req {
+  nx_uint8_t cmd;
+  nx_uint8_t imgno;
+  nx_union {
+    nx_uint16_t offset;
+    nx_uint16_t when;
+    nx_uint16_t nimages;
+  } cmd_data;
+  nx_uint8_t data[0];
+} prog_req_t;
+
+typedef nx_struct prog_reply {
+  nx_uint8_t error;
+  nx_uint8_t pad;
+  nx_struct prog_req req;
+} prog_reply_t;
+
+#endif
diff --git a/tos/lib/net/blip/nwprog/DelugePatch.nc b/tos/lib/net/blip/nwprog/DelugePatch.nc
new file mode 100644 (file)
index 0000000..ae94655
--- /dev/null
@@ -0,0 +1,14 @@
+/**
+ *  An interface for obtaining the identification data of an
+ *  image. The pointer returned by readDone will be destroyed by the
+ *  next read.
+ *
+ *  @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ *  @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+interface DelugePatch
+{
+  command error_t decodePatch(uint8_t imgNumPatch, uint8_t imgNumSrc, uint8_t imgNumDst);
+  event void decodePatchDone(uint8_t imgNumPatch, uint8_t imgNumSrc, uint8_t imgNumDst, error_t error);
+}
diff --git a/tos/lib/net/blip/nwprog/DelugePatchC.nc b/tos/lib/net/blip/nwprog/DelugePatchC.nc
new file mode 100644 (file)
index 0000000..1c901db
--- /dev/null
@@ -0,0 +1,60 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+configuration DelugePatchC
+{
+  provides interface DelugePatch[uint8_t client];
+  uses event void storageReady();
+}
+
+implementation
+{
+  components MainC;
+  components DelugePatchP;
+
+  DelugePatch = DelugePatchP;
+  storageReady = DelugePatchP;
+
+  components new BlockReaderC(VOLUME_GOLDENIMAGE) as BlockReaderGoldenImage;
+  components new BlockReaderC(VOLUME_DELUGE1) as BlockReaderDeluge1;
+  components new BlockReaderC(VOLUME_DELUGE2) as BlockReaderDeluge2;
+  components new BlockReaderC(VOLUME_DELUGE3) as BlockReaderDeluge3;
+
+  DelugePatchP.BlockRead[VOLUME_GOLDENIMAGE] -> BlockReaderGoldenImage;
+  DelugePatchP.BlockRead[VOLUME_DELUGE1] -> BlockReaderDeluge1;
+  DelugePatchP.BlockRead[VOLUME_DELUGE2] -> BlockReaderDeluge2;
+  DelugePatchP.BlockRead[VOLUME_DELUGE3] -> BlockReaderDeluge3;
+
+  components new BlockWriterC(VOLUME_GOLDENIMAGE) as BlockWriterGoldenImage;
+  components new BlockWriterC(VOLUME_DELUGE1) as BlockWriterDeluge1;
+  components new BlockWriterC(VOLUME_DELUGE2) as BlockWriterDeluge2;
+  components new BlockWriterC(VOLUME_DELUGE3) as BlockWriterDeluge3;
+
+  DelugePatchP.BlockWrite[VOLUME_GOLDENIMAGE] -> BlockWriterGoldenImage;
+  DelugePatchP.BlockWrite[VOLUME_DELUGE1] -> BlockWriterDeluge1;
+  DelugePatchP.BlockWrite[VOLUME_DELUGE2] -> BlockWriterDeluge2;
+  DelugePatchP.BlockWrite[VOLUME_DELUGE3] -> BlockWriterDeluge3;
+}
diff --git a/tos/lib/net/blip/nwprog/DelugePatchClientC.nc b/tos/lib/net/blip/nwprog/DelugePatchClientC.nc
new file mode 100644 (file)
index 0000000..999c55a
--- /dev/null
@@ -0,0 +1,40 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+generic configuration DelugePatchClientC()
+{
+  provides interface DelugePatch;
+}
+
+implementation
+{
+  enum {
+    CLIENT_ID = unique(UQ_DELUGE_PATCH)
+  };
+
+  components DelugePatchC;
+  DelugePatch = DelugePatchC.DelugePatch[CLIENT_ID];
+}
diff --git a/tos/lib/net/blip/nwprog/DelugePatchP.nc b/tos/lib/net/blip/nwprog/DelugePatchP.nc
new file mode 100644 (file)
index 0000000..d2c7878
--- /dev/null
@@ -0,0 +1,244 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "imgNum2volumeId.h"
+
+module DelugePatchP
+{
+  provides interface DelugePatch[uint8_t client];
+  uses {
+    interface BlockRead[uint8_t volumeId];
+    interface BlockWrite[uint8_t volumeId];
+    interface StorageMap[uint8_t volumeId];
+    event void storageReady();
+  }
+}
+
+implementation
+{
+  enum {
+    S_READ_IDENT,
+    S_READY,
+    S_BUSY,
+    S_READ_PATCH_CMD,
+    S_READ_PATCH_DATA, 
+    S_READ_PATCH_COPY,
+    S_WRITE_PATCH,
+  };
+
+  DelugeIdent ident;
+  DelugePatchCmd patch;
+
+  uint8_t patchData[MAX_PATCH_DATA_SIZE];
+
+  uint8_t state;
+  uint8_t currentClient;
+
+  uint16_t patchNumLinesRead;
+  uint16_t patchNumLines;
+
+  uint32_t patchByteAddr;  
+  uint8_t patchVolume;
+  uint8_t patchImageIdx;
+  uint8_t patchPage;
+
+  uint32_t dstByteAddr;  
+  uint8_t srcVolume;
+  uint8_t srcImageIdx;
+  uint8_t srcPage;
+
+  uint32_t dstByteAddr;  
+  uint8_t dstVolume;
+  uint8_t dstImageIdx;
+  uint8_t dstPage;
+
+
+  void setStorageReady()
+  {
+    signal storageReady();
+    state = S_READY;
+  }
+
+  void notifySuccess() 
+  {
+    signal DelugePatch.decodePatchDone[currentClient](
+            patchImageIdx, srcImageIdx, dstImageIdx, SUCCESS);
+    setStorageReady();
+  }
+
+  void notifyFailure(error_t error)
+  {
+    signal DelugePatch.decodePatchDone[currentClient](
+            patchImageIdx, srcImageIdx, dstImageIdx, error);
+    setStorageReady();
+  }
+
+  command error_t DelugePatch.decodePatch[uint8_t client](uint8_t imgNumPatch,
+                                                          uint8_t imgNumSrc,
+                                                          uint8_t imgNumDst)
+  {
+    patchImageIdx = imgNumPatch;
+    patchVolume   = _imgNum2volumeId[patchImageIdx];
+    srcImageIdx   = imgNumSrc;
+    srcVolume     = _imgNum2volumeId[srcImageIdx];
+    dstImageIdx   = imgNumDst;
+    dstVolume     = _imgNum2volumeId[dstImageIdx];
+
+    // First, read the DelugeIdent section.
+    if (patchImageIdx < DELUGE_NUM_VOLUMES) {
+      state = S_READ_IDENT;
+      call BlockRead.read[patchVolume](0, &ident, sizeof(ident));
+    } else {
+      signal storageReady();
+      state = S_READY;
+    }
+
+    return SUCCESS;
+  }
+
+  event void BlockRead.readDone[uint8_t imgNum](
+    storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    switch (state) {
+    case S_BUSY:
+      notifyFailure(error);
+      break;
+    // Read the DelugeIdent structure into ident.
+    // If it is valid, ident.userhash contains
+    // number of patch command lines.
+    // Initialize patchByteAddr to the beginning of
+    // the patch commands.
+    case S_READ_IDENT:
+      if (error == SUCCESS) {
+        if (ident.uidhash != DELUGE_INVALID_UID) {
+          patchNumLines = ident.userhash;
+          state = S_READ_PATCH_CMD;
+          patchByteAddr = DELUGE_IDENT_SIZE + DELUGE_CRC_BLOCK_SIZE; 
+          call BlockRead.read[patchVolume](patchByteAddr, &patch, sizeof(patch)); 
+          break;
+        } 
+      }
+      notifyFailure(error);
+      break;
+    // Read a patch command.
+    // If successful, check it is UPLOAD or COPY.
+    // For an UPLOAD commandy
+    //   increment the number of patch lines read,
+    //   increase patchByteAddr by PATCH_LINE_SIZE,
+    //   and read the patch data.
+    // For a COPY command,
+    //   increment the number of patch lines read,
+    //   increase patchByteAddr by PATCH_LINE_SIZE,
+    //   and read data from the source volume.
+    case S_READ_PATCH_CMD:
+      if (error == SUCCESS) {
+        if (patch.cmd == PATCH_CMD_UPLOAD) { 
+          patchNumLinesRead++;
+          patchByteAddr += PATCH_LINE_SIZE;  // read the next line of patch
+          state = S_READ_PATCH_DATA;
+          call BlockRead.read[patchVolume](patchByteAddr, patchData, patch.data_length);
+          break;
+        }
+        else if (patch.cmd == PATCH_CMD_COPY) { 
+          patchNumLinesRead++; 
+          patchByteAddr += PATCH_LINE_SIZE;  // read the next line of patch
+          state = S_READ_PATCH_COPY;
+          call BlockRead.read[srcVolume](patch.src_offset, patchData, patch.data_length);
+          break;
+        }
+      }
+      notifyFailure(error);
+      break;
+    // When the patch data of PATCH_UPLOAD is ready,
+    // increase patchByteAddr ceiling(len / PATCH_LINE_SIZE) * PATCH_LINE_SIZE,
+    // and  write it into the destination volume.  
+    case S_READ_PATCH_DATA:
+      if (error == SUCCESS) {
+        state = S_WRITE_PATCH;
+        patchByteAddr += ((len + PATCH_LINE_SIZE - 1) / PATCH_LINE_SIZE * PATCH_LINE_SIZE); 
+        call BlockWrite.write[dstVolume](patch.dst_offset, buf, len);
+        break;
+      }
+      notifyFailure(error);
+      break;
+    // When the source data of PATCH_COPY is ready,
+    // write it into the destination volume.
+    case S_READ_PATCH_COPY:
+      if (error == SUCCESS) {
+        state = S_WRITE_PATCH;
+        call BlockWrite.write[dstVolume](patch.dst_offset, buf, len);
+        break;
+      }
+      notifyFailure(error);
+      break;
+    }
+  }
+
+  event void BlockWrite.writeDone[uint8_t imgNum](
+    storage_addr_t addr, void* buf, storage_len_t len, error_t error) 
+  {
+    switch (state) {
+    case S_WRITE_PATCH:
+      if (error == SUCCESS) {
+        // When more patch commands remaining, read the next one.
+        if (patchNumLinesRead < patchNumLines) {
+          state = S_READ_PATCH_CMD;
+          call BlockRead.read[patchVolume](patchByteAddr, &patch, sizeof(patch)); 
+        }
+        else {
+          notifySuccess();
+        }
+        break;
+      }
+      notifyFailure(error);
+      break;
+    }
+  }
+
+  event void BlockWrite.eraseDone[uint8_t imgNum](error_t error)
+  {
+    switch (state) {
+    case S_READY:
+      signal BlockWrite.eraseDone[imgNum](error);
+      break;
+    }
+  }
+
+  default command error_t BlockWrite.write[uint8_t imgNum](
+    storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t BlockRead.read[uint8_t imgNum](
+    storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t BlockRead.computeCrc[uint8_t imgNum](
+    storage_addr_t addr, storage_len_t len, uint16_t crc) { return FAIL; }
+  event void BlockRead.computeCrcDone[uint8_t imgNum](
+    storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error) {}
+  event void BlockWrite.syncDone[uint8_t imgNum](error_t error) {}
+  default command error_t BlockWrite.erase[uint8_t imgNum]() { return FAIL; }
+  default event void storageReady() {}
+  default event void DelugePatch.decodePatchDone[uint8_t client](
+    uint8_t imgNumPatch, uint8_t imgNumSrc, uint8_t imgNumDst, error_t error) {}
+
+}
diff --git a/tos/lib/net/blip/nwprog/DelugeReadIdent.nc b/tos/lib/net/blip/nwprog/DelugeReadIdent.nc
new file mode 100644 (file)
index 0000000..efa1c1a
--- /dev/null
@@ -0,0 +1,20 @@
+/**
+ *  An interface for obtaining the identification data of an
+ *  image. The pointer returned by readDone will be destroyed by the
+ *  next read.
+ *
+ *  @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ *  @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+interface DelugeReadIdent
+{
+  command error_t readNumVolumes();
+  command error_t readVolume(uint8_t imgNum);
+
+  event void readNumVolumesDone(uint8_t validVolumes, uint8_t volumeFields, error_t error);
+  event void readVolumeDone(uint8_t imgNum, DelugeIdent* ident, error_t error);
+
+  //command error_t read(uint8_t imgNum);
+  //event void readDone(uint8_t imgNum, DelugeIdent* ident, error_t error);
+}
diff --git a/tos/lib/net/blip/nwprog/DelugeReadIdentC.nc b/tos/lib/net/blip/nwprog/DelugeReadIdentC.nc
new file mode 100644 (file)
index 0000000..2656e62
--- /dev/null
@@ -0,0 +1,51 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+configuration DelugeReadIdentC
+{
+  provides interface DelugeReadIdent[uint8_t client];
+  uses event void storageReady();
+}
+
+implementation
+{
+  components MainC;
+  components DelugeReadIdentP;
+
+  DelugeReadIdent = DelugeReadIdentP;
+  storageReady = DelugeReadIdentP;
+  DelugeReadIdentP.Boot -> MainC;
+
+  components new BlockReaderC(VOLUME_GOLDENIMAGE) as BlockReaderGoldenImage;
+  components new BlockReaderC(VOLUME_DELUGE1) as BlockReaderDeluge1;
+  components new BlockReaderC(VOLUME_DELUGE2) as BlockReaderDeluge2;
+  components new BlockReaderC(VOLUME_DELUGE3) as BlockReaderDeluge3;
+
+  DelugeReadIdentP.BlockRead[VOLUME_GOLDENIMAGE] -> BlockReaderGoldenImage;
+  DelugeReadIdentP.BlockRead[VOLUME_DELUGE1] -> BlockReaderDeluge1;
+  DelugeReadIdentP.BlockRead[VOLUME_DELUGE2] -> BlockReaderDeluge2;
+  DelugeReadIdentP.BlockRead[VOLUME_DELUGE3] -> BlockReaderDeluge3;
+}
diff --git a/tos/lib/net/blip/nwprog/DelugeReadIdentClientC.nc b/tos/lib/net/blip/nwprog/DelugeReadIdentClientC.nc
new file mode 100644 (file)
index 0000000..53c80c5
--- /dev/null
@@ -0,0 +1,40 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+generic configuration DelugeReadIdentClientC()
+{
+  provides interface DelugeReadIdent;
+}
+
+implementation
+{
+  enum {
+    CLIENT_ID = unique(UQ_DELUGE_READ_IDENT)
+  };
+
+  components DelugeReadIdentC;
+  DelugeReadIdent = DelugeReadIdentC.DelugeReadIdent[CLIENT_ID];
+}
diff --git a/tos/lib/net/blip/nwprog/DelugeReadIdentP.nc b/tos/lib/net/blip/nwprog/DelugeReadIdentP.nc
new file mode 100644 (file)
index 0000000..ba5116d
--- /dev/null
@@ -0,0 +1,147 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "imgNum2volumeId.h"
+
+module DelugeReadIdentP
+{
+  provides interface DelugeReadIdent[uint8_t client];
+  uses {
+    interface Boot;
+    interface BlockRead[uint8_t volumeId];
+    interface StorageMap[uint8_t volumeId];
+    event void storageReady();
+  }
+}
+
+implementation
+{
+  enum {
+    S_READY,
+    S_READ_VOLUME,
+    S_READ_NUM_VOLUMES,
+  };
+  
+  DelugeIdent ident;
+  uint8_t state;
+  uint8_t currentClient;
+  uint8_t currentIdx;
+  uint8_t currentVolume;
+  uint8_t fields;
+  uint8_t validVolumes;
+
+  event void Boot.booted() { }
+
+  command error_t DelugeReadIdent.readVolume[uint8_t client](uint8_t imgNum)
+  {
+    if (state != S_READY) {
+      return FAIL;
+    }
+    else {
+      currentClient = client;
+      currentIdx = imgNum;
+      currentVolume = _imgNum2volumeId[currentIdx];
+      if (imgNum < DELUGE_NUM_VOLUMES) {
+        state = S_READ_VOLUME;
+        return call BlockRead.read[currentVolume](0, &ident, sizeof(ident)); 
+      }
+      else {
+        return FAIL;
+      } 
+    }
+  }
+
+  command error_t DelugeReadIdent.readNumVolumes[uint8_t client]()
+  {
+    if (state != S_READY) {
+      return FAIL;
+    }
+    else {
+      fields = 0;
+      validVolumes = 0;
+      currentClient = client;
+      currentIdx = 0;
+      currentVolume = _imgNum2volumeId[currentIdx];
+      state = S_READ_NUM_VOLUMES;
+      return call BlockRead.read[currentVolume](0, &ident, sizeof(ident)); 
+    }
+  }
+
+
+  event void BlockRead.readDone[uint8_t imgNum](
+    storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    switch (state) {
+    case S_READ_VOLUME:
+      if (error == SUCCESS && ident.uidhash != DELUGE_INVALID_UID) {
+        signal DelugeReadIdent.readVolumeDone[currentClient](currentIdx, buf, SUCCESS);
+      }
+      else {
+        signal DelugeReadIdent.readVolumeDone[currentClient](currentIdx, buf, FAIL);
+      }
+      state = S_READY;
+      signal storageReady();
+      break; 
+    case S_READ_NUM_VOLUMES:
+      if (error == SUCCESS && ident.uidhash != DELUGE_INVALID_UID) {
+        // Increment valid volumes only when uidhash is valid.
+        fields |= (1 << currentIdx);
+        validVolumes++; 
+      } 
+
+      // Increment the number volumes read.
+      currentIdx++;
+      currentVolume = _imgNum2volumeId[currentIdx];
+
+      // Read the next volume when it didn't reach the end.
+      if (currentIdx < DELUGE_NUM_VOLUMES) {
+        call BlockRead.read[currentVolume](0, &ident, sizeof(ident)); 
+      }
+      // Otherwise, notify the success.
+      else {
+        state = S_READY;
+        signal storageReady();
+        signal DelugeReadIdent.readNumVolumesDone[currentClient](
+          validVolumes, fields, SUCCESS);
+      }
+      break; 
+    }
+  }
+
+  event void BlockRead.computeCrcDone[uint8_t imgNum](
+    storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error) {}
+  default command error_t BlockRead.read[uint8_t imgNum](
+    storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t BlockRead.computeCrc[uint8_t imgNum](
+    storage_addr_t addr, storage_len_t len, uint16_t crc) { return FAIL; }
+  default event void storageReady() {} 
+  default event void DelugeReadIdent.readNumVolumesDone[uint8_t client](
+    uint8_t validVols, uint8_t volumeFields, error_t error) {}
+  default event void DelugeReadIdent.readVolumeDone[uint8_t client](
+    uint8_t imgNum, DelugeIdent* id, error_t error) {} 
+
+}
+
diff --git a/tos/lib/net/blip/nwprog/DelugeVerify.nc b/tos/lib/net/blip/nwprog/DelugeVerify.nc
new file mode 100644 (file)
index 0000000..979392d
--- /dev/null
@@ -0,0 +1,14 @@
+/**
+ *  An interface for obtaining the identification data of an
+ *  image. The pointer returned by readDone will be destroyed by the
+ *  next read.
+ *
+ *  @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ *  @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+interface DelugeVerify
+{
+  command error_t verifyImg(uint8_t imgNum);
+  event void verifyImgDone(uint8_t imgNum, error_t error);
+}
diff --git a/tos/lib/net/blip/nwprog/DelugeVerifyC.nc b/tos/lib/net/blip/nwprog/DelugeVerifyC.nc
new file mode 100644 (file)
index 0000000..67c0556
--- /dev/null
@@ -0,0 +1,60 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+configuration DelugeVerifyC
+{
+  provides interface DelugeVerify[uint8_t client];
+  uses event void storageReady();
+}
+
+implementation
+{
+  components MainC;
+  components DelugeVerifyP;
+
+  DelugeVerify = DelugeVerifyP;
+  storageReady = DelugeVerifyP;
+
+  components new BlockReaderC(VOLUME_GOLDENIMAGE) as BlockReaderGoldenImage;
+  components new BlockReaderC(VOLUME_DELUGE1) as BlockReaderDeluge1;
+  components new BlockReaderC(VOLUME_DELUGE2) as BlockReaderDeluge2;
+  components new BlockReaderC(VOLUME_DELUGE3) as BlockReaderDeluge3;
+
+  DelugeVerifyP.BlockRead[VOLUME_GOLDENIMAGE] -> BlockReaderGoldenImage;
+  DelugeVerifyP.BlockRead[VOLUME_DELUGE1] -> BlockReaderDeluge1;
+  DelugeVerifyP.BlockRead[VOLUME_DELUGE2] -> BlockReaderDeluge2;
+  DelugeVerifyP.BlockRead[VOLUME_DELUGE3] -> BlockReaderDeluge3;
+
+  components new BlockWriterC(VOLUME_GOLDENIMAGE) as BlockWriterGoldenImage;
+  components new BlockWriterC(VOLUME_DELUGE1) as BlockWriterDeluge1;
+  components new BlockWriterC(VOLUME_DELUGE2) as BlockWriterDeluge2;
+  components new BlockWriterC(VOLUME_DELUGE3) as BlockWriterDeluge3;
+
+  DelugeVerifyP.BlockWrite[VOLUME_GOLDENIMAGE] -> BlockWriterGoldenImage;
+  DelugeVerifyP.BlockWrite[VOLUME_DELUGE1] -> BlockWriterDeluge1;
+  DelugeVerifyP.BlockWrite[VOLUME_DELUGE2] -> BlockWriterDeluge2;
+  DelugeVerifyP.BlockWrite[VOLUME_DELUGE3] -> BlockWriterDeluge3;
+}
diff --git a/tos/lib/net/blip/nwprog/DelugeVerifyClientC.nc b/tos/lib/net/blip/nwprog/DelugeVerifyClientC.nc
new file mode 100644 (file)
index 0000000..045eb07
--- /dev/null
@@ -0,0 +1,40 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+generic configuration DelugeVerifyClientC()
+{
+  provides interface DelugeVerify;
+}
+
+implementation
+{
+  enum {
+    CLIENT_ID = unique(UQ_DELUGE_VERIFY)
+  };
+
+  components DelugeVerifyC;
+  DelugeVerify = DelugeVerifyC.DelugeVerify[CLIENT_ID];
+}
diff --git a/tos/lib/net/blip/nwprog/DelugeVerifyP.nc b/tos/lib/net/blip/nwprog/DelugeVerifyP.nc
new file mode 100644 (file)
index 0000000..8a1e8af
--- /dev/null
@@ -0,0 +1,161 @@
+/* Copyright (c) 2007 Johns Hopkins University.
+*  All rights reserved.
+*
+*  Permission to use, copy, modify, and distribute this software and its
+*  documentation for any purpose, without fee, and without written
+*  agreement is hereby granted, provided that the above copyright
+*  notice, the (updated) modification history and the author appear in
+*  all copies of this source code.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+*  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+*  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+*  ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+*  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+*  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+*  OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+*  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+*  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+*  THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "imgNum2volumeId.h"
+
+module DelugeVerifyP
+{
+  provides interface DelugeVerify[uint8_t client];
+  uses {
+    interface BlockRead[uint8_t volumeId];
+    interface BlockWrite[uint8_t volumeId];
+    interface StorageMap[uint8_t volumeId];
+    event void storageReady();
+  }
+}
+
+implementation
+{
+  enum {
+    S_READ_IDENT,
+    S_READ_CRC,
+    S_CRC,
+    S_READY,
+    S_BUSY,
+  };
+  
+  DelugeIdent ident;
+  uint8_t state;
+  uint8_t currentVolume;
+  uint8_t currentImageIdx;
+  uint8_t currentPage;
+  nx_uint16_t currentCrc;
+  uint8_t currentClient;
+
+  void setStorageReady()
+  {
+    signal storageReady();
+    state = S_READY;
+  }
+
+  uint32_t calcCrcAddr()
+  {
+    return DELUGE_IDENT_SIZE + currentPage * sizeof(uint16_t);
+  }
+  
+  uint32_t calcPageAddr()
+  {
+    return DELUGE_IDENT_SIZE + DELUGE_CRC_BLOCK_SIZE + currentPage * DELUGE_BYTES_PER_PAGE;
+  }
+
+  command error_t DelugeVerify.verifyImg[uint8_t client](uint8_t imgNum)
+  {
+    // We are going to verify the integrity of the specified image.
+    // We first read the ident to find the number of pages and 
+    // then iterate over all of them, compute the CRC and 
+    // check it against the corresponding value from the CRCs block.
+    state = S_READ_IDENT;
+    currentImageIdx = imgNum;
+    currentVolume = _imgNum2volumeId[currentImageIdx];
+
+    if (currentImageIdx < DELUGE_NUM_VOLUMES) {
+      state = S_READ_IDENT;
+      call BlockRead.read[currentVolume](0, &ident, sizeof(ident));
+    } else {
+      signal storageReady();
+      state = S_READY;
+    }
+
+    return SUCCESS;
+  }
+
+  event void BlockRead.readDone[uint8_t imgNum](storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    switch (state) {
+    case S_BUSY:
+      setStorageReady();
+      signal DelugeVerify.verifyImgDone[currentClient](imgNum, error);
+      break;
+    case S_READ_IDENT:
+      if (error == SUCCESS) {
+        if (ident.uidhash != DELUGE_INVALID_UID) {
+          currentPage = 0;
+          state = S_READ_CRC;
+          call BlockRead.read[currentVolume](calcCrcAddr(), &currentCrc, sizeof(currentCrc));
+          break;
+        } 
+      }
+      setStorageReady();
+      signal DelugeVerify.verifyImgDone[currentClient](imgNum, FAIL);
+      break;
+    case S_READ_CRC:
+      state = S_CRC;
+      call BlockRead.computeCrc[currentVolume](calcPageAddr(), DELUGE_BYTES_PER_PAGE, 0);
+      break;
+    }
+  }
+
+  event void BlockRead.computeCrcDone[uint8_t imgNum](storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error)
+  {
+    switch (state) {
+    case S_CRC:
+      if (crc != currentCrc) {
+        setStorageReady();
+        signal DelugeVerify.verifyImgDone[currentClient](imgNum, FAIL);
+      } else {
+        currentPage++;
+        if (currentPage < ident.numPgs) {
+          state = S_READ_CRC;
+          call BlockRead.read[currentVolume](calcCrcAddr(), &currentCrc, sizeof(currentCrc));
+        } 
+        else {
+          setStorageReady();
+          signal DelugeVerify.verifyImgDone[currentClient](imgNum, error); 
+        }
+      }
+      break;
+    }
+  }
+
+  default command error_t BlockRead.read[uint8_t imgNum](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t BlockRead.computeCrc[uint8_t imgNum](storage_addr_t addr, storage_len_t len, uint16_t crc) { return FAIL; }
+
+  event void BlockWrite.writeDone[uint8_t imgNum](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {}
+  event void BlockWrite.eraseDone[uint8_t imgNum](error_t error)
+  {
+    switch (state) {
+    case S_READY:
+      signal BlockWrite.eraseDone[imgNum](error);
+      break;
+    }
+  }
+
+  event void BlockWrite.syncDone[uint8_t imgNum](error_t error) {}
+  default command error_t BlockWrite.erase[uint8_t imgNum]() { return FAIL; }
+  default event void storageReady() {}
+  default event void DelugeVerify.verifyImgDone[uint8_t client](uint8_t imgNum, error_t error) {}
+
+}
diff --git a/tos/lib/net/blip/nwprog/NWProgC.nc b/tos/lib/net/blip/nwprog/NWProgC.nc
new file mode 100644 (file)
index 0000000..330dcdb
--- /dev/null
@@ -0,0 +1,51 @@
+
+#include "StorageVolumes.h"
+#include "Deluge.h"
+
+configuration NWProgC {
+  provides interface BootImage;
+} implementation {
+
+  // send and receive pages
+  components MainC, new UdpSocketC();
+  components NetProgC, NWProgP;
+
+  BootImage = NWProgP;
+
+  components BlockStorageManagerC;
+  components new BlockStorageLockClientC();
+  components new BlockWriterC(VOLUME_GOLDENIMAGE) as BlockWriterDeluge0;
+  components new BlockWriterC(VOLUME_DELUGE1) as BlockWriterDeluge1;
+  components new BlockWriterC(VOLUME_DELUGE2) as BlockWriterDeluge2;
+  components new BlockWriterC(VOLUME_DELUGE3) as BlockWriterDeluge3;
+
+  components new BlockReaderC(VOLUME_GOLDENIMAGE) as BlockReaderDeluge0;
+  components new BlockReaderC(VOLUME_DELUGE1) as BlockReaderDeluge1;
+  components new BlockReaderC(VOLUME_DELUGE2) as BlockReaderDeluge2;
+  components new BlockReaderC(VOLUME_DELUGE3) as BlockReaderDeluge3;
+
+  NWProgP.Boot -> MainC;
+  NWProgP.NetProg -> NetProgC;
+  NWProgP.StorageMap -> BlockStorageManagerC;
+  NWProgP.Recv -> UdpSocketC; // IPDispatchC.UDP[5213];
+  NWProgP.Resource -> BlockStorageLockClientC;
+
+  NWProgP.BlockWrite[VOLUME_GOLDENIMAGE] -> BlockWriterDeluge0;
+  NWProgP.BlockWrite[VOLUME_DELUGE1] -> BlockWriterDeluge1;
+  NWProgP.BlockWrite[VOLUME_DELUGE2] -> BlockWriterDeluge2;
+  NWProgP.BlockWrite[VOLUME_DELUGE3] -> BlockWriterDeluge3;
+
+  NWProgP.BlockRead[VOLUME_GOLDENIMAGE] -> BlockReaderDeluge0;
+  NWProgP.BlockRead[VOLUME_DELUGE1] -> BlockReaderDeluge1;
+  NWProgP.BlockRead[VOLUME_DELUGE2] -> BlockReaderDeluge2;
+  NWProgP.BlockRead[VOLUME_DELUGE3] -> BlockReaderDeluge3;
+
+  components new ShellCommandC("nwprog");
+  NWProgP.ShellCommand -> ShellCommandC;
+
+  components new TimerMilliC();
+  NWProgP.RebootTimer -> TimerMilliC;
+  components new DelugeMetadataClientC();
+  NWProgP.DelugeMetadata -> DelugeMetadataClientC;
+
+}
diff --git a/tos/lib/net/blip/nwprog/NWProgP.nc b/tos/lib/net/blip/nwprog/NWProgP.nc
new file mode 100644 (file)
index 0000000..81afca2
--- /dev/null
@@ -0,0 +1,339 @@
+
+#include <Storage.h>
+#include <Shell.h>
+#include "imgNum2volumeId.h"
+#include "Deluge.h"
+#include "PrintfUART.h"
+module NWProgP {
+  provides interface BootImage;
+  uses {
+    interface Boot;
+    interface UDP as Recv;
+    interface StorageMap[uint8_t imag_num];
+    interface NetProg;
+    interface BlockRead[uint8_t img_num];
+    interface BlockWrite[uint8_t img_num];
+    interface Resource;
+    interface DelugeMetadata;
+    interface Timer<TMilli> as RebootTimer;
+
+    event void storageReady();
+
+    interface ShellCommand;
+  }
+} implementation {
+
+  enum {
+    S_IDLE,
+    S_BUSY,
+  };
+  uint8_t state;
+  struct sockaddr_in6 endpoint;
+  prog_reply_t reply;
+  prog_reply_t *read_buffer;
+
+  // SDH : if this is defined, we read back each packet after we write
+  // it and check that it matches.  It turns out that this doesn't
+  // actually guarantee you much, due to buffering.
+#undef PARANOID
+
+#ifdef PARANOID
+  bool paranoid_read;
+  uint16_t cmp_len;
+  uint8_t cmp_img;
+  uint32_t cmp_off;
+  uint8_t cmp_buf[256];
+#endif
+
+  // Begin-added by Jaein Jeong
+  command error_t BootImage.erase(uint8_t img_num) {
+    error_t error = call BlockWrite.erase[img_num]();
+    return error;
+  }
+  // End-added
+
+  command void BootImage.reboot() {
+    call NetProg.reboot();
+  }
+
+  command error_t BootImage.boot(uint8_t img_num) {
+    return call NetProg.programImageAndReboot(call StorageMap.getPhysicalAddress[img_num](0));
+  }
+
+  event void Boot.booted() {
+#ifdef PARANOID
+    paranoid_read = FALSE;
+#endif
+    state = S_IDLE;
+    call Recv.bind(5213);
+  }
+
+  void sendDone(error_t error) {
+    reply.error = error;
+    call Recv.sendto(&endpoint, &reply, sizeof(prog_reply_t));
+  }
+
+  event void Recv.recvfrom(struct sockaddr_in6 *from,
+                           void *payload, uint16_t len,
+                           struct ip_metadata *meta) {
+    prog_req_t *req = (prog_req_t *)payload;
+    uint8_t imgNum = imgNum2volumeId(req->imgno);
+    error_t error = FAIL;
+    void *buffer;
+
+    // just copy the payload out and write it into flash
+    // we'll send the ack from the write done event.
+    if (state != S_IDLE) return;
+    
+    memcpy(&endpoint, from, sizeof(struct sockaddr_in6));
+    memcpy(&reply.req, req, sizeof(prog_req_t));
+
+    if (!call Resource.isOwner()) {
+      error = call Resource.immediateRequest();
+    }
+    if (error == SUCCESS) {
+      switch (req->cmd) {
+      case NWPROG_CMD_ERASE:
+        error = call BlockWrite.erase[imgNum]();
+        break;
+      case NWPROG_CMD_WRITE:
+        len -= sizeof(prog_req_t);
+
+#ifdef PARANOID
+        if (len > sizeof(cmp_buf)) {
+          error = ENOMEM;
+          break;
+        }
+        memcpy(cmp_buf, req->data, len);
+        cmp_len = len;
+        cmp_off = req->cmd_data.offset;
+        cmp_img = imgNum;
+#endif
+        
+        buffer = ip_malloc(len);
+        if (buffer == NULL) {
+          error = ENOMEM;
+          break;
+        }
+        memcpy(buffer, req->data, len);
+        error = call BlockWrite.write[imgNum](req->cmd_data.offset,
+                                              buffer,
+                                              len);
+        if (error != SUCCESS) ip_free(buffer);
+        break;
+      case NWPROG_CMD_READ: {
+
+        read_buffer = (prog_reply_t *)ip_malloc(64 + sizeof(prog_reply_t));
+        if (read_buffer == NULL) {
+          error = ENOMEM;
+          break;
+        }
+        memcpy(&read_buffer->req, req, sizeof(prog_req_t));
+        error = call BlockRead.read[imgNum](req->cmd_data.offset,
+                                            read_buffer->req.data,
+                                            64);
+        if (error != SUCCESS) {
+          ip_free(read_buffer);
+        }
+        break;
+      }
+      default:
+        error = FAIL;
+      }
+    }
+
+    if (error != SUCCESS) {
+      sendDone(error);
+      if (call Resource.isOwner()) {
+        call Resource.release();
+      }
+    } else {
+      state = S_BUSY;
+    }
+  }
+
+  event void BlockWrite.writeDone[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {
+    if (state != S_BUSY) return;
+
+#ifdef PARANOID
+    if (len != cmp_len) {
+      printfUART("WARNING: write length changed from %i to %lu!\n", cmp_len, len);
+    }
+    if (addr != cmp_off) {
+      printfUART("WARNING: write address changed from %li to %li!\n", cmp_off, addr);
+    }
+    if (img_num != cmp_img) {
+      printfUART("WARNING: write volume changed from %i to %i\n", cmp_img, img_num);
+    }
+    if (memcmp(buf, cmp_buf, cmp_len) != 0) {
+      printfUART("WARNING: write data changed during call!\n");
+    }
+    memset(buf, 0, cmp_len);
+    if (call BlockRead.read[cmp_img](cmp_off, buf, cmp_len) == SUCCESS) {
+      paranoid_read = TRUE;
+      return;
+    } 
+
+
+#else
+    ip_free(buf);
+#endif
+
+    if (error == SUCCESS) {
+      call BlockWrite.sync[img_num]();
+    } else {
+      state = S_IDLE;
+      call Resource.release();
+      sendDone(error);
+    }
+  }
+  event void BlockRead.readDone[uint8_t img_num](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {
+
+#ifdef PARANOID
+    if (paranoid_read) {
+      if (len != cmp_len) {
+        printfUART("WARNING: read length changed from %u to %lu!\n", cmp_len, len);
+      }
+      if (addr != cmp_off) {
+        printfUART("WARNING: read address changed from %li to %li!\n", cmp_off, addr);
+      }
+      if (img_num != cmp_img) {
+        printfUART("WARNING: read volume changed from %i to %i\n", cmp_img, img_num);
+      }
+      if (memcmp(buf, cmp_buf, cmp_len) != 0) {
+        printfUART("WARNING: write data changed during call!\n");
+      } else {
+        printfUART("SUCCESS: write verified!\n");
+      }
+
+      paranoid_read = FALSE;
+      ip_free(buf);
+      if (error == SUCCESS) {
+        call BlockWrite.sync[img_num]();
+      } else {
+        call Resource.release();
+        state = S_IDLE;
+        sendDone(error);
+      }
+
+      return;
+    }
+#endif
+
+
+    if (state != S_BUSY || buf != read_buffer->req.data) return;
+    call Resource.release();
+
+    read_buffer->error = error;
+    call Recv.sendto(&endpoint, read_buffer, sizeof(prog_reply_t) + 64);
+
+    ip_free(read_buffer);
+    state = S_IDLE;
+  }
+
+  event void BlockWrite.eraseDone[uint8_t img_num](error_t error) {
+    if (state != S_BUSY) return;
+    if (error == SUCCESS) 
+      call BlockWrite.sync[img_num]();
+    else {
+      sendDone(error);
+      state = S_IDLE;
+      call Resource.release();
+    }
+  }
+
+  event void BlockWrite.syncDone[uint8_t img_num](error_t error) { 
+    if (state != S_BUSY) return;
+    sendDone(error);
+    state = S_IDLE;
+    call Resource.release();
+  }
+
+  event void Resource.granted() {
+
+  }
+
+
+  /*
+   * Shell command implementation
+   */
+  uint8_t nwprog_currentvol, nwprog_validvols;
+  uint8_t boot_image;
+
+  uint8_t volumeID2imgNum(uint8_t volumeID) {
+    switch(volumeID) {
+    case VOLUME_GOLDENIMAGE: return 0;
+    case VOLUME_DELUGE1: return 1;
+    case VOLUME_DELUGE2: return 2;
+    case VOLUME_DELUGE3: return 3;
+    }
+  }
+  event void DelugeMetadata.readDone(uint8_t imgNum, DelugeIdent* ident, error_t error) {
+    int len;
+    char *reply_buf = call ShellCommand.getBuffer(MAX_REPLY_LEN);
+    if (error == SUCCESS) {
+      if (ident->uidhash != DELUGE_INVALID_UID) {
+        len = snprintf(reply_buf, MAX_REPLY_LEN,
+                       "image: %i\n\t[size: %li]\n\t[app: %s]\n\t[user: %s]\n\t[host: %s]\n\t[arch: %s]\n\t[time: 0x%lx]\n",
+                       volumeID2imgNum(imgNum), ident->size, (char *)ident->appname, (char *) ident->username,
+                       (char *)ident->hostname, (char *)ident->platform, (uint32_t)ident->timestamp);
+        nwprog_validvols++;
+        call ShellCommand.write(reply_buf, len);
+      }
+      
+    }
+    if (++nwprog_currentvol < DELUGE_NUM_VOLUMES) {
+      call DelugeMetadata.read(imgNum2volumeId(nwprog_currentvol));
+    } else {
+      len = snprintf(reply_buf, MAX_REPLY_LEN,
+                     "%i valid image(s)\n", nwprog_validvols);
+      call ShellCommand.write(reply_buf, len);
+    }
+  }
+
+  event void RebootTimer.fired() {
+    call BootImage.boot(boot_image);
+  }
+
+  event char *ShellCommand.eval(int argc, char **argv) {
+    char *nwprog_help_str = "nwprog [list | boot <imgno> [when] | reboot]\n";
+    if (argc >= 2) {
+      if (memcmp(argv[1], "list", 4) == 0) {
+        nwprog_currentvol = 0;
+        nwprog_validvols = 0;
+        call DelugeMetadata.read(imgNum2volumeId(nwprog_currentvol));
+        return NULL;
+      } else if (memcmp(argv[1], "boot", 4) == 0 && (argc == 3 || argc == 4)) {
+
+        uint32_t when = 15;
+        boot_image = atoi(argv[2]),
+        boot_image = imgNum2volumeId(boot_image);
+        if (argc == 4)
+          when = atoi(argv[3]);
+        if (when == 0)
+          call RebootTimer.stop();
+        else {
+          char *ack = call ShellCommand.getBuffer(15);
+          snprintf(ack, 15, "REBOOT %li\n", when);
+          call RebootTimer.startOneShot(when);
+          return ack;
+        }
+        return NULL;
+      } else if (memcmp(argv[1], "reboot", 6) == 0) {
+        call BootImage.reboot();
+        return NULL;
+      } 
+    }
+    return nwprog_help_str;
+  }
+
+  default command error_t BlockWrite.write[uint8_t imgNum](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t BlockWrite.erase[uint8_t imgNum]() { return FAIL; }
+  default command error_t BlockWrite.sync[uint8_t imgNum]() { return FAIL; }
+  
+ default command error_t BlockRead.read[uint8_t imgNum](storage_addr_t addr, void* buf, storage_len_t len) {return FAIL;}
+
+  event void BlockRead.computeCrcDone[uint8_t imgNum](storage_addr_t addr, storage_len_t len,uint16_t crc, error_t error) {}
+
+
+}
diff --git a/tos/lib/net/blip/platform/CC2420ReadLqiC.nc b/tos/lib/net/blip/platform/CC2420ReadLqiC.nc
new file mode 100644 (file)
index 0000000..372d24c
--- /dev/null
@@ -0,0 +1,15 @@
+
+uint16_t adjustLQI(uint8_t val) {
+  uint16_t result = (80 - (val - 50));
+  result = (((result * result) >> 3) * result) >> 3;  // result = (result ^ 3) / 64
+  return result;
+}
+
+module CC2420ReadLqiC {
+  provides interface ReadLqi;
+  uses interface CC2420Packet;
+} implementation {
+  command uint8_t ReadLqi.read(message_t *msg) {
+    return call CC2420Packet.getLqi(msg);
+  }
+}
diff --git a/tos/lib/net/blip/platform/RF230ReadLqiC.nc b/tos/lib/net/blip/platform/RF230ReadLqiC.nc
new file mode 100644 (file)
index 0000000..f814aee
--- /dev/null
@@ -0,0 +1,15 @@
+
+uint16_t adjustLQI(uint8_t val) {
+  uint16_t result = 64 - (val / 4);
+  result = (((result * result) >> 3) * result) >> 3;  // result = (result ^ 3) / 64
+  return result;
+}
+
+module RF230ReadLqiC {
+  provides interface ReadLqi;
+  uses interface PacketField<uint8_t> as SubLqi;
+} implementation {
+  command uint8_t ReadLqi.read(message_t *msg) {
+    return call SubLqi.get(msg);
+  }
+}
diff --git a/tos/lib/net/blip/serial/SerialDevConf.h b/tos/lib/net/blip/serial/SerialDevConf.h
new file mode 100644 (file)
index 0000000..ab1ec8a
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _SERIALDEVCONF_H_
+#define _SERIALDEVCONF_H_
+
+enum {
+  TOS_SERIAL_DEVCONF = 3,
+};
+
+#endif
diff --git a/tos/lib/net/blip/serial/SerialDevConfC.nc b/tos/lib/net/blip/serial/SerialDevConfC.nc
new file mode 100644 (file)
index 0000000..f3214ed
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+//$Id$
+
+/* "Copyright (c) 2000-2005 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * Implementation of communication 802.15.4 message_t packets over the
+ * serial port.
+ *
+ * @author Philip Levis
+ * @author Ben Greenstein
+ * @date August 7 2005
+ *
+ */
+
+#include "SerialDevConf.h"
+configuration SerialDevConfC {
+  provides {
+    interface Send;
+    interface Receive;
+  }
+  uses interface Leds;
+}
+implementation { 
+  components SerialPacketInfoDevConfP as Info, SerialDispatcherC;
+
+  Leds = SerialDispatcherC;
+  Send = SerialDispatcherC.Send[TOS_SERIAL_DEVCONF];
+  Receive = SerialDispatcherC.Receive[TOS_SERIAL_DEVCONF];
+  SerialDispatcherC.SerialPacketInfo[TOS_SERIAL_DEVCONF] -> Info;
+}
diff --git a/tos/lib/net/blip/serial/SerialPacketInfoDevConfP.nc b/tos/lib/net/blip/serial/SerialPacketInfoDevConfP.nc
new file mode 100644 (file)
index 0000000..99ac36e
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+/* "Copyright (c) 2000-2005 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+module SerialPacketInfoDevConfP {
+  provides interface SerialPacketInfo as Info;
+}
+implementation {
+  async command uint8_t Info.offset() {
+    // no header
+    return sizeof(message_header_t);
+  }
+  async command uint8_t Info.dataLinkLength(message_t* msg, uint8_t upperLen) {
+    // no header or footer
+    return upperLen;
+  }
+  async command uint8_t Info.upperLength(message_t* msg, uint8_t dataLinkLen) {
+    return dataLinkLen;
+  }
+}
diff --git a/tos/lib/net/blip/shell/FlashShellC.nc b/tos/lib/net/blip/shell/FlashShellC.nc
new file mode 100644 (file)
index 0000000..cc09e4e
--- /dev/null
@@ -0,0 +1,14 @@
+
+#include "StorageVolumes.h"
+
+configuration FlashShellC {
+  
+} implementation {
+  components new ShellCommandC("flash");
+  FlashShellP.ShellCommand -> ShellCommandC;
+
+  components new BlockStorageC(VOLUME_DELUGE1);
+  FlashShellP.BlockRead -> BlockStorageC;
+  FlashShellP.BlockWrite -> BlockStorageC;
+
+}
diff --git a/tos/lib/net/blip/shell/FlashShellP.nc b/tos/lib/net/blip/shell/FlashShellP.nc
new file mode 100644 (file)
index 0000000..cb87f9a
--- /dev/null
@@ -0,0 +1,46 @@
+module FlashShellP {
+  uses {
+    interface Boot;
+    interface Leds;
+    interface ShellCommand;
+    interface BlockRead;
+    interface BlockWrite;
+  }
+} implementation {
+
+  event void Boot.booted() {
+    if (call BlockWrite.erase() != SUCCESS)
+       call Leds.led1Toggle();
+  }
+
+  event void BlockRead.readDone(storage_addr_t addr, void* buf, storage_len_t len,
+                                error_t error) {
+    uint16_t r_len = snprintf(reply_buf, MAX_REPLY_LEN,"read done addr: 0x%x len: %i error: %i data: ", 
+                              addr, len, error);
+    if (len < MAX_REPLY_LEN - r_len - 1)
+      memcpy(reply_buf + r_len, buf, len);
+    reply_buf[r_len + len + 1] = '\n';
+    call UDP.sendto(&session_endpoint, reply_buf, r_len + len + 1);
+    
+  }
+
+  event void BlockRead.computeCrcDone(storage_addr_t addr, storage_len_t len,
+                                         uint16_t crc, error_t error) {
+
+  }
+
+  event void BlockWrite.writeDone(storage_addr_t addr, void* buf, storage_len_t len,
+                                  error_t error) {
+    uint16_t r_len = snprintf(reply_buf, MAX_REPLY_LEN,"write done addr: 0x%x len: %i error: %i\n", 
+                              addr, len, error);
+    call UDP.sendto(&session_endpoint, reply_buf, r_len);
+  }
+
+  event void BlockWrite.eraseDone(error_t error) {
+    call Leds.led0Toggle();
+  }
+
+  event void BlockWrite.syncDone(error_t error) {
+
+  }
+}
diff --git a/tos/lib/net/blip/shell/RegisterShellCommand.nc b/tos/lib/net/blip/shell/RegisterShellCommand.nc
new file mode 100644 (file)
index 0000000..fb98013
--- /dev/null
@@ -0,0 +1,4 @@
+
+interface RegisterShellCommand {
+  event char *getCommandName();
+}
diff --git a/tos/lib/net/blip/shell/Shell.h b/tos/lib/net/blip/shell/Shell.h
new file mode 100644 (file)
index 0000000..c9bdc25
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef _SHELL_H
+#define _SHELL_H
+
+enum {
+  MAX_REPLY_LEN = 128,
+};
+
+#endif
diff --git a/tos/lib/net/blip/shell/ShellCommand.nc b/tos/lib/net/blip/shell/ShellCommand.nc
new file mode 100644 (file)
index 0000000..075c55c
--- /dev/null
@@ -0,0 +1,25 @@
+
+interface ShellCommand {
+
+  /*
+   * evaluate the command that this command provides
+   * @argc the number of arguments
+   * @argv the arguments
+   * @return a string to send back as the reply to the shell client.
+   *         if NULL, nothing is sent.
+   */
+  event char *eval(int argc, char **argv);
+
+  /*
+   * request a buffer.  The result of this command may be returned
+   * from 'eval', but otherwise the buffer may not be used outside of
+   * the context it is called from.
+   */
+  command char *getBuffer(uint16_t len);
+
+  /*
+   * write a string to the shell buffer; if no client is connected it
+   * will fail silently
+   */
+  command void write(char *str, int len);
+}
diff --git a/tos/lib/net/blip/shell/ShellCommandC.nc b/tos/lib/net/blip/shell/ShellCommandC.nc
new file mode 100644 (file)
index 0000000..7343617
--- /dev/null
@@ -0,0 +1,14 @@
+
+generic configuration ShellCommandC(char cmd_name[]) {
+  provides interface ShellCommand;
+} implementation {
+
+  enum {
+    CMD_ID = unique("UDPSHELL_CLIENTCOUNT"),
+  };
+
+  components new ShellCommandP(cmd_name), UDPShellP;
+
+  ShellCommandP.RegisterShellCommand ->  UDPShellP.RegisterShellCommand[CMD_ID];
+  ShellCommand = UDPShellP.ShellCommand[CMD_ID];
+}
diff --git a/tos/lib/net/blip/shell/ShellCommandP.nc b/tos/lib/net/blip/shell/ShellCommandP.nc
new file mode 100644 (file)
index 0000000..6f9af62
--- /dev/null
@@ -0,0 +1,8 @@
+
+generic module ShellCommandP(char cmd_name[]) {
+  uses interface RegisterShellCommand;
+} implementation {
+  event char *RegisterShellCommand.getCommandName() {
+    return cmd_name;
+  }
+}
diff --git a/tos/lib/net/blip/shell/UDPShellC.nc b/tos/lib/net/blip/shell/UDPShellC.nc
new file mode 100644 (file)
index 0000000..d3d3a03
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <6lowpan.h>
+
+configuration UDPShellC {
+
+
+} implementation {
+
+  components new UdpSocketC();
+  components UDPShellP, LedsC;
+
+  UDPShellP.UDP -> UdpSocketC;
+
+  UDPShellP.Leds -> LedsC;
+  components ICMPResponderC;
+  UDPShellP.ICMPPing -> ICMPResponderC.ICMPPing[unique("PING")];
+
+#if defined(PLATFORM_TELOSB) || defined(PLATFORM_EPIC)
+  components CounterMilli32C;
+  UDPShellP.Uptime -> CounterMilli32C;
+#endif
+
+  components MainC;
+  UDPShellP.Boot -> MainC;
+
+}
diff --git a/tos/lib/net/blip/shell/UDPShellP.nc b/tos/lib/net/blip/shell/UDPShellP.nc
new file mode 100644 (file)
index 0000000..7c968aa
--- /dev/null
@@ -0,0 +1,291 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <ip.h>
+#include <IPDispatch.h>
+#include <ICMP.h>
+#include "Shell.h"
+
+module UDPShellP {
+  provides {
+    interface ShellCommand[uint8_t cmd_id];
+    interface RegisterShellCommand[uint8_t cmd_id];
+  }
+  uses {
+    interface Boot;
+    interface UDP;
+    interface Leds;
+    
+    interface ICMPPing;
+#if defined(PLATFORM_TELOSB) || defined(PLATFORM_EPIC)
+    interface Counter<TMilli, uint32_t> as Uptime;
+#endif
+
+  }
+
+} implementation {
+
+  bool session_active;
+  struct sockaddr_in6 session_endpoint;
+  uint32_t boot_time;
+  uint64_t uptime;
+
+  enum {
+    N_EXTERNAL = uniqueCount("UDPSHELL_CLIENTCOUNT"),
+  };
+
+  // and corresponding indeces
+  enum {
+    N_BUILTINS = 5,
+    // the maximum number of arguments a command can take
+    N_ARGS = 10,
+    CMD_HELP = 0,
+    CMD_ECHO = 1,
+    CMD_PING6 = 2,
+    CMD_TRACERT6 = 3,
+
+    CMD_NO_CMD = 0xfe,
+    CMDNAMSIZ = 10,
+  };
+  
+  struct cmd_name {
+    uint8_t c_len;
+    char c_name[CMDNAMSIZ];
+  };
+  struct cmd_builtin {
+    void (*action)(int, char **);
+  };
+
+  struct cmd_name externals[N_EXTERNAL];
+
+
+  event void Boot.booted() {
+    int i;
+    atomic {
+      uptime = 0;
+#if defined(PLATFORM_TELOSB) || defined(PLATFORM_EPIC)
+      boot_time = call Uptime.get();
+#endif
+    }
+    for (i = 0; i < N_EXTERNAL; i++) {
+      externals[i].c_name[CMDNAMSIZ-1] = '\0';
+      strncpy(externals[i].c_name, signal RegisterShellCommand.getCommandName[i](), CMDNAMSIZ);
+      externals[i].c_len = strlen(externals[i].c_name);
+    }
+    call UDP.bind(2000);
+  }
+
+
+#define DEREF(X)  #X
+#define QUOTE(X)  DEREF(X)
+  char reply_buf[MAX_REPLY_LEN];
+  char *help_str = "sdsh-0.9\tbuiltins: [help, echo, ping6, uptime, ident]\n";
+  const char *ping_fmt = " icmp_seq=%i ttl=%i time=%i ms\n";
+  const char *ping_summary = "%i packets transmitted, %i received\n";
+  char *ident_string = "\t[app: "
+    IDENT_APPNAME "]\n\t[user: " IDENT_USERNAME "]\n\t[host: " IDENT_HOSTNAME
+    "]\n\t[time: " QUOTE(IDENT_TIMESTAMP) "]\n";
+  
+
+  void action_help(int argc, char **argv) {
+    int i = 0;
+    char *pos = reply_buf;
+    call UDP.sendto(&session_endpoint, help_str, strlen(help_str));
+    if (N_EXTERNAL > 0) {
+      strcpy(pos, "\t\t[");
+      pos += 3;
+      for (i = 0; i < N_EXTERNAL; i++) {
+        if (externals[i].c_len + 4 < MAX_REPLY_LEN - (pos - reply_buf)) {
+          memcpy(pos, externals[i].c_name, externals[i].c_len);
+          pos += externals[i].c_len;
+          if (i < N_EXTERNAL-1) {
+            pos[0] = ',';
+            pos[1] = ' ';
+            pos += 2;
+          } 
+        } else {
+          pos[0] = '.';
+          pos[1] = '.';
+          pos[2] = '.';
+          pos += 3;
+          break;
+        }
+      }
+      *pos++ = ']';
+      *pos++ = '\n';
+      call UDP.sendto(&session_endpoint, reply_buf, pos - reply_buf);
+    }
+  }
+
+  command char *ShellCommand.getBuffer[uint8_t cmd_id](uint16_t len) {
+    reply_buf[0] = '\0';
+    if (len <= MAX_REPLY_LEN) return reply_buf;
+    return NULL;
+  }
+
+  command void ShellCommand.write[uint8_t cmd_id](char *str, int len) {
+    call UDP.sendto(&session_endpoint, str, len);    
+  }
+
+  void action_echo(int argc, char **argv) {
+    int i, arg_len;
+    char *payload = reply_buf;
+
+    if (argc < 2) return;
+    for (i = 1; i < argc; i++) {
+      arg_len = strlen(argv[i]);
+      if ((payload - reply_buf) + arg_len + 1 > MAX_REPLY_LEN) break;
+      memcpy(payload, argv[i], arg_len);
+      payload += arg_len;
+      *payload = ' ';
+      payload++;
+    }
+    *(payload - 1) = '\n';
+
+    call UDP.sendto(&session_endpoint, reply_buf, payload - reply_buf);
+  }
+
+  void action_ping6(int argc, char **argv) {
+    struct in6_addr dest;
+
+    if (argc < 2) return;
+        inet_pton6(argv[1], &dest);
+    call ICMPPing.ping(&dest, 1024, 10);
+  }
+
+
+  void action_uptime(int argc, char **argv) {
+#if defined(PLATFORM_TELOSB) || defined(PLATFORM_EPIC)
+    int len;
+    uint64_t tval = call Uptime.get();
+    atomic
+      tval = (uptime + tval - boot_time) / 1024;
+    len = snprintf(reply_buf, MAX_REPLY_LEN, "up %li seconds\n",
+                   (uint32_t)tval);
+    call UDP.sendto(&session_endpoint, reply_buf, len);
+#endif
+  }
+
+  void action_ident(int argc, char **argv) {
+    call UDP.sendto(&session_endpoint, ident_string, strlen(ident_string));
+  }
+
+  // commands 
+  struct cmd_name builtins[N_BUILTINS] = {{4, "help"},
+                                          {4, "echo"},  
+                                          {5, "ping6"},
+                                          {6, "uptime"},
+                                          {5, "ident"}};
+  struct cmd_builtin builtin_actions[N_BUILTINS] = {{action_help},
+                                                    {action_echo},
+                                                    {action_ping6},
+                                                    {action_uptime},
+                                                    {action_ident}};
+
+
+  // break up a command given as a string into a sequence of null terminated
+  // strings, and initialize the argv array to point into it.
+  void init_argv(char *cmd, uint16_t len, char **argv, int *argc) {
+    int inArg = 0;
+    *argc = 0;
+    while (len > 0 && *argc < N_ARGS) {
+      if (*cmd == ' ' || *cmd == '\n' || *cmd == '\t' || *cmd == '\0' || len == 1){
+        if (inArg) {
+          *argc = *argc + 1;
+          inArg = 0;
+          *cmd = '\0';
+        }
+      } else if (!inArg) {
+        argv[*argc] = cmd;
+        inArg = 1;
+      }
+      cmd ++;
+      len --;
+    }
+  }
+
+  int lookup_cmd(char *cmd, int dbsize, struct cmd_name *db) {
+    int i;
+    for (i = 0; i < dbsize; i++) {
+      if (memcmp(cmd, db[i].c_name, db[i].c_len) == 0 
+          && cmd[db[i].c_len] == '\0')
+        return i;
+    }
+    return CMD_NO_CMD;
+  }
+
+  event void UDP.recvfrom(struct sockaddr_in6 *from, void *data, 
+                          uint16_t len, struct ip_metadata *meta) {
+    char *argv[N_ARGS];
+    int argc, cmd;
+
+    memcpy(&session_endpoint, from, sizeof(struct sockaddr_in6));
+    init_argv((char *)data, len, argv, &argc);
+
+    if (argc > 0) {
+      cmd = lookup_cmd(argv[0], N_BUILTINS, builtins);
+      if (cmd != CMD_NO_CMD) {
+        builtin_actions[cmd].action(argc, argv);
+        return;
+      }
+      cmd = lookup_cmd(argv[0], N_EXTERNAL, externals);
+      if (cmd != CMD_NO_CMD) {
+        char *reply = signal ShellCommand.eval[cmd](argc, argv);
+        if (reply != NULL)
+          call UDP.sendto(&session_endpoint, reply, strlen(reply));
+        return;
+      }
+      cmd = snprintf(reply_buf, MAX_REPLY_LEN, "sdsh: %s: command not found\n", argv[0]);
+      call UDP.sendto(&session_endpoint, reply_buf, cmd);
+    }
+  }
+
+  event void ICMPPing.pingReply(struct in6_addr *source, struct icmp_stats *stats) {
+    int len;
+    len = inet_ntop6(source, reply_buf, MAX_REPLY_LEN);
+    if (len > 0) {
+      len += snprintf(reply_buf + len - 1, MAX_REPLY_LEN - len + 1, ping_fmt,
+                      stats->seq, stats->ttl, stats->rtt);
+      call UDP.sendto(&session_endpoint, reply_buf, len);
+    }
+  }
+
+  event void ICMPPing.pingDone(uint16_t ping_rcv, uint16_t ping_n) {
+    int len;
+    len = snprintf(reply_buf, MAX_REPLY_LEN, ping_summary, ping_n, ping_rcv);
+    call UDP.sendto(&session_endpoint, reply_buf, len);
+  }
+
+#if  defined(PLATFORM_TELOSB) || defined(PLATFORM_EPIC)
+  async event void Uptime.overflow() {
+    atomic
+      uptime += 0xffffffff;
+  }
+#endif
+
+  default event char *ShellCommand.eval[uint8_t cmd_id](int argc, char **argv) {
+    return NULL;
+  }
+  default event char *RegisterShellCommand.getCommandName[uint8_t cmd_id]() {
+    return NULL;
+  }
+}
diff --git a/tos/lib/net/blip/table.c b/tos/lib/net/blip/table.c
new file mode 100644 (file)
index 0000000..3cb912e
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <stdlib.h>
+#include "table.h"
+
+void table_init(table_t *table, void *data,
+                uint16_t elt_len, uint16_t n_elts) {
+  table->data = data;
+  table->elt_len  = elt_len;
+  table->n_elts   = n_elts;
+}
+
+void *table_search(table_t *table, int (*pred)(void *)) {
+  int i;
+  void *cur;
+  for (i = 0; i < table->n_elts; i++) {
+    cur = table->data + (i * table->elt_len);
+    switch (pred(cur)) {
+    case 1: return cur;
+    case -1: return NULL;
+    default: continue;
+    }
+  }
+  return NULL;
+}
+
+void table_map(table_t *table, void(*fn)(void *)) {
+  int i;
+  for (i = 0; i < table->n_elts; i++)
+    fn(table->data + (i * table->elt_len));
+}
+
diff --git a/tos/lib/net/blip/table.h b/tos/lib/net/blip/table.h
new file mode 100644 (file)
index 0000000..3f2914b
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+#ifndef TABLE_H_
+#define TABLE_H_
+
+#include <stdint.h>
+
+typedef struct {
+  void *data;
+  uint16_t elt_len;
+  uint16_t n_elts;
+} table_t;
+
+void table_init(table_t *table, void *data,uint16_t elt_len, uint16_t n_elts);
+void *table_search(table_t *table, int (*pred)(void *));
+void table_map(table_t *table, void (*fn)(void *));
+
+#endif
index 3f9528d794685c4e86d5f5484527c0c6726d85ae..ddebdac648b9c17f3a51a0814eac96445c72e21b 100644 (file)
@@ -25,8 +25,9 @@
  */
 
 /** Link estimator asks the routing engine if this entry
- * should be inserted into the neighbor table given the
- * white bit. The return value is the "pin bit" - if true
+ * should be inserted into the neighbor table if the
+ * white bit on a link is set but there is no room for the link
+ * on the link table. The return value is the "pin bit" - if true
  * insert into the neighbor table. In the reference implementation
  * the router will return true if the path through the source
  * will be better than a path through at least one current neighbor.
@@ -38,5 +39,6 @@
 interface CompareBit {
 
   /* should the source of this message be inserted into the neighbor table? */
-   event bool shouldInsert(message_t * ONE msg, void* COUNT_NOK(len) payload, uint8_t len, bool white_bit);
+  /* expect to be called only for links with the white bit set */
+   event bool shouldInsert(message_t * ONE msg, void* COUNT_NOK(len) payload, uint8_t len);
 }
index 7d3b19b51a668bdf690d9842c3afd7975e578c4d..fe5ad7e6336294d5b8fcd631a7ddf6f77f24c53e 100644 (file)
@@ -57,6 +57,7 @@ enum {
     // CTP Options:
     CTP_OPT_PULL      = 0x80, // TEP 123: P field
     CTP_OPT_ECN       = 0x40, // TEP 123: C field
+    CTP_OPT_ALL       = 0xff
 };
 
 typedef nx_uint8_t nx_ctp_options_t;
index d0946336d65f4480d722e5729523ce8ddc6bcf92..ccb92dbf3db3a1f1ccbf02db384d0af55b09358e 100644 (file)
  */
 
 enum {
-#if PLATFORM_MICAZ || PLATFORM_TELOSA || PLATFORM_TELOSB || PLATFORM_TMOTE || PLATFORM_INTELMOTE2
-  FORWARD_PACKET_TIME = 4,
+#if PLATFORM_MICAZ || PLATFORM_TELOSA || PLATFORM_TELOSB || PLATFORM_TMOTE || PLATFORM_INTELMOTE2 || PLATFORM_SHIMMER || PLATFORM_IRIS
+  FORWARD_PACKET_TIME = 7,
 #else
   FORWARD_PACKET_TIME = 32,
 #endif
 };
 
 enum {
-  SENDDONE_FAIL_OFFSET      =                       512,
-  SENDDONE_NOACK_OFFSET     = FORWARD_PACKET_TIME  << 2,
-  SENDDONE_OK_OFFSET        = FORWARD_PACKET_TIME  << 2,
-  LOOPY_OFFSET              = FORWARD_PACKET_TIME  << 4,
-  SENDDONE_FAIL_WINDOW      = SENDDONE_FAIL_OFFSET  - 1,
-  LOOPY_WINDOW              = LOOPY_OFFSET          - 1,
-  SENDDONE_NOACK_WINDOW     = SENDDONE_NOACK_OFFSET - 1,
-  SENDDONE_OK_WINDOW        = SENDDONE_OK_OFFSET    - 1,
+  SENDDONE_OK_OFFSET        = FORWARD_PACKET_TIME,
+  SENDDONE_OK_WINDOW        = FORWARD_PACKET_TIME,
+  SENDDONE_NOACK_OFFSET     = FORWARD_PACKET_TIME,
+  SENDDONE_NOACK_WINDOW     = FORWARD_PACKET_TIME,
+  SENDDONE_FAIL_OFFSET      = FORWARD_PACKET_TIME  << 2,
+  SENDDONE_FAIL_WINDOW      = SENDDONE_FAIL_OFFSET,
+  LOOPY_OFFSET              = FORWARD_PACKET_TIME  << 2,
+  LOOPY_WINDOW              = LOOPY_OFFSET,
   CONGESTED_WAIT_OFFSET     = FORWARD_PACKET_TIME  << 2,
-  CONGESTED_WAIT_WINDOW     = CONGESTED_WAIT_OFFSET - 1,
+  CONGESTED_WAIT_WINDOW     = CONGESTED_WAIT_OFFSET,
+  NO_ROUTE_RETRY            = 10000
 };
 
 
@@ -89,19 +90,6 @@ enum {
   MAX_RETRIES = 30
 };
 
-/*
- * The network header that the ForwardingEngine introduces.
- * This header will change for the TinyOS 2.0 full release 
- * (it needs several optimizations).
- */
-typedef nx_struct {
-  nx_uint8_t control;
-  nx_am_addr_t origin;
-  nx_uint8_t seqno;
-  nx_uint8_t collectid;
-  nx_uint16_t gradient;
-} network_header_t;
-
 /*
  * An element in the ForwardingEngine send queue.
  * The client field keeps track of which send client 
index 16c1803cc4173593671f793623acb9e0360ab830..964e35a5ef39ef92b842769ae24534c86ac91392 100644 (file)
@@ -1,6 +1,6 @@
 /* $Id$ */
 /*
- * Copyright (c) 2006 Stanford University.
+ * Copyright (c) 2008-9 Stanford University.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  */
 
 /**
- *  The ForwardingEngine is responsible for queueing and scheduling outgoing
- *  packets in a collection protocol. It maintains a pool of forwarding messages 
- *  and a packet send 
- *  queue. A ForwardingEngine with a forwarding message pool of size <i>F</i> 
- *  and <i>C</i> CollectionSenderC clients has a send queue of size
- *  <i>F + C</i>. This implementation has a large number of configuration
- *  constants, which can be found in <code>ForwardingEngine.h</code>.
+ *  This component contains the forwarding path of CTP Noe, the
+ *  standard CTP implementation packaged with TinyOS 2.x. The CTP
+ *  specification can be found in TEP 123.  The paper entitled
+ *  "Collection Tree Protocol," by Omprakash Gnawali et al., in SenSys
+ *  2009, describes the implementation and provides detailed
+ *  performance results of CTP Noe.</p>
  *
- *  <p>Packets in the send queue are sent in FIFO order, with head-of-line
- *  blocking. Because this is a tree collection protocol, all packets are going
- *  to the same destination, and so the ForwardingEngine does not distinguish
- *  packets from one another: packets from CollectionSenderC clients are
- *  treated identically to forwarded packets.</p>
+ *  <p>The CTP ForwardingEngine is responsible for queueing and
+ *  scheduling outgoing packets. It maintains a pool of forwarding
+ *  messages and a packet send queue. A ForwardingEngine with a
+ *  forwarding message pool of size <i>F</i> and <i>C</i>
+ *  CollectionSenderC clients has a send queue of size <i>F +
+ *  C</i>. This implementation several configuration constants, which
+ *  can be found in <code>ForwardingEngine.h</code>.</p>
+ *
+ *  <p>Packets in the send queue are sent in FIFO order, with
+ *  head-of-line blocking. Because this is a tree collection protocol,
+ *  all packets are going to the same destination, and so the
+ *  ForwardingEngine does not distinguish packets from one
+ *  another. Packets from CollectionSenderC clients are sent
+ *  identically to forwarded packets: only their buffer handling is
+ *  different.</p>
  *
  *  <p>If ForwardingEngine is on top of a link layer that supports
  *  synchronous acknowledgments, it enables them and retransmits packets
  *  when they are not acked. It transmits a packet up to MAX_RETRIES times
- *  before giving up and dropping the packet.</p> 
+ *  before giving up and dropping the packet. MAX_RETRIES is typically a
+ *  large number (e.g., >20), as this implementation assumes there is
+ *  link layer feedback on failed packets, such that link costs will go
+ *  up and cause the routing layer to pick a next hop. If the underlying
+ *  link layer does not support acknowledgments, ForwardingEngine sends
+ *  a packet only once.</p> 
  *
  *  <p>The ForwardingEngine detects routing loops and tries to correct
- *  them. It assumes that the collection tree is based on a gradient,
- *  such as hop count or estimated transmissions. When the ForwardingEngine
- *  sends a packet to the next hop, it puts the local gradient value in
- *  the packet header. If a node receives a packet to forward whose
- *  gradient value is less than its own, then the gradient is not monotonically
- *  decreasing and there may be a routing loop. When the ForwardingEngine
- *  receives such a packet, it tells the RoutingEngine to advertise its
- *  gradient value soon, with the hope that the advertisement will update
- *  the node who just sent a packet and break the loop.
+ *  them. Routing is in terms of a cost gradient, where the collection
+ *  root has a cost of zero and a node's cost is the cost of its next
+ *  hop plus the cost of the link to that next hop.  If there are no
+ *  loops, then this gradient value decreases monotonically along a
+ *  route. When the ForwardingEngine sends a packet to the next hop,
+ *  it puts the local gradient value in the packet header. If a node
+ *  receives a packet to forward whose gradient value is less than its
+ *  own, then the gradient is not monotonically decreasing and there
+ *  may be a routing loop. When the ForwardingEngine receives such a
+ *  packet, it tells the RoutingEngine to advertise its gradient value
+ *  soon, with the hope that the advertisement will update the node
+ *  who just sent a packet and break the loop. It also pauses the
+ *  before the next packet transmission, in hopes of giving the
+ *  routing layer's packet a priority.</p>
  *  
- *  <p>ForwardingEngine times its packet transmissions. It differentiates
- *  between four transmission cases: forwarding, success, ack failure, 
- *  and loop detection. In each case, the
- *  ForwardingEngine waits a randomized period of time before sending the next
- *  packet. This approach assumes that the network is operating at low
- *  utilization; its goal is to prevent correlated traffic -- such as 
- *  nodes along a route forwarding packets -- from interfering with itself.
+ *  <p>ForwardingEngine times its packet transmissions. It
+ *  differentiates between four transmission cases: forwarding,
+ *  success, ack failure, and loop detection. In each case, the
+ *  ForwardingEngine waits a randomized period of time before sending
+ *  the next packet. This approach assumes that the network is
+ *  operating at low utilization; its goal is to prevent correlated
+ *  traffic -- such as nodes along a route forwarding packets -- from
+ *  interfering with itself.</p>
  *
- *  <table>
- *    <tr>
- *      <td><b>Case</b></td>
- *      <td><b>CC2420 Wait (ms)</b></td>
- *      <td><b>Other Wait (ms)</b></td>
- *      <td><b>Description</b></td>
- *    </tr>
- *    <tr>
- *      <td>Forwarding</td>
- *      <td>Immediate</td>
- *      <td>Immediate</td>
- *      <td>When the ForwardingEngine receives a packet to forward and it is not
- *          already sending a packet (queue is empty). In this case, it immediately
- *          forwards the packet.</td>
- *    </tr>
- *    <tr>
- *      <td>Success</td>
- *      <td>16-31</td>
- *      <td>128-255</td>
- *      <td>When the ForwardingEngine successfully sends a packet to the next
- *          hop, it waits this long before sending the next packet in the queue.
- *          </td>
- *    </tr>
- *    <tr>
- *      <td>Ack Failure</td>
- *      <td>8-15</td>
- *      <td>128-255</td>
- *      <td>If the link layer supports acks and the ForwardingEngine did not
- *          receive an acknowledgment from the next hop, it waits this long before
- *          trying a retransmission. If the packet has exceeded the retransmission
- *          count, ForwardingEngine drops the packet and uses the Success timer instead. </td>
- *    </tr>
- *    <tr>
- *      <td>Loop Detection</td>
- *      <td>32-63</td>
- *      <td>512-1023</td>
- *      <td>If the ForwardingEngine is asked to forward a packet from a node that
- *          believes it is closer to the root, the ForwardingEngine pauses its
- *          transmissions for this interval and triggers the RoutingEngine to 
- *          send an update. The goal is to let the gradient become consistent before
- *          sending packets, in order to prevent routing loops from consuming
- *          bandwidth and energy.</td>
- *    </tr>
- *  </table>  
+ *  <p>While this implementation can work on top of a variety of link
+ *  estimators, it is designed to work with a 4-bit link estimator
+ *  (4B). Details on 4B can be found in the HotNets paper "Four Bit
+ *  Link Estimation" by Rodrigo Fonseca et al. The forwarder provides
+ *  the "ack" bit for each sent packet, telling the estimator whether
+ *  the packet was acknowledged.</p>
  *
- *  <p>The times above are all for CC2420-based platforms. The timings for
- *  other platforms depend on their bit rates, as they are based on packet
- *  transmission times.</p>
-
  *  @author Philip Levis
  *  @author Kyle Jamieson
  *  @date   $Date$
@@ -140,32 +118,48 @@ generic module CtpForwardingEngineP() {
     interface CtpCongestion;
   }
   uses {
+    // These five interfaces are used in the forwarding path
+    //   SubSend is for sending packets
+    //   PacketAcknowledgements is for enabling layer 2 acknowledgments
+    //   RetxmitTimer is for timing packet sends for improved performance
+    //   LinkEstimator is for providing the ack bit to a link estimator
     interface AMSend as SubSend;
-    interface Receive as SubReceive;
-    interface Receive as SubSnoop;
-    interface Packet as SubPacket;
+    interface PacketAcknowledgements;
+    interface Timer<TMilli> as RetxmitTimer;
+    interface LinkEstimator; 
     interface UnicastNameFreeRouting;
-    interface SplitControl as RadioControl;
+    interface Packet as SubPacket;
+
+    // These four data structures are used to manage packets to forward.
+    // SendQueue and QEntryPool are the forwarding queue.
+    // MessagePool is the buffer pool for messages to forward.
+    // SentCache is for suppressing duplicate packet transmissions.
     interface Queue<fe_queue_entry_t*> as SendQueue;
     interface Pool<fe_queue_entry_t> as QEntryPool;
     interface Pool<message_t> as MessagePool;
-    interface Timer<TMilli> as RetxmitTimer;
-
-    interface LinkEstimator;
-
-    // Counts down from the last time we heard from our parent; used
-    // to expire local state about parent congestion.
-    interface Timer<TMilli> as CongestionTimer;
-
     interface Cache<message_t*> as SentCache;
+    
+    interface Receive as SubReceive;
+    interface Receive as SubSnoop;
     interface CtpInfo;
-    interface PacketAcknowledgements;
-    interface Random;
     interface RootControl;
     interface CollectionId[uint8_t client];
     interface AMPacket;
-    interface CollectionDebug;
     interface Leds;
+    interface Random;
+
+    // This implementation has extensive debugging instrumentation.
+    // Wiring up the CollectionDebug interface provides information
+    // on important events, such as transmissions, receptions,
+    // and cache checks. The TinyOS release includes scripts for
+    // parsing these messages.
+    interface CollectionDebug;
+
+    
+    // The ForwardingEngine monitors whether the underlying
+    // radio is on or not in order to start/stop forwarding
+    // as appropriate.
+    interface SplitControl as RadioControl;
   }
 }
 implementation {
@@ -173,34 +167,22 @@ implementation {
    * masked by the given mask and added to the given offset.
    */
   static void startRetxmitTimer(uint16_t mask, uint16_t offset);
-  static void startCongestionTimer(uint16_t mask, uint16_t offset);
-
-  /* Indicates whether our client is congested */
-  bool clientCongested = FALSE;
-
-  /* Tracks our parent's congestion state. */
-  bool parentCongested = FALSE;
-
-  /* Threshold for congestion */
-  uint8_t congestionThreshold;
-
-  /* Keeps track of whether the routing layer is running; if not,
-   * it will not send packets. */
-  bool running = FALSE;
-
-  /* Keeps track of whether the radio is on; no sense sending packets
-   * if the radio is off. */
-  bool radioOn = FALSE;
+  void clearState(uint8_t state);
+  bool hasState(uint8_t state);
+  void setState(uint8_t state);
 
-  /* Keeps track of whether an ack is pending on an outgoing packet,
-   * so that the engine can work unreliably when the data-link layer
-   * does not support acks. */
-  bool ackPending = FALSE;
-
-  /* Keeps track of whether the packet on the head of the queue
-   * is being used, and control access to the data-link layer.*/
-  bool sending = FALSE;
+  // CTP state variables.
+  enum {
+    QUEUE_CONGESTED  = 0x1, // Need to set C bit?
+    ROUTING_ON       = 0x2, // Forwarding running?
+    RADIO_ON         = 0x4, // Radio is on?
+    ACK_PENDING      = 0x8, // Have an ACK pending?
+    SENDING          = 0x10 // Am sending a packet?
+  };
 
+  // Start with all states false
+  uint8_t forwardingState = 0; 
+  
   /* Keep track of the last parent address we sent to, so that
      unacked packets to an old parent are not incorrectly attributed
      to a new parent. */
@@ -237,7 +219,6 @@ implementation {
       clientPtrs[i] = clientEntries + i;
       dbg("Forwarder", "clientPtrs[%hhu] = %p\n", i, clientPtrs[i]);
     }
-    congestionThreshold = (call SendQueue.maxSize()) >> 1;
     loopbackMsgPtr = &loopbackMsg;
     lastParent = call AMPacket.address();
     seqno = 0;
@@ -245,12 +226,12 @@ implementation {
   }
 
   command error_t StdControl.start() {
-    running = TRUE;
+    setState(ROUTING_ON);
     return SUCCESS;
   }
 
   command error_t StdControl.stop() {
-    running = FALSE;
+    clearState(ROUTING_ON);
     return SUCCESS;
   }
 
@@ -263,19 +244,29 @@ implementation {
      when it turns on, it then starts sending packets. */ 
   event void RadioControl.startDone(error_t err) {
     if (err == SUCCESS) {
-      radioOn = TRUE;
+      setState(RADIO_ON);
       if (!call SendQueue.empty()) {
+       dbg("FHangBug", "%s posted sendTask.\n", __FUNCTION__);
         post sendTask();
       }
     }
   }
+
+  static void startRetxmitTimer(uint16_t window, uint16_t offset) {
+    uint16_t r = call Random.rand16();
+    r %= window;
+    r += offset;
+    call RetxmitTimer.startOneShot(r);
+    dbg("Forwarder", "Rexmit timer will fire in %hu ms\n", r);
+  }
+  
   /* 
    * If the ForwardingEngine has stopped sending packets because
    * these has been no route, then as soon as one is found, start
    * sending packets.
    */ 
   event void UnicastNameFreeRouting.routeFound() {
+    dbg("FHangBug", "%s posted sendTask.\n", __FUNCTION__);
     post sendTask();
   }
 
@@ -287,7 +278,7 @@ implementation {
   
   event void RadioControl.stopDone(error_t err) {
     if (err == SUCCESS) {
-      radioOn = FALSE;
+      clearState(RADIO_ON);
     }
   }
 
@@ -302,13 +293,15 @@ implementation {
    * already sending packets (the RetxmitTimer isn't running), post
    * sendTask. It could be that the engine is running and sendTask
    * has already been posted, but the post-once semantics make this
-   * not matter.
+   * not matter. What's important is that you don't post sendTask
+   * if the retransmit timer is running; this would circumvent the
+   * timer and send a packet before it fires.
    */ 
   command error_t Send.send[uint8_t client](message_t* msg, uint8_t len) {
     ctp_data_header_t* hdr;
     fe_queue_entry_t *qe;
     dbg("Forwarder", "%s: sending packet from client %hhu: %x, len %hhu\n", __FUNCTION__, client, msg, len);
-    if (!running) {return EOFF;}
+    if (!hasState(ROUTING_ON)) {return EOFF;}
     if (len > call Send.maxPayloadLength[client]()) {return ESIZE;}
     
     call Packet.setPayloadLength(msg, len);
@@ -329,7 +322,8 @@ implementation {
     qe->retries = MAX_RETRIES;
     dbg("Forwarder", "%s: queue entry for %hhu is %hhu deep\n", __FUNCTION__, client, call SendQueue.size());
     if (call SendQueue.enqueue(qe) == SUCCESS) {
-      if (radioOn && !call RetxmitTimer.isRunning()) {
+      if (hasState(RADIO_ON) && !hasState(SENDING)) {
+       dbg("FHangBug", "%s posted sendTask.\n", __FUNCTION__);
         post sendTask();
       }
       clientPtrs[client] = NULL;
@@ -366,7 +360,8 @@ implementation {
    * These is where all of the send logic is. When the ForwardingEngine
    * wants to send a packet, it posts this task. The send logic is
    * independent of whether it is a forwarded packet or a packet from
-   * a send client. 
+   * a send clientL the two cases differ in how memory is managed in
+   * sendDone.
    *
    * The task first checks that there is a packet to send and that
    * there is a valid route. It then marshals the relevant arguments
@@ -380,156 +375,105 @@ implementation {
    */
 
   task void sendTask() {
+    uint16_t gradient;
     dbg("Forwarder", "%s: Trying to send a packet. Queue size is %hhu.\n", __FUNCTION__, call SendQueue.size());
-    if (sending) {
-      dbg("Forwarder", "%s: busy, don't send\n", __FUNCTION__);
-      call CollectionDebug.logEvent(NET_C_FE_SEND_BUSY);
-      return;
-    }
-    else if (call SendQueue.empty()) {
-      dbg("Forwarder", "%s: queue empty, don't send\n", __FUNCTION__);
+    if (hasState(SENDING) || call SendQueue.empty()) {
       call CollectionDebug.logEvent(NET_C_FE_SENDQUEUE_EMPTY);
       return;
     }
-    else if (!call RootControl.isRoot() && 
-             !call UnicastNameFreeRouting.hasRoute()) {
-      dbg("Forwarder", "%s: no route, don't send, start retry timer\n", __FUNCTION__);
-      call RetxmitTimer.startOneShot(10000);
-
-      // send a debug message to the uart
+    else if ((!call RootControl.isRoot() && 
+             !call UnicastNameFreeRouting.hasRoute()) ||
+            (call CtpInfo.getEtx(&gradient) != SUCCESS)) {
+      /* This code path is for when we don't have a valid next
+       * hop. We set a retry timer.
+       *
+       * Technically, this timer isn't necessary, as if a route
+       * is found we'll get an event. But just in case such an event
+       * is lost (e.g., a bug in the routing engine), we retry.
+       * Otherwise the forwarder might hang indefinitely. As this test
+       * doesn't require radio activity, the energy cost is minimal. */
+      dbg("Forwarder", "%s: no route, don't send, try again in %i.\n", __FUNCTION__, NO_ROUTE_RETRY);
+      call RetxmitTimer.startOneShot(NO_ROUTE_RETRY);
       call CollectionDebug.logEvent(NET_C_FE_NO_ROUTE);
-
       return;
     }
-    /*
-    else if (parentCongested) {
-      // Do nothing; the congestion timer is necessarily set which
-      // will clear parentCongested and repost sendTask().
-      dbg("Forwarder", "%s: sendTask deferring for congested parent\n",
-          __FUNCTION__);
-      call CollectionDebug.logEvent(NET_C_FE_CONGESTION_SENDWAIT);
-    }
-    */
     else {
+      /* We can send a packet.
+        First check if it's a duplicate;
+        if not, try to send/forward. */
       error_t subsendResult;
       fe_queue_entry_t* qe = call SendQueue.head();
       uint8_t payloadLen = call SubPacket.payloadLength(qe->msg);
       am_addr_t dest = call UnicastNameFreeRouting.nextHop();
-      uint16_t gradient;
 
-      if (call CtpInfo.isNeighborCongested(dest)) {
-        // Our parent is congested. We should wait.
-        // Don't repost the task, CongestionTimer will do the job
-        if (! parentCongested ) {
-          parentCongested = TRUE;
-          call CollectionDebug.logEvent(NET_C_FE_CONGESTION_BEGIN);
-        }
-        if (! call CongestionTimer.isRunning()) {
-          startCongestionTimer(CONGESTED_WAIT_WINDOW, CONGESTED_WAIT_OFFSET);
-        } 
-        dbg("Forwarder", "%s: sendTask deferring for congested parent\n",
-            __FUNCTION__);
-        //call CollectionDebug.logEvent(NET_C_FE_CONGESTION_SENDWAIT);
-        return;
-      } 
-      if (parentCongested) {
-        parentCongested = FALSE;
-        call CollectionDebug.logEvent(NET_C_FE_CONGESTION_END);
-      } 
-      // Once we are here, we have decided to send the packet.
       if (call SentCache.lookup(qe->msg)) {
+       /* This packet is a duplicate, so suppress it: free memory and
+        * send next packet.  Duplicates are only possible for
+        * forwarded packets, so we can circumvent the client or
+        * forwarded branch for freeing the buffer. */
         call CollectionDebug.logEvent(NET_C_FE_DUPLICATE_CACHE_AT_SEND);
         call SendQueue.dequeue();
-       if (call MessagePool.put(qe->msg) != SUCCESS)
-         call CollectionDebug.logEvent(NET_C_FE_PUT_MSGPOOL_ERR);
-       if (call QEntryPool.put(qe) != SUCCESS)
-         call CollectionDebug.logEvent(NET_C_FE_PUT_QEPOOL_ERR);
+       if (call MessagePool.put(qe->msg) != SUCCESS) 
+         call CollectionDebug.logEvent(NET_C_FE_PUT_MSGPOOL_ERR); 
+       if (call QEntryPool.put(qe) != SUCCESS) 
+         call CollectionDebug.logEvent(NET_C_FE_PUT_QEPOOL_ERR); 
+         
         post sendTask();
         return;
       }
-      /* If our current parent is not the same as the last parent
-         we sent do, then reset the count of unacked packets: don't
-         penalize a new parent for the failures of a prior one.*/
-      if (dest != lastParent) {
-        qe->retries = MAX_RETRIES;
-        lastParent = dest;
-      }
+      
+      // Not a duplicate: we've decided we're going to send.
       dbg("Forwarder", "Sending queue entry %p\n", qe);
+
       if (call RootControl.isRoot()) {
+       /* Code path for roots: copy the packet and signal receive. */
         collection_id_t collectid = getHeader(qe->msg)->type;
+       uint8_t* payload;
+       uint8_t payloadLength;
+
         memcpy(loopbackMsgPtr, qe->msg, sizeof(message_t));
-        ackPending = FALSE;
-       
+
+       payload = call Packet.getPayload(loopbackMsgPtr, call Packet.payloadLength(loopbackMsgPtr));
+       payloadLength =  call Packet.payloadLength(loopbackMsgPtr);
         dbg("Forwarder", "%s: I'm a root, so loopback and signal receive.\n", __FUNCTION__);
         loopbackMsgPtr = signal Receive.receive[collectid](loopbackMsgPtr,
-                                                          call Packet.getPayload(loopbackMsgPtr, call Packet.payloadLength(loopbackMsgPtr)), 
-                                                          call Packet.payloadLength(loopbackMsgPtr));
+                                                          payload,
+                                                          payloadLength);
         signal SubSend.sendDone(qe->msg, SUCCESS);
-        return;
       }
-      
-      // Loop-detection functionality:
-      if (call CtpInfo.getEtx(&gradient) != SUCCESS) {
-        // If we have no metric, set our gradient conservatively so
-        // that other nodes don't automatically drop our packets.
-        gradient = 0;
-      }
-      call CtpPacket.setEtx(qe->msg, gradient);
-      
-      ackPending = (call PacketAcknowledgements.requestAck(qe->msg) == SUCCESS);
-
-      // Set or clear the congestion bit on *outgoing* packets.
-      if (call CtpCongestion.isCongested())
-        call CtpPacket.setOption(qe->msg, CTP_OPT_ECN);
-      else
-        call CtpPacket.clearOption(qe->msg, CTP_OPT_ECN);
-      
-      subsendResult = call SubSend.send(dest, qe->msg, payloadLen);
-      if (subsendResult == SUCCESS) {
-        // Successfully submitted to the data-link layer.
-        sending = TRUE;
-        dbg("Forwarder", "%s: subsend succeeded with %p.\n", __FUNCTION__, qe->msg);
-        if (qe->client < CLIENT_COUNT) {
-               dbg("Forwarder", "%s: client packet.\n", __FUNCTION__);
-        }
-        else {
-               dbg("Forwarder", "%s: forwarded packet.\n", __FUNCTION__);
-        }
-        return;
-      }
-      else if (subsendResult == EOFF) {
-       // The radio has been turned off underneath us. Assume that
-       // this is for the best. When the radio is turned back on, we'll
-       // handle a startDone event and resume sending.
-        radioOn = FALSE;
-       dbg("Forwarder", "%s: subsend failed from EOFF.\n", __FUNCTION__);
-        // send a debug message to the uart
-       call CollectionDebug.logEvent(NET_C_FE_SUBSEND_OFF);
-      }
-      else if (subsendResult == EBUSY) {
-       // This shouldn't happen, as we sit on top of a client and
-        // control our own output; it means we're trying to
-        // double-send (bug). This means we expect a sendDone, so just
-        // wait for that: when the sendDone comes in, // we'll try
-        // sending this packet again.  
-       dbg("Forwarder", "%s: subsend failed from EBUSY.\n", __FUNCTION__);
-        // send a debug message to the uart
-        call CollectionDebug.logEvent(NET_C_FE_SUBSEND_BUSY);
-      }
-      else if (subsendResult == ESIZE) {
-       dbg("Forwarder", "%s: subsend failed from ESIZE: truncate packet.\n", __FUNCTION__);
-       call Packet.setPayloadLength(qe->msg, call Packet.maxPayloadLength());
-       post sendTask();
-       call CollectionDebug.logEvent(NET_C_FE_SUBSEND_SIZE);
+      else {
+       /* The basic forwarding/sending case. */
+       call CtpPacket.setEtx(qe->msg, gradient);
+       call CtpPacket.clearOption(qe->msg, CTP_OPT_ECN | CTP_OPT_PULL);
+       if (call PacketAcknowledgements.requestAck(qe->msg) == SUCCESS) {
+         setState(ACK_PENDING);
+       }
+       if (hasState(QUEUE_CONGESTED)) {
+         call CtpPacket.setOption(qe->msg, CTP_OPT_ECN); 
+         clearState(QUEUE_CONGESTED);
+       }
+       
+       subsendResult = call SubSend.send(dest, qe->msg, payloadLen);
+       if (subsendResult == SUCCESS) {
+         // Successfully submitted to the data-link layer.
+         setState(SENDING);
+         dbg("Forwarder", "%s: subsend succeeded with %p.\n", __FUNCTION__, qe->msg);
+         return;
+       }
+       // The packet is too big: truncate it and retry.
+       else if (subsendResult == ESIZE) {
+         dbg("Forwarder", "%s: subsend failed from ESIZE: truncate packet.\n", __FUNCTION__);
+         call Packet.setPayloadLength(qe->msg, call Packet.maxPayloadLength());
+         post sendTask();
+         call CollectionDebug.logEvent(NET_C_FE_SUBSEND_SIZE);
+       }
+       else {
+         dbg("Forwarder", "%s: subsend failed from %i\n", __FUNCTION__, (int)subsendResult);
+       }
       }
     }
   }
 
-  void sendDoneBug() {
-    // send a debug message to the uart
-    call CollectionDebug.logEvent(NET_C_FE_BAD_SENDDONE);
-  }
 
   /*
    * The second phase of a send operation; based on whether the transmission was
@@ -542,97 +486,92 @@ implementation {
    * 
    */
 
+  void packetComplete(fe_queue_entry_t* qe, message_t* msg, bool success) {
+    // Four cases:
+    // Local packet: success or failure
+    // Forwarded packet: success or failure
+    if (qe->client < CLIENT_COUNT) { 
+      clientPtrs[qe->client] = qe;
+      signal Send.sendDone[qe->client](msg, SUCCESS);
+      if (success) {
+       dbg("CtpForwarder", "%s: packet %hu.%hhu for client %hhu acknowledged.\n", __FUNCTION__, call CollectionPacket.getOrigin(msg), call CollectionPacket.getSequenceNumber(msg), qe->client);
+       call CollectionDebug.logEventMsg(NET_C_FE_SENT_MSG, 
+                                        call CollectionPacket.getSequenceNumber(msg), 
+                                        call CollectionPacket.getOrigin(msg), 
+                                         call AMPacket.destination(msg));
+      } else {
+       dbg("CtpForwarder", "%s: packet %hu.%hhu for client %hhu dropped.\n", __FUNCTION__, call CollectionPacket.getOrigin(msg), call CollectionPacket.getSequenceNumber(msg), qe->client);
+       call CollectionDebug.logEventMsg(NET_C_FE_SENDDONE_FAIL_ACK_SEND, 
+                                        call CollectionPacket.getSequenceNumber(msg), 
+                                        call CollectionPacket.getOrigin(msg), 
+                                        call AMPacket.destination(msg));
+      }
+    }
+    else { 
+      if (success) {
+       call SentCache.insert(qe->msg);
+       dbg("CtpForwarder", "%s: forwarded packet %hu.%hhu acknowledged: insert in transmit queue.\n", __FUNCTION__, call CollectionPacket.getOrigin(msg), call CollectionPacket.getSequenceNumber(msg));
+       call CollectionDebug.logEventMsg(NET_C_FE_FWD_MSG, 
+                                        call CollectionPacket.getSequenceNumber(msg), 
+                                        call CollectionPacket.getOrigin(msg), 
+                                         call AMPacket.destination(msg));
+      }
+      else {
+       dbg("CtpForwarder", "%s: forwarded packet %hu.%hhu dropped.\n", __FUNCTION__, call CollectionPacket.getOrigin(msg), call CollectionPacket.getSequenceNumber(msg));
+       call CollectionDebug.logEventMsg(NET_C_FE_SENDDONE_FAIL_ACK_FWD, 
+                                        call CollectionPacket.getSequenceNumber(msg), 
+                                        call CollectionPacket.getOrigin(msg), 
+                                        call AMPacket.destination(msg));
+      }
+      if (call MessagePool.put(qe->msg) != SUCCESS)
+       call CollectionDebug.logEvent(NET_C_FE_PUT_MSGPOOL_ERR);
+      if (call QEntryPool.put(qe) != SUCCESS)
+       call CollectionDebug.logEvent(NET_C_FE_PUT_QEPOOL_ERR);
+    }
+  }
+  
   event void SubSend.sendDone(message_t* msg, error_t error) {
     fe_queue_entry_t *qe = call SendQueue.head();
     dbg("Forwarder", "%s to %hu and %hhu\n", __FUNCTION__, call AMPacket.destination(msg), error);
-    if (qe == NULL || qe->msg != msg) {
-      dbg("Forwarder", "%s: BUG: not our packet (%p != %p)!\n", __FUNCTION__, msg, qe->msg);
-      sendDoneBug();      // Not our packet, something is very wrong...
-      return;
-    }
-    else if (error != SUCCESS) {
-      // Immediate retransmission is the worst thing to do.
+
+    if (error != SUCCESS) {
+      /* The radio wasn't able to send the packet: retransmit it. */
       dbg("Forwarder", "%s: send failed\n", __FUNCTION__);
       call CollectionDebug.logEventMsg(NET_C_FE_SENDDONE_FAIL, 
-                                        call CollectionPacket.getSequenceNumber(msg), 
-                                        call CollectionPacket.getOrigin(msg), 
-                                         call AMPacket.destination(msg));
+                                      call CollectionPacket.getSequenceNumber(msg), 
+                                      call CollectionPacket.getOrigin(msg), 
+                                      call AMPacket.destination(msg));
       startRetxmitTimer(SENDDONE_FAIL_WINDOW, SENDDONE_FAIL_OFFSET);
     }
-    else if (ackPending && !call PacketAcknowledgements.wasAcked(msg)) {
-      // AckPending is for case when DL cannot support acks.
+    else if (hasState(ACK_PENDING) && !call PacketAcknowledgements.wasAcked(msg)) {
+      /* No ack: if countdown is not 0, retransmit, else drop the packet. */
       call LinkEstimator.txNoAck(call AMPacket.destination(msg));
       call CtpInfo.recomputeRoutes();
       if (--qe->retries) { 
-        dbg("Forwarder", "%s: not acked\n", __FUNCTION__);
+        dbg("Forwarder", "%s: not acked, retransmit\n", __FUNCTION__);
         call CollectionDebug.logEventMsg(NET_C_FE_SENDDONE_WAITACK, 
                                         call CollectionPacket.getSequenceNumber(msg), 
                                         call CollectionPacket.getOrigin(msg), 
                                          call AMPacket.destination(msg));
         startRetxmitTimer(SENDDONE_NOACK_WINDOW, SENDDONE_NOACK_OFFSET);
       } else {
-        //max retries, dropping packet
-        if (qe->client < CLIENT_COUNT) {
-            clientPtrs[qe->client] = qe;
-            signal Send.sendDone[qe->client](msg, FAIL);
-            call CollectionDebug.logEventMsg(NET_C_FE_SENDDONE_FAIL_ACK_SEND, 
-                                        call CollectionPacket.getSequenceNumber(msg), 
-                                        call CollectionPacket.getOrigin(msg), 
-                                         call AMPacket.destination(msg));
-        } else {
-           if (call MessagePool.put(qe->msg) != SUCCESS)
-             call CollectionDebug.logEvent(NET_C_FE_PUT_MSGPOOL_ERR);
-           if (call QEntryPool.put(qe) != SUCCESS)
-             call CollectionDebug.logEvent(NET_C_FE_PUT_QEPOOL_ERR);
-           call CollectionDebug.logEventMsg(NET_C_FE_SENDDONE_FAIL_ACK_FWD, 
-                                        call CollectionPacket.getSequenceNumber(msg), 
-                                        call CollectionPacket.getOrigin(msg), 
-                                         call AMPacket.destination(msg));
-        }
-        call SendQueue.dequeue();
-        sending = FALSE;
+       /* Hit max retransmit threshold: drop the packet. */
+       call SendQueue.dequeue();
+        clearState(SENDING);
         startRetxmitTimer(SENDDONE_OK_WINDOW, SENDDONE_OK_OFFSET);
+       
+       packetComplete(qe, msg, FALSE);
       }
     }
-    else if (qe->client < CLIENT_COUNT) {
-      ctp_data_header_t* hdr;
-      uint8_t client = qe->client;
-      dbg("Forwarder", "%s: our packet for client %hhu, remove %p from queue\n", 
-          __FUNCTION__, client, qe);
-      call CollectionDebug.logEventMsg(NET_C_FE_SENT_MSG, 
-                                        call CollectionPacket.getSequenceNumber(msg), 
-                                        call CollectionPacket.getOrigin(msg), 
-                                         call AMPacket.destination(msg));
-      call LinkEstimator.txAck(call AMPacket.destination(msg));
-      clientPtrs[client] = qe;
-      hdr = getHeader(qe->msg);
+    else {
+      /* Packet was acknowledged. Updated the link estimator,
+        free the buffer (pool or sendDone), start timer to
+        send next packet. */
       call SendQueue.dequeue();
-      signal Send.sendDone[client](msg, SUCCESS);
-      sending = FALSE;
+      clearState(SENDING);
       startRetxmitTimer(SENDDONE_OK_WINDOW, SENDDONE_OK_OFFSET);
-    }
-    else if (call MessagePool.size() < call MessagePool.maxSize()) {
-      // A successfully forwarded packet.
-      dbg("Forwarder,Route", "%s: successfully forwarded packet (client: %hhu), message pool is %hhu/%hhu.\n", __FUNCTION__, qe->client, call MessagePool.size(), call MessagePool.maxSize());
-      call CollectionDebug.logEventMsg(NET_C_FE_FWD_MSG, 
-                                        call CollectionPacket.getSequenceNumber(msg), 
-                                        call CollectionPacket.getOrigin(msg), 
-                                         call AMPacket.destination(msg));
       call LinkEstimator.txAck(call AMPacket.destination(msg));
-      call SentCache.insert(qe->msg);
-      call SendQueue.dequeue();
-      if (call MessagePool.put(qe->msg) != SUCCESS)
-        call CollectionDebug.logEvent(NET_C_FE_PUT_MSGPOOL_ERR);
-      if (call QEntryPool.put(qe) != SUCCESS)
-        call CollectionDebug.logEvent(NET_C_FE_PUT_QEPOOL_ERR);
-      sending = FALSE;
-      startRetxmitTimer(SENDDONE_OK_WINDOW, SENDDONE_OK_OFFSET);
-    }
-    else {
-      dbg("Forwarder", "%s: BUG: we have a pool entry, but the pool is full, client is %hhu.\n", __FUNCTION__, qe->client);
-      sendDoneBug();    // It's a forwarded packet, but there's no room the pool;
-      // someone has double-stored a pointer somewhere and we have nowhere
-      // to put this, so we have to leak it...
+      packetComplete(qe, msg, TRUE);
     }
   }
 
@@ -701,6 +640,7 @@ implementation {
         if (!call RetxmitTimer.isRunning()) {
           // sendTask is only immediately posted if we don't detect a
           // loop.
+         dbg("FHangBug", "%s: posted sendTask.\n", __FUNCTION__);
           post sendTask();
         }
         
@@ -812,39 +752,28 @@ implementation {
   }
   
   event void RetxmitTimer.fired() {
-    sending = FALSE;
-    post sendTask();
-  }
-
-  event void CongestionTimer.fired() {
-    //parentCongested = FALSE;
-    //call CollectionDebug.logEventSimple(NET_C_FE_CONGESTION_END, 0);
+    clearState(SENDING);
+    dbg("FHangBug", "%s posted sendTask.\n", __FUNCTION__);
     post sendTask();
   }
-  
 
   command bool CtpCongestion.isCongested() {
-    // A simple predicate for now to determine congestion state of
-    // this node.
-    bool congested = (call SendQueue.size() > congestionThreshold) ? 
-      TRUE : FALSE;
-    return ((congested || clientCongested)?TRUE:FALSE);
+    return FALSE;
   }
 
   command void CtpCongestion.setClientCongested(bool congested) {
-    bool wasCongested = call CtpCongestion.isCongested();
-    clientCongested = congested;
-    if (!wasCongested && congested) {
-      call CtpInfo.triggerImmediateRouteUpdate();
-    } else if (wasCongested && ! (call CtpCongestion.isCongested())) {
-      call CtpInfo.triggerRouteUpdate();
-    }
+    // Do not respond to congestion.
   }
+  
+  /* signalled when this neighbor is evicted from the neighbor table */
+  event void LinkEstimator.evicted(am_addr_t neighbor) {}
 
+  
+  // Packet ADT commands
   command void Packet.clear(message_t* msg) {
     call SubPacket.clear(msg);
   }
-  
+
   command uint8_t Packet.payloadLength(message_t* msg) {
     return call SubPacket.payloadLength(msg) - sizeof(ctp_data_header_t);
   }
@@ -865,44 +794,38 @@ implementation {
     return payload;
   }
 
+  // CollectionPacket ADT commands
   command am_addr_t       CollectionPacket.getOrigin(message_t* msg) {return getHeader(msg)->origin;}
-
   command collection_id_t CollectionPacket.getType(message_t* msg) {return getHeader(msg)->type;}
   command uint8_t         CollectionPacket.getSequenceNumber(message_t* msg) {return getHeader(msg)->originSeqNo;}
   command void CollectionPacket.setOrigin(message_t* msg, am_addr_t addr) {getHeader(msg)->origin = addr;}
   command void CollectionPacket.setType(message_t* msg, collection_id_t id) {getHeader(msg)->type = id;}
   command void CollectionPacket.setSequenceNumber(message_t* msg, uint8_t _seqno) {getHeader(msg)->originSeqNo = _seqno;}
-  
-  //command ctp_options_t CtpPacket.getOptions(message_t* msg) {return getHeader(msg)->options;}
 
+  // CtpPacket ADT commands
   command uint8_t       CtpPacket.getType(message_t* msg) {return getHeader(msg)->type;}
   command am_addr_t     CtpPacket.getOrigin(message_t* msg) {return getHeader(msg)->origin;}
   command uint16_t      CtpPacket.getEtx(message_t* msg) {return getHeader(msg)->etx;}
   command uint8_t       CtpPacket.getSequenceNumber(message_t* msg) {return getHeader(msg)->originSeqNo;}
   command uint8_t       CtpPacket.getThl(message_t* msg) {return getHeader(msg)->thl;}
-  
   command void CtpPacket.setThl(message_t* msg, uint8_t thl) {getHeader(msg)->thl = thl;}
   command void CtpPacket.setOrigin(message_t* msg, am_addr_t addr) {getHeader(msg)->origin = addr;}
   command void CtpPacket.setType(message_t* msg, uint8_t id) {getHeader(msg)->type = id;}
-
+  command void CtpPacket.setEtx(message_t* msg, uint16_t e) {getHeader(msg)->etx = e;}
+  command void CtpPacket.setSequenceNumber(message_t* msg, uint8_t _seqno) {getHeader(msg)->originSeqNo = _seqno;}
   command bool CtpPacket.option(message_t* msg, ctp_options_t opt) {
     return ((getHeader(msg)->options & opt) == opt) ? TRUE : FALSE;
   }
-
   command void CtpPacket.setOption(message_t* msg, ctp_options_t opt) {
     getHeader(msg)->options |= opt;
   }
-
   command void CtpPacket.clearOption(message_t* msg, ctp_options_t opt) {
     getHeader(msg)->options &= ~opt;
   }
 
-  command void CtpPacket.setEtx(message_t* msg, uint16_t e) {getHeader(msg)->etx = e;}
-  command void CtpPacket.setSequenceNumber(message_t* msg, uint8_t _seqno) {getHeader(msg)->originSeqNo = _seqno;}
 
   // A CTP packet ID is based on the origin and the THL field, to
   // implement duplicate suppression as described in TEP 123.
-
   command bool CtpPacket.matchInstance(message_t* m1, message_t* m2) {
     return (call CtpPacket.getOrigin(m1) == call CtpPacket.getOrigin(m2) &&
            call CtpPacket.getSequenceNumber(m1) == call CtpPacket.getSequenceNumber(m2) &&
@@ -916,6 +839,19 @@ implementation {
            call CtpPacket.getType(m1) == call CtpPacket.getType(m2));
   }
 
+
+  void clearState(uint8_t state) {
+    forwardingState = forwardingState & ~state;
+  }
+  bool hasState(uint8_t state) {
+    return forwardingState & state;
+  }
+  void setState(uint8_t state) {
+    forwardingState = forwardingState | state;
+  }
+  
+  /******** Defaults. **************/
+   
   default event void
   Send.sendDone[uint8_t client](message_t *msg, error_t error) {
   }
@@ -941,64 +877,26 @@ implementation {
   default command collection_id_t CollectionId.fetch[uint8_t client]() {
     return 0;
   }
-
-  static void startRetxmitTimer(uint16_t mask, uint16_t offset) {
-    uint16_t r = call Random.rand16();
-    r &= mask;
-    r += offset;
-    call RetxmitTimer.startOneShot(r);
-    dbg("Forwarder", "Rexmit timer will fire in %hu ms\n", r);
-  }
-
-  static void startCongestionTimer(uint16_t mask, uint16_t offset) {
-    uint16_t r = call Random.rand16();
-    r &= mask;
-    r += offset;
-    call CongestionTimer.startOneShot(r);
-    dbg("Forwarder", "Congestion timer will fire in %hu ms\n", r);
-  }
-
-  /* signalled when this neighbor is evicted from the neighbor table */
-  event void LinkEstimator.evicted(am_addr_t neighbor) {
-  }
-
-
+  
   /* Default implementations for CollectionDebug calls.
    * These allow CollectionDebug not to be wired to anything if debugging
    * is not desired. */
-
-    default command error_t CollectionDebug.logEvent(uint8_t type) {
-        return SUCCESS;
-    }
-    default command error_t CollectionDebug.logEventSimple(uint8_t type, uint16_t arg) {
-        return SUCCESS;
-    }
-    default command error_t CollectionDebug.logEventDbg(uint8_t type, uint16_t arg1, uint16_t arg2, uint16_t arg3) {
-        return SUCCESS;
-    }
-    default command error_t CollectionDebug.logEventMsg(uint8_t type, uint16_t msg, am_addr_t origin, am_addr_t node) {
-        return SUCCESS;
-    }
-    default command error_t CollectionDebug.logEventRoute(uint8_t type, am_addr_t parent, uint8_t hopcount, uint16_t metric) {
-        return SUCCESS;
-    }
+  
+  default command error_t CollectionDebug.logEvent(uint8_t type) {
+    return SUCCESS;
+  }
+  default command error_t CollectionDebug.logEventSimple(uint8_t type, uint16_t arg) {
+    return SUCCESS;
+  }
+  default command error_t CollectionDebug.logEventDbg(uint8_t type, uint16_t arg1, uint16_t arg2, uint16_t arg3) {
+    return SUCCESS;
+  }
+  default command error_t CollectionDebug.logEventMsg(uint8_t type, uint16_t msg, am_addr_t origin, am_addr_t node) {
+    return SUCCESS;
+  }
+  default command error_t CollectionDebug.logEventRoute(uint8_t type, am_addr_t parent, uint8_t hopcount, uint16_t metric) {
+    return SUCCESS;
+  }
    
 }
 
-/* Rodrigo. This is an alternative
-  event void CtpInfo.ParentCongested(bool congested) {
-    if (congested) {
-      // We've overheard our parent's ECN bit set.
-      startCongestionTimer(CONGESTED_WAIT_WINDOW, CONGESTED_WAIT_OFFSET);
-      parentCongested = TRUE;
-      call CollectionDebug.logEvent(NET_C_FE_CONGESTION_BEGIN);
-    } else {
-      // We've overheard our parent's ECN bit cleared.
-      call CongestionTimer.stop();
-      parentCongested = FALSE;
-      call CollectionDebug.logEventSimple(NET_C_FE_CONGESTION_END, 1);
-      post sendTask();
-    }
-  }
-*/
-
index ad0687e267ed1badaaaae0341bb9bfcaffee684b..7e8654951f7779ada76a4aacfcf74eb841f7011d 100644 (file)
@@ -81,7 +81,7 @@ interface CtpInfo {
   command bool isNeighborCongested(am_addr_t n);
 
   command uint8_t numNeighbors();
-  command uint16_t getNeighborLinkQuality(uint8_t neighbor);
-  command uint16_t getNeighborRouteQuality(uint8_t neighbor);
-  command am_addr_t getNeighborAddr(uint8_t neighbor);
+  command uint16_t getNeighborLinkQuality(uint8_t n);
+  command uint16_t getNeighborRouteQuality(uint8_t n);
+  command am_addr_t getNeighborAddr(uint8_t n);
 }
index 79e6aeccb9aa45472decfd72523a812c16fc1124..af6e1566643990ea7b11352ba038887c9b178c4b 100644 (file)
@@ -157,9 +157,6 @@ implementation {
   components new TimerMilliC() as RetxmitTimer;
   Forwarder.RetxmitTimer -> RetxmitTimer;
 
-  components new TimerMilliC() as CongestionTimer;
-  Forwarder.CongestionTimer -> CongestionTimer;
-
   components RandomC;
   Router.Random -> RandomC;
   Forwarder.Random -> RandomC;
@@ -196,6 +193,8 @@ implementation {
 #endif
 #elif defined (PLATFORM_MICA2) || defined (PLATFORM_MICA2DOT)
   components CC1000ActiveMessageC as PlatformActiveMessageC;
+#elif defined(PLATFORM_EYESIFXV1) || defined(PLATFORM_EYESIFXV2)
+  components WhiteBitAccessorC as PlatformActiveMessageC;    
 #else
   components DummyActiveMessageP as PlatformActiveMessageC;
 #endif
index 342f2f53d52360a21c53579416adb7a65a0bf6d4..4657a00f20ccffc96657bcd4079e827f207a80b0 100644 (file)
@@ -151,13 +151,6 @@ implementation {
     uint32_t parentChanges;
     /* end statistics */
 
-    uint32_t routeUpdateTimerCount;
-
-    // Maximimum it takes to hear four beacons
-    enum {
-      DEATH_TEST_INTERVAL = (maxInterval * 4) / (BEACON_INTERVAL / 1024),
-    };
-    
     // forward declarations
     void routingTableInit();
     uint8_t routingTableFind(am_addr_t);
@@ -199,7 +192,6 @@ implementation {
 
     command error_t Init.init() {
         uint8_t maxLength;
-        routeUpdateTimerCount = 0;
         radioOn = FALSE;
         running = FALSE;
         parentChanges = 0;
@@ -250,16 +242,9 @@ implementation {
     /* Is this quality measure better than the minimum threshold? */
     // Implemented assuming quality is EETX
     bool passLinkEtxThreshold(uint16_t etx) {
-       return TRUE;
         return (etx < ETX_THRESHOLD);
     }
 
-    /* Converts the output of the link estimator to path metric
-     * units, that can be *added* to form path metric measures */
-    uint16_t evaluateEtx(uint16_t quality) {
-        //dbg("TreeRouting","%s %d -> %d\n",__FUNCTION__,quality, quality+10);
-        return (quality + 10);
-    }
 
     /* updates the routing information, using the info that has been received
      * from neighbor beacons. Two things can cause this info to change: 
@@ -294,11 +279,11 @@ implementation {
                   i, entry->neighbor, entry->info.parent);
               continue;
             }
-            /* Compute this neighbor's path metric */
-            linkEtx = evaluateEtx(call LinkEstimator.getLinkQuality(entry->neighbor));
+
+            linkEtx = call LinkEstimator.getLinkQuality(entry->neighbor);
             dbg("TreeRouting", 
-                "routingTable[%d]: neighbor: [id: %d parent: %d etx: %d]\n",  
-                i, entry->neighbor, entry->info.parent, linkEtx);
+                "routingTable[%d]: neighbor: [id: %d parent: %d etx: %d retx: %d]\n",  
+                i, entry->neighbor, entry->info.parent, linkEtx, entry->info.etx);
             pathEtx = linkEtx + entry->info.etx;
             /* Operations specific to the current parent */
             if (entry->neighbor == routeInfo.parent) {
@@ -321,6 +306,7 @@ implementation {
             }
             
             if (pathEtx < minEtx) {
+             dbg("TreeRouting", "   best is %d, setting to %d\n", pathEtx, entry->neighbor);
                 minEtx = pathEtx;
                 best = entry;
             }  
@@ -354,11 +340,15 @@ implementation {
                 call LinkEstimator.unpinNeighbor(routeInfo.parent);
                 call LinkEstimator.pinNeighbor(best->neighbor);
                 call LinkEstimator.clearDLQ(best->neighbor);
-                atomic {
+
+               atomic {
                     routeInfo.parent = best->neighbor;
                     routeInfo.etx = best->info.etx;
                     routeInfo.congested = best->info.congested;
                 }
+               if (currentEtx - minEtx > 20) {
+                 call CtpInfo.triggerRouteUpdate();
+               }
             }
         }    
 
@@ -403,8 +393,7 @@ implementation {
             beaconMsg->etx = routeInfo.etx;
             beaconMsg->options |= CTP_OPT_PULL;
         } else {
-            beaconMsg->etx = routeInfo.etx +
-                                evaluateEtx(call LinkEstimator.getLinkQuality(routeInfo.parent));
+            beaconMsg->etx = routeInfo.etx + call LinkEstimator.getLinkQuality(routeInfo.parent);
         }
 
         dbg("TreeRouting", "%s parent: %d etx: %d\n",
@@ -547,8 +536,7 @@ implementation {
        if (state_is_root == 1) {
          *etx = 0;
        } else {
-         // path etx = etx(parent) + etx(link to the parent)
-         *etx = routeInfo.etx + evaluateEtx(call LinkEstimator.getLinkQuality(routeInfo.parent));
+         *etx = routeInfo.etx + call LinkEstimator.getLinkQuality(routeInfo.parent);
        }
         return SUCCESS;
     }
@@ -631,26 +619,20 @@ implementation {
     }
 
 
-  /* This should see if the node should be inserted in the table.
-   * If the white_bit is set, this means the LL believes this is a good
-   * first hop link. 
-   * The link will be recommended for insertion if it is better* than some
+  /* The link will be recommended for insertion if it is better* than some
    * link in the routing table that is not our parent.
    * We are comparing the path quality up to the node, and ignoring the link
    * quality from us to the node. This is because of a couple of things:
-   *   1. because of the white bit, we assume that the 1-hop to the candidate
-   *      link is good (say, etx=1)
+   *   1. we expect this call only for links with white bit set
    *   2. we are being optimistic to the nodes in the table, by ignoring the
    *      1-hop quality to them (which means we are assuming it's 1 as well)
    *      This actually sets the bar a little higher for replacement
    *   3. this is faster
-   *   4. it doesn't require the link estimator to have stabilized on a link
    */
-    event bool CompareBit.shouldInsert(message_t *msg, void* payload, uint8_t len, bool white_bit) {
+    event bool CompareBit.shouldInsert(message_t *msg, void* payload, uint8_t len) {
         
         bool found = FALSE;
         uint16_t pathEtx;
-        //uint16_t linkEtx = evaluateEtx(0);
         uint16_t neighEtx;
         int i;
         routing_table_entry* entry;
@@ -679,7 +661,6 @@ implementation {
             if (entry->neighbor == routeInfo.parent)
                 continue;
             neighEtx = entry->info.etx;
-            //neighEtx = evaluateEtx(call LinkEstimator.getLinkQuality(entry->neighbor));
             found |= (pathEtx < neighEtx); 
         }
         return found;
@@ -718,7 +699,7 @@ implementation {
     error_t routingTableUpdateEntry(am_addr_t from, am_addr_t parent, uint16_t etx)    {
         uint8_t idx;
         uint16_t  linkEtx;
-        linkEtx = evaluateEtx(call LinkEstimator.getLinkQuality(from));
+        linkEtx = call LinkEstimator.getLinkQuality(from);
 
         idx = routingTableFind(from);
         if (idx == routingTableSize) {
@@ -818,7 +799,7 @@ implementation {
     command uint16_t      CtpRoutingPacket.getEtx(message_t* msg) {
       return getHeader(msg)->etx;
     }
-    command void          CtpRoutingPacket.setEtx(message_t* msg, uint8_t etx) {
+    command void          CtpRoutingPacket.setEtx(message_t* msg, uint16_t etx) {
       getHeader(msg)->etx = etx;
     }
 
index fb5ec31dd205921139e698c6a9efafd5e1cac275..00153e61f8442886af5c798032036cae23835705 100644 (file)
@@ -54,5 +54,5 @@ interface CtpRoutingPacket {
   command void          setParent(message_t* ONE msg, am_addr_t addr);
 
   command uint16_t      getEtx(message_t* ONE msg);
-  command void          setEtx(message_t* ONE msg, uint8_t etx);
+  command void          setEtx(message_t* ONE msg, uint16_t etx);
 }
diff --git a/tos/lib/net/dhv/AMDhvC.nc b/tos/lib/net/dhv/AMDhvC.nc
new file mode 100755 (executable)
index 0000000..ffa47b1
--- /dev/null
@@ -0,0 +1,46 @@
+/**
+ * Active Message Configuration.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Took the source code from Dip
+ **/
+
+#include <Dhv.h>
+
+configuration AMDhvC {
+  provides interface DhvSend;
+  provides interface DhvReceive as DataReceive;
+  provides interface DhvReceive as VectorReceive;
+  provides interface DhvReceive as SummaryReceive;
+  provides interface DhvReceive as DhvVBitReceive;
+  provides interface DhvReceive as DhvHSumReceive;
+}
+
+implementation {
+  components AMDhvP;
+  components new AMSenderC(AM_DHV) as SendC;
+  components new AMReceiverC(AM_DHV) as ReceiveC;
+
+  AMDhvP.NetAMSend -> SendC.AMSend;
+  AMDhvP.NetReceive -> ReceiveC.Receive;
+
+  components MainC;
+  MainC.SoftwareInit -> AMDhvP.Init;
+  AMDhvP.Boot -> MainC;
+
+  components ActiveMessageC;
+  AMDhvP.AMSplitControl -> ActiveMessageC;
+
+  DhvSend = AMDhvP.DhvSend;
+  DataReceive = AMDhvP.DhvDataReceive;
+  VectorReceive = AMDhvP.DhvVectorReceive;
+  SummaryReceive = AMDhvP.DhvSummaryReceive;
+  DhvVBitReceive = AMDhvP.DhvVBitReceive;
+  DhvHSumReceive = AMDhvP.DhvHSumReceive;
+
+}
diff --git a/tos/lib/net/dhv/AMDhvP.nc b/tos/lib/net/dhv/AMDhvP.nc
new file mode 100755 (executable)
index 0000000..22d275d
--- /dev/null
@@ -0,0 +1,158 @@
+/**
+ * Active Message Implementation.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV interfaces type and renamed the instances to distinguish from DIP.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+module AMDhvP {
+  provides interface Init;
+  provides interface DhvSend;
+  provides interface DhvReceive as DhvDataReceive;
+  provides interface DhvReceive as DhvVectorReceive;
+  provides interface DhvReceive as DhvSummaryReceive;
+  provides interface DhvReceive as DhvHSumReceive;
+  provides interface DhvReceive as DhvVBitReceive;
+
+  uses interface AMSend as NetAMSend;
+  uses interface Receive as NetReceive;
+  uses interface SplitControl as AMSplitControl;
+  uses interface Boot;
+}
+
+implementation {
+  message_t am_msg;
+  uint32_t send_count;
+  bool busy;
+
+  event void Boot.booted() {
+    send_count = 0;
+    call AMSplitControl.start();
+  }
+
+  event void AMSplitControl.startDone(error_t err) {
+    if(err != SUCCESS) {
+      call AMSplitControl.start();
+      return;
+    }
+    dbg("AMDhvP", "ActiveMessageC started!\n");
+  }
+
+  event void AMSplitControl.stopDone(error_t err) { }
+
+  command error_t Init.init() {
+    busy = FALSE;
+    return SUCCESS;
+  }
+
+  command error_t DhvSend.send(uint8_t len) {
+    error_t err;
+    dhv_msg_t* dmsg;
+    uint8_t type;
+
+    dmsg = (dhv_msg_t *) (&am_msg)->data;
+    type = dmsg->type;
+
+    send_count = send_count + 1;
+
+    switch(type){
+      case ID_DHV_SUMMARY: 
+        dbg("AMDhvP", "Sending SUMMARY : length %d  count %d at %s \n", len, send_count, sim_time_string());
+        break;
+      case ID_DHV_VBIT: 
+        dbg("AMDhvP", "Sending VBIT : length %d  count %d at %s \n", len, send_count, sim_time_string());
+        break;
+      case ID_DHV_HSUM: 
+        dbg("AMDhvP", "Sending HSUM : length %d  count %d at %s \n", len, send_count, sim_time_string());
+        break;
+      case ID_DHV_VECTOR: 
+        dbg("AMDhvP", "Sending VECTOR : length %d  count %d at %s \n", len, send_count, sim_time_string());
+        break;
+      case ID_DHV_VECTOR_REQ: 
+        dbg("AMDhvP", "Sending VECTOR_REQ : length %d  count %d at %s \n", len, send_count, sim_time_string());
+        break;
+      case ID_DHV_DATA: 
+        dbg("AMDhvP", "Sending DATA : length %d  count %d at %s \n", len, send_count, sim_time_string());
+        break;
+      default : 
+        dbg("AMDhvP", "Sending UNKNOWN : length %d  count %d at %s \n", len, send_count, sim_time_string());
+        break;
+    }
+    err = call NetAMSend.send(AM_BROADCAST_ADDR, &am_msg, len);
+
+    if(err == SUCCESS) {
+      busy = TRUE;
+    }else{
+      dbg("AMDhvP", "Send failed \n");
+    }
+
+    return err;
+  }
+
+  command void* DhvSend.getPayloadPtr() {
+    // returns NULL if message is busy
+    if(busy) {
+      return NULL;
+    }
+    return call NetAMSend.getPayload(&am_msg, 0);
+  }
+
+  command uint8_t DhvSend.maxPayloadLength() {
+    return call NetAMSend.maxPayloadLength();
+  }
+
+  event void NetAMSend.sendDone(message_t* msg, error_t err) {
+    //dbg("AMDhvP", "Data send successfully in the air\n");
+    if(msg == &am_msg) {
+      busy = FALSE;
+    }
+  }
+
+  event message_t* NetReceive.receive(message_t* msg, void* payload,
+      uint8_t len) {
+    dhv_msg_t* dmsg;
+    uint8_t type;
+
+    dmsg = (dhv_msg_t*) payload;
+    type = dmsg->type;
+    switch(type) {
+      case ID_DHV_DATA:
+
+        dbg("AMDhvPReceive", "Receive DATA : length %d at %s  \n",len,  sim_time_string() );
+        signal DhvDataReceive.receive(dmsg->content, len);
+        break;
+      case ID_DHV_VECTOR:
+
+        dbg("AMDhvPReceive", "Receive VECTOR : length %d at %s \n",len,  sim_time_string() );
+        signal DhvVectorReceive.receive(dmsg, len);
+        break;
+      case ID_DHV_SUMMARY:
+
+        dbg("AMDhvPReceive", "Receive SUMMARY : length %d at %s \n", len, sim_time_string() );
+        signal DhvSummaryReceive.receive(dmsg->content, len);
+        break;
+      case ID_DHV_HSUM:
+        dbg("AMDhvPReceive", "Receive HSUM length %d at %s \n", len, sim_time_string());
+        signal DhvHSumReceive.receive(dmsg->content, len);
+        break;  
+      case ID_DHV_VBIT:
+
+        dbg("AMDhvPReceive", "Receive VBIT : length %d at %s \n", len, sim_time_string());
+        signal DhvVBitReceive.receive(dmsg->content, len);
+        break;
+
+      case ID_DHV_VECTOR_REQ:
+
+        dbg("AMDhvPReceive", "Receive VECTOR_REQ : length %d at %s \n", len, sim_time_string());
+        signal DhvVectorReceive.receive(dmsg, len);
+        break;
+    }
+    return msg;
+  }
+}
diff --git a/tos/lib/net/dhv/Dhv.h b/tos/lib/net/dhv/Dhv.h
new file mode 100755 (executable)
index 0000000..f6ad31d
--- /dev/null
@@ -0,0 +1,123 @@
+/**
+ * DHV header file.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV packet type and renamed the variable
+ * @modified 8/28/2008  Take the source code from Dip
+ **/
+
+
+#ifndef __DHV_H__
+#define __DHV_H__
+
+#define DHV_TAU_LOW (1024L)
+#define DHV_TAU_HIGH (65535L)
+
+#define UQ_DHV unique("DHV")
+#define UQCOUNT_DHV uniqueCount("DHV")
+
+#define DHV_UNKNOWN_VERSION 0xFFFFFFFF
+#define DHV_UNKNOWN_INDEX 0xFFFF
+#define DHV_VERSION_LENGTH 4
+
+#define VBIT_LENGTH 8
+
+enum {
+  AM_DHV_TEST_MSG = 0xAB
+};
+
+
+typedef enum {
+  ID_DHV_INVALID = 0x0,
+  ID_DHV_SUMMARY = 0x1,
+  ID_DHV_VECTOR = 0x2,
+  ID_DHV_DATA = 0x3,
+  ID_DHV_HSUM = 0x4,
+  ID_DHV_VBIT = 0x5,
+  ID_DHV_VECTOR_REQ = 0x6
+} dhv_msgid_t;
+
+//status indicator : no action, ads, request
+enum{
+  ID_DHV_NO  = 0x0,
+  ID_DHV_ADS = 0x1,
+  ID_DHV_REQ = 0x2
+};
+
+enum {
+  AM_DHV = 0x63,
+  AM_DHV_DATA_MSG = 0x63, // For MIG tool
+  AM_DHV_MSG = 0x63, // For MIG tool
+  AM_DHV_DATA = 0x63 // For MIG tool
+};
+
+typedef uint16_t dhv_key_t;
+typedef uint16_t dhv_index_t;
+typedef nx_uint16_t nx_dhv_key_t;
+typedef uint32_t dhv_version_t;
+typedef nx_uint32_t nx_dhv_version_t;
+typedef uint8_t dhv_estimate_t;
+typedef dhv_index_t dhv_hashlen_t;
+
+typedef nx_struct dhv_msg {
+  nx_uint8_t type; 
+  nx_uint8_t content[0];
+} dhv_msg_t;
+
+typedef nx_struct dhv_data_msg {
+  nx_dhv_key_t key;
+  nx_dhv_version_t version;
+  nx_uint8_t size;
+  nx_uint8_t data[0];
+} dhv_data_msg_t;
+
+typedef nx_struct dhv_vector_msg {
+  nx_uint8_t unitLen;
+  nx_uint32_t vector[0];
+} dhv_vector_msg_t;
+
+typedef nx_struct dhv_summary_msg {
+  //nx_uint8_t unitLen;
+  nx_uint32_t salt;
+  nx_uint32_t info;
+} dhv_summary_msg_t;
+
+typedef nx_struct dhv_hsum_msg{
+  nx_uint32_t salt;
+  nx_uint32_t info;
+  nx_uint32_t checksum;
+} dhv_hsum_msg_t;
+
+typedef nx_struct dhv_vbit_msg{
+  nx_uint8_t numKey;
+  nx_uint8_t bindex;
+  nx_uint8_t vindex;
+  nx_uint32_t salt;
+  nx_uint32_t info; //include hash into vbit message
+  nx_uint8_t vbit[0];
+}dhv_vbit_msg_t;
+
+typedef nx_struct dhv_data {
+  nx_uint8_t data[16];
+} dhv_data_t;
+
+
+typedef nx_struct dhv_test_msg {
+  nx_uint16_t id;
+  nx_uint8_t count;
+  nx_uint8_t isOk;
+} dhv_test_msg_t;
+
+
+/* TUNABLE PARAMETERS */
+#define DHV_SUMMARY_VALUES_PER_PACKET 2
+#define DHV_VECTOR_VALUES_PER_PACKET 2
+
+#define DHV_SUMMARY_ENTRIES_PER_PACKET (DHV_SUMMARY_VALUES_PER_PACKET * 3)
+#define DHV_VECTOR_ENTRIES_PER_PACKET (DHV_VECTOR_VALUES_PER_PACKET * 2)
+#endif
diff --git a/tos/lib/net/dhv/DhvDataC.nc b/tos/lib/net/dhv/DhvDataC.nc
new file mode 100755 (executable)
index 0000000..6b0d15b
--- /dev/null
@@ -0,0 +1,44 @@
+/**
+* DHV header file.
+*
+* Define the interfaces and components.
+*
+* @author Thanh Dang
+* @author Seungweon Park
+*
+* @modified 1/3/2009   Added meaningful documentation.
+* @modified 8/28/2008  Defined DHV packet type and renamed the variable
+* @modified 8/28/2008  Take the source code from Dip
+**/
+
+
+
+configuration DhvDataC {
+  provides interface DhvDecision;
+
+  uses interface DhvSend as DataSend;
+  uses interface DhvReceive as DataReceive;
+
+  uses interface DisseminationUpdate<dhv_data_t>[dhv_key_t key];
+  uses interface DisseminationValue<dhv_data_t>[dhv_key_t key];
+       
+       uses interface DhvLogic as DataLogic;
+       uses interface DhvLogic as VectorLogic;
+
+  uses interface DhvHelp;
+}
+
+implementation {
+  components DhvDataP;
+  DhvDecision = DhvDataP;
+  DataSend = DhvDataP;
+  DataReceive = DhvDataP;
+  DisseminationUpdate = DhvDataP;
+  DisseminationValue = DhvDataP;
+  DhvHelp = DhvDataP;
+  DataLogic = DhvDataP.DataLogic;
+       VectorLogic = DhvDataP.VectorLogic;
+
+  components LedsC;
+  DhvDataP.Leds -> LedsC;
+}
diff --git a/tos/lib/net/dhv/DhvDataP.nc b/tos/lib/net/dhv/DhvDataP.nc
new file mode 100755 (executable)
index 0000000..b1259db
--- /dev/null
@@ -0,0 +1,127 @@
+/**
+ * DHV DATA Implementation.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV interfaces type.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+
+#include <Dhv.h>
+
+module DhvDataP {
+  provides interface DhvDecision;
+
+  uses interface DhvSend as DataSend;
+  uses interface DhvReceive as DataReceive;
+
+  uses interface DisseminationUpdate<dhv_data_t>[dhv_key_t key];
+  uses interface DisseminationValue<dhv_data_t>[dhv_key_t key];
+  uses interface DhvLogic as DataLogic;
+  uses interface DhvLogic as VectorLogic;
+
+  uses interface DhvHelp;
+  uses interface Leds;
+}
+
+implementation {
+  uint8_t commRate = 0;
+
+  command uint8_t DhvDecision.getCommRate() {
+    return commRate;
+  }
+
+  command void DhvDecision.resetCommRate() {
+    commRate = 0;
+  }
+
+  command error_t DhvDecision.send() {
+    dhv_key_t key;
+    uint8_t i;
+    dhv_version_t ver;
+    dhv_msg_t* dmsg;
+    dhv_data_msg_t* ddmsg;
+    const dhv_data_t* data;
+    error_t status;
+
+    status = FAIL;
+    //get the associated key of the data needed to send
+    i = call DataLogic.nextItem();
+    if(i == UQCOUNT_DHV){
+      return FAIL;
+    }
+    key = call DhvHelp.indexToKey(i);
+    ver = call DhvHelp.keyToVersion(key);
+    data = call DisseminationValue.get[key]();
+    dmsg = (dhv_msg_t*) call DataSend.getPayloadPtr();
+    if(dmsg == NULL) {
+      return FAIL;
+    }
+    ddmsg = (dhv_data_msg_t*) dmsg->content;
+    dmsg->type = ID_DHV_DATA;
+    ddmsg->key = key;
+    ddmsg->version = ver;
+    ddmsg->size = sizeof(dhv_data_t);
+    memcpy(ddmsg->data, data, sizeof(dhv_data_t));
+
+    dbg("DhvDataP", "Data sent with index %d key %x and version %08x\n",i, key, ver);
+    status = call DataSend.send(sizeof(dhv_data_msg_t) + sizeof(dhv_msg_t) + sizeof(dhv_data_t));
+    if(status == SUCCESS){
+      call DataLogic.unsetItem(key);
+    }
+
+    return status;
+  }
+
+  event void DataReceive.receive(void* payload, uint8_t len) {
+    dhv_key_t key;
+    dhv_version_t myVer;
+    dhv_version_t msgVer;
+    dhv_data_msg_t* ddmsg;
+
+    commRate = commRate + 1;
+    ddmsg = (dhv_data_msg_t*) payload;
+    key = ddmsg->key;
+    msgVer = ddmsg->version;
+    myVer = call DhvHelp.keyToVersion(key);
+    dbg("DhvDataP", "Data rcved with key %x and version %08x\n", key, msgVer);
+
+    // TODO: handle the invalid versions
+    if(myVer < msgVer) {
+      dbg("DhvDataP", "new version\n");
+      call DisseminationUpdate.change[key]((dhv_data_t*)ddmsg->data);
+      call DhvHelp.setVersion(key, msgVer);
+      call DataLogic.setItem(key);
+      call VectorLogic.setItem(key);
+      //set bindex to 0
+    }
+    else if (myVer > msgVer) {
+      dbg("DhvDataP", "Old version\n");
+      //report older key to dhvlogic to set data item to send
+      //reset timer
+      call DataLogic.setItem(key);
+      call VectorLogic.setItem(key);
+
+    }
+    else {
+      dbg("DhvDataP", "Same version\n");
+      //keep quite
+      call DataLogic.unsetItem(key);
+      call VectorLogic.unsetItem(key);
+      //set bindex to 0
+    }
+  }
+
+  event void DisseminationValue.changed[dhv_key_t key]() {  }
+
+  default command const dhv_data_t* DisseminationValue.get[dhv_key_t key]() {
+    return NULL;
+  }
+
+  default command void DisseminationUpdate.change[dhv_key_t key](dhv_data_t* val) { }
+
+}
diff --git a/tos/lib/net/dhv/DhvHSumC.nc b/tos/lib/net/dhv/DhvHSumC.nc
new file mode 100755 (executable)
index 0000000..6b98086
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+ * DHV Horizontal Summary Implementation.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV interfaces type.
+ **/
+
+configuration DhvHSumC{
+  provides interface DhvDecision;
+
+  uses interface DhvSend as HSumSend;
+  uses interface DhvReceive as HSumReceive;
+  uses interface DhvStateLogic as VBitLogic;
+  uses interface DhvHelp;
+}
+
+implementation{        
+  components DhvHSumP, RandomC;
+  DhvDecision          = DhvHSumP;
+  HSumSend             = DhvHSumP;
+  HSumReceive          = DhvHSumP;
+  VBitLogic            = DhvHSumP;
+  DhvHelp              = DhvHSumP;
+  DhvHSumP.Random      -> RandomC;
+}
diff --git a/tos/lib/net/dhv/DhvHSumP.nc b/tos/lib/net/dhv/DhvHSumP.nc
new file mode 100755 (executable)
index 0000000..e550f61
--- /dev/null
@@ -0,0 +1,89 @@
+/**
+ * DHV Horizontal Summary Implementation.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV interfaces type.
+ **/
+
+#include<Dhv.h>
+
+module DhvHSumP{
+  provides interface DhvDecision;
+
+  uses interface DhvSend as HSumSend;
+  uses interface DhvReceive as HSumReceive;
+  uses interface DhvStateLogic as VBitLogic;
+  uses interface DhvHelp;
+  uses interface Random;       
+}
+
+implementation{
+  uint8_t commRate;
+
+  command uint8_t DhvDecision.getCommRate(){
+    return commRate;
+  }
+  command void DhvDecision.resetCommRate(){
+    commRate = 0;
+  }
+  command error_t DhvDecision.send(){
+    dhv_hsum_msg_t* dhsmsg;
+    dhv_msg_t*                         dmsg;
+    uint32_t  salt;
+    error_t sendResult;
+
+    dmsg = call HSumSend.getPayloadPtr();
+    if(dmsg == NULL)
+        return FAIL;
+
+    dmsg->type = ID_DHV_HSUM;
+    dhsmsg = (dhv_hsum_msg_t*) dmsg->content;
+
+    //add the hash value
+    salt = call Random.rand32();
+    dhsmsg->info = call DhvHelp.computeHash(0, UQCOUNT_DHV, salt);
+    dhsmsg->salt = salt;
+    dhsmsg->checksum = call DhvHelp.getHSum();
+
+    sendResult = call HSumSend.send(sizeof(dhv_msg_t) + sizeof(dhv_hsum_msg_t));
+    if(sendResult == SUCCESS){
+      call VBitLogic.unsetHSumStatus();
+    }
+    return sendResult;
+  }    
+
+  event void HSumReceive.receive(void* payload, uint8_t len){
+    dhv_hsum_msg_t * rcv_dhmsg;
+    int32_t local_checksum;
+    int32_t rcv_checksum;
+    int32_t xor_checksum;
+    int32_t salt;
+    int32_t rcv_hash;
+    int32_t local_hash;
+
+    rcv_dhmsg = (dhv_hsum_msg_t*) payload;
+
+    rcv_checksum = rcv_dhmsg->checksum;
+    local_checksum = call DhvHelp.getHSum();
+    xor_checksum = rcv_checksum^local_checksum;
+    dbg("DhvHSumP", " xor_checksum 0x%08x  0x%08x  0x%08x \n",rcv_checksum, local_checksum, xor_checksum);
+    if(xor_checksum == 0){
+      //check for the hash
+      rcv_hash = rcv_dhmsg->info;
+      salt = rcv_dhmsg->salt;
+      local_hash = call DhvHelp.computeHash(0, UQCOUNT_DHV, salt);
+      if(rcv_hash == local_hash) {
+        call VBitLogic.setSameSummary();
+      }else{
+        call VBitLogic.setVBitState(1);
+      }
+    }else{
+      dbg("DhvHSumP"," detect a difference in checksum \n" );
+      call VBitLogic.setVBitState(xor_checksum);
+    }
+  }
+}
diff --git a/tos/lib/net/dhv/DhvLogicC.nc b/tos/lib/net/dhv/DhvLogicC.nc
new file mode 100755 (executable)
index 0000000..b349bdf
--- /dev/null
@@ -0,0 +1,84 @@
+/**
+ * DHV Logic Implementation.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV interfaces type.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+#include <Dhv.h>
+
+configuration DhvLogicC {
+  provides interface DisseminationUpdate<dhv_data_t>[dhv_key_t key];
+       provides interface DhvLogic as DataLogic;
+       provides interface DhvLogic as VectorLogic;
+       provides interface DhvStateLogic;
+  provides interface StdControl;
+}
+
+implementation {
+  components DhvLogicP;
+  DisseminationUpdate = DhvLogicP;
+  StdControl = DhvLogicP;
+  DataLogic  = DhvLogicP.DataLogic;
+       VectorLogic= DhvLogicP.VectorLogic;
+       DhvStateLogic = DhvLogicP;
+
+  components MainC;
+  MainC.SoftwareInit -> DhvLogicP;
+  DhvLogicP.Boot -> MainC;
+
+  components DhvTrickleMilliC;
+  DhvLogicP.DhvTrickleTimer -> DhvTrickleMilliC;
+
+  components DhvVersionC;
+  DhvLogicP.VersionUpdate -> DhvVersionC;
+  DhvLogicP.DhvHelp -> DhvVersionC;
+       DhvLogicP.DhvDataCache -> DhvVersionC.DataCache;
+       DhvLogicP.DhvVectorCache -> DhvVersionC.VectorCache;
+
+  components AMDhvC;
+
+  components DhvDataC;
+  DhvLogicP.DhvDataDecision -> DhvDataC;
+  DhvDataC.DataSend -> AMDhvC.DhvSend;
+  DhvDataC.DataReceive -> AMDhvC.DataReceive;
+  DhvDataC.DhvHelp -> DhvVersionC;
+  DhvDataC.DataLogic -> DhvLogicP.DataLogic;
+  DhvDataC.VectorLogic -> DhvLogicP.VectorLogic;       
+
+  components DhvVectorC;
+  DhvLogicP.DhvVectorDecision -> DhvVectorC;
+  DhvVectorC.VectorSend -> AMDhvC.DhvSend;
+  DhvVectorC.VectorReceive -> AMDhvC.VectorReceive;
+  DhvVectorC.DhvHelp -> DhvVersionC;
+       DhvVectorC.VectorLogic -> DhvLogicP.VectorLogic;
+       DhvVectorC.DataLogic -> DhvLogicP.DataLogic;
+
+  components DhvSummaryC;
+  DhvLogicP.DhvSummaryDecision -> DhvSummaryC;
+  DhvSummaryC.SummarySend -> AMDhvC.DhvSend;
+  DhvSummaryC.SummaryReceive -> AMDhvC.SummaryReceive;
+  DhvSummaryC.DhvHelp -> DhvVersionC;
+       DhvSummaryC.StateLogic -> DhvLogicP.DhvStateLogic;
+
+       components DhvVBitC;
+       DhvLogicP.DhvVBitDecision -> DhvVBitC;
+       DhvVBitC.VBitSend -> AMDhvC.DhvSend;
+       DhvVBitC.VBitReceive -> AMDhvC.DhvVBitReceive;
+       DhvVBitC.DhvHelp -> DhvVersionC;
+       DhvVBitC.VectorLogic -> DhvLogicP.VectorLogic;
+       DhvVBitC.VBitLogic  -> DhvLogicP.DhvStateLogic;
+
+  components DhvHSumC;
+  DhvHSumC.VBitLogic -> DhvLogicP.DhvStateLogic;
+  DhvHSumC.DhvHelp    -> DhvVersionC;
+  DhvHSumC.HSumSend   -> AMDhvC.DhvSend;
+  DhvHSumC.HSumReceive-> AMDhvC.DhvHSumReceive;
+  DhvLogicP.DhvHSumDecision -> DhvHSumC;
+}
diff --git a/tos/lib/net/dhv/DhvLogicP.nc b/tos/lib/net/dhv/DhvLogicP.nc
new file mode 100755 (executable)
index 0000000..de9d3ca
--- /dev/null
@@ -0,0 +1,402 @@
+/**
+ * DHV Logic Implementation.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV interfaces type.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+#include <Dhv.h>
+
+module DhvLogicP {
+  provides interface DisseminationUpdate<dhv_data_t>[dhv_key_t key];
+
+  provides interface Init;
+  provides interface StdControl;
+       provides interface DhvLogic as VectorLogic;
+       provides interface DhvLogic as DataLogic;
+  provides interface DhvStateLogic;    
+
+  uses interface Boot;
+  uses interface DhvTrickleTimer;
+  uses interface DisseminationUpdate<dhv_data_t> as VersionUpdate[dhv_key_t key];
+
+  uses interface DhvDecision as DhvDataDecision;
+  uses interface DhvDecision as DhvVectorDecision;
+  uses interface DhvDecision as DhvSummaryDecision;
+       uses interface DhvDecision as DhvVBitDecision;
+  uses interface DhvDecision as DhvHSumDecision;
+
+       uses interface DhvCache as DhvDataCache;
+       uses interface DhvCache as DhvVectorCache;
+  uses interface DhvHelp;
+
+}
+
+implementation {
+  uint32_t windowSize;
+  uint8_t sendDecision();
+       uint8_t getState();
+  uint32_t bitIndex;
+  uint8_t hsum_status;
+       uint32_t diffHash;
+
+  command error_t Init.init() {
+    windowSize = DHV_TAU_LOW;
+    dbg("DhvLogicP","DHV ready\n");
+    return SUCCESS;
+  }
+
+  event void Boot.booted() {
+               hsum_status = 0;
+    bitIndex = 0;
+  }
+
+  command error_t StdControl.start() {
+    return call DhvTrickleTimer.start();
+  }
+
+  command error_t StdControl.stop() {
+    call DhvTrickleTimer.stop();
+    return SUCCESS;
+  }
+
+
+       /*Logic operation on the vector */      
+       command error_t VectorLogic.setItem(dhv_key_t key){
+               call DhvVectorCache.addItem(key);
+               call DhvTrickleTimer.reset();
+               return SUCCESS;
+       }
+
+       command error_t VectorLogic.setReqItem(dhv_key_t key){
+               call DhvVectorCache.addReqItem(key);
+               call DhvTrickleTimer.reset();
+               return SUCCESS;
+       }
+
+       command error_t VectorLogic.unsetItem(dhv_key_t key){
+               call DhvVectorCache.removeItem(key);
+               call DhvStateLogic.setVBitState(0);
+               return SUCCESS;
+       }
+
+       command uint8_t * VectorLogic.allItem(){
+               return call DhvVectorCache.allItem();
+       }
+
+       command uint8_t VectorLogic.nextItem(){
+               return call DhvVectorCache.nextItem();
+       }
+
+       /*logic operations on the data*/
+       command error_t DataLogic.setItem(dhv_key_t key){
+               call DhvDataCache.addItem( key);
+               call DhvTrickleTimer.reset();
+               return SUCCESS;
+       }
+
+       command error_t DataLogic.setReqItem(dhv_key_t key){
+               call DhvDataCache.addReqItem( key);
+               call DhvTrickleTimer.reset();
+               return SUCCESS;
+       }
+
+       command error_t  DataLogic.unsetItem(dhv_key_t key){
+               call DhvDataCache.removeItem(key);
+               call DhvStateLogic.setVBitState(0);
+               return SUCCESS;
+       }
+
+       command uint8_t* DataLogic.allItem(){
+               return call DhvDataCache.allItem();
+       }
+
+       command uint8_t DataLogic.nextItem(){
+               return call DhvDataCache.nextItem();
+       }
+
+  /*logic operation for the summary and vbit*/
+  command void DhvStateLogic.setHSumStatus(){
+               hsum_status = 1;
+         call  DhvTrickleTimer.reset();
+  }
+  
+  command void DhvStateLogic.unsetHSumStatus(){
+               hsum_status = 0;
+  }
+
+  command uint8_t DhvStateLogic.getHSumStatus(){
+               return hsum_status;
+       }
+
+       command void DhvStateLogic.setDiffSummary(){
+               if(bitIndex == 0){
+                       bitIndex=1;
+               }
+
+         call  DhvTrickleTimer.reset();
+       }
+
+       command void DhvStateLogic.setSameSummary(){
+               bitIndex = 0;
+               hsum_status = 0;
+        //reset all the vector and data status to avoid flooding
+        call DhvDataCache.removeAll();
+        call DhvVectorCache.removeAll();
+       
+       }       
+
+       command void DhvStateLogic.setVBitState(uint32_t state){
+               bitIndex = state;
+    if(state != 0){
+                 call  DhvTrickleTimer.reset();
+               }
+       }
+
+       command uint32_t DhvStateLogic.getVBitState(){
+               return bitIndex;
+       }
+
+ //unset one bit at index location
+ command void DhvStateLogic.unsetVBitIndex(uint8_t dindex){
+    uint32_t mask;
+               mask = 1;
+
+    mask = mask << (dindex-1);
+         dbg("TempDebug", "TempDebug: Before mask dindex bitIndex %d %d %d\n", mask, dindex, bitIndex);
+               if((bitIndex & mask) != 0){
+                       bitIndex = bitIndex^mask;
+               }
+         dbg("TempDebug", "TempDebug: After bitIndex %d\n", bitIndex); 
+ }
+
+ command void DhvStateLogic.setVBitIndex(uint8_t dindex){
+    uint32_t mask;
+               mask = 1;
+    mask = mask << (dindex-1);
+         
+               bitIndex = bitIndex | mask;
+   
+         call  DhvTrickleTimer.reset();
+}
+
+//get the non-zero bit index to extract the vertical bits.
+command uint8_t DhvStateLogic.getVBitIndex(){
+
+  uint32_t mask;
+  uint8_t i;
+  uint32_t xor;
+
+       if(bitIndex == 0){
+               return 0;
+       }else
+       {
+               mask = 1;
+               for(i = 1; i <= 32; i++){
+                       xor = bitIndex & mask;
+                       
+      dbg("TempDebug", "TempDebug: %d  %d  %d  %d \n", i, bitIndex, mask, xor);
+                       if(xor != 0){
+                               return i;
+                       }
+                       mask = mask << 1;                       
+               }
+               return 0;
+       }
+}
+
+
+
+  command void DisseminationUpdate.change[dhv_key_t key](dhv_data_t* val) {
+
+    dbg("DhvLogicP","App notified key %x is new\n", key);
+               
+               //update data: actual reprogramming job
+    call VersionUpdate.change[key](val);
+
+    //set data
+               call DhvDataCache.addItem(key);
+
+               //set to advertise its version
+               call DhvVectorCache.addItem(key);
+
+               //reset bindex
+               call DhvStateLogic.setVBitState(0);     
+
+               dbg("DhvLogicP","Reset bindex to 0\n");
+               //reset timer             
+    call DhvTrickleTimer.reset();
+  }
+
+  event uint32_t DhvTrickleTimer.requestWindowSize() {
+    //TODO: consider if this is neccessary
+               uint8_t decision;
+
+               decision =  sendDecision();
+
+   if(decision == ID_DHV_SUMMARY){
+                               windowSize = windowSize << 1;
+                               if(windowSize > DHV_TAU_HIGH){
+                                       windowSize = DHV_TAU_HIGH;
+                               }
+               }else{
+                        if(decision != ID_DHV_INVALID){
+                                        windowSize = DHV_TAU_LOW;
+                               }
+               }
+
+               /*if(decision == ID_DHV_DATA){
+                       windowSize = DHV_TAU_LOW;
+               }else{
+                       if(decision == ID_DHV_VBIT){
+                               windowSize = DHV_TAU_LOW;
+                       }else{
+                               windowSize = windowSize << 1;
+                               if(windowSize > DHV_TAU_HIGH){
+                                       windowSize = DHV_TAU_HIGH;
+                               }
+                       }
+               }
+               */
+    dbg("DhvLogicP", "Time window size requested, give %u : send decision %d \n", windowSize, decision);
+    return windowSize;
+  }
+
+  event void DhvTrickleTimer.fired() {
+    uint8_t decision;
+
+    dbg("DhvLogicP","Trickle Timer fired!\n");
+
+    decision = sendDecision();
+
+    switch(decision) {
+    case ID_DHV_INVALID:
+      dbg("DhvLogicP", "Decision to SUPPRESS\n");
+      break;
+    case ID_DHV_SUMMARY:
+      dbg("DhvLogicP", "Decision to SUMMARY\n");
+      call DhvSummaryDecision.send();
+      break;
+    case ID_DHV_VECTOR:
+      dbg("DhvLogicP", "Decision to VECTOR\n");
+      call DhvVectorDecision.send();
+      break;
+    case ID_DHV_DATA:
+      dbg("DhvLogicP", "Decision to DATA\n");
+      call DhvDataDecision.send();
+      break;
+               case ID_DHV_VBIT:
+                       dbg("DhvLogicP", "Decision to VSUM\n");
+                       call DhvVBitDecision.send();
+                       break;
+         case ID_DHV_HSUM:
+                       dbg("DhvLogicP", "Decision to HSUM\n");
+                       call DhvHSumDecision.send();
+                       break;
+    }
+    call DhvDataDecision.resetCommRate();
+    call DhvVectorDecision.resetCommRate();
+    call DhvSummaryDecision.resetCommRate();
+               call DhvVBitDecision.resetCommRate();
+               call DhvHSumDecision.resetCommRate();
+
+               //set bitstate to zero
+               call DhvStateLogic.setVBitState(0);     
+  }
+
+
+  uint8_t getState() {
+               bool hasItemToSend;
+               uint32_t bindex;
+
+               hasItemToSend = FALSE;
+
+    hasItemToSend = call DhvDataCache.hasItemToSend();
+               if(hasItemToSend){
+                       dbg("DhvLogicP", "has data to send? %u \n", hasItemToSend);
+                       return ID_DHV_DATA;
+               }else{
+                       hasItemToSend = call DhvVectorCache.hasItemToSend();
+                       dbg("DhvLogicP", "has vector to send? %u \n", hasItemToSend);
+                       if(hasItemToSend){
+                               return ID_DHV_VECTOR;
+                       }else{
+                               bindex = call DhvStateLogic.getVBitState();
+                               dbg("DhvLogicP", "send decision bindex %d \n", bindex);         
+                       
+                               if(bindex !=  0){
+                                       return ID_DHV_VBIT;
+                               }else{
+                                       if(hsum_status != 0){
+                                               return ID_DHV_HSUM;
+                                       }else {
+                                               return ID_DHV_SUMMARY;          
+                                       }
+                               }
+                       }
+               }
+       }
+
+
+  uint8_t sendDecision() {
+
+               bool hasItemToSend;
+               uint32_t bindex;
+    uint8_t dataCommRate;
+    uint8_t vectorCommRate;
+    uint8_t summaryCommRate;
+               uint8_t vbitCommRate;
+    uint8_t hsumCommRate;
+
+    dataCommRate = call DhvDataDecision.getCommRate();
+    vectorCommRate = call DhvVectorDecision.getCommRate();
+    summaryCommRate = call DhvSummaryDecision.getCommRate();
+               vbitCommRate    = call DhvVBitDecision.getCommRate();
+    hsumCommRate    = call DhvHSumDecision.getCommRate();
+
+               hasItemToSend = FALSE;
+    hasItemToSend = call DhvDataCache.hasItemToSend();
+               if(hasItemToSend){
+                       dbg("DhvLogicP", "has data to send? %u \n", hasItemToSend);
+                       return ID_DHV_DATA;
+               }
+
+               bindex = call DhvStateLogic.getVBitState();
+               dbg("DhvLogicP", "send decision bindex %d \n", bindex);         
+
+               if(bindex != 0){
+                       return ID_DHV_VBIT;
+               }
+       
+         if(hsum_status != 0){
+                       return ID_DHV_HSUM;
+               }
+
+       if(dataCommRate > 1) {
+                       dbg("DhvLogicP", "Heard data\n");
+       return ID_DHV_INVALID;
+       }
+
+
+               hasItemToSend = call DhvVectorCache.hasItemToSend();
+               dbg("DhvLogicP", "has vector to send? %u \n", hasItemToSend);
+
+               if(hasItemToSend){
+                       return ID_DHV_VECTOR;
+               }
+
+               // didn't send or hear data at this point
+       if(vectorCommRate + summaryCommRate + vbitCommRate > 1) {
+       dbg("DhvLogicP", "Heard an advertisement\n");
+       return ID_DHV_INVALID;
+       }
+
+               return ID_DHV_SUMMARY;          
+       }
+}
diff --git a/tos/lib/net/dhv/DhvSummaryC.nc b/tos/lib/net/dhv/DhvSummaryC.nc
new file mode 100755 (executable)
index 0000000..0cece24
--- /dev/null
@@ -0,0 +1,32 @@
+/**
+ * DHV Summary Message Configuration.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV interfaces type.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+configuration DhvSummaryC {
+  provides interface DhvDecision;
+
+  uses interface DhvSend as SummarySend;
+  uses interface DhvReceive as SummaryReceive;
+       uses interface DhvStateLogic as StateLogic;
+  uses interface DhvHelp;
+}
+
+implementation {
+  components DhvSummaryP;
+  DhvDecision = DhvSummaryP;
+  SummarySend = DhvSummaryP;
+  SummaryReceive = DhvSummaryP;
+       StateLogic = DhvSummaryP;
+  DhvHelp = DhvSummaryP;
+  components RandomC;
+  DhvSummaryP.Random -> RandomC; 
+}
diff --git a/tos/lib/net/dhv/DhvSummaryP.nc b/tos/lib/net/dhv/DhvSummaryP.nc
new file mode 100755 (executable)
index 0000000..eb97dd4
--- /dev/null
@@ -0,0 +1,79 @@
+/**
+ * DHV Summary Message Implementation.
+ *
+ * Define the interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV interfaces type.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+#include <Dhv.h>
+
+module DhvSummaryP {
+  provides interface DhvDecision;
+
+  uses interface DhvSend as SummarySend;
+  uses interface DhvReceive as SummaryReceive;
+  uses interface DhvHelp;
+  uses interface Random;
+       uses interface DhvStateLogic as StateLogic;
+}
+
+implementation {
+  uint32_t computeHash(dhv_index_t left, dhv_index_t right,
+                      dhv_version_t* basedata, uint32_t salt);
+  uint8_t commRate;
+
+  command uint8_t DhvDecision.getCommRate() {
+    return commRate;
+  }
+
+  command void DhvDecision.resetCommRate() {
+    commRate = 0;
+  }
+
+  command error_t DhvDecision.send() {
+    uint32_t salt;
+    dhv_msg_t* dmsg;
+    dhv_summary_msg_t* dsmsg;
+
+    dmsg = (dhv_msg_t*) call SummarySend.getPayloadPtr();
+    if(dmsg == NULL)
+        return FAIL;
+
+    dmsg->type = ID_DHV_SUMMARY;
+    dsmsg = (dhv_summary_msg_t*) dmsg->content;
+
+    salt = call Random.rand32();
+    dsmsg->info = call DhvHelp.computeHash(0, UQCOUNT_DHV, salt);
+    dsmsg->salt = salt;
+
+    dbg("DhvSummaryP", "Hash Entry: %08x \n",   dsmsg->info);
+    return call SummarySend.send(sizeof(dhv_msg_t) + sizeof(dhv_summary_msg_t));
+  }
+
+  event void SummaryReceive.receive(void* payload, uint8_t len) {
+    dhv_summary_msg_t* dsmsg;
+    uint32_t salt, myHash;
+
+    commRate = commRate + 1;
+
+    dsmsg = (dhv_summary_msg_t*) payload;
+    salt = dsmsg->salt;
+    
+    myHash = call DhvHelp.computeHash(0, UQCOUNT_DHV, salt);
+    if(myHash != dsmsg->info) {
+                               //call StateLogic.setDiffSummary();
+                               call StateLogic.setHSumStatus();
+        dbg("DhvSummaryP", "Hashes don't match\n");
+    }
+      else {
+                               call StateLogic.setSameSummary();
+        dbg("DhvSummaryP", "Hashes match\n");
+    }
+  }
+}
diff --git a/tos/lib/net/dhv/DhvTrickleMilliC.nc b/tos/lib/net/dhv/DhvTrickleMilliC.nc
new file mode 100755 (executable)
index 0000000..1ae0291
--- /dev/null
@@ -0,0 +1,62 @@
+// $Id$
+/*
+ * "Copyright (c) 2006 Stanford University. All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+ * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
+ * HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
+ * ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/*
+ * Configuration that encapsulates the trickle timer implementation to
+ * its needed services and initialization. For details on the working
+ * of the parameters, please refer to Levis et al., "A Self-Regulating
+ * Algorithm for Code Maintenance and Propagation in Wireless Sensor
+ * Networks," NSDI 2004.
+ *
+ * @param l Lower bound of the time period in seconds.
+ * @param h Upper bound of the time period in seconds.
+ * @param k Redundancy constant.
+ * @param count How many timers to provide.
+ *
+ * @author Philip Levis
+ * @author Gilman Tolle
+ * @date   Jan 7 2006
+ */ 
+
+
+configuration DhvTrickleMilliC {
+  provides interface DhvTrickleTimer as TrickleTimer;
+}
+implementation {
+  components DhvTrickleMilliP as TrickleP;
+  components MainC, RandomC;
+  components new TimerMilliC() as PeriodicIntervalTimer;
+  components new TimerMilliC() as SingleEventTimer;
+  components LedsC;
+  TrickleTimer = TrickleP;
+
+  TrickleP.PeriodicIntervalTimer -> PeriodicIntervalTimer;
+  TrickleP.SingleEventTimer -> SingleEventTimer;
+  TrickleP.Random -> RandomC;
+  
+  TrickleP.Leds -> LedsC;
+  MainC.SoftwareInit -> TrickleP;
+}
+
+  
diff --git a/tos/lib/net/dhv/DhvTrickleMilliP.nc b/tos/lib/net/dhv/DhvTrickleMilliP.nc
new file mode 100755 (executable)
index 0000000..ab25c3c
--- /dev/null
@@ -0,0 +1,120 @@
+// $Id$
+/*
+ * "Copyright (c) 2006 Stanford University. All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+ * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
+ * HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
+ * ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/*
+ * Module that provides a service instance of trickle timers. For
+ * details on the working of the parameters, please refer to Levis et
+ * al., "A Self-Regulating Algorithm for Code Maintenance and
+ * Propagation in Wireless Sensor Networks," NSDI 2004.
+ *
+ * @param l Lower bound of the time period in seconds.
+ * @param h Upper bound of the time period in seconds.
+ * @param k Redundancy constant.
+ * @param count How many timers to provide.
+ *
+ * @author Philip Levis
+ * @author Gilman Tolle
+ * @date   Jan 7 2006
+ */ 
+
+#include <Timer.h>
+#include <Dhv.h>
+
+module DhvTrickleMilliP {
+  provides {
+    interface Init;
+    interface DhvTrickleTimer as TrickleTimer;
+  }
+  uses {
+    interface Timer<TMilli> as PeriodicIntervalTimer;
+    interface Timer<TMilli> as SingleEventTimer;
+    interface Random;
+    interface Leds;
+  }
+}
+implementation {
+
+  uint32_t period;
+
+  command error_t Init.init() {
+    period = DHV_TAU_HIGH;
+    return SUCCESS;
+  }
+
+  /**
+   * Start a trickle timer. Reset the counter to 0.
+   */
+  command error_t TrickleTimer.start() {
+    call PeriodicIntervalTimer.startOneShot(period);
+    dbg("DhvTrickleMilliP",
+       "Starting trickle timer @ %s\n", sim_time_string());
+    return SUCCESS;
+  }
+
+  /**
+   * Stop the trickle timer. This call sets the timer period to H.
+   */
+  command void TrickleTimer.stop() {
+    call PeriodicIntervalTimer.stop();
+    dbg("DhvTrickleMilliP",
+       "Stopping trickle timer @ %s\n", sim_time_string());
+  }
+
+  /**
+   * Reset the timer period to L. If called while the timer is running,
+   * then a new interval (of length L) begins immediately.
+   */
+  command void TrickleTimer.reset() {
+    period = DHV_TAU_LOW;
+    call PeriodicIntervalTimer.stop();
+    call PeriodicIntervalTimer.startOneShot(period);
+    dbg("DhvTrickleMilliP",
+       "Resetting trickle timer @ %s\n", sim_time_string());
+  }
+
+  command void TrickleTimer.maxInterval() {
+    period = DHV_TAU_HIGH;
+  }
+
+  /**
+   * The trickle timer has fired. Signaled if C &gt; K.
+   */
+  event void PeriodicIntervalTimer.fired() {
+    uint32_t dtfire;
+
+    dtfire = (call Random.rand16() % (period / 2)) + (period / 2);
+    dbg("DhvTrickleMilliP", "Scheduling Trickle event with %u\n", dtfire);
+    call SingleEventTimer.startOneShot(dtfire);
+    period = signal TrickleTimer.requestWindowSize();
+    call PeriodicIntervalTimer.startOneShot(period);
+    //call Leds.led0Toggle();
+  }
+
+  event void SingleEventTimer.fired() {
+    dbg("Trickle", "Firing Trickle Event Timer\n");
+    signal TrickleTimer.fired();
+  }
+}
+
+  
diff --git a/tos/lib/net/dhv/DhvVBitC.nc b/tos/lib/net/dhv/DhvVBitC.nc
new file mode 100755 (executable)
index 0000000..cdec7ee
--- /dev/null
@@ -0,0 +1,35 @@
+/**
+ * DHV Virtual Bits Check Configuration
+ *
+ * Define interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV modules.
+ **/
+
+configuration DhvVBitC{
+       provides interface DhvDecision;
+       
+       uses interface DhvSend as VBitSend;
+       uses interface DhvReceive as VBitReceive;
+       uses interface DhvStateLogic as VBitLogic;
+       uses interface DhvLogic as VectorLogic;
+       uses interface DhvHelp;
+}
+
+implementation{
+       
+       components DhvVBitP;
+       DhvDecision = DhvVBitP;
+       VBitSend                = DhvVBitP;
+       VBitReceive = DhvVBitP;
+       VBitLogic       = DhvVBitP;
+       VectorLogic = DhvVBitP;
+       DhvHelp                 = DhvVBitP;
+
+       components RandomC;
+       DhvVBitP.Random -> RandomC;
+}
diff --git a/tos/lib/net/dhv/DhvVBitP.nc b/tos/lib/net/dhv/DhvVBitP.nc
new file mode 100755 (executable)
index 0000000..9ebac2f
--- /dev/null
@@ -0,0 +1,221 @@
+/**
+ * DHV Virtual Bits Check Configuration
+ *
+ * Define interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV modules.
+ **/
+
+#include<Dhv.h>
+
+module DhvVBitP{
+  provides interface DhvDecision;
+
+  uses interface DhvSend as VBitSend;
+  uses interface DhvReceive as VBitReceive;
+  uses interface DhvStateLogic as VBitLogic;
+  uses interface DhvLogic as VectorLogic;
+  uses interface DhvHelp;      
+  uses interface Random;
+}
+
+implementation{
+  uint8_t commRate;
+
+  command uint8_t DhvDecision.getCommRate()
+  {
+    return commRate;
+  }
+
+  command void DhvDecision.resetCommRate(){
+    commRate  = 0;
+  }
+
+
+  /*construct a vector of bits and send it*/
+  command error_t DhvDecision.send(){
+    uint8_t bindex;
+    uint8_t vbit_size;
+    uint8_t msg_size;
+    uint8_t numMsg;
+    uint8_t maxDataLength;
+    uint8_t i, j;
+    dhv_msg_t* dmsg;
+    dhv_vbit_msg_t* dvbmsg;
+    uint8_t *versionPtr;
+    error_t sendResult;
+    uint32_t salt;
+
+    maxDataLength = TOSH_DATA_LENGTH - sizeof(dhv_msg_t) - sizeof(dhv_vbit_msg_t); 
+    sendResult = FAIL;
+
+    if(UQCOUNT_DHV != 0)
+    {
+      vbit_size = ((uint8_t)(UQCOUNT_DHV-1)/VBIT_LENGTH) + 1;
+      numMsg    = (vbit_size -1)/maxDataLength + 1;
+    }else
+    {
+      vbit_size = 0;
+      numMsg    = 0;
+    }
+
+    bindex = call VBitLogic.getVBitIndex();
+
+    //return if 0
+    if(bindex  == 0){
+      dbg("DhvVBitP", "Error: no vbit to send \n");
+    }
+
+
+    dmsg = call VBitSend.getPayloadPtr();
+    if(dmsg == NULL)
+      return FAIL;
+
+    dmsg->type = ID_DHV_VBIT;
+    dvbmsg = (dhv_vbit_msg_t*) dmsg->content;
+    dvbmsg->bindex = bindex;
+
+    //put the hash into the message
+    salt = call Random.rand32();
+    dvbmsg->info = call DhvHelp.computeHash(0, UQCOUNT_DHV, salt);
+    dvbmsg->salt = salt;                       
+
+    //put the vbit into the message
+    versionPtr = call DhvHelp.getVBits(bindex);
+
+    for(j = 0; j < numMsg; j++){//number of tos message_t 
+      if(j == numMsg-1){
+        //last message
+        msg_size = vbit_size - j*maxDataLength;
+      }else{
+        msg_size = maxDataLength;
+      }
+
+      //TODO: need to get this right
+      dvbmsg->numKey = msg_size*8;             //number of keys
+
+      for(i = 0; i < msg_size; i++){
+        dvbmsg->vindex = j;
+        dvbmsg->vbit[i] = versionPtr[j*maxDataLength + i];
+        dbg("DhvVBitP", "bindex %d vbit %d:  0x%02x  0x%02x \n",bindex, i, dvbmsg->vbit[i], versionPtr[i]);
+      }
+
+      dbg("DhvVBitP", "Sending vbit of index %d size %d \n", bindex, sizeof(dhv_msg_t) + sizeof(dhv_vbit_msg_t) + msg_size );
+
+      for(i = 0; i < msg_size; i++){
+        dbg("DhvVBitP", "vbit to send %d, 0x%02x \n", i, dvbmsg->vbit[i]);
+      }
+
+      //send the vbit out
+      sendResult = call VBitSend.send(sizeof(dhv_msg_t) + sizeof(dhv_vbit_msg_t) + msg_size);
+      if(sendResult == SUCCESS){
+        //call VBitLogic.unsetVBitIndex(bindex);
+        call VBitLogic.setVBitState(0);
+        call VBitLogic.unsetHSumStatus();
+      }
+    }
+    return sendResult; 
+  }
+
+
+  event void VBitReceive.receive(void* payload, uint8_t len){
+    dhv_vbit_msg_t * rcv_dvbmsg;
+    uint8_t bindex, vindex;
+    int i,j;
+    dhv_version_t version;
+    dhv_version_t mask;
+    uint8_t diffIndex;
+    dhv_key_t diffKey;
+    bool isDiff;
+    uint8_t vbit_size;
+    uint8_t* vbit;
+    uint32_t salt, myHash;
+    uint8_t maxDataLength;
+    uint8_t msg_size;
+    uint8_t numMsg;
+    uint32_t bitIndexValue;
+
+    isDiff = FALSE;
+    commRate = 1;
+
+    maxDataLength = TOSH_DATA_LENGTH - sizeof(dhv_msg_t) - sizeof(dhv_vbit_msg_t);
+    if(UQCOUNT_DHV != 0)
+    {
+      vbit_size = ((uint8_t)(UQCOUNT_DHV-1)/VBIT_LENGTH) + 1;  
+      numMsg = (vbit_size -1)/maxDataLength + 1;
+
+    }else
+    {
+      vbit_size = 0;
+      numMsg    = 0;   
+    }
+
+    rcv_dvbmsg = (dhv_vbit_msg_t*) payload;
+    bindex = rcv_dvbmsg->bindex;
+    vindex = rcv_dvbmsg->vindex;
+
+    dbg("DhvVBitP", "Receive vbit of index %d numMsg %d vbit_size %d \n", bindex, numMsg, vbit_size );
+
+    //compare the hash first
+    salt = rcv_dvbmsg->salt;
+    myHash = call DhvHelp.computeHash(0, UQCOUNT_DHV, salt);
+
+    if(myHash == rcv_dvbmsg->info){
+      //some duplicates
+      dbg("DhvVBitP", "same summary\n");
+      call VBitLogic.setSameSummary();
+
+    }else{
+      vbit = call DhvHelp.getVBits(bindex);    
+      if(vindex == numMsg-1){
+        msg_size = vbit_size - vindex*maxDataLength;
+        //dbg("DhvVBitP", "Last message vindex %d  numMsg %d msg_size %d \n", vindex, numMsg, msg_size );
+      }else{
+        msg_size = maxDataLength;
+        //dbg("DhvVBitP", "Not last message %d\n", msg_size);
+      }
+
+      //compare with the rcv vbits
+      for(i = 0; i < msg_size; i++){
+        dbg("DhvVBitP", "numMsg %d bindex %d vbit %d vindex %d: msg_size %d  local 0x%02x -  rcv  0x%02x \n",numMsg, bindex, i, vindex, msg_size ,vbit[vindex*maxDataLength+i],rcv_dvbmsg->vbit[i]);
+        if(vbit[vindex*maxDataLength + i] != rcv_dvbmsg->vbit[i]){
+          version = rcv_dvbmsg->vbit[i]^vbit[vindex*maxDataLength + i];
+          mask = 1;
+          if(version != 0){
+            dbg("DhvVBitP", "There is a difference \n");
+            isDiff = TRUE;
+            for(j = 0; j < VBIT_LENGTH; j++){
+              if((version & mask) != 0){
+                diffIndex = (VBIT_LENGTH -j) + VBIT_LENGTH*i + vindex*maxDataLength - 1 ;
+                dbg("DhvVBitP", "Detect difference at %d, %d %d  %d %d \n", diffIndex, i, j, vindex, maxDataLength);                                                           
+
+                diffKey = call DhvHelp.indexToKey(diffIndex);
+                call VectorLogic.setItem(diffKey);
+              }
+              mask = mask << 1;
+            }
+          } 
+        }
+      }
+
+      //reset this bit
+      call VBitLogic.unsetVBitIndex(bindex);
+
+      if((isDiff == FALSE)){
+        bitIndexValue = call VBitLogic.getVBitState();
+        if(bitIndexValue == 0){
+          //tell DhvLogic to send the next bindex
+          bindex++;
+          dbg("DhvVBitP", "No Difference detected, move to bindex %d \n", bindex );
+          call VBitLogic.setVBitIndex(bindex);                                         
+        }
+      }else{
+        dbg("DhvVBitP","difference detected, reset to 0 \n");
+      }        
+    }  
+  }
+}
diff --git a/tos/lib/net/dhv/DhvVectorC.nc b/tos/lib/net/dhv/DhvVectorC.nc
new file mode 100755 (executable)
index 0000000..7f14e55
--- /dev/null
@@ -0,0 +1,35 @@
+/**
+ * DHV Vector Message Configuration
+ *
+ * Define interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV modules.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+configuration DhvVectorC {
+  provides interface DhvDecision;
+
+  uses interface DhvSend as VectorSend;
+  uses interface DhvReceive as VectorReceive;
+  uses interface DhvLogic as VectorLogic;
+       uses interface DhvLogic as DataLogic;
+  uses interface DhvHelp;
+}
+
+implementation {
+  components DhvVectorP;
+  DhvDecision = DhvVectorP;
+  VectorSend = DhvVectorP;
+  VectorReceive = DhvVectorP;
+  DhvHelp = DhvVectorP;
+  VectorLogic = DhvVectorP.VectorLogic;
+       DataLogic   = DhvVectorP.DataLogic;
+  components RandomC;
+  DhvVectorP.Random -> RandomC;
+
+}
diff --git a/tos/lib/net/dhv/DhvVectorP.nc b/tos/lib/net/dhv/DhvVectorP.nc
new file mode 100755 (executable)
index 0000000..9a3b587
--- /dev/null
@@ -0,0 +1,163 @@
+/**
+ * DHV Vector Message Configuration
+ *
+ * Define interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV modules.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+#include <Dhv.h>
+
+module DhvVectorP {
+  provides interface DhvDecision;
+
+  uses interface DhvSend as VectorSend;
+  uses interface DhvReceive as VectorReceive;
+       uses interface DhvLogic as VectorLogic;
+       uses interface DhvLogic as DataLogic;
+  uses interface DhvHelp;
+  uses interface Random;
+}
+
+implementation {
+  uint8_t commRate = 0;
+
+  int myComparator(const void* a, const void* b);
+
+  command uint8_t DhvDecision.getCommRate() {
+    return commRate;
+  }
+
+  command void DhvDecision.resetCommRate() {
+    commRate = 0;
+  }
+
+  command error_t DhvDecision.send() {
+    dhv_index_t i, j;
+    dhv_key_t sendkey;
+               bool* keyvector;
+    dhv_msg_t* dmsg;
+    dhv_vector_msg_t* dvmsg;
+               error_t status;
+
+               dbg("DhvVectorP", "prepare to send vector out \n");
+
+    dmsg = call VectorSend.getPayloadPtr();
+    if(dmsg == NULL) {
+      return FAIL;
+    }
+
+               keyvector = call VectorLogic.allItem();
+    dmsg->type = ID_DHV_VECTOR;
+    dvmsg = (dhv_vector_msg_t*) dmsg->content;
+
+    //dvmsg->unitLen = DHV_VECTOR_ENTRIES_PER_PACKET;
+
+               //TODO: need to check for concurrency in here
+               i = 0;
+               for(j = 0; j < UQCOUNT_DHV; j++){
+                       if(keyvector[j] > ID_DHV_NO){
+                                       sendkey = call DhvHelp.indexToKey(j);
+
+                                       /*if(keyvector[j] == ID_DHV_REQ){
+                                               dbg("DhvVectorP", " keyvector %d == %d \n", keyvector[j], ID_DHV_REQ);
+                                               dmsg->type = ID_DHV_VECTOR_REQ;
+                                       }*/
+
+                       if(i < DHV_VECTOR_ENTRIES_PER_PACKET) {
+                       dvmsg->vector[i] = sendkey;
+                       dvmsg->vector[i+1] = call DhvHelp.keyToVersion(sendkey);
+                                               dbg("DhvVectorP","diff vector 0x%08x  0x%08x %d %d \n",dvmsg->vector[i] ,  dvmsg->vector[i+1], j, keyvector[j]);
+                                               i = i + 2;
+                                       }else{ break; }         
+       }
+               }
+               
+               dvmsg->unitLen = i;
+
+               //TODO: need to fix
+               dbg("DhvVectorP", "Sending vector message out ...unitLen 0x%02x \n", dvmsg->unitLen);
+    status = call VectorSend.send(sizeof(dhv_msg_t) + sizeof(dhv_vector_msg_t) +
+                               (i*sizeof(uint32_t)));
+
+               i = 0;
+               dbg("DhvVectorP","Send status %d vs FALSE %d \n", status, FALSE);
+
+               if(status == SUCCESS){dbg("DhvVectorP","status == SUCCESS\n");}
+               if(status == FAIL){dbg("DhvVectorP","status == FAIL\n");}
+
+               //TODO: need to check for actual send status here 
+               if(TRUE)
+               {
+                       dbg("DhvVectorP", "Send msg successfully \n");                  
+                       for(j = 0; j < UQCOUNT_DHV; j++){
+                               if(keyvector[j] > ID_DHV_NO){
+                                               sendkey = call DhvHelp.indexToKey(j);
+                               if(i < DHV_VECTOR_ENTRIES_PER_PACKET) {
+                                                       call VectorLogic.unsetItem(sendkey);
+                                                       i = i + 2;
+                                               }else{
+                                                       break;
+                                               }                       
+                       }
+                       }
+               }
+
+               dbg("DhvVectorP", "Sent vector message out ...unitLen %d \n", dvmsg->unitLen);
+               return SUCCESS; 
+  }
+
+       /*TODO: a callback event to remove the sent vectors*/
+  event void VectorReceive.receive(void* payload, uint8_t len) {
+    dhv_vector_msg_t* dvmsg;
+               dhv_msg_t* dmsg;
+
+    uint8_t unitlen;
+    uint8_t i;
+               uint8_t type;
+    uint32_t vectorkey;
+    uint32_t vectorver;
+    uint32_t myver;
+
+    commRate = commRate + 1;
+
+               dmsg  = (dhv_msg_t*) payload; 
+               type = dmsg->type;
+
+    dvmsg = (dhv_vector_msg_t*) dmsg->content;
+    unitlen = dvmsg->unitLen;
+
+               dbg("DhvVectorP", "Receive vector msg len %u  unitlen 0x%02x  0x%02x \n", len, unitlen, dvmsg->unitLen);                        
+
+    for(i = 0; i < unitlen; i += 2) {
+      vectorkey = dvmsg->vector[i];
+      vectorver = dvmsg->vector[i+1];
+      myver = call DhvHelp.keyToVersion(vectorkey);
+                       dbg("DhvVectorP", "key 0x%08x  version 0x%08x myver 0x%08x \n", vectorkey, vectorver, myver);
+      // TODO: handle the invalid versions
+      if(myver < vectorver) {
+                                       dbg("DhvVectorP", "I have an older version -> setReqItem \n");
+                                       call VectorLogic.setReqItem(vectorkey);
+      }
+      else if(myver > vectorver) {
+                                       dbg("DhvVectorP", "I have a newer version -> Data.setItem \n");
+                                       call DataLogic.setItem(vectorkey);
+      }
+      else{
+                                       if(type == ID_DHV_VECTOR_REQ){
+                                               dbg("DhvVectorP", "Request msg and I have that version -> Data.setItem \n");
+                                               call DataLogic.setItem(vectorkey);              
+                                       }else{
+                                                       
+                                               dbg("DhvVectorP", "Request msg and I have the same version -> keep quite \n");
+                                               call VectorLogic.unsetItem(vectorkey);          
+                                       }                               
+      }
+    }
+  }
+}
diff --git a/tos/lib/net/dhv/DhvVersionC.nc b/tos/lib/net/dhv/DhvVersionC.nc
new file mode 100755 (executable)
index 0000000..7b7f320
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+ * DHV Vector Message Configuration
+ *
+ * Define interfaces and components.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV modules.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+#include <Dhv.h>
+
+configuration DhvVersionC {
+  provides interface DhvHelp;
+  provides interface DisseminationUpdate<dhv_data_t>[dhv_key_t key];
+       provides interface DhvCache as DataCache;
+       provides interface DhvCache as VectorCache; 
+}
+
+implementation {
+  components DhvVersionP;
+  DhvHelp = DhvVersionP;
+  DisseminationUpdate = DhvVersionP;
+       DataCache = DhvVersionP.DhvDataCache;
+       VectorCache = DhvVersionP.DhvVectorCache;
+}
diff --git a/tos/lib/net/dhv/DhvVersionP.nc b/tos/lib/net/dhv/DhvVersionP.nc
new file mode 100755 (executable)
index 0000000..cc89a2f
--- /dev/null
@@ -0,0 +1,321 @@
+/**
+ * DHV Version Check Module
+ *
+ * Module checks version of the data item.
+ * details on the working of the parameters, please refer to Thanh Dang et al.,
+ * "DHV: A Code Consistency Maintenance Protocol for Multi-Hop Wireless Sensor
+ * Networks" EWSN 09.
+ *
+ * @author Thanh Dang
+ * @author Seungweon Park
+ *
+ * @modified 1/3/2009   Added meaningful documentation.
+ * @modified 8/28/2008  Defined DHV modules.
+ * @modified 8/28/2008  Took the source code from DIP.
+ **/
+
+module DhvVersionP {
+  provides interface DhvHelp;
+  provides interface DisseminationUpdate<dhv_data_t>[dhv_key_t key];
+       provides interface DhvCache as DhvDataCache;
+  provides interface DhvCache as DhvVectorCache;
+}
+
+implementation {
+
+  // keys are ordered from smallest to largest.
+  dhv_key_t keys[UQCOUNT_DHV];
+  dhv_version_t versions[UQCOUNT_DHV];
+  dhv_index_t count = 0;
+
+  //keep track of task
+  uint8_t data_to_send[UQCOUNT_DHV];
+  uint8_t vector_to_send[UQCOUNT_DHV];
+  uint8_t vbit[(UQCOUNT_DHV == 0)?0:((UQCOUNT_DHV-1)/VBIT_LENGTH +1)];
+
+/*utility for debugging purposes */
+       void printDataStatus()
+       {
+               dhv_index_t i;
+
+               for(i = 0; i < UQCOUNT_DHV; i++){
+                       dbg("DhvVersionP", "Data Status %d: %u \n",i, data_to_send[i]);
+               }
+       }
+
+
+       void printVectorStatus()
+       {
+               dhv_index_t i;
+
+               for(i = 0; i < UQCOUNT_DHV; i++){
+                       dbg("DhvVersionP", "T Vector Status %d: %u \n",i, vector_to_send[i]);
+               }
+       }
+
+       
+       void printVersionStatus()
+       {
+               dhv_index_t i;
+
+               for(i = 0; i < UQCOUNT_DHV; i++){
+                       dbg("DhvVersionP", "Version Status %d: 0x%08x \n",i, versions[i]);
+               }
+       }
+
+
+  /*DhvDataCache interface implementation */
+       command void DhvDataCache.addItem(dhv_key_t key){
+               dhv_index_t i;
+         
+               dbg("DhvVersionP", "Add Item to data vector key %d\n", i);      
+               i = call DhvHelp.keyToIndex(key);
+               data_to_send[i] = ID_DHV_ADS;
+               printDataStatus();
+       }
+
+       command void DhvDataCache.addReqItem(dhv_key_t key){
+               dhv_index_t i;
+         
+               dbg("DhvVersionP", "Add Req Item to data vector key %d\n", i);  
+               i = call DhvHelp.keyToIndex(key);
+               data_to_send[i] = ID_DHV_REQ;
+               printDataStatus();
+       }
+
+       command void DhvDataCache.removeItem(dhv_key_t key){
+               dhv_index_t i;
+
+               i = call DhvHelp.keyToIndex(key);
+               data_to_send[i] = ID_DHV_NO;
+               
+               dbg("DhvVersionP", "Remove Item from data vector key %d\n", i); 
+               printDataStatus();
+       }
+
+       command bool DhvDataCache.hasItemToSend(){
+               dhv_index_t i;
+
+               for(i = 0; i < UQCOUNT_DHV; i++){
+                       if(data_to_send[i] > ID_DHV_NO){return TRUE;}
+               }
+               return FALSE;
+       }
+
+       command uint8_t* DhvDataCache.allItem(){
+               return data_to_send;
+       }
+       
+       command uint8_t DhvDataCache.nextItem(){
+               dhv_index_t i;
+               for(i = 0; i < UQCOUNT_DHV; i++){
+                       if(data_to_send[i] > ID_DHV_NO ){
+                               return i;
+                       }
+               }
+               return UQCOUNT_DHV;
+       }
+
+       command void DhvDataCache.removeAll(){
+               dhv_index_t i;
+
+               for(i=0; i < UQCOUNT_DHV; i++){
+                       data_to_send[i] = ID_DHV_NO;
+               }
+       }
+
+       /*vector cache */
+       command void DhvVectorCache.addItem(dhv_key_t key){
+               dhv_index_t i;
+
+               i = call DhvHelp.keyToIndex(key);
+               vector_to_send[i] = ID_DHV_ADS;
+               
+               dbg("DhvVersionP", "Add Item to vector_to_send index %d\n", i);
+               printVectorStatus();
+       }
+
+       command void DhvVectorCache.addReqItem(dhv_key_t key){
+               dhv_index_t i;
+
+               i = call DhvHelp.keyToIndex(key);
+               vector_to_send[i] = ID_DHV_REQ;
+               
+               dbg("DhvVersionP", "Add Item to vector_to_send index %d\n", i);
+               printVectorStatus();
+       }
+
+       command void DhvVectorCache.removeItem(dhv_key_t key){
+               dhv_index_t i;
+
+               i = call DhvHelp.keyToIndex(key);
+               vector_to_send[i] = ID_DHV_NO;
+               
+               dbg("DhvVersionP", "Remove Item from vector_to_send index %d\n", i);
+               printVectorStatus();
+       }
+
+
+       command bool DhvVectorCache.hasItemToSend(){
+               dhv_index_t i;
+
+               for(i = 0; i < UQCOUNT_DHV; i++){
+                       if(vector_to_send[i] > ID_DHV_NO){return TRUE;}
+               }
+               return FALSE;
+       }
+
+  command uint8_t* DhvVectorCache.allItem(){
+               return vector_to_send;
+       }
+
+
+       command uint8_t DhvVectorCache.nextItem(){
+               dhv_index_t i;
+
+               for(i = 0; i < UQCOUNT_DHV; i++){
+                       if(vector_to_send[i] > ID_DHV_NO){
+                               return i;
+                       }
+               }
+               return UQCOUNT_DHV;
+       }
+
+
+       command void DhvVectorCache.removeAll(){
+               dhv_index_t i;
+
+               for(i=0; i < UQCOUNT_DHV; i++){
+                       vector_to_send[i] = ID_DHV_NO;
+               }
+       }
+
+
+  command void DhvHelp.registerKey(dhv_key_t key) {
+    keys[count] = key;
+    count = count + 1;
+    if(count == UQCOUNT_DHV) {
+      dbg("DhvVersionP","Key registration complete!\n");
+    }
+               //printVersionStatus();
+  }
+
+  command void DisseminationUpdate.change[dhv_key_t key](dhv_data_t* val) {
+    dhv_index_t i;
+    dhv_version_t ver;
+
+               dbg("DhvVersioP", "Updateing version for key %d \n", key);
+    i = call DhvHelp.keyToIndex(key);
+    ver = versions[i];
+    ver++;
+    versions[i] = ver;
+               printVersionStatus();
+  }
+
+  command dhv_index_t DhvHelp.keyToIndex(dhv_key_t key) {
+    dhv_index_t answer;
+    dhv_index_t i;
+
+    answer = DHV_UNKNOWN_INDEX;
+    // linear search for now since it's easier
+
+    for(i = 0; i < UQCOUNT_DHV; i++) {
+      if(keys[i] == key) { 
+                               answer = i;
+                               break;
+      }
+    }
+    dbg("DhvVersionP", "Converting key %x to index %u\n", key, answer);
+    return answer;
+  }
+
+  command dhv_key_t DhvHelp.indexToKey(dhv_index_t ind) {
+    return keys[ind];
+  }
+
+  command dhv_version_t DhvHelp.keyToVersion(dhv_key_t key) {
+    dhv_index_t i;
+    i = call DhvHelp.keyToIndex(key);
+    return versions[i];
+  }
+
+  command void DhvHelp.setVersion(dhv_key_t key, dhv_version_t ver) {
+    dhv_index_t i;
+    i = call DhvHelp.keyToIndex(key);
+    versions[i] = ver;
+    dbg("DhvVersionP","Setting key %x at index %u to version 0x%08x\n", key, i, ver);
+  }
+
+  command dhv_version_t* DhvHelp.getAllVersions() {
+    return versions;
+  }
+
+       command uint32_t DhvHelp.computeHash(uint8_t left, uint8_t right, uint32_t salt) {
+     dhv_index_t i;
+     uint32_t hashValue = salt;
+     uint8_t *sequence;
+     if(right <= left) return 0;
+     sequence = ((uint8_t*) (versions + left)); 
+     for(i = 0; i <= (right-left-1)*sizeof(dhv_version_t); i++) {
+       hashValue += sequence[i];
+       hashValue += (hashValue << 10);
+       hashValue ^= (hashValue >> 6);
+     }
+     hashValue += (hashValue << 3);
+     hashValue ^= (hashValue >> 11);
+     hashValue += (hashValue << 15);
+     return hashValue;
+   }
+
+ command uint8_t* DhvHelp.getVBits(uint32_t bindex){
+       dhv_version_t version;
+       uint8_t cur_byte;
+       dhv_index_t i,j;
+       
+
+       j = 0;
+       version = 0;
+       cur_byte = 0;
+
+       dbg("DhvVersionP", "getVBits at index %d \n", bindex);
+       printVersionStatus();
+
+       for(i = 1; i <= UQCOUNT_DHV; i++){
+      version = versions[i-1];
+                       //dbg("DhvVersionP", "version %d 0x%08x \n", i, version);
+      version = (version >>(bindex-1)) << (DHV_VERSION_LENGTH*8-1) >> (j + 24); //get the bindex bit
+
+                       //dbg("DhvVersionP", "shifted version 1 by %d :  0x%08x   -> 0x%08x : %d \n", VBIT_LENGTH-1, versions[i-1], version, j);
+      cur_byte = cur_byte | version; 
+                       //dbg("DhvVersionP", "shifted version 2  0x%08x   -> 0x%08x : %d  cur_byte 0x%08x \n\n\n", versions[i-1], version, j, cur_byte);
+      j++;
+
+      if(j == VBIT_LENGTH){  
+        //reset j
+        j = 0;
+        vbit[(i-1)/VBIT_LENGTH] = cur_byte;
+                               dbg("DhvVersionP", "vertical bits %d  0x%02x 0x%02x \n", (i-1)/VBIT_LENGTH, cur_byte, vbit[(i-1)/VBIT_LENGTH]);
+        cur_byte = 0;
+      }   
+    }
+               
+               //debug
+               for(i= 0; i < sizeof(vbit); i++){
+                       dbg("DhvVersionP", "vbit %d -> 0x%02x \n", i, vbit[i]);
+               }
+
+               return vbit;            
+       }
+
+       command dhv_version_t DhvHelp.getHSum(){
+               dhv_version_t hsum;
+               dhv_index_t i;
+               hsum = versions[0];
+
+               for(i =1 ; i < UQCOUNT_DHV; i++){
+                       hsum = hsum^versions[i];
+               }
+               return hsum;
+       }
+
+}
diff --git a/tos/lib/net/dhv/DisseminationC.nc b/tos/lib/net/dhv/DisseminationC.nc
new file mode 100755 (executable)
index 0000000..989eca9
--- /dev/null
@@ -0,0 +1,11 @@
+
+#include <Dhv.h>
+
+configuration DisseminationC {
+  provides interface StdControl;
+}
+
+implementation {
+  components DhvLogicC;
+  StdControl = DhvLogicC;
+}
diff --git a/tos/lib/net/dhv/DisseminatorC.nc b/tos/lib/net/dhv/DisseminatorC.nc
new file mode 100755 (executable)
index 0000000..d546f80
--- /dev/null
@@ -0,0 +1,77 @@
+#include <Dhv.h>
+
+/*
+ * Copyright (c) 2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ *
+ */
+
+/**
+ * The DisseminatorC component holds and synchronizes a single value
+ * of a chosen type, and identifies that value by a chosen 16-bit key.
+ * Different nodes should use the same key for the same value.
+ *
+ * See TEP118 - Dissemination for details.
+ * 
+ * @param t the type of the object that will be disseminated
+ * @param key the 16-bit identifier of the disseminated object
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$ $Date$
+ */
+
+generic configuration DisseminatorC(typedef t, dhv_key_t key) {
+  provides interface DisseminationValue<t>;
+  provides interface DisseminationUpdate<t>;
+}
+implementation {
+  enum {
+    JUST_NEED_COUNT = UQ_DHV
+  };
+
+  components new DisseminatorP(t, key);
+  DisseminationValue = DisseminatorP.AppDisseminationValue;
+  DisseminationUpdate = DisseminatorP.AppDisseminationUpdate;
+
+  components LedsC;
+  DisseminatorP.Leds -> LedsC;
+
+  components DhvLogicC;
+  DisseminatorP.DhvDisseminationUpdate -> DhvLogicC.DisseminationUpdate[key];
+
+  components DhvVersionC;
+  DisseminatorP.DhvHelp -> DhvVersionC;
+
+  components MainC;
+  MainC.SoftwareInit -> DisseminatorP;
+
+  components DhvDataC;
+  DhvDataC.DisseminationUpdate[key] -> DisseminatorP.DataDisseminationUpdate;
+  DhvDataC.DisseminationValue[key] -> DisseminatorP.DataDisseminationValue;
+}
diff --git a/tos/lib/net/dhv/DisseminatorP.nc b/tos/lib/net/dhv/DisseminatorP.nc
new file mode 100755 (executable)
index 0000000..6ecec98
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ *
+ */
+
+/**
+ * The DisseminatorP module holds and synchronizes a single value of a
+ * chosen type.
+ *
+ * See TEP118 - Dissemination for details.
+ * 
+ * @param t the type of the object that will be disseminated
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$ $Date$
+ */
+
+generic module DisseminatorP(typedef t, dhv_key_t key) {
+  provides interface DisseminationValue<t> as AppDisseminationValue;
+  provides interface DisseminationUpdate<t> as AppDisseminationUpdate;
+  provides interface DisseminationUpdate<dhv_data_t> as DataDisseminationUpdate;
+  provides interface DisseminationValue<dhv_data_t> as DataDisseminationValue;
+
+  provides interface Init;
+
+  uses interface DisseminationUpdate<dhv_data_t> as DhvDisseminationUpdate;
+  uses interface DhvHelp;
+  uses interface Leds;
+}
+implementation {
+  dhv_data_t valueCache;
+  
+  task void signalNewData() {
+    signal AppDisseminationValue.changed();
+  }
+  
+  command error_t Init.init() {
+    call DhvHelp.registerKey(key);
+    return SUCCESS;
+  }
+
+  // A sequence number is 32 bits. The top 16 bits are an incrementing
+  // counter, while the bottom 16 bits are a unique node identifier.
+  // But versions aren't stored here.
+
+  command const t* AppDisseminationValue.get() {
+    return (t*) &valueCache;
+  }
+
+  command void AppDisseminationValue.set( const t* val ) {
+    memcpy( &valueCache, val, sizeof(t) );
+    // must signal here instead of posting task to prevent race condition
+    signal AppDisseminationValue.changed();
+  }
+
+  command void AppDisseminationUpdate.change( t* newVal ) {
+    memcpy( &valueCache, newVal, sizeof(t) );
+    /* Increment the counter and append the local node ID later. */
+    /* DhvLogicC doesn't care what the data actually is,
+       it just wants the key, so we cast it recklessly */
+    call DhvDisseminationUpdate.change((dhv_data_t*)newVal);
+    post signalNewData();
+  }
+
+  command const dhv_data_t* DataDisseminationValue.get() {
+    return (dhv_data_t*) &valueCache;
+  }
+
+  command void DataDisseminationValue.set( const dhv_data_t* val ) {  }
+
+  command void DataDisseminationUpdate.change( dhv_data_t* newVal ) {
+    memcpy( &valueCache, newVal, sizeof(dhv_data_t) );
+    // don't post the task, this came from the network
+    signal AppDisseminationValue.changed();
+  }
+
+
+  default event void AppDisseminationValue.changed() { }
+
+  default event void DataDisseminationValue.changed() { }
+
+}
diff --git a/tos/lib/net/dhv/README b/tos/lib/net/dhv/README
new file mode 100755 (executable)
index 0000000..b465e6c
--- /dev/null
@@ -0,0 +1,29 @@
+
+Title: Dhv
+Author: Thanh Dang, Seungweon Park
+------------------
+
+DHV is a code consistency maintenance protocol to ensure that every node
+in a network will eventually have the same code. DHV is based on the
+simple observation that if two code versions are different, their
+corresponding version numbers often differ in only a few least significant
+bits of their binary representation. DHV allows nodes to carefully select
+and transmit only necessary bit level information to detect a newer code version
+in the network. Detail of the protocol can be found here
+
+Thanh Dang, Nirupama Bulusu, Wu-chi Feng, and Seungweon Park, 
+"DHV: A Code Consistent Maintenance Protocol for Wireless Sensor Networks.", 
+In Proceedings of EWSN 2009, Cork, Ireland, Feb 2009.
+
+Usage:
+------
+
+To use include the following in your Makefile:
+
+CFLAGS += -I$(TOSDIR)/lib/net
+CFLAGS += -I$(TOSDIR)/lib/net/dhv
+CFLAGS += -I$(TOSDIR)/lib/net/dhv/interfaces
+
+* add a following line when use BaseStation
+CFLAGS += -DTOSH_DATA_LENGTH=32
diff --git a/tos/lib/net/dhv/interfaces/DhvCache.nc b/tos/lib/net/dhv/interfaces/DhvCache.nc
new file mode 100755 (executable)
index 0000000..973ca19
--- /dev/null
@@ -0,0 +1,12 @@
+#include<Dhv.h>
+
+interface DhvCache{
+       command void addItem(dhv_key_t key);
+       command void addReqItem(dhv_key_t key);
+       command void removeItem(dhv_key_t key);
+       command bool hasItemToSend();
+       command uint8_t* allItem();
+       command uint8_t nextItem();
+       command void removeAll();
+}
+
diff --git a/tos/lib/net/dhv/interfaces/DhvDecision.nc b/tos/lib/net/dhv/interfaces/DhvDecision.nc
new file mode 100755 (executable)
index 0000000..8580760
--- /dev/null
@@ -0,0 +1,6 @@
+
+interface DhvDecision {
+  command uint8_t getCommRate();
+  command void resetCommRate();
+  command error_t send();
+}
diff --git a/tos/lib/net/dhv/interfaces/DhvEstimates.nc b/tos/lib/net/dhv/interfaces/DhvEstimates.nc
new file mode 100755 (executable)
index 0000000..9143677
--- /dev/null
@@ -0,0 +1,15 @@
+
+#include <Dhv.h>
+
+interface DhvEstimates {
+  command dhv_estimate_t* getEstimates();
+  command void decEstimateByIndex(dhv_index_t i);
+  command void decEstimateByKey(dhv_key_t key);
+  command dhv_hashlen_t estimateToHashlength(dhv_estimate_t est);
+  command dhv_estimate_t hashlengthToEstimate(dhv_hashlen_t len);
+  // special event to reset trickle timer too
+  command void setDataEstimate(dhv_key_t key);
+  command void setVectorEstimate(dhv_key_t key);
+  command void setSummaryEstimateByIndex(dhv_index_t ind,
+                                        dhv_estimate_t est);
+}
diff --git a/tos/lib/net/dhv/interfaces/DhvHelp.nc b/tos/lib/net/dhv/interfaces/DhvHelp.nc
new file mode 100755 (executable)
index 0000000..806ebab
--- /dev/null
@@ -0,0 +1,15 @@
+
+#include <Dhv.h>
+
+interface DhvHelp {
+  command void registerKey(dhv_key_t key);
+
+  command dhv_index_t keyToIndex(dhv_key_t key);
+  command dhv_key_t indexToKey(dhv_index_t ind);
+  command dhv_version_t keyToVersion(dhv_key_t key);
+  command void setVersion(dhv_key_t key, dhv_version_t ver);
+  command dhv_version_t* getAllVersions();
+       command dhv_version_t getHSum();
+       command uint8_t* getVBits(uint32_t bindex);
+       command uint32_t computeHash(uint8_t left, uint8_t right,uint32_t salt);         
+}
diff --git a/tos/lib/net/dhv/interfaces/DhvLogic.nc b/tos/lib/net/dhv/interfaces/DhvLogic.nc
new file mode 100755 (executable)
index 0000000..dc57e2c
--- /dev/null
@@ -0,0 +1,9 @@
+#include<Dhv.h>
+
+interface DhvLogic{
+       command error_t setItem(dhv_key_t key);
+       command error_t setReqItem(dhv_key_t key);
+       command error_t unsetItem(dhv_key_t key);
+       command uint8_t nextItem();
+  command uint8_t * allItem();
+} 
diff --git a/tos/lib/net/dhv/interfaces/DhvNeighbour.nc b/tos/lib/net/dhv/interfaces/DhvNeighbour.nc
new file mode 100755 (executable)
index 0000000..b8ea315
--- /dev/null
@@ -0,0 +1,5 @@
+#include<Dhv.h>
+interface DhvNeighbour{
+       command uint8_t getNeighbourCount();
+       command void addNeighbour(uint8_t nodeId);
+}
diff --git a/tos/lib/net/dhv/interfaces/DhvReceive.nc b/tos/lib/net/dhv/interfaces/DhvReceive.nc
new file mode 100755 (executable)
index 0000000..ebaeeb1
--- /dev/null
@@ -0,0 +1,4 @@
+
+interface DhvReceive {
+  event void receive(void* payload, uint8_t len);
+}
diff --git a/tos/lib/net/dhv/interfaces/DhvSend.nc b/tos/lib/net/dhv/interfaces/DhvSend.nc
new file mode 100755 (executable)
index 0000000..9fef6fb
--- /dev/null
@@ -0,0 +1,6 @@
+
+interface DhvSend {
+  command error_t send(uint8_t len);
+  command void* getPayloadPtr();
+  command uint8_t maxPayloadLength();
+}
diff --git a/tos/lib/net/dhv/interfaces/DhvStateLogic.nc b/tos/lib/net/dhv/interfaces/DhvStateLogic.nc
new file mode 100755 (executable)
index 0000000..9d2e71c
--- /dev/null
@@ -0,0 +1,12 @@
+interface DhvStateLogic{
+       command void setDiffSummary();
+       command void setSameSummary();
+       command uint32_t getVBitState();
+       command void setVBitState(uint32_t state);
+  command void unsetVBitIndex(uint8_t dindex);
+  command uint8_t getVBitIndex();
+  command void setVBitIndex(uint8_t dindex);
+  command void setHSumStatus();
+  command void unsetHSumStatus();
+  command uint8_t getHSumStatus();
+}
diff --git a/tos/lib/net/dhv/interfaces/DhvTrickleTimer.nc b/tos/lib/net/dhv/interfaces/DhvTrickleTimer.nc
new file mode 100755 (executable)
index 0000000..322bc4f
--- /dev/null
@@ -0,0 +1,90 @@
+// $Id$
+/*
+ * "Copyright (c) 2006 Stanford University. All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+ * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
+ * HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
+ * ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/*
+ * A network trickle timer. A trickle timer has a period in the range
+ * [L, H]. After firing, the period is doubled, up to H. If the period
+ * is P, then the timer is scheduled to fire in the interval [0.5P, P]
+ * (the second half of a period). The period can be reset to L (the
+ * smallest period, and therefore the highest frequency).
+ *
+ * The timer may be suppressed. If a user of the interface has heard
+ * enough packets from other nodes that indicate its transmitting a
+ * packet would be unncessarily redundant, then the timer does not
+ * fire. The timer has a constant K and a counter C. If C &gte; K, then
+ * the timer does not fire. When an interval ends, C is reset to 0.
+ * Calling <tt>incrementCounter</tt> increments C by one.
+ *
+ * For details, refer to Levis et al., "A Self-Regulating Algorithm
+ * for Code Maintenance and Propagation in Wireless Sensor Networks,"
+ * NSDI 2004. The component providing this interface defines the
+ * constants L, H, and K.
+ *
+ * @author Philip Levis
+ * @date   Jan 7 2006
+ * @author Thanh Dang
+ * @date   Aug 5 2009
+ */ 
+
+
+interface DhvTrickleTimer {
+
+  /**
+   * Start the trickle timer. At boot, the timer period is its maximum
+   * value (H). If a protocol requires starting at the minimum value
+   * (e.g., fast start), then it should call <tt>reset</tt> before
+   * <tt>start</tt>.
+   *
+   * @return error_t SUCCESS if the timer was started, EBUSY if it is already
+   * running, and FAIL otherwise.
+   */
+  command error_t start();
+
+  /**
+   * Stop the trickle timer. This call sets the timer period to H and
+   * C to 0.
+   */
+  command void stop();
+
+  /**
+   * Reset the timer period to L. If called while the timer is
+   * running, then a new interval (of length L) begins immediately.
+   */
+  command void reset();
+
+  /**
+   * The trickle timer has fired. Signaled if C &gt; K.
+   */  
+  event void fired();
+
+  /**
+   * Compute the window size based on Dip's estimates
+   */
+  event uint32_t requestWindowSize();
+
+  /**
+   * Resets the timer period to H.
+   */
+  command void maxInterval();
+}
diff --git a/tos/lib/net/dhv/interfaces/DhvVersion.nc b/tos/lib/net/dhv/interfaces/DhvVersion.nc
new file mode 100755 (executable)
index 0000000..b2b3684
--- /dev/null
@@ -0,0 +1,7 @@
+
+#include <Dhv.h>
+
+interface DhvVersion {
+  command void setVersion();
+  command void incVersion();
+}
index 2935a1f4d4e16630d75e19a689c84dde093f6463..edac8b17102a8caf9a2428361588f80faa62f77e 100644 (file)
@@ -17,10 +17,6 @@ implementation {
 
   components MainC;
   MainC.SoftwareInit -> AMDipP.Init;
-  AMDipP.Boot -> MainC;
-
-  components ActiveMessageC;
-  AMDipP.AMSplitControl -> ActiveMessageC;
 
   DipSend = AMDipP.DipSend;
   DataReceive = AMDipP.DipDataReceive;
index 48e3c677101112eae15d329b046b5e2d121cd951..a3be418f552ffd96e725b3be4268f4212f7e99dc 100644 (file)
@@ -10,28 +10,12 @@ module AMDipP {
   uses interface AMSend as NetAMSend;
   uses interface Receive as NetReceive;
 
-  uses interface SplitControl as AMSplitControl;
-  uses interface Boot;
 }
 
 implementation {
   message_t am_msg;
   bool busy;
 
-  event void Boot.booted() {
-    call AMSplitControl.start();
-  }
-
-  event void AMSplitControl.startDone(error_t err) {
-    if(err != SUCCESS) {
-      call AMSplitControl.start();
-      return;
-    }
-    dbg("AMDipP", "ActiveMessageC started!\n");
-  }
-
-  event void AMSplitControl.stopDone(error_t err) { }
-
   command error_t Init.init() {
     busy = FALSE;
     return SUCCESS;
index b001d3eb6610e24efe8f941e8d9a89df6cf47cc7..0d840f34709b8ddd348ef9e98f7b7dcc50a34faf 100644 (file)
@@ -2,14 +2,16 @@
 #ifndef __DIP_H__
 #define __DIP_H__
 
-#define DIP_TAU_LOW (1024L)
-#define DIP_TAU_HIGH (65535L)
 
 #define UQ_DIP unique("DIP")
 #define UQCOUNT_DIP uniqueCount("DIP")
 
-#define DIP_UNKNOWN_VERSION 0xFFFFFFFF
-#define DIP_UNKNOWN_INDEX 0xFFFF
+enum {
+  DIP_TAU_LOW = 1024L,
+  DIP_TAU_HIGH = 65535L,
+  DIP_UNKNOWN_VERSION = 0xFFFFFFFF,
+  DIP_UNKNOWN_INDEX = 0xFFFF
+};
 
 typedef enum {
   ID_DIP_INVALID = 0x0,
@@ -71,7 +73,9 @@ typedef nx_struct dip_data {
   nx_uint8_t data[16];
 } dip_data_t;
 
-#define DIP_SUMMARY_VALUES_PER_PACKET 2
-#define DIP_VECTOR_VALUES_PER_PACKET 2
+enum {
+  DIP_SUMMARY_VALUES_PER_PACKET = 2,
+  DIP_VECTOR_VALUES_PER_PACKET = 2
+};
 
 #endif
index 8b36f8cd459035b07950874d49f355a5871797d0..132e1450b49debf9196490de2529bd4ea502b770 100644 (file)
@@ -69,7 +69,9 @@ implementation {
 
     dbg("DipLogicP","App notified key %x is new\n", key);
     i = call DipHelp.keyToIndex(key);
+#ifndef DIP_JOINTEST
     estimates[i] = DIP_DATA_ESTIMATE;
+#endif
     call VersionUpdate.change[key](val);
     call DipTrickleTimer.reset();
   }
index 805831c98976595ec4d619d1adfb9f91e65b56dd..ea08cb81b978fb901d3be564210e383833c42e13 100644 (file)
@@ -50,6 +50,9 @@ implementation {
     dip_summary_msg_t* dsmsg;
 
     dmsg = (dip_msg_t*) call SummarySend.getPayloadPtr();
+    if(dmsg == NULL) {
+      return FAIL;
+    }
     dmsg->type = ID_DIP_SUMMARY;
     dsmsg = (dip_summary_msg_t*) dmsg->content;
 
@@ -105,6 +108,9 @@ implementation {
     for(i = 0; i < unitlen; i += 3) {
       splitRange(dsmsg->info[i], &left, &right);
       myHash = computeHash(left, right, allVers, salt);
+      //dbg("DipSummaryP", "Received Range: %u, %u\n", left, right);
+      //dbg("DipSummaryP", "Received Hash: %08x\n", dsmsg->info[i+1]);
+      //dbg("DipSummaryP", "My Hash: %08x\n", myHash);
       if(myHash != dsmsg->info[i+1]) {
        // hashes don't match
        adjustEstimatesDiff(left, right, allVers, salt, dsmsg->info[i+2]);
@@ -148,7 +154,7 @@ implementation {
     // initialize bounds on range
     if(highIndex < len - 1) { LBound = 0; }
     else { LBound = highIndex - len + 1; }
-    if(LBound + len > UQCOUNT_DIP) { RBound = UQCOUNT_DIP; }
+    if(highIndex + len > UQCOUNT_DIP) { RBound = UQCOUNT_DIP; }
     else { RBound = highIndex + len; }
 
     // adjust length if necessary
@@ -166,10 +172,13 @@ implementation {
 
     // iterate through the range
     runEstSum = highEstSum;
-    dbg("DipSummaryP", "Iterating from %u to %u\n", LBound, RBound);
-    for(i = LBound ; i + len <= RBound; i++) {
+    dbg("DipSummaryP", "Iterating from %u to %u with len %u\n", LBound, RBound, len);
+
+    for(i = LBound ; i + len < RBound; i++) {
       est1 = shadowEstimates[i];
       est2 = shadowEstimates[i + len];
+      //dbg("DipSummaryP", "i: %u\n", i);
+      //dbg("DipSummaryP", "i+len: %u\n", i+len);
       runEstSum = runEstSum - est1 + est2;
       // dbg("Dissemination","Next sum: %u\n", runEstSum);
       if(runEstSum > highEstSum) {
@@ -183,6 +192,7 @@ implementation {
     // and finish
     *left = highIndex;
     *right = highIndex + len;
+    dbg("DipSummaryP","Final Range: %u, %u\n", *left, *right);
   }
 
   uint32_t buildRange(dip_index_t left, dip_index_t right) {
@@ -196,12 +206,19 @@ implementation {
                       dip_version_t* basedata, uint32_t salt) {
     dip_index_t i;
     uint32_t hashValue = salt;
-    uint8_t *sequence; 
+    //uint8_t *sequence;
+    dip_version_t* sequence;
+    uint32_t iterations;
 
     if(right <= left) return 0;
-    sequence = ((uint8_t*) (basedata + left));
+    //sequence = ((uint8_t*) (basedata + left));
+    sequence = (basedata + left);
+    //iterations = (right - left - 1)*sizeof(dip_version_t);
+    iterations = (right - left - 1);
+
+    //dbg("DipSummaryP","Computing hash for %u, %u for %u iters\n", left, right,  iterations);
 
-    for(i = 0; i <= (right-left-1)*sizeof(dip_version_t); i++) {
+    for(i = 0; i <= iterations; i++) {
       hashValue += sequence[i];
       hashValue += (hashValue << 10);
       hashValue ^= (hashValue >> 6);
@@ -224,6 +241,7 @@ implementation {
       indexSeqPair[0] = i;
       indexSeqPair[1] = basedata[i];
       bit = computeHash(0, 2, indexSeqPair, salt) % 32;
+      //dbg("DipSummaryP", "Bloom Hash: %u, %u, %u\n", indexSeqPair[0], indexSeqPair[1], bit);
       returnHash |= (1 << bit);
     }
     return returnHash;
index 87922a1507735beb8a94481529cfbf0918dfca7a..e315b6c249c8da160f4070212f117ebec665e7fa 100644 (file)
@@ -68,6 +68,9 @@ implementation {
     dip_index_t i;
 
     i = call DipHelp.keyToIndex(key);
+    if(i == DIP_UNKNOWN_INDEX) {
+      return DIP_UNKNOWN_VERSION;
+    }
     return versions[i];
   }
 
index c8022efc568a526fe241e448afefa086db420188..16c80acae6b3a70adc1bcff80c9f5a22695bde48 100644 (file)
@@ -1,6 +1,6 @@
 
 Title: Dip
-Author: Kaisen Lin
+Author: Kaisen Lin (kaisenl@cs.ucsd.edu)
 ------------------
 
 Dip is a dissemination protocol for detecting and disseminating new
index c83727bf1ba5f88392708f3c0be2db4e4adbd3b9..5a0f1b62be1a8f338a2f6ea4af873d58d8f8c232 100644 (file)
@@ -252,7 +252,7 @@ implementation {
   // called when new beacon estimate is done
   // also called when new DEETX estimate is done
   void updateEETX(neighbor_table_entry_t *ne, uint16_t newEst) {
-    ne->eetx = (ALPHA * ne->eetx + (10 - ALPHA) * newEst)/10;
+    ne->eetx = (ALPHA * ne->eetx + (10 - ALPHA) * newEst + 5)/10;
   }
 
 
@@ -341,8 +341,8 @@ implementation {
              ne->inquality = (ALPHA * ne->inquality) / 10;
            } else {
              newEst = (255 * ne->rcvcnt) / totalPkt;
-             dbg("LI,LITest", "  %hu: %hhu -> %hhu", ne->ll_addr, ne->inquality, (ALPHA * ne->inquality + (10-ALPHA) * newEst)/10);
-             ne->inquality = (ALPHA * ne->inquality + (10-ALPHA) * newEst)/10;
+             dbg("LI,LITest", "  %hu: %hhu -> %hhu", ne->ll_addr, ne->inquality, (ALPHA * ne->inquality + (10-ALPHA) * newEst + 5)/10);
+             ne->inquality = (ALPHA * ne->inquality + (10-ALPHA) * newEst + 5)/10;
            }
            ne->rcvcnt = 0;
            ne->failcnt = 0;
index 15d1499c31ad534d8e527eba5ec14203ff4607ce..65662d186231c4c8a2e846ad60448da3f8986555 100644 (file)
@@ -137,6 +137,8 @@ implementation {
        dbg("fwe", "FE: The message was not acked => FAIL.\n");
        signal MHControl.sendFailed(msg, 2);
        signal LinkMonitor.brokenLink(call AMPacket.destination(msg));
+      } else {
+        signal LinkMonitor.refreshedLink(call AMPacket.destination(msg));
       }
     } else if (e != SUCCESS) {
       dbg("fwe", "FE: ...but failed!\n");
index fd86277ecb2c618c6fbc2e8068d98255ccb368d1..b03ca4df37b709a5837f94cc2fc84944b1c6dfe5 100644 (file)
@@ -6,7 +6,7 @@
 #include "AM.h"
 
 /**
- * LinkMonitor - Interface to signals broken links in the neighborhood.
+ * LinkMonitor - Interface to signals broken and used links in the neighborhood.
  *
  * @author Romain Thouvenin
  */
@@ -15,4 +15,6 @@ interface LinkMonitor {
 
   event void brokenLink(am_addr_t neighbor);
 
+  event void refreshedLink(am_addr_t neighbor);
+
 }
index d0e00dd8610b62fadc26219c5dbbde01d7c39c28..7467d3c793c0ede5cd2e2aca7ef480b63631d2b8 100644 (file)
@@ -252,6 +252,13 @@ implementation {
     }
   }
 
+  event void LinkMonitor.refreshedLink(addr_t neighbor) {
+    int8_t i = get_route(neighbor);
+    if (i != -1) {
+      replace_info(i, &table[i].info);
+    }
+  }
+
   void replace_info(uint8_t pos, const rt_info_t * route_info){
     table[pos].info = *route_info;
     table[pos].flags = FLAG_NEW;
index 470fb6dc3a7a6cf29f1610016e02fb5a7cd10c7e..24d390667ba9bbdae74063a0e6a95ceedf08f94d 100644 (file)
@@ -36,7 +36,7 @@ implementation {
   }
 
   command void * Packet.getPayload(message_t *msg, uint8_t len){
-    nx_uint8_t * p = call SubPacket.getPayload(msg, len);
+    nx_uint8_t * p = call SubPacket.getPayload(msg, len + sizeof(mhpacket_header_t));
     return (void *)(p + sizeof(mhpacket_header_t));
   }
 
diff --git a/tos/lib/net/zigbee/apps/AssociationExample/AssociationExample.nc b/tos/lib/net/zigbee/apps/AssociationExample/AssociationExample.nc
deleted file mode 100644 (file)
index 75aa75f..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-#include <Timer.h>
-
-#include "associationexample.h"
-#include "phy_const.h"
-#include "phy_enumerations.h"
-#include "mac_const.h"
-#include "mac_enumerations.h"
-#include "mac_func.h"
-
-
-configuration AssociationExample {
-}
-implementation {
-
-  components MainC;
-  components LedsC;
-  components AssociationExampleM;
-    
-  AssociationExampleM.Boot -> MainC;
-    
-  components Mac;
-  
-  AssociationExampleM.Leds -> LedsC;
-  
-  components new TimerMilliC() as Timer0;
-  AssociationExampleM.Timer0 -> Timer0;
-   
-  components new TimerMilliC() as Timer_Send;
-  AssociationExampleM.Timer_Send ->Timer_Send;
-   
-   
-  //MAC interfaces
-  
-  AssociationExampleM.MLME_START -> Mac.MLME_START;
-  
-  AssociationExampleM.MLME_GET ->Mac.MLME_GET;
-  AssociationExampleM.MLME_SET ->Mac.MLME_SET;
-  
-  AssociationExampleM.MLME_BEACON_NOTIFY ->Mac.MLME_BEACON_NOTIFY;
-  AssociationExampleM.MLME_GTS -> Mac.MLME_GTS;
-  
-  AssociationExampleM.MLME_ASSOCIATE->Mac.MLME_ASSOCIATE;
-  AssociationExampleM.MLME_DISASSOCIATE->Mac.MLME_DISASSOCIATE;
-  
-  AssociationExampleM.MLME_ORPHAN->Mac.MLME_ORPHAN;
-  AssociationExampleM.MLME_SYNC->Mac.MLME_SYNC;
-  AssociationExampleM.MLME_SYNC_LOSS->Mac.MLME_SYNC_LOSS;
-  AssociationExampleM.MLME_RESET->Mac.MLME_RESET;
-  
-  AssociationExampleM.MLME_SCAN->Mac.MLME_SCAN;
-  
-  
-  AssociationExampleM.MCPS_DATA->Mac.MCPS_DATA;
-  
-  
-}
diff --git a/tos/lib/net/zigbee/apps/AssociationExample/AssociationExampleC.nc b/tos/lib/net/zigbee/apps/AssociationExample/AssociationExampleC.nc
new file mode 100644 (file)
index 0000000..bebb506
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+#include <Timer.h>
+
+#include "associationexample.h"
+#include "phy_const.h"
+#include "phy_enumerations.h"
+#include "mac_const.h"
+#include "mac_enumerations.h"
+#include "mac_func.h"
+
+
+configuration AssociationExampleC {
+}
+implementation {
+
+  components MainC;
+  components LedsC;
+  components AssociationExampleP;
+    
+  AssociationExampleP.Boot -> MainC;
+    
+  components MacC;
+  
+  AssociationExampleP.Leds -> LedsC;
+  
+  components new TimerMilliC() as Timer0;
+  AssociationExampleP.Timer0 -> Timer0;
+   
+  components new TimerMilliC() as Timer_Send;
+  AssociationExampleP.Timer_Send ->Timer_Send;
+   
+   
+  //MAC interfaces
+  
+  AssociationExampleP.MLME_START -> MacC.MLME_START;
+  
+  AssociationExampleP.MLME_GET ->MacC.MLME_GET;
+  AssociationExampleP.MLME_SET ->MacC.MLME_SET;
+  
+  AssociationExampleP.MLME_BEACON_NOTIFY ->MacC.MLME_BEACON_NOTIFY;
+  AssociationExampleP.MLME_GTS -> MacC.MLME_GTS;
+  
+  AssociationExampleP.MLME_ASSOCIATE->MacC.MLME_ASSOCIATE;
+  AssociationExampleP.MLME_DISASSOCIATE->MacC.MLME_DISASSOCIATE;
+  
+  AssociationExampleP.MLME_ORPHAN->MacC.MLME_ORPHAN;
+  AssociationExampleP.MLME_SYNC->MacC.MLME_SYNC;
+  AssociationExampleP.MLME_SYNC_LOSS->MacC.MLME_SYNC_LOSS;
+  AssociationExampleP.MLME_RESET->MacC.MLME_RESET;
+  
+  AssociationExampleP.MLME_SCAN->MacC.MLME_SCAN;
+  
+  
+  AssociationExampleP.MCPS_DATA->MacC.MCPS_DATA;
+  
+  
+}
diff --git a/tos/lib/net/zigbee/apps/AssociationExample/AssociationExampleM.nc b/tos/lib/net/zigbee/apps/AssociationExample/AssociationExampleM.nc
deleted file mode 100644 (file)
index 99e4c79..0000000
+++ /dev/null
@@ -1,489 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-#include <Timer.h>
-#include "printfUART.h"
-
-module AssociationExampleM {
-
-       uses interface Boot;
-       uses interface Leds;
-       
-       uses interface Timer<TMilli> as Timer0;
-       
-       uses interface Timer<TMilli> as Timer_Send;
-       //MAC interfaces
-       
-       uses interface MLME_START;
-       
-       uses interface MLME_GET;
-       uses interface MLME_SET;
-       
-       uses interface MLME_BEACON_NOTIFY;
-       uses interface MLME_GTS;
-       
-       uses interface MLME_ASSOCIATE;
-       uses interface MLME_DISASSOCIATE;
-       
-       uses interface MLME_ORPHAN;
-       
-       uses interface MLME_SYNC;
-       uses interface MLME_SYNC_LOSS;
-       
-       uses interface MLME_RESET;
-       
-       uses interface MLME_SCAN;
-       
-       
-       uses interface MCPS_DATA;
-  
-}
-implementation {
-
-
-       //number of data frames sent after association and before dissassociation
-       uint16_t frame_counter=0;
-
-       //associated devices
-       uint16_t address_poll = 0x0003;
-               
-       neighbour_table associated_devices[4];
-       
-       uint16_t search_associated_devices(uint32_t ext1, uint32_t ext2);
-       
-       uint8_t number_associations =0;
-       
-       PANDescriptor pan_des;
-
-       void try_disassociation();
-       
-       uint16_t my_short_address= 0xffff;
-       
-       uint8_t received_beacon_count=0;
-       uint32_t coordinator_addr[2];
-       
-       uint8_t go_associate =0;
-
-  event void Boot.booted() {
-       
-       printfUART_init();
-       
-       if (TYPE_DEVICE == COORDINATOR)
-       {
-               //assign the short address of the device
-               my_short_address = 0x0000;
-               call Timer0.startOneShot(3000);
-       }
-       else
-       {
-               call Timer0.startOneShot(8000);
-       }
-
-  }
-
-
-event void Timer0.fired() {
-    
-       uint8_t v_temp[2];
-       uint32_t c_addr[2];
-
-       if (TYPE_DEVICE == COORDINATOR)
-       {
-       
-               associated_devices[0].extended1=0x00000002;
-               associated_devices[0].extended2=0x00000002;
-               associated_devices[0].assigned_short=0x0004;
-       
-               //set the MAC short address variable
-               v_temp[0] = (uint8_t)(my_short_address >> 8);
-               v_temp[1] = (uint8_t)(my_short_address );
-               
-               call MLME_SET.request(MACSHORTADDRESS,v_temp);
-       
-               //set the MAC PANID variable
-               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
-               v_temp[1] = (uint8_t)(MAC_PANID );
-               
-               call MLME_SET.request(MACPANID,v_temp);
-       
-               //start sending beacons
-               call MLME_START.request(MAC_PANID, LOGICAL_CHANNEL, BEACON_ORDER, SUPERFRAME_ORDER,1,0,0,0,0);
-               
-               //call Timer_Send.startPeriodic(3000);
-       }
-       else
-       {
-               //the device will try to scan all the channels looking for a suitable PAN coordinator
-               //only the ACTIVE SCAN/ED SCAN  and a full channel scan is implemented
-               //call MLME_SCAN.request(PASSIVE_SCAN,0xFFFFFFFF,7);
-               //call MLME_SCAN.request(ED_SCAN,0xFFFFFFFF,0x10);
-               
-               c_addr[0] = 0x00000000;
-               c_addr[1] = 0x00000000;
-               
-               call MLME_ASSOCIATE.request(0x15,SHORT_ADDRESS,0x1234,c_addr,0x00,0x00);
-               
-               //call Leds.redOn();
-               call Timer0.stop();
-       }
-}
-  
-event void Timer_Send.fired() {
-
-       uint32_t SrcAddr[2];
-       uint32_t DstAddr[2];
-       
-       uint8_t msdu_payload[4];
-       
-       frame_counter++;
-       
-       if (frame_counter == 5)
-       {
-               //after sending 5 data frames the device tries to dissassociate from the PAN
-               call Timer_Send.stop();
-               try_disassociation();
-       
-       }
-       else
-       {
-               if (my_short_address == 0x0000ffff)
-                       return;
-               
-               SrcAddr[0]=0x00000000;
-               SrcAddr[1]=my_short_address;
-               
-               DstAddr[0]=0x00000000;
-               DstAddr[1]=0x00000000;
-                               
-               call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DstAddr, 4, msdu_payload,1,set_txoptions(1,0,0,0));
-       }
-}
-
-/*****************************************************************************************************/  
-/**************************************MLME-SCAN*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
-{
-//the device channel scan ends with a scan confirm containing a list of the PANs (beacons received during the scan) 
-
-       int i;
-       uint8_t max_lqi=0;
-       uint8_t best_pan_index=0;
-       
-       //call Leds.redOff();
-       
-       printfUART("MLME_SCAN.confirm %i\n", ScanType);
-       
-       if (ScanType == ORPHAN_SCAN)
-       {
-               printfUART("new scan \n", "");
-       
-               call MLME_SCAN.request(PASSIVE_SCAN,0xFFFFFFFF,7);
-               return SUCCESS;
-       }
-       
-       
-       
-       if(ScanType == ED_SCAN)
-       {
-               for(i=0;i<ResultListSize;i++)
-               {
-                       printfUART("ED SCAN %i %i\n", (0x0A + i),EnergyDetectList[i]);
-               }
-               return SUCCESS;
-       }
-       
-       for (i=0; i<ResultListSize;i++)
-       {               /*
-                       printfUART("cord id %i", PANDescriptorList[i].CoordPANId);
-                       printfUART("CoordAddress %i", PANDescriptorList[i].CoordAddress);
-                       printfUART("LogicalChannel %i", PANDescriptorList[i].LogicalChannel);
-                       printfUART("SuperframeSpec %i", PANDescriptorList[i].SuperframeSpec);
-                       printfUART("lqi %i\n", PANDescriptorList[i].lqi);
-                       */
-               if(max_lqi < PANDescriptorList[i].lqi)
-               {
-                       max_lqi =PANDescriptorList[i].lqi;
-                       best_pan_index = i;
-               }
-       }
-       
-       printfUART("SELECTED cord id %i", PANDescriptorList[best_pan_index].CoordPANId);
-       printfUART("CoordAddress %i", PANDescriptorList[best_pan_index].CoordAddress);
-       printfUART("LogicalChannel %i", PANDescriptorList[best_pan_index].LogicalChannel);
-       printfUART("SuperframeSpec %i", PANDescriptorList[best_pan_index].SuperframeSpec);
-       printfUART("lqi %i\n", PANDescriptorList[best_pan_index].lqi);
-       
-       coordinator_addr[0] = 0x00000001;
-       
-       coordinator_addr[1] = (uint32_t)PANDescriptorList[best_pan_index].CoordAddress;
-       
-       //pan_des = PANDescriptorList[best_pan_index];
-
-       
-       //BUILD the PAN descriptor of the COORDINATOR
-       //assuming that the adress is short
-       pan_des.CoordAddrMode = SHORT_ADDRESS;
-       pan_des.CoordPANId = PANDescriptorList[best_pan_index].CoordAddress;
-       pan_des.CoordAddress0=0x00000000;
-       pan_des.CoordAddress1=0x00000000;
-       pan_des.LogicalChannel=PANDescriptorList[best_pan_index].LogicalChannel;
-       //superframe specification field
-       pan_des.SuperframeSpec = PANDescriptorList[best_pan_index].SuperframeSpec;
-       
-       pan_des.GTSPermit=0x01;
-       pan_des.LinkQuality=0x00;
-       pan_des.TimeStamp=0x000000;
-       pan_des.SecurityUse=0;
-       pan_des.ACLEntry=0x00;
-       pan_des.SecurityFailure=0x00;
-       
-       received_beacon_count=0;
-       go_associate=1;
-       //enables the TimerAsync events, in order to enable the synchronization with the PAN coordinator
-       call MLME_SYNC.request(PANDescriptorList[best_pan_index].LogicalChannel,0);
-       
-       
-       
-       return SUCCESS;
-}
-
-/*****************************************************************************************************/  
-/**************************************MLME-ORPHAN****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
-{
-
-       uint16_t assigned_address;
-       
-       assigned_address = search_associated_devices(OrphanAddress[0],OrphanAddress[1]);
-       
-       if (assigned_address == 0x0000)
-       {
-               printfUART("not my child\n","");
-       }
-       else
-       {
-               //printfUART("my child\n","");
-               call MLME_ORPHAN.response(OrphanAddress,assigned_address,0x01, 0x00);
-       }
-
-       return SUCCESS;
-}
-
-       uint16_t search_associated_devices(uint32_t ext1, uint32_t ext2)
-       {
-               int i;
-               
-               for(i=0;i<4;i++)
-               {
-                       //printfUART("ad %i %i %i\n",associated_devices[i].extended1,associated_devices[i].extended2,associated_devices[i].assigned_short);
-                       if(associated_devices[i].extended1 == ext1 && associated_devices[i].extended2 == ext2 )
-                       {
-                       
-                               return associated_devices[i].assigned_short;
-                       }
-               
-               }
-               
-               return 0x0000;
-       }
-
-/*****************************************************************************************************/  
-/**************************************MLME-RESET*****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_RESET.confirm(uint8_t status)
-{
-
-
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-SYNC-LOSS*************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
-{
-               printfUART("SL\n","");
-               
-               call MLME_SCAN.request(ORPHAN_SCAN,0xFFFFFFFF,7);
-
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-GTS*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
-{
-
-
-
-       return SUCCESS;
-}
-
-event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
-{
-
-
-
-       return SUCCESS;
-}
-
-/*****************************************************************************************************/  
-/**************************************MLME-BEACON NOTIFY*********************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
-{
-       
-       if (go_associate==1)
-       {
-               received_beacon_count++;
-               
-               printfUART("bn %i\n", received_beacon_count);
-               
-               if (received_beacon_count==5)
-               {
-                               printfUART("sa \n", "");
-                               go_associate=0;
-                               call MLME_ASSOCIATE.request(pan_des.LogicalChannel,SHORT_ADDRESS,pan_des.CoordPANId,coordinator_addr,0x00,0x00);
-               
-               
-               }
-               
-       }
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-START*****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_START.confirm(uint8_t status)
-{
-       
-       
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**********************                                  MLME-SET                          ******************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
-{
-       
-       
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/*************************                     MLME-GET                            ******************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
-{
-       
-       
-       return SUCCESS;
-}
-       
-/*****************************************************************************************************/  
-/**************************************MLME-ASSOCIATE*************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
-{
-               //the coordinator device receives the association request and assigns the device with a short address
-               address_poll ++;
-               number_associations++;
-               
-               printfUART("address pool: %i %i\n", address_poll,number_associations);
-               
-               call MLME_ASSOCIATE.response(DeviceAddress,address_poll, CMD_RESP_ASSOCIATION_SUCCESSFUL, 0);
-       return SUCCESS;
-}
-
-event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
-{
-
-//the end device receives the association confirm and activates the data frame send timer
-       uint8_t v_temp[2];
-       
-       printfUART("MLME_ASSOCIATE.confirm\n", "");
-
-       printfUART("Short: %x\n", AssocShortAddress);
-       printfUART("Status: %i\n", status);
-       
-       if (AssocShortAddress == 0x0000)
-       {
-               //call Timer0.startOneShot(8000);
-       
-       }
-       else
-       {
-               
-               my_short_address = AssocShortAddress;
-                       
-               v_temp[0] = (my_short_address >> 8);
-               v_temp[1] = my_short_address;
-               
-               //call Leds.redOn();
-               call MLME_SET.request(MACSHORTADDRESS,v_temp);
-               
-               call Timer_Send.startPeriodic(3000);
-               
-               call Timer0.stop();
-       }
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-DISASSOCIATE**********************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
-{
-       return SUCCESS;
-}
-  
-event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
-{
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/*****************************************************************************************************/  
-/****************                                      MCPS EVENTS                              *************************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/  
-
-
-/*****************************************************************************************************/  
-/*********************                                 MCPS-DATA                          ***************************************/
-/*****************************************************************************************************/ 
-event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
-{
-       
-return SUCCESS;
-}  
-event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
-{
-       //call Leds.led1Toggle();
-       
-return SUCCESS;
-}
-
-
-
-void try_disassociation()
-{
-
-       uint32_t coordinator_addr1[2];
-       
-       coordinator_addr1[0] = 0x00000001;
-       
-       coordinator_addr1[1] = 0x00000001;
-       
-       call MLME_DISASSOCIATE.request(coordinator_addr1,MAC_PAN_DEVICE_LEAVE,0x00);
-       
-
-return;
-}
-  
-}
-
diff --git a/tos/lib/net/zigbee/apps/AssociationExample/AssociationExampleP.nc b/tos/lib/net/zigbee/apps/AssociationExample/AssociationExampleP.nc
new file mode 100644 (file)
index 0000000..6ba8d55
--- /dev/null
@@ -0,0 +1,489 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+#include <Timer.h>
+#include "printfUART.h"
+
+module AssociationExampleP {
+
+       uses interface Boot;
+       uses interface Leds;
+       
+       uses interface Timer<TMilli> as Timer0;
+       
+       uses interface Timer<TMilli> as Timer_Send;
+       //MAC interfaces
+       
+       uses interface MLME_START;
+       
+       uses interface MLME_GET;
+       uses interface MLME_SET;
+       
+       uses interface MLME_BEACON_NOTIFY;
+       uses interface MLME_GTS;
+       
+       uses interface MLME_ASSOCIATE;
+       uses interface MLME_DISASSOCIATE;
+       
+       uses interface MLME_ORPHAN;
+       
+       uses interface MLME_SYNC;
+       uses interface MLME_SYNC_LOSS;
+       
+       uses interface MLME_RESET;
+       
+       uses interface MLME_SCAN;
+       
+       
+       uses interface MCPS_DATA;
+  
+}
+implementation {
+
+
+       //number of data frames sent after association and before dissassociation
+       uint16_t frame_counter=0;
+
+       //associated devices
+       uint16_t address_poll = 0x0003;
+               
+       neighbour_table associated_devices[4];
+       
+       uint16_t search_associated_devices(uint32_t ext1, uint32_t ext2);
+       
+       uint8_t number_associations =0;
+       
+       PANDescriptor pan_des;
+
+       void try_disassociation();
+       
+       uint16_t my_short_address= 0xffff;
+       
+       uint8_t received_beacon_count=0;
+       uint32_t coordinator_addr[2];
+       
+       uint8_t go_associate =0;
+
+  event void Boot.booted() {
+       
+       printfUART_init();
+       
+       if (TYPE_DEVICE == COORDINATOR)
+       {
+               //assign the short address of the device
+               my_short_address = 0x0000;
+               call Timer0.startOneShot(3000);
+       }
+       else
+       {
+               call Timer0.startOneShot(8000);
+       }
+
+  }
+
+
+event void Timer0.fired() {
+    
+       uint8_t v_temp[2];
+       uint32_t c_addr[2];
+
+       if (TYPE_DEVICE == COORDINATOR)
+       {
+       
+               associated_devices[0].extended1=0x00000002;
+               associated_devices[0].extended2=0x00000002;
+               associated_devices[0].assigned_short=0x0004;
+       
+               //set the MAC short address variable
+               v_temp[0] = (uint8_t)(my_short_address >> 8);
+               v_temp[1] = (uint8_t)(my_short_address );
+               
+               call MLME_SET.request(MACSHORTADDRESS,v_temp);
+       
+               //set the MAC PANID variable
+               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
+               v_temp[1] = (uint8_t)(MAC_PANID );
+               
+               call MLME_SET.request(MACPANID,v_temp);
+       
+               //start sending beacons
+               call MLME_START.request(MAC_PANID, LOGICAL_CHANNEL, BEACON_ORDER, SUPERFRAME_ORDER,1,0,0,0,0);
+               
+               //call Timer_Send.startPeriodic(3000);
+       }
+       else
+       {
+               //the device will try to scan all the channels looking for a suitable PAN coordinator
+               //only the ACTIVE SCAN/ED SCAN  and a full channel scan is implemented
+               //call MLME_SCAN.request(PASSIVE_SCAN,0xFFFFFFFF,7);
+               //call MLME_SCAN.request(ED_SCAN,0xFFFFFFFF,0x10);
+               
+               c_addr[0] = 0x00000000;
+               c_addr[1] = 0x00000000;
+               
+               call MLME_ASSOCIATE.request(0x15,SHORT_ADDRESS,0x1234,c_addr,0x00,0x00);
+               
+               //call Leds.redOn();
+               call Timer0.stop();
+       }
+}
+  
+event void Timer_Send.fired() {
+
+       uint32_t SrcAddr[2];
+       uint32_t DstAddr[2];
+       
+       uint8_t msdu_payload[4];
+       
+       frame_counter++;
+       
+       if (frame_counter == 5)
+       {
+               //after sending 5 data frames the device tries to dissassociate from the PAN
+               call Timer_Send.stop();
+               try_disassociation();
+       
+       }
+       else
+       {
+               if (my_short_address == 0x0000ffff)
+                       return;
+               
+               SrcAddr[0]=0x00000000;
+               SrcAddr[1]=my_short_address;
+               
+               DstAddr[0]=0x00000000;
+               DstAddr[1]=0x00000000;
+                               
+               call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DstAddr, 4, msdu_payload,1,set_txoptions(1,0,0,0));
+       }
+}
+
+/*****************************************************************************************************/  
+/**************************************MLME-SCAN*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
+{
+//the device channel scan ends with a scan confirm containing a list of the PANs (beacons received during the scan) 
+
+       int i;
+       uint8_t max_lqi=0;
+       uint8_t best_pan_index=0;
+       
+       //call Leds.redOff();
+       
+       printfUART("MLME_SCAN.confirm %i\n", ScanType);
+       
+       if (ScanType == ORPHAN_SCAN)
+       {
+               printfUART("new scan \n", "");
+       
+               call MLME_SCAN.request(PASSIVE_SCAN,0xFFFFFFFF,7);
+               return SUCCESS;
+       }
+       
+       
+       
+       if(ScanType == ED_SCAN)
+       {
+               for(i=0;i<ResultListSize;i++)
+               {
+                       printfUART("ED SCAN %i %i\n", (0x0A + i),EnergyDetectList[i]);
+               }
+               return SUCCESS;
+       }
+       
+       for (i=0; i<ResultListSize;i++)
+       {               /*
+                       printfUART("cord id %i", PANDescriptorList[i].CoordPANId);
+                       printfUART("CoordAddress %i", PANDescriptorList[i].CoordAddress);
+                       printfUART("LogicalChannel %i", PANDescriptorList[i].LogicalChannel);
+                       printfUART("SuperframeSpec %i", PANDescriptorList[i].SuperframeSpec);
+                       printfUART("lqi %i\n", PANDescriptorList[i].lqi);
+                       */
+               if(max_lqi < PANDescriptorList[i].lqi)
+               {
+                       max_lqi =PANDescriptorList[i].lqi;
+                       best_pan_index = i;
+               }
+       }
+       
+       printfUART("SELECTED cord id %i", PANDescriptorList[best_pan_index].CoordPANId);
+       printfUART("CoordAddress %i", PANDescriptorList[best_pan_index].CoordAddress);
+       printfUART("LogicalChannel %i", PANDescriptorList[best_pan_index].LogicalChannel);
+       printfUART("SuperframeSpec %i", PANDescriptorList[best_pan_index].SuperframeSpec);
+       printfUART("lqi %i\n", PANDescriptorList[best_pan_index].lqi);
+       
+       coordinator_addr[0] = 0x00000001;
+       
+       coordinator_addr[1] = (uint32_t)PANDescriptorList[best_pan_index].CoordAddress;
+       
+       //pan_des = PANDescriptorList[best_pan_index];
+
+       
+       //BUILD the PAN descriptor of the COORDINATOR
+       //assuming that the adress is short
+       pan_des.CoordAddrMode = SHORT_ADDRESS;
+       pan_des.CoordPANId = PANDescriptorList[best_pan_index].CoordAddress;
+       pan_des.CoordAddress0=0x00000000;
+       pan_des.CoordAddress1=0x00000000;
+       pan_des.LogicalChannel=PANDescriptorList[best_pan_index].LogicalChannel;
+       //superframe specification field
+       pan_des.SuperframeSpec = PANDescriptorList[best_pan_index].SuperframeSpec;
+       
+       pan_des.GTSPermit=0x01;
+       pan_des.LinkQuality=0x00;
+       pan_des.TimeStamp=0x000000;
+       pan_des.SecurityUse=0;
+       pan_des.ACLEntry=0x00;
+       pan_des.SecurityFailure=0x00;
+       
+       received_beacon_count=0;
+       go_associate=1;
+       //enables the TimerAsync events, in order to enable the synchronization with the PAN coordinator
+       call MLME_SYNC.request(PANDescriptorList[best_pan_index].LogicalChannel,0);
+       
+       
+       
+       return SUCCESS;
+}
+
+/*****************************************************************************************************/  
+/**************************************MLME-ORPHAN****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
+{
+
+       uint16_t assigned_address;
+       
+       assigned_address = search_associated_devices(OrphanAddress[0],OrphanAddress[1]);
+       
+       if (assigned_address == 0x0000)
+       {
+               printfUART("not my child\n","");
+       }
+       else
+       {
+               //printfUART("my child\n","");
+               call MLME_ORPHAN.response(OrphanAddress,assigned_address,0x01, 0x00);
+       }
+
+       return SUCCESS;
+}
+
+       uint16_t search_associated_devices(uint32_t ext1, uint32_t ext2)
+       {
+               int i;
+               
+               for(i=0;i<4;i++)
+               {
+                       //printfUART("ad %i %i %i\n",associated_devices[i].extended1,associated_devices[i].extended2,associated_devices[i].assigned_short);
+                       if(associated_devices[i].extended1 == ext1 && associated_devices[i].extended2 == ext2 )
+                       {
+                       
+                               return associated_devices[i].assigned_short;
+                       }
+               
+               }
+               
+               return 0x0000;
+       }
+
+/*****************************************************************************************************/  
+/**************************************MLME-RESET*****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_RESET.confirm(uint8_t status)
+{
+
+
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-SYNC-LOSS*************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
+{
+               printfUART("SL\n","");
+               
+               call MLME_SCAN.request(ORPHAN_SCAN,0xFFFFFFFF,7);
+
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-GTS*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
+{
+
+
+
+       return SUCCESS;
+}
+
+event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
+{
+
+
+
+       return SUCCESS;
+}
+
+/*****************************************************************************************************/  
+/**************************************MLME-BEACON NOTIFY*********************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
+{
+       
+       if (go_associate==1)
+       {
+               received_beacon_count++;
+               
+               printfUART("bn %i\n", received_beacon_count);
+               
+               if (received_beacon_count==5)
+               {
+                               printfUART("sa \n", "");
+                               go_associate=0;
+                               call MLME_ASSOCIATE.request(pan_des.LogicalChannel,SHORT_ADDRESS,pan_des.CoordPANId,coordinator_addr,0x00,0x00);
+               
+               
+               }
+               
+       }
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-START*****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_START.confirm(uint8_t status)
+{
+       
+       
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**********************                                  MLME-SET                          ******************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
+{
+       
+       
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/*************************                     MLME-GET                            ******************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
+{
+       
+       
+       return SUCCESS;
+}
+       
+/*****************************************************************************************************/  
+/**************************************MLME-ASSOCIATE*************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
+{
+               //the coordinator device receives the association request and assigns the device with a short address
+               address_poll ++;
+               number_associations++;
+               
+               printfUART("address pool: %i %i\n", address_poll,number_associations);
+               
+               call MLME_ASSOCIATE.response(DeviceAddress,address_poll, CMD_RESP_ASSOCIATION_SUCCESSFUL, 0);
+       return SUCCESS;
+}
+
+event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
+{
+
+//the end device receives the association confirm and activates the data frame send timer
+       uint8_t v_temp[2];
+       
+       printfUART("MLME_ASSOCIATE.confirm\n", "");
+
+       printfUART("Short: %x\n", AssocShortAddress);
+       printfUART("Status: %i\n", status);
+       
+       if (AssocShortAddress == 0x0000)
+       {
+               //call Timer0.startOneShot(8000);
+       
+       }
+       else
+       {
+               
+               my_short_address = AssocShortAddress;
+                       
+               v_temp[0] = (my_short_address >> 8);
+               v_temp[1] = my_short_address;
+               
+               //call Leds.redOn();
+               call MLME_SET.request(MACSHORTADDRESS,v_temp);
+               
+               call Timer_Send.startPeriodic(3000);
+               
+               call Timer0.stop();
+       }
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-DISASSOCIATE**********************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
+{
+       return SUCCESS;
+}
+  
+event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
+{
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/*****************************************************************************************************/  
+/****************                                      MCPS EVENTS                              *************************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/  
+
+
+/*****************************************************************************************************/  
+/*********************                                 MCPS-DATA                          ***************************************/
+/*****************************************************************************************************/ 
+event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
+{
+       
+return SUCCESS;
+}  
+event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
+{
+       //call Leds.led1Toggle();
+       
+return SUCCESS;
+}
+
+
+
+void try_disassociation()
+{
+
+       uint32_t coordinator_addr1[2];
+       
+       coordinator_addr1[0] = 0x00000001;
+       
+       coordinator_addr1[1] = 0x00000001;
+       
+       call MLME_DISASSOCIATE.request(coordinator_addr1,MAC_PAN_DEVICE_LEAVE,0x00);
+       
+
+return;
+}
+  
+}
+
index 61dcca8f0226bab6dc8a9d9e4795c5f45466ca90..3d1ca3b4cffa0c1dbf710e0579d6418fa2f11331 100644 (file)
@@ -1,4 +1,4 @@
-COMPONENT=AssociationExample
+COMPONENT=AssociationExampleC
 
 PFLAGS +=      -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/includes \
                        -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/mac \
diff --git a/tos/lib/net/zigbee/apps/DataSendExample/DataSendExample.nc b/tos/lib/net/zigbee/apps/DataSendExample/DataSendExample.nc
deleted file mode 100644 (file)
index 1463b31..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- */
-#include <Timer.h>
-
-#include "datasendexample.h"
-#include "phy_const.h"
-#include "phy_enumerations.h"
-#include "mac_const.h"
-#include "mac_enumerations.h"
-#include "mac_func.h"
-configuration DataSendExample {
-}
-implementation
-{
-  components MainC;
-  components LedsC;
-  components DataSendExampleM;
-    
-  DataSendExampleM.Boot -> MainC;
-    
-  components Mac;
-  
-  DataSendExampleM.Leds -> LedsC;
-  
-  components new TimerMilliC() as Timer0;
-  DataSendExampleM.Timer0 -> Timer0;
-   
-  components new TimerMilliC() as Timer_Send;
-  DataSendExampleM.Timer_Send ->Timer_Send;
-   
-   
-  //MAC interfaces
-  
-  DataSendExampleM.MLME_START -> Mac.MLME_START;
-  
-  DataSendExampleM.MLME_GET ->Mac.MLME_GET;
-  DataSendExampleM.MLME_SET ->Mac.MLME_SET;
-  
-  DataSendExampleM.MLME_BEACON_NOTIFY ->Mac.MLME_BEACON_NOTIFY;
-  DataSendExampleM.MLME_GTS -> Mac.MLME_GTS;
-  
-  DataSendExampleM.MLME_ASSOCIATE->Mac.MLME_ASSOCIATE;
-  DataSendExampleM.MLME_DISASSOCIATE->Mac.MLME_DISASSOCIATE;
-  
-  DataSendExampleM.MLME_ORPHAN->Mac.MLME_ORPHAN;
-  DataSendExampleM.MLME_SYNC->Mac.MLME_SYNC;
-  DataSendExampleM.MLME_SYNC_LOSS->Mac.MLME_SYNC_LOSS;
-  DataSendExampleM.MLME_RESET->Mac.MLME_RESET;
-  
-  DataSendExampleM.MLME_SCAN->Mac.MLME_SCAN;
-  
-  DataSendExampleM.MCPS_DATA->Mac.MCPS_DATA;
-
-  
-}
-
diff --git a/tos/lib/net/zigbee/apps/DataSendExample/DataSendExampleC.nc b/tos/lib/net/zigbee/apps/DataSendExample/DataSendExampleC.nc
new file mode 100644 (file)
index 0000000..d4ee637
--- /dev/null
@@ -0,0 +1,60 @@
+/**
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ */
+#include <Timer.h>
+
+#include "datasendexample.h"
+#include "phy_const.h"
+#include "phy_enumerations.h"
+#include "mac_const.h"
+#include "mac_enumerations.h"
+#include "mac_func.h"
+configuration DataSendExampleC {
+}
+implementation
+{
+  components MainC;
+  components LedsC;
+  components DataSendExampleP;
+    
+  DataSendExampleP.Boot -> MainC;
+    
+  components MacC;
+  
+  DataSendExampleP.Leds -> LedsC;
+  
+  components new TimerMilliC() as Timer0;
+  DataSendExampleP.Timer0 -> Timer0;
+   
+  components new TimerMilliC() as Timer_Send;
+  DataSendExampleP.Timer_Send ->Timer_Send;
+   
+   
+  //MAC interfaces
+  
+  DataSendExampleP.MLME_START -> MacC.MLME_START;
+  
+  DataSendExampleP.MLME_GET ->MacC.MLME_GET;
+  DataSendExampleP.MLME_SET ->MacC.MLME_SET;
+  
+  DataSendExampleP.MLME_BEACON_NOTIFY ->MacC.MLME_BEACON_NOTIFY;
+  DataSendExampleP.MLME_GTS -> MacC.MLME_GTS;
+  
+  DataSendExampleP.MLME_ASSOCIATE->MacC.MLME_ASSOCIATE;
+  DataSendExampleP.MLME_DISASSOCIATE->MacC.MLME_DISASSOCIATE;
+  
+  DataSendExampleP.MLME_ORPHAN->MacC.MLME_ORPHAN;
+  DataSendExampleP.MLME_SYNC->MacC.MLME_SYNC;
+  DataSendExampleP.MLME_SYNC_LOSS->MacC.MLME_SYNC_LOSS;
+  DataSendExampleP.MLME_RESET->MacC.MLME_RESET;
+  
+  DataSendExampleP.MLME_SCAN->MacC.MLME_SCAN;
+  
+  DataSendExampleP.MCPS_DATA->MacC.MCPS_DATA;
+
+  
+}
+
diff --git a/tos/lib/net/zigbee/apps/DataSendExample/DataSendExampleM.nc b/tos/lib/net/zigbee/apps/DataSendExample/DataSendExampleM.nc
deleted file mode 100644 (file)
index fd8760b..0000000
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- *
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-#include <Timer.h>
-#include "printfUART.h"
-
-module DataSendExampleM {
-
-       uses interface Boot;
-       uses interface Leds;
-       
-       uses interface Timer<TMilli> as Timer0;
-       
-       uses interface Timer<TMilli> as Timer_Send;
-       //MAC interfaces
-       
-       uses interface MLME_START;
-       
-       uses interface MLME_GET;
-       uses interface MLME_SET;
-       
-       uses interface MLME_BEACON_NOTIFY;
-       uses interface MLME_GTS;
-       
-       uses interface MLME_ASSOCIATE;
-       uses interface MLME_DISASSOCIATE;
-       
-       uses interface MLME_ORPHAN;
-       
-       uses interface MLME_SYNC;
-       uses interface MLME_SYNC_LOSS;
-               
-       uses interface MLME_RESET;
-       
-       uses interface MLME_SCAN;
-       
-       uses interface MCPS_DATA;
-  
-}
-implementation {
-
-       uint8_t beacon_present=0;
-       uint8_t on_sync=0;
-       
-       PANDescriptor pan_des;
-       
-       uint32_t my_short_address=0x00000000;
-       uint32_t my_pan_id=0x00001234;
-       
-       uint32_t DestinationMote[2];
-       
-
-  event void Boot.booted() {
-       
-       printfUART_init();
-       
-       printfUART("i_am_pan: %i\n", TYPE_DEVICE);
-       
-       DestinationMote[0]=0x00000000;
-       DestinationMote[1]=0x00000002;
-       
-       if (TYPE_DEVICE == COORDINATOR)
-       {
-               my_short_address = 0x0000;
-               call Timer0.startOneShot(3000);
-       }
-       else
-       {
-               call Timer0.startOneShot(8000);
-       }
-
-  }
-
-  event void Timer0.fired() {
-    
-       uint8_t v_temp[2];
-       
-       
-       if (TYPE_DEVICE == END_DEVICE)
-       {
-       
-               my_short_address = TOS_NODE_ID;
-               
-               //set the MAC short address variable
-               v_temp[0] = (uint8_t)(my_short_address >> 8);
-               v_temp[1] = (uint8_t)(my_short_address );
-               
-               call MLME_SET.request(MACSHORTADDRESS,v_temp);
-       
-               //set the MAC PANID variable
-               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
-               v_temp[1] = (uint8_t)(MAC_PANID );
-               
-               call MLME_SET.request(MACPANID,v_temp);
-               
-               call Timer_Send.startPeriodic(3000);
-
-       }
-       else
-       {
-               //set the MAC short address variable
-               v_temp[0] = (uint8_t)(my_short_address >> 8);
-               v_temp[1] = (uint8_t)(my_short_address );
-               
-               call MLME_SET.request(MACSHORTADDRESS,v_temp);
-       
-               //set the MAC PANID variable
-               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
-               v_temp[1] = (uint8_t)(MAC_PANID );
-               
-               call MLME_SET.request(MACPANID,v_temp);
-       
-               //start sending beacons
-               call MLME_START.request(MAC_PANID, LOGICAL_CHANNEL, BEACON_ORDER, SUPERFRAME_ORDER,1,0,0,0,0);
-               
-               //call Timer_send.start(TIMER_REPEAT,8000);
-       }
-       
-       
-       
-       
-  }
-  
-event void Timer_Send.fired() {
-       
-       
-       uint32_t SrcAddr[2];
-       
-       uint8_t msdu_payload[4];
-       
-       SrcAddr[0]=0x00000000;
-       SrcAddr[1]=TOS_NODE_ID;
-       
-       //DestinationMote[0]=0x00000000;
-       //DestinationMote[1]=0x0000FFFF;
-       
-       
-       
-       if(TYPE_DEVICE == COORDINATOR)
-       {
-       
-                       SrcAddr[0]=0x00000000;
-                       SrcAddr[1]=TOS_NODE_ID;
-                       
-                       if (DestinationMote[1]==0x00000002)
-                       {
-                               DestinationMote[1]=0x00000003;
-                       }else{
-                               DestinationMote[1]=0x00000002;
-                       }
-                       //printfUART("send to: %i\n", DestinationMote[1]);
-                       //call Leds.greenToggle();
-                                                                                                                                                                               //set_txoptions(ack, gts, indirect_transmission, security)
-                       call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DestinationMote, 4, msdu_payload,1,set_txoptions(1,0,0,0));
-       }
-       else
-       {
-       
-                       DestinationMote[0]=0x00000000;
-                       DestinationMote[1]=0x00000000;
-                                                                                                                                                                                               //set_txoptions(ack, gts, indirect_transmission, security)
-                       call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DestinationMote, 4, msdu_payload,1,set_txoptions(1,0,0,0));
-       }
-
-       
-       }
-/*****************************************************************************************************/  
-/**************************************MLME-SCAN*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
-{
-
-       
-       return SUCCESS;
-}
-
-/*****************************************************************************************************/  
-/**************************************MLME-ORPHAN*******************************************************/
-/*****************************************************************************************************/ 
-  
-event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
-{
-
-return SUCCESS;
-}
-
-/*****************************************************************************************************/  
-/**************************************MLME-RESET*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_RESET.confirm(uint8_t status)
-{
-
-return SUCCESS;
-}
-
-
- /*****************************************************************************************************/  
-/**************************************MLME-SYNC-LOSS*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
-{
-
-return SUCCESS;
-}
-  
-  
-  /*****************************************************************************************************/  
-/**************************************MLME-GTS*******************************************************/
-/*****************************************************************************************************/ 
-
-event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
-{
-       
-       return SUCCESS;
-}
-
-event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
-{
-       return SUCCESS;
-}
-  /*****************************************************************************************************/  
-/**************************************MLME-BEACON NOTIFY*********************************************/
-/*****************************************************************************************************/ 
-
-event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
-{
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-START*****************************************************/
-/*****************************************************************************************************/ 
-    event error_t MLME_START.confirm(uint8_t status)
-       {
-       
-       
-       return SUCCESS;
-       }
-  /*****************************************************************************************************/  
-/**********************                                  MLME-SET                          ******************************************/
-/*****************************************************************************************************/ 
-  
-      event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
-       {
-       
-       
-       return SUCCESS;
-       }
-       /*****************************************************************************************************/  
-/*************************                     MLME-GET                            ******************************************/
-/*****************************************************************************************************/ 
-           event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
-       {
-       
-       
-       return SUCCESS;
-       }
-       
-       
-       /*****************************************************************************************************/  
-/**************************************MLME-ASSOCIATE*************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
-{
-
-       return SUCCESS;
-}
-
-event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
-{
-
-       return SUCCESS;
-}
-       /*****************************************************************************************************/  
-/**************************************MLME-DISASSOCIATE**********************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
-{
-       return SUCCESS;
-}
-  
-event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
-{
-       return SUCCESS;
-}
-  /*****************************************************************************************************/  
-/*****************************************************************************************************/  
-/****************                                      MCPS EVENTS                              *************************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/  
-
-
-/*****************************************************************************************************/  
-/*********************                                 MCPS-DATA                          ***************************************/
-/*****************************************************************************************************/ 
-event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
-{
-       
-return SUCCESS;
-}  
-event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
-{
-       //call Leds.led1Toggle();
-       
-return SUCCESS;
-}
-
-  
-}
-
diff --git a/tos/lib/net/zigbee/apps/DataSendExample/DataSendExampleP.nc b/tos/lib/net/zigbee/apps/DataSendExample/DataSendExampleP.nc
new file mode 100644 (file)
index 0000000..f9c3835
--- /dev/null
@@ -0,0 +1,315 @@
+/*
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+#include <Timer.h>
+#include "printfUART.h"
+
+module DataSendExampleP {
+
+       uses interface Boot;
+       uses interface Leds;
+       
+       uses interface Timer<TMilli> as Timer0;
+       
+       uses interface Timer<TMilli> as Timer_Send;
+       //MAC interfaces
+       
+       uses interface MLME_START;
+       
+       uses interface MLME_GET;
+       uses interface MLME_SET;
+       
+       uses interface MLME_BEACON_NOTIFY;
+       uses interface MLME_GTS;
+       
+       uses interface MLME_ASSOCIATE;
+       uses interface MLME_DISASSOCIATE;
+       
+       uses interface MLME_ORPHAN;
+       
+       uses interface MLME_SYNC;
+       uses interface MLME_SYNC_LOSS;
+               
+       uses interface MLME_RESET;
+       
+       uses interface MLME_SCAN;
+       
+       uses interface MCPS_DATA;
+  
+}
+implementation {
+
+       uint8_t beacon_present=0;
+       uint8_t on_sync=0;
+       
+       PANDescriptor pan_des;
+       
+       uint32_t my_short_address=0x00000000;
+       uint32_t my_pan_id=0x00001234;
+       
+       uint32_t DestinationMote[2];
+       
+
+  event void Boot.booted() {
+       
+       printfUART_init();
+       
+       printfUART("i_am_pan: %i\n", TYPE_DEVICE);
+       
+       DestinationMote[0]=0x00000000;
+       DestinationMote[1]=0x00000002;
+       
+       if (TYPE_DEVICE == COORDINATOR)
+       {
+               my_short_address = 0x0000;
+               call Timer0.startOneShot(3000);
+       }
+       else
+       {
+               call Timer0.startOneShot(8000);
+       }
+
+  }
+
+  event void Timer0.fired() {
+    
+       uint8_t v_temp[2];
+       
+       
+       if (TYPE_DEVICE == END_DEVICE)
+       {
+       
+               my_short_address = TOS_NODE_ID;
+               
+               //set the MAC short address variable
+               v_temp[0] = (uint8_t)(my_short_address >> 8);
+               v_temp[1] = (uint8_t)(my_short_address );
+               
+               call MLME_SET.request(MACSHORTADDRESS,v_temp);
+       
+               //set the MAC PANID variable
+               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
+               v_temp[1] = (uint8_t)(MAC_PANID );
+               
+               call MLME_SET.request(MACPANID,v_temp);
+               
+               call Timer_Send.startPeriodic(3000);
+
+       }
+       else
+       {
+               //set the MAC short address variable
+               v_temp[0] = (uint8_t)(my_short_address >> 8);
+               v_temp[1] = (uint8_t)(my_short_address );
+               
+               call MLME_SET.request(MACSHORTADDRESS,v_temp);
+       
+               //set the MAC PANID variable
+               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
+               v_temp[1] = (uint8_t)(MAC_PANID );
+               
+               call MLME_SET.request(MACPANID,v_temp);
+       
+               //start sending beacons
+               call MLME_START.request(MAC_PANID, LOGICAL_CHANNEL, BEACON_ORDER, SUPERFRAME_ORDER,1,0,0,0,0);
+               
+               //call Timer_send.start(TIMER_REPEAT,8000);
+       }
+       
+       
+       
+       
+  }
+  
+event void Timer_Send.fired() {
+       
+       
+       uint32_t SrcAddr[2];
+       
+       uint8_t msdu_payload[4];
+       
+       SrcAddr[0]=0x00000000;
+       SrcAddr[1]=TOS_NODE_ID;
+       
+       //DestinationMote[0]=0x00000000;
+       //DestinationMote[1]=0x0000FFFF;
+       
+       
+       
+       if(TYPE_DEVICE == COORDINATOR)
+       {
+       
+                       SrcAddr[0]=0x00000000;
+                       SrcAddr[1]=TOS_NODE_ID;
+                       
+                       if (DestinationMote[1]==0x00000002)
+                       {
+                               DestinationMote[1]=0x00000003;
+                       }else{
+                               DestinationMote[1]=0x00000002;
+                       }
+                       //printfUART("send to: %i\n", DestinationMote[1]);
+                       //call Leds.greenToggle();
+                                                                                                                                                                               //set_txoptions(ack, gts, indirect_transmission, security)
+                       call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DestinationMote, 4, msdu_payload,1,set_txoptions(1,0,0,0));
+       }
+       else
+       {
+       
+                       DestinationMote[0]=0x00000000;
+                       DestinationMote[1]=0x00000000;
+                                                                                                                                                                                               //set_txoptions(ack, gts, indirect_transmission, security)
+                       call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DestinationMote, 4, msdu_payload,1,set_txoptions(1,0,0,0));
+       }
+
+       
+       }
+/*****************************************************************************************************/  
+/**************************************MLME-SCAN*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
+{
+
+       
+       return SUCCESS;
+}
+
+/*****************************************************************************************************/  
+/**************************************MLME-ORPHAN*******************************************************/
+/*****************************************************************************************************/ 
+  
+event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
+{
+
+return SUCCESS;
+}
+
+/*****************************************************************************************************/  
+/**************************************MLME-RESET*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_RESET.confirm(uint8_t status)
+{
+
+return SUCCESS;
+}
+
+
+ /*****************************************************************************************************/  
+/**************************************MLME-SYNC-LOSS*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
+{
+
+return SUCCESS;
+}
+  
+  
+  /*****************************************************************************************************/  
+/**************************************MLME-GTS*******************************************************/
+/*****************************************************************************************************/ 
+
+event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
+{
+       
+       return SUCCESS;
+}
+
+event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
+{
+       return SUCCESS;
+}
+  /*****************************************************************************************************/  
+/**************************************MLME-BEACON NOTIFY*********************************************/
+/*****************************************************************************************************/ 
+
+event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
+{
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-START*****************************************************/
+/*****************************************************************************************************/ 
+    event error_t MLME_START.confirm(uint8_t status)
+       {
+       
+       
+       return SUCCESS;
+       }
+  /*****************************************************************************************************/  
+/**********************                                  MLME-SET                          ******************************************/
+/*****************************************************************************************************/ 
+  
+      event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
+       {
+       
+       
+       return SUCCESS;
+       }
+       /*****************************************************************************************************/  
+/*************************                     MLME-GET                            ******************************************/
+/*****************************************************************************************************/ 
+           event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
+       {
+       
+       
+       return SUCCESS;
+       }
+       
+       
+       /*****************************************************************************************************/  
+/**************************************MLME-ASSOCIATE*************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
+{
+
+       return SUCCESS;
+}
+
+event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
+{
+
+       return SUCCESS;
+}
+       /*****************************************************************************************************/  
+/**************************************MLME-DISASSOCIATE**********************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
+{
+       return SUCCESS;
+}
+  
+event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
+{
+       return SUCCESS;
+}
+  /*****************************************************************************************************/  
+/*****************************************************************************************************/  
+/****************                                      MCPS EVENTS                              *************************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/  
+
+
+/*****************************************************************************************************/  
+/*********************                                 MCPS-DATA                          ***************************************/
+/*****************************************************************************************************/ 
+event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
+{
+       
+return SUCCESS;
+}  
+event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
+{
+       //call Leds.led1Toggle();
+       
+return SUCCESS;
+}
+
+  
+}
+
index f9e6b4b5a9c1ca1cc9ae3b97ad0be203a8bf7ebc..24d32aba664a274a954035460b1e33c417d48617 100644 (file)
@@ -1,4 +1,4 @@
-COMPONENT=DataSendExample
+COMPONENT=DataSendExampleC
 
 PFLAGS +=      -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/includes \
                        -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/mac \
diff --git a/tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExample.nc b/tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExample.nc
deleted file mode 100644 (file)
index fda840e..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- */
-#include <Timer.h>
-
-#include "gtsmanagementexample.h"
-#include "phy_const.h"
-#include "phy_enumerations.h"
-#include "mac_const.h"
-#include "mac_enumerations.h"
-#include "mac_func.h"
-
-
-configuration GTSManagementExample {
-}
-implementation {
-
-  components MainC;
-  components LedsC;
-  components GTSManagementExampleM;
-    
-  GTSManagementExampleM.Boot -> MainC;
-    
-  components Mac;
-  
-  GTSManagementExampleM.Leds -> LedsC;
-  
-  components new TimerMilliC() as Timer0;
-  GTSManagementExampleM.Timer0 -> Timer0;
-   
-  components new TimerMilliC() as Timer_Send;
-  GTSManagementExampleM.Timer_Send ->Timer_Send;
-   
-   
-  //MAC interfaces
-  
-  GTSManagementExampleM.MLME_START -> Mac.MLME_START;
-  
-  GTSManagementExampleM.MLME_GET ->Mac.MLME_GET;
-  GTSManagementExampleM.MLME_SET ->Mac.MLME_SET;
-  
-  GTSManagementExampleM.MLME_BEACON_NOTIFY ->Mac.MLME_BEACON_NOTIFY;
-  GTSManagementExampleM.MLME_GTS -> Mac.MLME_GTS;
-  
-  GTSManagementExampleM.MLME_ASSOCIATE->Mac.MLME_ASSOCIATE;
-  GTSManagementExampleM.MLME_DISASSOCIATE->Mac.MLME_DISASSOCIATE;
-  
-  GTSManagementExampleM.MLME_ORPHAN->Mac.MLME_ORPHAN;
-  GTSManagementExampleM.MLME_SYNC->Mac.MLME_SYNC;
-  GTSManagementExampleM.MLME_SYNC_LOSS->Mac.MLME_SYNC_LOSS;
-  GTSManagementExampleM.MLME_RESET->Mac.MLME_RESET;
-  
-  GTSManagementExampleM.MLME_SCAN->Mac.MLME_SCAN;
-  
-  
-  GTSManagementExampleM.MCPS_DATA->Mac.MCPS_DATA;
-  
-  
-}
-
diff --git a/tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExampleC.nc b/tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExampleC.nc
new file mode 100644 (file)
index 0000000..dd5a929
--- /dev/null
@@ -0,0 +1,61 @@
+/**
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ */
+#include <Timer.h>
+
+#include "gtsmanagementexample.h"
+#include "phy_const.h"
+#include "phy_enumerations.h"
+#include "mac_const.h"
+#include "mac_enumerations.h"
+#include "mac_func.h"
+
+
+configuration GTSManagementExampleC {
+}
+implementation {
+
+  components MainC;
+  components LedsC;
+  components GTSManagementExampleP;
+    
+  GTSManagementExampleP.Boot -> MainC;
+    
+  components MacC;
+  
+  GTSManagementExampleP.Leds -> LedsC;
+  
+  components new TimerMilliC() as Timer0;
+  GTSManagementExampleP.Timer0 -> Timer0;
+   
+  components new TimerMilliC() as Timer_Send;
+  GTSManagementExampleP.Timer_Send ->Timer_Send;
+   
+   
+  //MAC interfaces
+  
+  GTSManagementExampleP.MLME_START -> MacC.MLME_START;
+  
+  GTSManagementExampleP.MLME_GET ->MacC.MLME_GET;
+  GTSManagementExampleP.MLME_SET ->MacC.MLME_SET;
+  
+  GTSManagementExampleP.MLME_BEACON_NOTIFY ->MacC.MLME_BEACON_NOTIFY;
+  GTSManagementExampleP.MLME_GTS -> MacC.MLME_GTS;
+  
+  GTSManagementExampleP.MLME_ASSOCIATE->MacC.MLME_ASSOCIATE;
+  GTSManagementExampleP.MLME_DISASSOCIATE->MacC.MLME_DISASSOCIATE;
+  
+  GTSManagementExampleP.MLME_ORPHAN->MacC.MLME_ORPHAN;
+  GTSManagementExampleP.MLME_SYNC->MacC.MLME_SYNC;
+  GTSManagementExampleP.MLME_SYNC_LOSS->MacC.MLME_SYNC_LOSS;
+  GTSManagementExampleP.MLME_RESET->MacC.MLME_RESET;
+  
+  GTSManagementExampleP.MLME_SCAN->MacC.MLME_SCAN;
+  
+  
+  GTSManagementExampleP.MCPS_DATA->MacC.MCPS_DATA;
+  
+  
+}
+
diff --git a/tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExampleM.nc b/tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExampleM.nc
deleted file mode 100644 (file)
index 5ba5556..0000000
+++ /dev/null
@@ -1,339 +0,0 @@
-/*
- *
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-#include <Timer.h>
-#include "printfUART.h"
-
-module GTSManagementExampleM {
-
-       uses interface Boot;
-       uses interface Leds;
-       
-       uses interface Timer<TMilli> as Timer0;
-       
-       uses interface Timer<TMilli> as Timer_Send;
-       //MAC interfaces
-       
-       uses interface MLME_START;
-       
-       uses interface MLME_GET;
-       uses interface MLME_SET;
-       
-       uses interface MLME_BEACON_NOTIFY;
-       uses interface MLME_GTS;
-       
-       uses interface MLME_ASSOCIATE;
-       uses interface MLME_DISASSOCIATE;
-       
-       uses interface MLME_ORPHAN;
-       
-       uses interface MLME_SYNC;
-       uses interface MLME_SYNC_LOSS;
-       
-       uses interface MLME_RESET;
-       
-       uses interface MLME_SCAN;
-       
-       uses interface MCPS_DATA;
-  
-}
-implementation {
-
-
-       uint8_t beacon_present=0;
-       uint8_t on_sync=0;
-       uint8_t gts_allocated=0;
-       
-       uint8_t gts_superframe_count=0;
-       
-       PANDescriptor pan_des;
-       
-       uint32_t my_short_address=0x00000000;
-       uint32_t my_pan_id=0x00000001;
-       
-       
-
-  event void Boot.booted() {
-       
-       printfUART_init();
-       
-       if (TYPE_DEVICE == COORDINATOR)
-       {
-               //assign the short address of the device
-               my_short_address = 0x0000;
-               call Timer0.startOneShot(5000);
-       }
-       else
-       {
-               call Timer0.startOneShot(8000);
-       }
-
-  }
-
-
-  event void Timer0.fired() {
-    
-       uint8_t v_temp[2];
-       
-       
-
-       if (TYPE_DEVICE == COORDINATOR)
-       {
-       
-               //set the MAC short address variable
-               v_temp[0] = (uint8_t)(my_short_address >> 8);
-               v_temp[1] = (uint8_t)(my_short_address );
-               
-               call MLME_SET.request(MACSHORTADDRESS,v_temp);
-       
-               //set the MAC PANID variable
-               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
-               v_temp[1] = (uint8_t)(MAC_PANID );
-               
-               call MLME_SET.request(MACPANID,v_temp);
-       
-               //start sending beacons
-               call MLME_START.request(MAC_PANID, LOGICAL_CHANNEL, BEACON_ORDER, SUPERFRAME_ORDER,1,0,0,0,0);
-               
-               //call Timer_Send.startPeriodic(3000);
-       }
-       else
-       {
-               my_short_address = TOS_NODE_ID;
-               v_temp[0] = (uint8_t)(my_short_address >> 8);
-               v_temp[1] = (uint8_t)(my_short_address );
-               
-               call MLME_SET.request(MACSHORTADDRESS,v_temp);
-               
-               //call Leds.greenOn();
-               gts_superframe_count=0;
-               
-               
-               printfUART("GTS req: %i\n", TYPE_DEVICE);
-               
-               
-               //allocate a transmission GTS - enables a GTS time slot allocation for the device transmission to the PAN Coordinator
-               call MLME_GTS.request(set_gts_characteristics(1, GTS_TX_ONLY,1),0x00);
-               
-               //allocate a transmission GTS - enables a GTS time slot allocation for the PAN coordinator transmission to the device
-               //call MLME_GTS.request(set_gts_characteristics(1, GTS_RX_ONLY,1),0x00);
-               
-               
-               //enable the transmission of the device to the PAN coordinator in the allocated transmit GTS
-               call Timer_Send.startPeriodic(1000);
-
-       }
-       
-  }
-  
-event void Timer_Send.fired() {
-       
-       
-       uint32_t SrcAddr[2];
-       uint32_t DstAddr[2];
-       uint8_t msdu_payload[4];
-       
-       if (TYPE_DEVICE == COORDINATOR)
-       {
-               SrcAddr[0]=0x00000000;
-               SrcAddr[1]=TOS_NODE_ID;
-       
-               DstAddr[0]=0x00000000;
-               DstAddr[1]=0x00000002;
-       
-               call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DstAddr, 4, msdu_payload,1,set_txoptions(1,1,0,0));
-       }
-       else
-       {
-           call Leds.led1Toggle();
-               
-               
-               SrcAddr[0]=0x00000000;
-               SrcAddr[1]=TOS_NODE_ID;
-       
-               DstAddr[0]=0x00000000;
-               DstAddr[1]=0x00000000;
-       
-               call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DstAddr, 4, msdu_payload,1,set_txoptions(1,1,0,0));
-       }
-       
-}
-
-
-/*****************************************************************************************************/  
-/**************************************MLME-SCAN*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
-{
-
-       return SUCCESS;
-}
-
-/*****************************************************************************************************/  
-/**************************************MLME-ORPHAN****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
-{
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-RESET*****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_RESET.confirm(uint8_t status)
-{
-
-
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-SYNC-LOSS*************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
-{
-
-       return SUCCESS;
-}
-  
-/*****************************************************************************************************/  
-/**************************************MLME-GTS*******************************************************/
-/*****************************************************************************************************/ 
-
-event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
-{
-       switch(status)
-       {
-               case MAC_SUCCESS:  gts_allocated=1;
-                                                       call Leds.led1Toggle();
-                                                       break;
-               
-               case MAC_DENIED: gts_allocated=0;
-                                                       break;
-               
-               case MAC_NO_SHORT_ADDRESS: gts_allocated=0;
-                                                                       break;
-               
-               case MAC_CHANNEL_ACCESS_FAILURE: gts_allocated=0;
-                                                                       break;
-               
-               case MAC_NO_ACK: gts_allocated=0;break;
-               
-               case MAC_NO_DATA: gts_allocated=0;break;
-                                               
-               
-               default: break;
-       
-       }
-
-       return SUCCESS;
-}
-
-event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
-{
-       return SUCCESS;
-}
-  /*****************************************************************************************************/  
-/**************************************MLME-BEACON NOTIFY*********************************************/
-/*****************************************************************************************************/ 
-
-event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
-{
-       gts_superframe_count++;
-       if (gts_superframe_count==30)
-       {
-               //call Leds.greenOff();
-               call MLME_GTS.request(set_gts_characteristics(1, GTS_TX_ONLY,0),0x00);
-       }
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-START*****************************************************/
-/*****************************************************************************************************/ 
-    event error_t MLME_START.confirm(uint8_t status)
-       {
-       
-       
-       return SUCCESS;
-       }
-  /*****************************************************************************************************/  
-/**********************                                  MLME-SET                          ******************************************/
-/*****************************************************************************************************/ 
-  
-      event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
-       {
-       
-       
-       return SUCCESS;
-       }
-       /*****************************************************************************************************/  
-/*************************                     MLME-GET                            ******************************************/
-/*****************************************************************************************************/ 
-           event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
-       {
-       
-       
-       return SUCCESS;
-       }
-       
-       
-       /*****************************************************************************************************/  
-/**************************************MLME-ASSOCIATE*************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
-{
-
-       return SUCCESS;
-}
-
-event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
-{
-
-       return SUCCESS;
-}
-       /*****************************************************************************************************/  
-/**************************************MLME-DISASSOCIATE**********************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
-{
-       return SUCCESS;
-}
-  
-event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
-{
-       return SUCCESS;
-}
-  /*****************************************************************************************************/  
-/*****************************************************************************************************/  
-/****************                                      MCPS EVENTS                              *************************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/  
-
-
-/*****************************************************************************************************/  
-/*********************                                 MCPS-DATA                          ***************************************/
-/*****************************************************************************************************/ 
-event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
-{
-       
-return SUCCESS;
-}  
-event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
-{
-       
-       
-return SUCCESS;
-}
-
-  
-}
-
diff --git a/tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExampleP.nc b/tos/lib/net/zigbee/apps/GTSManagementExample/GTSManagementExampleP.nc
new file mode 100644 (file)
index 0000000..ff859d0
--- /dev/null
@@ -0,0 +1,339 @@
+/*
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+#include <Timer.h>
+#include "printfUART.h"
+
+module GTSManagementExampleP {
+
+       uses interface Boot;
+       uses interface Leds;
+       
+       uses interface Timer<TMilli> as Timer0;
+       
+       uses interface Timer<TMilli> as Timer_Send;
+       //MAC interfaces
+       
+       uses interface MLME_START;
+       
+       uses interface MLME_GET;
+       uses interface MLME_SET;
+       
+       uses interface MLME_BEACON_NOTIFY;
+       uses interface MLME_GTS;
+       
+       uses interface MLME_ASSOCIATE;
+       uses interface MLME_DISASSOCIATE;
+       
+       uses interface MLME_ORPHAN;
+       
+       uses interface MLME_SYNC;
+       uses interface MLME_SYNC_LOSS;
+       
+       uses interface MLME_RESET;
+       
+       uses interface MLME_SCAN;
+       
+       uses interface MCPS_DATA;
+  
+}
+implementation {
+
+
+       uint8_t beacon_present=0;
+       uint8_t on_sync=0;
+       uint8_t gts_allocated=0;
+       
+       uint8_t gts_superframe_count=0;
+       
+       PANDescriptor pan_des;
+       
+       uint32_t my_short_address=0x00000000;
+       uint32_t my_pan_id=0x00000001;
+       
+       
+
+  event void Boot.booted() {
+       
+       printfUART_init();
+       
+       if (TYPE_DEVICE == COORDINATOR)
+       {
+               //assign the short address of the device
+               my_short_address = 0x0000;
+               call Timer0.startOneShot(5000);
+       }
+       else
+       {
+               call Timer0.startOneShot(8000);
+       }
+
+  }
+
+
+  event void Timer0.fired() {
+    
+       uint8_t v_temp[2];
+       
+       
+
+       if (TYPE_DEVICE == COORDINATOR)
+       {
+       
+               //set the MAC short address variable
+               v_temp[0] = (uint8_t)(my_short_address >> 8);
+               v_temp[1] = (uint8_t)(my_short_address );
+               
+               call MLME_SET.request(MACSHORTADDRESS,v_temp);
+       
+               //set the MAC PANID variable
+               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
+               v_temp[1] = (uint8_t)(MAC_PANID );
+               
+               call MLME_SET.request(MACPANID,v_temp);
+       
+               //start sending beacons
+               call MLME_START.request(MAC_PANID, LOGICAL_CHANNEL, BEACON_ORDER, SUPERFRAME_ORDER,1,0,0,0,0);
+               
+               //call Timer_Send.startPeriodic(3000);
+       }
+       else
+       {
+               my_short_address = TOS_NODE_ID;
+               v_temp[0] = (uint8_t)(my_short_address >> 8);
+               v_temp[1] = (uint8_t)(my_short_address );
+               
+               call MLME_SET.request(MACSHORTADDRESS,v_temp);
+               
+               //call Leds.greenOn();
+               gts_superframe_count=0;
+               
+               
+               printfUART("GTS req: %i\n", TYPE_DEVICE);
+               
+               
+               //allocate a transmission GTS - enables a GTS time slot allocation for the device transmission to the PAN Coordinator
+               call MLME_GTS.request(set_gts_characteristics(1, GTS_TX_ONLY,1),0x00);
+               
+               //allocate a transmission GTS - enables a GTS time slot allocation for the PAN coordinator transmission to the device
+               //call MLME_GTS.request(set_gts_characteristics(1, GTS_RX_ONLY,1),0x00);
+               
+               
+               //enable the transmission of the device to the PAN coordinator in the allocated transmit GTS
+               call Timer_Send.startPeriodic(1000);
+
+       }
+       
+  }
+  
+event void Timer_Send.fired() {
+       
+       
+       uint32_t SrcAddr[2];
+       uint32_t DstAddr[2];
+       uint8_t msdu_payload[4];
+       
+       if (TYPE_DEVICE == COORDINATOR)
+       {
+               SrcAddr[0]=0x00000000;
+               SrcAddr[1]=TOS_NODE_ID;
+       
+               DstAddr[0]=0x00000000;
+               DstAddr[1]=0x00000002;
+       
+               call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DstAddr, 4, msdu_payload,1,set_txoptions(1,1,0,0));
+       }
+       else
+       {
+           call Leds.led1Toggle();
+               
+               
+               SrcAddr[0]=0x00000000;
+               SrcAddr[1]=TOS_NODE_ID;
+       
+               DstAddr[0]=0x00000000;
+               DstAddr[1]=0x00000000;
+       
+               call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DstAddr, 4, msdu_payload,1,set_txoptions(1,1,0,0));
+       }
+       
+}
+
+
+/*****************************************************************************************************/  
+/**************************************MLME-SCAN*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
+{
+
+       return SUCCESS;
+}
+
+/*****************************************************************************************************/  
+/**************************************MLME-ORPHAN****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
+{
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-RESET*****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_RESET.confirm(uint8_t status)
+{
+
+
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-SYNC-LOSS*************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
+{
+
+       return SUCCESS;
+}
+  
+/*****************************************************************************************************/  
+/**************************************MLME-GTS*******************************************************/
+/*****************************************************************************************************/ 
+
+event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
+{
+       switch(status)
+       {
+               case MAC_SUCCESS:  gts_allocated=1;
+                                                       call Leds.led1Toggle();
+                                                       break;
+               
+               case MAC_DENIED: gts_allocated=0;
+                                                       break;
+               
+               case MAC_NO_SHORT_ADDRESS: gts_allocated=0;
+                                                                       break;
+               
+               case MAC_CHANNEL_ACCESS_FAILURE: gts_allocated=0;
+                                                                       break;
+               
+               case MAC_NO_ACK: gts_allocated=0;break;
+               
+               case MAC_NO_DATA: gts_allocated=0;break;
+                                               
+               
+               default: break;
+       
+       }
+
+       return SUCCESS;
+}
+
+event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
+{
+       return SUCCESS;
+}
+  /*****************************************************************************************************/  
+/**************************************MLME-BEACON NOTIFY*********************************************/
+/*****************************************************************************************************/ 
+
+event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
+{
+       gts_superframe_count++;
+       if (gts_superframe_count==30)
+       {
+               //call Leds.greenOff();
+               call MLME_GTS.request(set_gts_characteristics(1, GTS_TX_ONLY,0),0x00);
+       }
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-START*****************************************************/
+/*****************************************************************************************************/ 
+    event error_t MLME_START.confirm(uint8_t status)
+       {
+       
+       
+       return SUCCESS;
+       }
+  /*****************************************************************************************************/  
+/**********************                                  MLME-SET                          ******************************************/
+/*****************************************************************************************************/ 
+  
+      event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
+       {
+       
+       
+       return SUCCESS;
+       }
+       /*****************************************************************************************************/  
+/*************************                     MLME-GET                            ******************************************/
+/*****************************************************************************************************/ 
+           event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
+       {
+       
+       
+       return SUCCESS;
+       }
+       
+       
+       /*****************************************************************************************************/  
+/**************************************MLME-ASSOCIATE*************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
+{
+
+       return SUCCESS;
+}
+
+event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
+{
+
+       return SUCCESS;
+}
+       /*****************************************************************************************************/  
+/**************************************MLME-DISASSOCIATE**********************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
+{
+       return SUCCESS;
+}
+  
+event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
+{
+       return SUCCESS;
+}
+  /*****************************************************************************************************/  
+/*****************************************************************************************************/  
+/****************                                      MCPS EVENTS                              *************************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/  
+
+
+/*****************************************************************************************************/  
+/*********************                                 MCPS-DATA                          ***************************************/
+/*****************************************************************************************************/ 
+event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
+{
+       
+return SUCCESS;
+}  
+event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
+{
+       
+       
+return SUCCESS;
+}
+
+  
+}
+
index 13e57082468e1261b5074103601610e5c8851956..9eab3ac622b2de45e559fde811e3b7af95ceca43 100644 (file)
@@ -1,4 +1,4 @@
-COMPONENT=GTSManagementExample
+COMPONENT=GTSManagementExampleC
 
 PFLAGS +=      -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/includes \
                        -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/mac \
index 4c3b2fcf9ee671969db96043033c80b44e7d7644..f44b8b3cbbce15b5bb31e75770911fc590ad0a0f 100644 (file)
@@ -1,4 +1,4 @@
-COMPONENT=SimpleRoutingExample
+COMPONENT=SimpleRoutingExampleC
 
 PFLAGS +=      -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/includes \
                        -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/mac \
diff --git a/tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExample.nc b/tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExample.nc
deleted file mode 100644 (file)
index 115572b..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/**
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- */
-#include <Timer.h>
-
-#include "simpleroutingexample.h"
-#include "phy_const.h"
-#include "phy_enumerations.h"
-#include "mac_const.h"
-#include "mac_enumerations.h"
-#include "mac_func.h"
-
- configuration SimpleRoutingExample {
-}
-implementation
-{
-  components MainC;
-  components LedsC;
-  components SimpleRoutingExampleM;
-    
-  SimpleRoutingExampleM.Boot -> MainC;
-    
-  components Mac;
-  
-  SimpleRoutingExampleM.Leds -> LedsC;
-  
-  components new TimerMilliC() as Timer0;
-  SimpleRoutingExampleM.Timer0 -> Timer0;
-   
-  components new TimerMilliC() as Timer_Send;
-  SimpleRoutingExampleM.Timer_Send ->Timer_Send;
-   
-   
-  //MAC interfaces
-  
-  SimpleRoutingExampleM.MLME_START -> Mac.MLME_START;
-  
-  SimpleRoutingExampleM.MLME_GET ->Mac.MLME_GET;
-  SimpleRoutingExampleM.MLME_SET ->Mac.MLME_SET;
-  
-  SimpleRoutingExampleM.MLME_BEACON_NOTIFY ->Mac.MLME_BEACON_NOTIFY;
-  SimpleRoutingExampleM.MLME_GTS -> Mac.MLME_GTS;
-  
-  SimpleRoutingExampleM.MLME_ASSOCIATE->Mac.MLME_ASSOCIATE;
-  SimpleRoutingExampleM.MLME_DISASSOCIATE->Mac.MLME_DISASSOCIATE;
-  
-  SimpleRoutingExampleM.MLME_ORPHAN->Mac.MLME_ORPHAN;
-  SimpleRoutingExampleM.MLME_SYNC->Mac.MLME_SYNC;
-  SimpleRoutingExampleM.MLME_SYNC_LOSS->Mac.MLME_SYNC_LOSS;
-  SimpleRoutingExampleM.MLME_RESET->Mac.MLME_RESET;
-  
-  SimpleRoutingExampleM.MLME_SCAN->Mac.MLME_SCAN;
-  
-  
-  SimpleRoutingExampleM.MCPS_DATA->Mac.MCPS_DATA;
-
-  
-}
-
diff --git a/tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExampleC.nc b/tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExampleC.nc
new file mode 100644 (file)
index 0000000..f43915c
--- /dev/null
@@ -0,0 +1,61 @@
+/**
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ */
+#include <Timer.h>
+
+#include "simpleroutingexample.h"
+#include "phy_const.h"
+#include "phy_enumerations.h"
+#include "mac_const.h"
+#include "mac_enumerations.h"
+#include "mac_func.h"
+
+ configuration SimpleRoutingExampleC {
+}
+implementation
+{
+  components MainC;
+  components LedsC;
+  components SimpleRoutingExampleP;
+    
+  SimpleRoutingExampleP.Boot -> MainC;
+    
+  components MacC;
+  
+  SimpleRoutingExampleP.Leds -> LedsC;
+  
+  components new TimerMilliC() as Timer0;
+  SimpleRoutingExampleP.Timer0 -> Timer0;
+   
+  components new TimerMilliC() as Timer_Send;
+  SimpleRoutingExampleP.Timer_Send ->Timer_Send;
+   
+   
+  //MAC interfaces
+  
+  SimpleRoutingExampleP.MLME_START -> MacC.MLME_START;
+  
+  SimpleRoutingExampleP.MLME_GET ->MacC.MLME_GET;
+  SimpleRoutingExampleP.MLME_SET ->MacC.MLME_SET;
+  
+  SimpleRoutingExampleP.MLME_BEACON_NOTIFY ->MacC.MLME_BEACON_NOTIFY;
+  SimpleRoutingExampleP.MLME_GTS -> MacC.MLME_GTS;
+  
+  SimpleRoutingExampleP.MLME_ASSOCIATE->MacC.MLME_ASSOCIATE;
+  SimpleRoutingExampleP.MLME_DISASSOCIATE->MacC.MLME_DISASSOCIATE;
+  
+  SimpleRoutingExampleP.MLME_ORPHAN->MacC.MLME_ORPHAN;
+  SimpleRoutingExampleP.MLME_SYNC->MacC.MLME_SYNC;
+  SimpleRoutingExampleP.MLME_SYNC_LOSS->MacC.MLME_SYNC_LOSS;
+  SimpleRoutingExampleP.MLME_RESET->MacC.MLME_RESET;
+  
+  SimpleRoutingExampleP.MLME_SCAN->MacC.MLME_SCAN;
+  
+  
+  SimpleRoutingExampleP.MCPS_DATA->MacC.MCPS_DATA;
+
+  
+}
+
diff --git a/tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExampleM.nc b/tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExampleM.nc
deleted file mode 100644 (file)
index 8f25b93..0000000
+++ /dev/null
@@ -1,308 +0,0 @@
-/*
- *
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-
-#include <Timer.h>
-#include "printfUART.h"
-
-module SimpleRoutingExampleM {
-
-       uses interface Boot;
-       uses interface Leds;
-       
-       uses interface Timer<TMilli> as Timer0;
-       
-       uses interface Timer<TMilli> as Timer_Send;
-       //MAC interfaces
-       
-       uses interface MLME_START;
-       
-       uses interface MLME_GET;
-       uses interface MLME_SET;
-       
-       uses interface MLME_BEACON_NOTIFY;
-       uses interface MLME_GTS;
-       
-       uses interface MLME_ASSOCIATE;
-       uses interface MLME_DISASSOCIATE;
-       
-       uses interface MLME_ORPHAN;
-       
-       uses interface MLME_SYNC;
-       uses interface MLME_SYNC_LOSS;
-       
-       uses interface MLME_RESET;
-       
-       uses interface MLME_SCAN;
-       
-       uses interface MCPS_DATA;
-  
-}
-implementation {
-
-       PANDescriptor pan_des;
-       
-       uint32_t my_short_address=0x00000000;
-
-       uint32_t DestinationMote[2];
-       uint32_t SourceMoteAddr[2];
-       
-       //number of routed packet (coordinator)
-       uint8_t routed_packets = 0x00;
-       
-
-  event void Boot.booted() {
-       
-       printfUART_init();
-       
-       printfUART("i_am_pan: %i\n", TYPE_DEVICE);
-       
-       DestinationMote[0]=0x00000000;
-       DestinationMote[1]=0x00000002;
-       
-       if (TYPE_DEVICE == COORDINATOR)
-       {
-               my_short_address = 0x0000;
-               call Timer0.startOneShot(4000);
-       }
-       else
-       {
-               call Timer0.startOneShot(4000);
-       }
-
-  }
-
-  event void Timer0.fired() {
-    
-       uint8_t v_temp[2];
-       
-       
-       if (TYPE_DEVICE == END_DEVICE)
-       {
-       
-               my_short_address = TOS_NODE_ID;
-               
-               //set the MAC short address variable
-               v_temp[0] = (uint8_t)(my_short_address >> 8);
-               v_temp[1] = (uint8_t)(my_short_address );
-               
-               call MLME_SET.request(MACSHORTADDRESS,v_temp);
-       
-               //set the MAC PANID variable
-               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
-               v_temp[1] = (uint8_t)(MAC_PANID );
-               
-               call MLME_SET.request(MACPANID,v_temp);
-               
-               call Timer_Send.startPeriodic(3000);
-
-       }
-       else
-       {
-               //set the MAC short address variable
-               v_temp[0] = (uint8_t)(my_short_address >> 8);
-               v_temp[1] = (uint8_t)(my_short_address );
-               
-               call MLME_SET.request(MACSHORTADDRESS,v_temp);
-       
-               //set the MAC PANID variable
-               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
-               v_temp[1] = (uint8_t)(MAC_PANID );
-               
-               call MLME_SET.request(MACPANID,v_temp);
-       
-               //start sending beacons
-               call MLME_START.request(MAC_PANID, LOGICAL_CHANNEL, BEACON_ORDER, SUPERFRAME_ORDER,1,0,0,0,0);
-               
-               //call Timer_send.start(TIMER_REPEAT,8000);
-       }
-               
-  }
-  
-event void Timer_Send.fired() {
-       
-       
-       uint8_t msdu_payload[4];
-       
-       DestinationMote[0]=0x00000000;
-       DestinationMote[1]=0x00000000;
-       
-       //NKL destination address, coordinator will route packet to this address
-       msdu_payload[0] = 0x00;
-       msdu_payload[1] = 0x03;
-       
-       SourceMoteAddr[0]=0x00000000;
-       SourceMoteAddr[1]=TOS_NODE_ID;
-       
-       if (TOS_NODE_ID == 0x02)
-       {
-               call Leds.led2Toggle();                                                                                                                                                                                                 //set_txoptions(ack, gts, indirect_transmission, security)
-               call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SourceMoteAddr, SHORT_ADDRESS, MAC_PANID, DestinationMote, 2, msdu_payload,1,set_txoptions(1,0,0,0));
-       }
-
-       
-       }
-
-/*****************************************************************************************************/  
-/**************************************MLME-SCAN*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
-{
-
-       return SUCCESS;
-}
-
-/*****************************************************************************************************/  
-/**************************************MLME-ORPHAN****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
-{
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-RESET*****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_RESET.confirm(uint8_t status)
-{
-
-
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-SYNC-LOSS*************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
-{
-
-       return SUCCESS;
-}
-   
-/*****************************************************************************************************/  
-/**************************************MLME-GTS*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
-{
-       
-       return SUCCESS;
-}
-
-event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
-{
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-BEACON NOTIFY*********************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
-{
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-START*****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_START.confirm(uint8_t status)
-{
-
-
-return SUCCESS;
-}
- /*****************************************************************************************************/  
-/**********************                                  MLME-SET                          ******************************************/
-/*****************************************************************************************************/ 
-  
-event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
-{
-
-
-return SUCCESS;
-}
-/*****************************************************************************************************/  
-/*************************                     MLME-GET                            ******************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
-{
-
-
-return SUCCESS;
-}
-       
-       
-/*****************************************************************************************************/  
-/**************************************MLME-ASSOCIATE*************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
-{
-
-       return SUCCESS;
-}
-
-event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
-{
-
-       return SUCCESS;
-}
-       /*****************************************************************************************************/  
-/**************************************MLME-DISASSOCIATE**********************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
-{
-       return SUCCESS;
-}
-  
-event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
-{
-       return SUCCESS;
-}
-  /*****************************************************************************************************/  
-/*****************************************************************************************************/  
-/****************                                      MCPS EVENTS                              *************************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/  
-
-
-/*****************************************************************************************************/  
-/*********************                                 MCPS-DATA                          ***************************************/
-/*****************************************************************************************************/ 
-event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
-{
-       
-return SUCCESS;
-}  
-event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
-{
-
-//routing procedure, the short address of the destination device is the first 2 bytes of the data payload
-               if (TYPE_DEVICE == COORDINATOR)
-               {
-                       
-                       //route to the desired address
-                       DestinationMote[0]=0x00000000;
-                       DestinationMote[1]=(uint32_t) msdu[1];
-                       
-                       routed_packets++;
-                       msdu[0] = routed_packets;
-                                                                                                                                                                                                               //set_txoptions(ack, gts, indirect_transmission, security)
-                       call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DestinationMote, 1, msdu,1,set_txoptions(1,0,0,0));
-               }
-               else
-               {
-               
-                       call Leds.led1Toggle();
-               
-               }
-               
-       
-       
-return SUCCESS;
-}
-
-  
-}
-
diff --git a/tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExampleP.nc b/tos/lib/net/zigbee/apps/SimpleRoutingExample/SimpleRoutingExampleP.nc
new file mode 100644 (file)
index 0000000..3314907
--- /dev/null
@@ -0,0 +1,308 @@
+/*
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+
+#include <Timer.h>
+#include "printfUART.h"
+
+module SimpleRoutingExampleP {
+
+       uses interface Boot;
+       uses interface Leds;
+       
+       uses interface Timer<TMilli> as Timer0;
+       
+       uses interface Timer<TMilli> as Timer_Send;
+       //MAC interfaces
+       
+       uses interface MLME_START;
+       
+       uses interface MLME_GET;
+       uses interface MLME_SET;
+       
+       uses interface MLME_BEACON_NOTIFY;
+       uses interface MLME_GTS;
+       
+       uses interface MLME_ASSOCIATE;
+       uses interface MLME_DISASSOCIATE;
+       
+       uses interface MLME_ORPHAN;
+       
+       uses interface MLME_SYNC;
+       uses interface MLME_SYNC_LOSS;
+       
+       uses interface MLME_RESET;
+       
+       uses interface MLME_SCAN;
+       
+       uses interface MCPS_DATA;
+  
+}
+implementation {
+
+       PANDescriptor pan_des;
+       
+       uint32_t my_short_address=0x00000000;
+
+       uint32_t DestinationMote[2];
+       uint32_t SourceMoteAddr[2];
+       
+       //number of routed packet (coordinator)
+       uint8_t routed_packets = 0x00;
+       
+
+  event void Boot.booted() {
+       
+       printfUART_init();
+       
+       printfUART("i_am_pan: %i\n", TYPE_DEVICE);
+       
+       DestinationMote[0]=0x00000000;
+       DestinationMote[1]=0x00000002;
+       
+       if (TYPE_DEVICE == COORDINATOR)
+       {
+               my_short_address = 0x0000;
+               call Timer0.startOneShot(4000);
+       }
+       else
+       {
+               call Timer0.startOneShot(4000);
+       }
+
+  }
+
+  event void Timer0.fired() {
+    
+       uint8_t v_temp[2];
+       
+       
+       if (TYPE_DEVICE == END_DEVICE)
+       {
+       
+               my_short_address = TOS_NODE_ID;
+               
+               //set the MAC short address variable
+               v_temp[0] = (uint8_t)(my_short_address >> 8);
+               v_temp[1] = (uint8_t)(my_short_address );
+               
+               call MLME_SET.request(MACSHORTADDRESS,v_temp);
+       
+               //set the MAC PANID variable
+               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
+               v_temp[1] = (uint8_t)(MAC_PANID );
+               
+               call MLME_SET.request(MACPANID,v_temp);
+               
+               call Timer_Send.startPeriodic(3000);
+
+       }
+       else
+       {
+               //set the MAC short address variable
+               v_temp[0] = (uint8_t)(my_short_address >> 8);
+               v_temp[1] = (uint8_t)(my_short_address );
+               
+               call MLME_SET.request(MACSHORTADDRESS,v_temp);
+       
+               //set the MAC PANID variable
+               v_temp[0] = (uint8_t)(MAC_PANID >> 8);
+               v_temp[1] = (uint8_t)(MAC_PANID );
+               
+               call MLME_SET.request(MACPANID,v_temp);
+       
+               //start sending beacons
+               call MLME_START.request(MAC_PANID, LOGICAL_CHANNEL, BEACON_ORDER, SUPERFRAME_ORDER,1,0,0,0,0);
+               
+               //call Timer_send.start(TIMER_REPEAT,8000);
+       }
+               
+  }
+  
+event void Timer_Send.fired() {
+       
+       
+       uint8_t msdu_payload[4];
+       
+       DestinationMote[0]=0x00000000;
+       DestinationMote[1]=0x00000000;
+       
+       //NKL destination address, coordinator will route packet to this address
+       msdu_payload[0] = 0x00;
+       msdu_payload[1] = 0x03;
+       
+       SourceMoteAddr[0]=0x00000000;
+       SourceMoteAddr[1]=TOS_NODE_ID;
+       
+       if (TOS_NODE_ID == 0x02)
+       {
+               call Leds.led2Toggle();                                                                                                                                                                                                 //set_txoptions(ack, gts, indirect_transmission, security)
+               call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SourceMoteAddr, SHORT_ADDRESS, MAC_PANID, DestinationMote, 2, msdu_payload,1,set_txoptions(1,0,0,0));
+       }
+
+       
+       }
+
+/*****************************************************************************************************/  
+/**************************************MLME-SCAN*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
+{
+
+       return SUCCESS;
+}
+
+/*****************************************************************************************************/  
+/**************************************MLME-ORPHAN****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
+{
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-RESET*****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_RESET.confirm(uint8_t status)
+{
+
+
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-SYNC-LOSS*************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
+{
+
+       return SUCCESS;
+}
+   
+/*****************************************************************************************************/  
+/**************************************MLME-GTS*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
+{
+       
+       return SUCCESS;
+}
+
+event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
+{
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-BEACON NOTIFY*********************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
+{
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-START*****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_START.confirm(uint8_t status)
+{
+
+
+return SUCCESS;
+}
+ /*****************************************************************************************************/  
+/**********************                                  MLME-SET                          ******************************************/
+/*****************************************************************************************************/ 
+  
+event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
+{
+
+
+return SUCCESS;
+}
+/*****************************************************************************************************/  
+/*************************                     MLME-GET                            ******************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
+{
+
+
+return SUCCESS;
+}
+       
+       
+/*****************************************************************************************************/  
+/**************************************MLME-ASSOCIATE*************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
+{
+
+       return SUCCESS;
+}
+
+event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
+{
+
+       return SUCCESS;
+}
+       /*****************************************************************************************************/  
+/**************************************MLME-DISASSOCIATE**********************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
+{
+       return SUCCESS;
+}
+  
+event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
+{
+       return SUCCESS;
+}
+  /*****************************************************************************************************/  
+/*****************************************************************************************************/  
+/****************                                      MCPS EVENTS                              *************************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/  
+
+
+/*****************************************************************************************************/  
+/*********************                                 MCPS-DATA                          ***************************************/
+/*****************************************************************************************************/ 
+event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
+{
+       
+return SUCCESS;
+}  
+event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
+{
+
+//routing procedure, the short address of the destination device is the first 2 bytes of the data payload
+               if (TYPE_DEVICE == COORDINATOR)
+               {
+                       
+                       //route to the desired address
+                       DestinationMote[0]=0x00000000;
+                       DestinationMote[1]=(uint32_t) msdu[1];
+                       
+                       routed_packets++;
+                       msdu[0] = routed_packets;
+                                                                                                                                                                                                               //set_txoptions(ack, gts, indirect_transmission, security)
+                       call MCPS_DATA.request(SHORT_ADDRESS, MAC_PANID, SrcAddr, SHORT_ADDRESS, MAC_PANID, DestinationMote, 1, msdu,1,set_txoptions(1,0,0,0));
+               }
+               else
+               {
+               
+                       call Leds.led1Toggle();
+               
+               }
+               
+       
+       
+return SUCCESS;
+}
+
+  
+}
+
index 04386a649ea2b908aff8c20d90c8b75ee6821a8a..31172b4b62039fa02612ca8a38ba463f4694d7d4 100644 (file)
@@ -1,5 +1,8 @@
-COMPONENT=Test_APL
+COMPONENT=Test_APLC
 
+TKN154_PLATFORM_INCLUDE=$(TOSROOT)/tos/platforms/telosb/mac/tkn154/Makefile.include
+
+ifndef TKN154_MAC
 PFLAGS +=      -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/includes \
                        -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/macTDBS \
                        -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/phy \
@@ -9,7 +12,31 @@ PFLAGS +=     -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/includes \
                        -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/interfaces/phy \
                        -I$(TOSROOT)/tos/lib/net/zigbee/cc2420 \
                        -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/interfaces/nwk \
-                       -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/nwk
-                       
-include $(MAKERULES)
+                       -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/nwk\
+
+
+
+else
+PFLAGS += -DTKN154_MAC
+PFLAGS += -I$(TOSROOT)/tos/lib/mac/tkn154 \
+       -I$(TOSROOT)/tos/lib/mac/tkn154/dummies \
+       -I$(TOSROOT)/tos/lib/mac/tkn154/interfaces/MCPS \
+       -I$(TOSROOT)/tos/lib/mac/tkn154/interfaces/MLME \
+       -I$(TOSROOT)/tos/lib/mac/tkn154/interfaces/private \
+       -I$(TOSROOT)/tos/lib/mac/tkn154/interfaces/public\
+\
+-I$(TOSROOT)/tos/lib/net/zigbee/wrapper\
+-I$(TOSROOT)/tos/lib/net/zigbee/wrapper/interfaces/mac\
+-I$(TOSROOT)/tos/lib/net/zigbee/wrapper/includes \
+-I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/interfaces/nwk \
+ -I$(TOSROOT)/tos/lib/net/zigbee/ieee802154/nwk
+
+  include $(TKN154_PLATFORM_INCLUDE)   
+
+
+
+endif
+
+include $(MAKERULES)           
+
 
diff --git a/tos/lib/net/zigbee/apps/Test_APL/Test_APL.nc b/tos/lib/net/zigbee/apps/Test_APL/Test_APL.nc
deleted file mode 100644 (file)
index 3ea6d59..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-#include <Timer.h>
-
-#include "phy_const.h"
-#include "phy_enumerations.h"
-#include "mac_const.h"
-#include "mac_enumerations.h"
-#include "mac_func.h"
-
-#include "nwk_const.h"
-#include "nwk_enumerations.h"
-#include "nwk_func.h"
-#include "UserButton.h"
-
-configuration Test_APL {
-}
-implementation {
-
-  components MainC;
-  components LedsC;
-  components Test_APLM;
-    
-  Test_APLM.Boot -> MainC;
-    
-  components NWK;
-  
-  Test_APLM.Leds -> LedsC;
-  
-  
-       components new TimerMilliC() as T_init;
-       Test_APLM.T_init -> T_init;
-               
-       components new TimerMilliC() as T_test;
-       Test_APLM.T_test -> T_test;
-               
-       components new TimerMilliC() as T_schedule;
-       Test_APLM.T_schedule -> T_schedule;
-  
-  
-  //User Button
-  components UserButtonC;
-
-  Test_APLM.Get -> UserButtonC;
-  Test_APLM.Notify -> UserButtonC;
-  
-  
-  Test_APLM.NLDE_DATA ->NWK.NLDE_DATA;
-  
-  Test_APLM.NLME_NETWORK_DISCOVERY -> NWK.NLME_NETWORK_DISCOVERY;
-  Test_APLM.NLME_NETWORK_FORMATION -> NWK.NLME_NETWORK_FORMATION;
-  /*Test_APLM.NLME_PERMIT_JOINING-> NWK_control.NLME_PERMIT_JOINING;
-  */
-  Test_APLM.NLME_START_ROUTER -> NWK.NLME_START_ROUTER;
-  Test_APLM.NLME_JOIN -> NWK.NLME_JOIN;
-  /*Test_APLM.NLME_DIRECT_JOIN -> NWK_control.NLME_DIRECT_JOIN;
-  */
-  Test_APLM.NLME_LEAVE -> NWK.NLME_LEAVE;
-  /*Test_APLM.NLME_RESET -> NWK_control.NLME_RESET;
-  */
-  Test_APLM.NLME_SYNC -> NWK.NLME_SYNC;
-  Test_APLM.NLME_GET -> NWK.NLME_GET;
-  Test_APLM.NLME_SET -> NWK.NLME_SET;
-}
-
diff --git a/tos/lib/net/zigbee/apps/Test_APL/Test_APLC.nc b/tos/lib/net/zigbee/apps/Test_APL/Test_APLC.nc
new file mode 100644 (file)
index 0000000..efd41b8
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ * @author Ricardo Severino <rars@isep.ipp.pt>
+ *
+ */
+#include <Timer.h>
+
+#ifndef TKN154_MAC
+
+#include "phy_const.h"
+#include "phy_enumerations.h"
+#include "mac_const.h"
+#include "mac_enumerations.h"
+#include "mac_func.h"
+
+#endif
+
+#include "nwk_const.h"
+#include "nwk_enumerations.h"
+#include "nwk_func.h"
+#include "UserButton.h"
+
+
+
+configuration Test_APLC {
+}
+implementation {
+
+  components MainC;
+  components LedsC;
+  components Test_APLP;
+    
+  Test_APLP.Boot -> MainC;
+    
+  components NWKC;
+  
+  Test_APLP.Leds -> LedsC;
+  
+  
+       components new TimerMilliC() as T_init;
+       Test_APLP.T_init -> T_init;
+               
+       components new TimerMilliC() as T_test;
+       Test_APLP.T_test -> T_test;
+               
+       components new TimerMilliC() as T_schedule;
+       Test_APLP.T_schedule -> T_schedule;
+  
+  
+  //User Button
+  components UserButtonC;
+
+  Test_APLP.Get -> UserButtonC;
+  Test_APLP.Notify -> UserButtonC;
+  
+  
+  Test_APLP.NLDE_DATA ->NWKC.NLDE_DATA;
+  
+  Test_APLP.NLME_NETWORK_DISCOVERY -> NWKC.NLME_NETWORK_DISCOVERY;
+  Test_APLP.NLME_NETWORK_FORMATION -> NWKC.NLME_NETWORK_FORMATION;
+  /*Test_APLP.NLME_PERMIT_JOINING-> NWKC.NLME_PERMIT_JOINING;
+  */
+  Test_APLP.NLME_START_ROUTER -> NWKC.NLME_START_ROUTER;
+  Test_APLP.NLME_JOIN -> NWKC.NLME_JOIN;
+  /*Test_APLP.NLME_DIRECT_JOIN -> NWKC.NLME_DIRECT_JOIN;
+  */
+  Test_APLP.NLME_LEAVE -> NWKC.NLME_LEAVE;
+  Test_APLP.NLME_RESET -> NWKC.NLME_RESET;
+  
+  Test_APLP.NLME_SYNC -> NWKC.NLME_SYNC;
+  Test_APLP.NLME_GET -> NWKC.NLME_GET;
+  Test_APLP.NLME_SET -> NWKC.NLME_SET;
+}
+
diff --git a/tos/lib/net/zigbee/apps/Test_APL/Test_APLM.nc b/tos/lib/net/zigbee/apps/Test_APL/Test_APLM.nc
deleted file mode 100644 (file)
index 7e58da6..0000000
+++ /dev/null
@@ -1,873 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-#include <Timer.h>
-#include "printfUART.h"
-
-module Test_APLM {
-
-       uses interface Boot;
-       uses interface Leds;
-       
-       uses interface NLDE_DATA;
-//NLME NWK Management services
-       uses interface NLME_NETWORK_DISCOVERY;
-       uses interface NLME_NETWORK_FORMATION;  
-       uses interface NLME_START_ROUTER;
-       uses interface NLME_JOIN;
-       uses interface NLME_LEAVE;
-       uses interface NLME_SYNC;
-       
-       /*
-       uses interface NLME_PERMIT_JOINING;
-       uses interface NLME_DIRECT_JOIN;
-       uses interface NLME_RESET;
-       */
-       
-       uses interface NLME_GET;
-       uses interface NLME_SET;
-                       
-       uses interface Timer<TMilli> as T_init;
-       
-       uses interface Timer<TMilli> as T_test;
-       
-       uses interface Timer<TMilli> as T_schedule;             
-
-//user button
-  uses interface Get<button_state_t>;
-  uses interface Notify<button_state_t>;       
-  
-}
-implementation {
-       
-       //descriptor of the Parent device
-       networkdescriptor PAN_network;
-       //boolean variable definig if the device has joined to the PAN
-       uint8_t joined =0x00;
-       //boolean variable defining if the device is waiting for the beacon request response
-       uint8_t requested_scheduling = 0x00;
-       //function used to start the beacon broadcast (router devices)
-       task void start_sending_beacons_request();
-       //function used to schedule the beacon requests (PAN coordinator)
-       void process_beacon_scheduling(uint16_t source_address,uint8_t beacon_order, uint8_t superframe_order);
-       
-       void process_beacon_scheduling(uint16_t source_address,uint8_t beacon_order, uint8_t superframe_order)
-       {
-       
-               uint8_t nsdu_pay[6];
-               
-               beacon_scheduling *beacon_scheduling_ptr;
-               
-               beacon_scheduling_ptr = (beacon_scheduling *)&nsdu_pay[0];
-               
-               switch(source_address)
-               {
-                       
-                       /*****************************************************************************/
-                       /*DEPTH 
-                       mwkMaxChildren (Cm)     6
-                       nwkMaxDepth (Lm)        4
-                       mwkMaxRouters (Rm)      4
-                       */
-                       /*
-                       case 0x0001: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0002: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0021: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x01;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x2C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0003: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0022: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0004: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0005: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       
-                       case 0x0023: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       
-                       case 0x0024: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                                               */                      
-                       /*****************************************************************************/
-                       /*NORMAL TEST
-                       mwkMaxChildren (Cm)     6
-                       nwkMaxDepth (Lm)        3
-                       mwkMaxRouters (Rm)      4
-*/
-                       case 0x0001: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0020: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x01;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xE0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0002: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0009: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0021: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0028: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0003: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0004: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x000a: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x000b: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0022: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0023: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0029: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x002a: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       
-                       /*******************************************************************/
-                       /*
-                       case 0x0001: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0002: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0009: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                                       
-                                       
-                       case 0x0020: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0021: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0028: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;          
-                       
-                       case 0x003F: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x01;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xE0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0040: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0047: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                                       
-                       case 0x005e: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x02;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xDC;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x005f: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0066: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;  
-                       */
-                       /*******************************************************************/
-                       /*
-                       case 0x0001: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0002: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0009: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x00010: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xB4;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0017: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;          
-                       
-                       
-                       case 0x0020: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x01;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x68;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0021: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0028: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0002F: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xB4;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0036: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;          
-                       
-                       
-                       case 0x003F: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x02;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xD0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0040: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0047: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0004E: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xB4;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0055: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;  
-                                       
-                                       
-                                       
-                       case 0x005e: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x04;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x38;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x005F: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0066: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0006D: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xB4;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-                       case 0x0074: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;  
-                       */
-                       default: 
-                                       beacon_scheduling_ptr->request_type = SCHEDULING_DENY;
-                                       beacon_scheduling_ptr->beacon_order = beacon_order;
-                                       beacon_scheduling_ptr->superframe_order = superframe_order;
-                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[1] = 0x00;
-                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-                                       break;
-               
-               }
-
-               
-               call NLDE_DATA.request(source_address,0x06, nsdu_pay, 1, 1, 0x00, 0);
-       return;
-       }
-
-       task void start_sending_beacons_request()
-       {
-               uint8_t nsdu_pay[6];
-               
-               beacon_scheduling *beacon_scheduling_ptr;
-               
-               beacon_scheduling_ptr = (beacon_scheduling *)&nsdu_pay[0];
-               
-               beacon_scheduling_ptr->request_type = SCHEDULING_REQUEST;
-               beacon_scheduling_ptr->beacon_order = BEACON_ORDER;
-               beacon_scheduling_ptr->superframe_order = SUPERFRAME_ORDER;
-               beacon_scheduling_ptr->transmission_offset[0] = 0x00;
-               beacon_scheduling_ptr->transmission_offset[1] = 0x00;
-               beacon_scheduling_ptr->transmission_offset[2] = 0x00;
-       
-               requested_scheduling = 0x01;
-
-               //command result_t NLDE_DATA.request(uint16_t DstAddr, uint8_t NsduLength, uint8_t Nsdu[], uint8_t NsduHandle, uint8_t Radius, uint8_t DiscoverRoute, bool SecurityEnable)
-               call NLDE_DATA.request(0x0000,0x06, nsdu_pay, 0x01, 0x01, 0x00, 0x00);
-       
-               call T_schedule.startOneShot(20000);
-               //call Schedule_timer.start(TIMER_ONE_SHOT,20000);
-       return;
-       }
-       
-       
-       
-  event void Boot.booted() {
-       
-       call Notify.enable();   
-       
-       //using the telosb motes the used button enables the association to the network (routers and end devices)
-       //or the beacon broadcasting (PAN coordinator)
-       //in the MICAz motes a timer is needed to start all the above operations
-               
-       //if (TYPE_DEVICE == COORDINATOR)
-       //      call T_init.startOneShot(12000);
-               
-  }
-
-
-/*****************************************************
-****************TIMER EVENTS***************************
-******************************************************/ 
-
-
-/*******************T_init**************************/
-  event void T_init.fired() {
-    
-    //printfUART("Timer fired\n", "");
-       if (TYPE_DEVICE == COORDINATOR)
-       {       
-               //printfUART("coordinator procedure\n", "");
-               //start forming a PAN
-               //command result_t request(uint32_t ScanChannels, uint8_t ScanDuration, uint8_t BeaconOrder, uint8_t SuperframeOrder, uint16_t PANId, bool BatteryLifeExtension);
-               call NLME_NETWORK_FORMATION.request(0x000000ff, 8, BEACON_ORDER, SUPERFRAME_ORDER, MAC_PANID,0);
-               
-               //call Leds.redOff();
-               call Leds.led0Off();
-               //call Test_timer.start(TIMER_REPEAT, 8000); 
-       }
-       else
-       {       
-               //printfUART("child procedure\n", "");
-               
-               //call NLME_NETWORK_FORMATION.request(0x000000ff, 8, BEACON_ORDER, SUPERFRAME_ORDER, PANID,0);
-               
-               call NLME_NETWORK_DISCOVERY.request(0x000000ff, 8);
-               
-               //call Test_timer.start(TIMER_REPEAT,9000);
-               
-       }
-       return;
-  }
-
-/*******************T_test**************************/
-  event void T_test.fired() {
-    
-       uint8_t nsdu_pay[20];
-       //printfUART("Test_timer.fired\n", "");
-       nsdu_pay[0]=0x05;
-       nsdu_pay[1]=0x05;
-       nsdu_pay[2]=0x05;
-       nsdu_pay[3]=0x05;
-       nsdu_pay[4]=0x05;
-       nsdu_pay[5]=0x05;
-       nsdu_pay[6]=0x05;
-       
-       //call Leds.redToggle();
-       
-       //command result_t NLDE_DATA.request(uint16_t DstAddr, uint8_t NsduLength, uint8_t Nsdu[], uint8_t NsduHandle, uint8_t Radius, uint8_t DiscoverRoute, bool SecurityEnable)
-       call NLDE_DATA.request(0x0000,0x07, nsdu_pay, 1, 1, 0x00, 0);
-  }
-  
-  /*******************T_schedule**************************/
-  event void T_schedule.fired() {
-       //event that fires if the negotiation for beacon transmission is unsuccessful 
-       //(the device does not receive any negotiation reply)
-       if(requested_scheduling == 0x01)
-       {
-               post start_sending_beacons_request();
-       }
-    
-  }
-
-
-/*****************************************************
-****************NLDE EVENTS***************************
-******************************************************/ 
-
-/*************************NLDE_DATA*****************************/
-
-event error_t NLDE_DATA.confirm(uint8_t NsduHandle, uint8_t Status)
-{
-       //printfUART("NLME_DATA.confirm\n", "");
-       
-       return SUCCESS;
-}
-
-event error_t NLDE_DATA.indication(uint16_t SrcAddress, uint16_t NsduLength,uint8_t Nsdu[100], uint16_t LinkQuality)
-{
-
-       uint32_t start_time=0x00000000;
-       uint16_t start_time1=0x0000;
-       uint16_t start_time2=0x0000;
-               
-       if (TYPE_DEVICE == COORDINATOR)
-       {       
-               if(Nsdu[0] == SCHEDULING_REQUEST)
-               {
-                       //the PAN coordinator receives a negotiation request
-                       process_beacon_scheduling(SrcAddress,Nsdu[1],Nsdu[2]);
-               }
-       }
-       
-       if(TYPE_DEVICE==ROUTER && requested_scheduling ==0x01)
-       {
-               //the routes receives a negotiation reply
-               atomic requested_scheduling =0x00;
-
-               if(Nsdu[0] == SCHEDULING_ACCEPT)
-               {
-                       start_time1 =( (Nsdu[3] << 0) ) ;
-                       start_time2 =( (Nsdu[4] << 8 ) | (Nsdu[5] << 0 ) );
-                       
-                       start_time = ( ((uint32_t)start_time1 << 16) | (start_time2 << 0));
-                       
-                       call NLME_START_ROUTER.request(Nsdu[1],Nsdu[2],0,start_time);
-               }
-
-       }
-       
-       return SUCCESS;
-}
-
-/*****************************************************
-****************NLME EVENTS***************************
-******************************************************/ 
-
-/*****************NLME_NETWORK_DISCOVERY**************************/
-event error_t NLME_NETWORK_DISCOVERY.confirm(uint8_t NetworkCount,networkdescriptor networkdescriptorlist[], uint8_t Status)
-{
-       //printfUART("NLME_NETWORK_DISCOVERY.confirm\n", ""); 
-
-       PAN_network = networkdescriptorlist[0];
-       
-       if (TYPE_DEVICE == ROUTER)
-       {
-               //printfUART("go join router\n", ""); 
-               call NLME_JOIN.request(networkdescriptorlist[0].PANId, 0x01, 0, 0x000000ff, 8, 0, 0, 0);
-       }
-       else
-       {
-               //printfUART("go join non router\n", ""); 
-               call NLME_JOIN.request(networkdescriptorlist[0].PANId, 0x00, 0, 0x000000ff, 8, 0, 0, 0);
-       }       
-       return SUCCESS;
-}
-
-/*****************NLME_NETWORK_FORMATION**********************/
-
-event error_t NLME_NETWORK_FORMATION.confirm(uint8_t Status)
-{      
-       //printfUART("NLME_NETWORK_FORMATION.confirm\n", ""); 
-
-       return SUCCESS;
-}
-/*****************NLME_START_ROUTER*****************************/
-event error_t NLME_START_ROUTER.confirm(uint8_t Status)
-{ 
-       //printfUART("NLME_START_ROUTER.confirm\n", ""); 
-               
-       return SUCCESS;
-}
-
-/*************************NLME_JOIN*****************************/
-
-event error_t NLME_JOIN.indication(uint16_t ShortAddress, uint32_t ExtendedAddress[], uint8_t CapabilityInformation, bool SecureJoin)
-{
-       //printfUART("NLME_JOIN.indication\n", "");
-       
-       return SUCCESS;
-}
-
-event error_t NLME_JOIN.confirm(uint16_t PANId, uint8_t Status)
-{      
-       //printfUART("NLME_JOIN.confirm\n", "");
-       
-       switch(Status)
-       {
-       
-               case NWK_SUCCESS:                       joined =0x01;
-                                                                       if (TYPE_DEVICE == ROUTER)
-                                                                       {
-                                                                               //join procedure successful
-                                                                               //call Leds.redOff();
-                                                                               call Leds.led0Off();
-                                                                               
-                                                                               requested_scheduling = 0x01;
-                                                                               
-                                                                               call T_schedule.startOneShot(9000);
-                                                                               
-
-                                                                               //call Test_timer.start(TIMER_REPEAT, 8000); 
-                                                                       }
-                                                                       else
-                                                                       {
-                                                                               //the device is an end device and starts transmitting data periodically
-                                                                               call T_test.startPeriodic(10000);
-                                                                               //call Test_timer.start(TIMER_REPEAT, 10000); 
-                                                                       }
-                                                                       break;
-                                                                       
-               case NWK_NOT_PERMITTED:         joined =0x00;
-                                                                       //join failed
-                                                                       break;
-                                                                       
-               default:                                        //default procedure - join failed
-                                                                       joined =0x00;
-                                                                       break;
-       }
-       return SUCCESS;
-}
-
-
-/*************************NLME_LEAVE****************************/
-
-event error_t NLME_LEAVE.indication(uint32_t DeviceAddress[])
-{
-       ////printfUART("NLME_LEAVE.indication\n", "");
-       return SUCCESS;
-}
-
-event error_t NLME_LEAVE.confirm(uint32_t DeviceAddress[], uint8_t Status)
-{
-       //printfUART("NLME_LEAVE.confirm\n", "");
-       return SUCCESS;
-}
-
-
-
-/*************************NLME_SYNC*****************************/
-
-event error_t NLME_SYNC.indication()
-{
-       //printfUART("NLME_SYNC.indication\n", "");
-       return SUCCESS;
-}
-
-event error_t NLME_SYNC.confirm(uint8_t Status)
-{
-       
-       return SUCCESS;
-}
-
-
-/*************************************************************/
-/*****************        NLME-SET     ********************/
-/*************************************************************/
-
-event error_t NLME_SET.confirm(uint8_t Status, uint8_t NIBAttribute)
-{
-
-return SUCCESS;
-}
-
-/*************************************************************/
-/*****************        NLME-GET     ********************/
-/*************************************************************/
-
-event error_t NLME_GET.confirm(uint8_t Status, uint8_t NIBAttribute, uint16_t NIBAttributeLength, uint16_t NIBAttributeValue)
-{
-
-
-return SUCCESS;
-}
-
-
-
-event void Notify.notify( button_state_t state)
-{
-       if (state == BUTTON_PRESSED) {
-               call Leds.led0On();
-               call T_init.startOneShot(5000);
-
-       }
-    
-}
-
-
-  
-}
-
diff --git a/tos/lib/net/zigbee/apps/Test_APL/Test_APLP.nc b/tos/lib/net/zigbee/apps/Test_APL/Test_APLP.nc
new file mode 100644 (file)
index 0000000..2755af5
--- /dev/null
@@ -0,0 +1,886 @@
+//#define OPEN_ZB_MAC
+
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ * @author Ricardo Severino <rars@isep.ipp.pt>
+ *
+ */
+#include <Timer.h>
+#include "printfUART.h"
+
+module Test_APLP {
+
+       uses interface Boot;
+       uses interface Leds;
+       
+       uses interface NLDE_DATA;
+//NLME NWK Management services
+       uses interface NLME_NETWORK_DISCOVERY;
+       uses interface NLME_NETWORK_FORMATION;  
+       uses interface NLME_START_ROUTER;
+       uses interface NLME_JOIN;
+       uses interface NLME_LEAVE;
+       uses interface NLME_SYNC;
+       
+       /*
+       uses interface NLME_PERMIT_JOINING;
+       uses interface NLME_DIRECT_JOIN;*/
+       uses interface NLME_RESET;
+       
+       
+       uses interface NLME_GET;
+       uses interface NLME_SET;
+                       
+       uses interface Timer<TMilli> as T_init;
+       
+       uses interface Timer<TMilli> as T_test;
+       
+       uses interface Timer<TMilli> as T_schedule;             
+
+//user button
+  uses interface Get<button_state_t>;
+  uses interface Notify<button_state_t>;       
+  
+}
+implementation {
+       
+       //descriptor of the Parent device
+       networkdescriptor PAN_network;
+       //boolean variable definig if the device has joined to the PAN
+       uint8_t joined =0x00;
+       //boolean variable defining if the device is waiting for the beacon request response
+       uint8_t requested_scheduling = 0x00;
+       //function used to start the beacon broadcast (router devices)
+       task void start_sending_beacons_request();
+       //function used to schedule the beacon requests (PAN coordinator)
+       void process_beacon_scheduling(uint16_t source_address,uint8_t beacon_order, uint8_t superframe_order);
+       
+       void process_beacon_scheduling(uint16_t source_address,uint8_t beacon_order, uint8_t superframe_order)
+       {
+       
+               uint8_t nsdu_pay[6];
+               
+               beacon_scheduling *beacon_scheduling_ptr;
+               
+               beacon_scheduling_ptr = (beacon_scheduling *)&nsdu_pay[0];
+               
+               switch(source_address)
+               {
+                       
+                       /*****************************************************************************/
+                       /*DEPTH 
+                       mwkMaxChildren (Cm)     6
+                       nwkMaxDepth (Lm)        4
+                       mwkMaxRouters (Rm)      4
+                       */
+                       /*
+                       case 0x0001: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0002: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0021: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x01;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x2C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0003: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0022: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0004: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0005: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       
+                       case 0x0023: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       
+                       case 0x0024: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                                               */                      
+                       /*****************************************************************************/
+                       /*NORMAL TEST
+                       mwkMaxChildren (Cm)     6
+                       nwkMaxDepth (Lm)        3
+                       mwkMaxRouters (Rm)      4
+*/
+                       case 0x0001: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0020: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x01;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xE0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0002: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0009: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0021: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0028: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0003: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0004: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x000a: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x000b: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0022: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0023: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0029: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x002a: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       
+                       /*******************************************************************/
+                       /*
+                       case 0x0001: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0002: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0009: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                                       
+                                       
+                       case 0x0020: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0021: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0028: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;          
+                       
+                       case 0x003F: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x01;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xE0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0040: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0047: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                                       
+                       case 0x005e: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x02;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xDC;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x005f: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0066: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;  
+                       */
+                       /*******************************************************************/
+                       /*
+                       case 0x0001: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0002: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0009: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x00010: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xB4;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0017: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;          
+                       
+                       
+                       case 0x0020: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x01;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x68;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0021: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0028: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0002F: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xB4;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0036: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;          
+                       
+                       
+                       case 0x003F: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x02;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xD0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0040: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0047: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0004E: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xB4;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0055: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;  
+                                       
+                                       
+                                       
+                       case 0x005e: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x04;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x38;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x005F: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x3C;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0066: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x78;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0006D: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xB4;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+                       case 0x0074: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_ACCEPT;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0xF0;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;  
+                       */
+                       default: 
+                                       beacon_scheduling_ptr->request_type = SCHEDULING_DENY;
+                                       beacon_scheduling_ptr->beacon_order = beacon_order;
+                                       beacon_scheduling_ptr->superframe_order = superframe_order;
+                                       beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[1] = 0x00;
+                                       beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+                                       break;
+               
+               }
+
+               
+               call NLDE_DATA.request(source_address,0x06, nsdu_pay, 1, 1, 0x00, 0);
+       return;
+       }
+
+       task void start_sending_beacons_request()
+       {
+               uint8_t nsdu_pay[6];
+               
+               beacon_scheduling *beacon_scheduling_ptr;
+               
+               beacon_scheduling_ptr = (beacon_scheduling *)&nsdu_pay[0];
+               
+               beacon_scheduling_ptr->request_type = SCHEDULING_REQUEST;
+               beacon_scheduling_ptr->beacon_order = BEACON_ORDER;
+               beacon_scheduling_ptr->superframe_order = SUPERFRAME_ORDER;
+               beacon_scheduling_ptr->transmission_offset[0] = 0x00;
+               beacon_scheduling_ptr->transmission_offset[1] = 0x00;
+               beacon_scheduling_ptr->transmission_offset[2] = 0x00;
+       
+               requested_scheduling = 0x01;
+
+               //command result_t NLDE_DATA.request(uint16_t DstAddr, uint8_t NsduLength, uint8_t Nsdu[], uint8_t NsduHandle, uint8_t Radius, uint8_t DiscoverRoute, bool SecurityEnable)
+               call NLDE_DATA.request(0x0000,0x06, nsdu_pay, 0x01, 0x01, 0x00, 0x00);
+       
+               call T_schedule.startOneShot(20000);
+               //call Schedule_timer.start(TIMER_ONE_SHOT,20000);
+       return;
+       }
+       
+       
+       
+  event void Boot.booted() {
+       
+       call Notify.enable();   
+       
+       //using the telosb motes the used button enables the association to the network (routers and end devices)
+       //or the beacon broadcasting (PAN coordinator)
+       //in the MICAz motes a timer is needed to start all the above operations
+               
+       //if (TYPE_DEVICE == COORDINATOR)
+       //      call T_init.startOneShot(12000);
+               
+  }
+
+
+/*****************************************************
+****************TIMER EVENTS***************************
+******************************************************/ 
+
+
+/*******************T_init**************************/
+  event void T_init.fired() {
+    //printfUART("Timer fired\n", "");
+       if (TYPE_DEVICE == COORDINATOR)
+       {       
+               
+
+
+//printfUART("coordinator procedure\n", "");
+               //start forming a PAN
+               //command result_t request(uint32_t ScanChannels, uint8_t ScanDuration, uint8_t BeaconOrder, uint8_t SuperframeOrder, uint16_t PANId, bool BatteryLifeExtension);
+               call NLME_NETWORK_FORMATION.request(0x000000ff, 8, BEACON_ORDER, SUPERFRAME_ORDER, MAC_PANID,0);
+               
+               //call Leds.redOff();
+               //call Leds.led0Off();
+               //call Test_timer.start(TIMER_REPEAT, 8000); 
+       }
+       else
+       {       
+
+//printfUART("child procedure\n", "");
+       
+       
+               call NLME_NETWORK_DISCOVERY.request(0x000000ff, 8);
+       
+                       
+       }
+       return;
+  }
+
+/*******************T_test**************************/
+  event void T_test.fired() {
+    
+       uint8_t nsdu_pay[20];
+       //printfUART("Test_timer.fired\n", "");
+       nsdu_pay[0]=0x05;
+       nsdu_pay[1]=0x05;
+       nsdu_pay[2]=0x05;
+       nsdu_pay[3]=0x05;
+       nsdu_pay[4]=0x05;
+       nsdu_pay[5]=0x05;
+       nsdu_pay[6]=0x05;
+       
+       //call Leds.redToggle();
+       
+       //command result_t NLDE_DATA.request(uint16_t DstAddr, uint8_t NsduLength, uint8_t Nsdu[], uint8_t NsduHandle, uint8_t Radius, uint8_t DiscoverRoute, bool SecurityEnable)
+       call NLDE_DATA.request(0x0000,0x07, nsdu_pay, 1, 1, 0x00, 0);
+  }
+  
+  /*******************T_schedule**************************/
+  event void T_schedule.fired() {
+       //event that fires if the negotiation for beacon transmission is unsuccessful 
+       //(the device does not receive any negotiation reply)
+       if(requested_scheduling == 0x01)
+       {
+               post start_sending_beacons_request();
+       }
+    
+  }
+
+
+/*****************************************************
+****************NLDE EVENTS***************************
+******************************************************/ 
+
+/*************************NLDE_DATA*****************************/
+
+event error_t NLDE_DATA.confirm(uint8_t NsduHandle, uint8_t Status)
+{
+       //printfUART("NLME_DATA.confirm\n", "");
+       
+       return SUCCESS;
+}
+
+event error_t NLDE_DATA.indication(uint16_t SrcAddress, uint16_t NsduLength,uint8_t Nsdu[100], uint16_t LinkQuality)
+{
+
+       uint32_t start_time=0x00000000;
+       uint16_t start_time1=0x0000;
+       uint16_t start_time2=0x0000;
+               
+       if (TYPE_DEVICE == COORDINATOR)
+       {       
+               if(Nsdu[0] == SCHEDULING_REQUEST)
+               {
+                       //the PAN coordinator receives a negotiation request
+                       process_beacon_scheduling(SrcAddress,Nsdu[1],Nsdu[2]);
+               }
+       }
+       
+       if(TYPE_DEVICE==ROUTER && requested_scheduling ==0x01)
+       {
+               //the routes receives a negotiation reply
+               atomic requested_scheduling =0x00;
+
+               if(Nsdu[0] == SCHEDULING_ACCEPT)
+               {
+                       start_time1 =( (Nsdu[3] << 0) ) ;
+                       start_time2 =( (Nsdu[4] << 8 ) | (Nsdu[5] << 0 ) );
+                       
+                       start_time = ( ((uint32_t)start_time1 << 16) | (start_time2 << 0));
+                       
+                       call NLME_START_ROUTER.request(Nsdu[1],Nsdu[2],0,start_time);
+               }
+
+       }
+       
+       return SUCCESS;
+}
+
+/*****************************************************
+****************NLME EVENTS***************************
+******************************************************/ 
+
+/*****************NLME_NETWORK_DISCOVERY**************************/
+event error_t NLME_NETWORK_DISCOVERY.confirm(uint8_t NetworkCount,networkdescriptor networkdescriptorlist[], uint8_t Status)
+{
+       //printfUART("NLME_NETWORK_DISCOVERY.confirm\n", ""); 
+
+       PAN_network = networkdescriptorlist[0];
+       
+       if (TYPE_DEVICE == ROUTER)
+       {
+               //printfUART("go join router\n", ""); 
+               call NLME_JOIN.request(networkdescriptorlist[0].PANId, 0x01, 0, 0x000000ff, 8, 0, 0, 0);
+       }
+       else
+       {
+               //printfUART("go join non router\n", ""); 
+               call NLME_SYNC.request(1);
+               call NLME_JOIN.request(networkdescriptorlist[0].PANId, 0x00, 0, 0x000000ff, 8, 0, 0, 0);
+       }       
+       return SUCCESS;
+}
+
+/*****************NLME_NETWORK_FORMATION**********************/
+
+event error_t NLME_NETWORK_FORMATION.confirm(uint8_t Status)
+{      
+       
+
+//printfUART("NLME_NETWORK_FORMATION.confirm\n", ""); 
+
+       return SUCCESS;
+}
+/*****************NLME_START_ROUTER*****************************/
+event error_t NLME_START_ROUTER.confirm(uint8_t Status)
+{ 
+       //printfUART("NLME_START_ROUTER.confirm\n", ""); 
+               
+       return SUCCESS;
+}
+
+/*************************NLME_JOIN*****************************/
+
+event error_t NLME_JOIN.indication(uint16_t ShortAddress, uint32_t ExtendedAddress[], uint8_t CapabilityInformation, bool SecureJoin)
+{
+       //printfUART("NLME_JOIN.indication\n", "");
+       
+       return SUCCESS;
+}
+
+event error_t NLME_JOIN.confirm(uint16_t PANId, uint8_t Status)
+{      
+       //printfUART("NLME_JOIN.confirm\n", "");
+       
+       switch(Status)
+       {
+       
+               case NWK_SUCCESS:                       joined =0x01;
+                                                                       if (TYPE_DEVICE == ROUTER)
+                                                                       {
+                                                                               //join procedure successful
+                                                                               //call Leds.redOff();
+                                                                               call Leds.led0Off();
+                                                                               
+                                                                               requested_scheduling = 0x01;
+                                                                               
+                                                                               call T_schedule.startOneShot(9000);
+                                                                               
+
+                                                                               //call Test_timer.start(TIMER_REPEAT, 8000); 
+                                                                       }
+                                                                       else
+                                                                       {
+                                                                               //the device is an end device and starts transmitting data periodically
+                                                                               call T_test.startPeriodic(10000);
+                                                                               //call Test_timer.start(TIMER_REPEAT, 10000); 
+                                                                       }
+                                                                       break;
+                                                                       
+               case NWK_NOT_PERMITTED:         joined =0x00;
+                                                                       //join failed
+                                                                       break;
+                                                                       
+               default:                                        //default procedure - join failed
+                                                                       joined =0x00;
+                                                                       break;
+       }
+       return SUCCESS;
+}
+
+
+/*************************NLME_LEAVE****************************/
+
+event error_t NLME_LEAVE.indication(uint32_t DeviceAddress[])
+{
+       ////printfUART("NLME_LEAVE.indication\n", "");
+       return SUCCESS;
+}
+
+event error_t NLME_LEAVE.confirm(uint32_t DeviceAddress[], uint8_t Status)
+{
+       //printfUART("NLME_LEAVE.confirm\n", "");
+       return SUCCESS;
+}
+
+
+
+/*************************NLME_SYNC*****************************/
+
+event error_t NLME_SYNC.indication()
+{
+       //printfUART("NLME_SYNC.indication\n", "");
+       return SUCCESS;
+}
+
+event error_t NLME_SYNC.confirm(uint8_t Status)
+{
+       
+       return SUCCESS;
+}
+
+
+/*************************************************************/
+/*****************        NLME-SET     ********************/
+/*************************************************************/
+
+event error_t NLME_SET.confirm(uint8_t Status, uint8_t NIBAttribute)
+{
+
+return SUCCESS;
+}
+
+/*************************************************************/
+/*****************        NLME-GET     ********************/
+/*************************************************************/
+
+event error_t NLME_GET.confirm(uint8_t Status, uint8_t NIBAttribute, uint16_t NIBAttributeLength, uint16_t NIBAttributeValue)
+{
+
+
+return SUCCESS;
+}
+
+event error_t NLME_RESET.confirm(uint8_t status){
+
+call T_init.startOneShot(5000);
+return SUCCESS;
+}
+
+event void Notify.notify( button_state_t state)
+{
+       if (state == BUTTON_PRESSED) {
+               //call Leds.led0On();
+               
+               call NLME_RESET.request();
+
+       }
+    
+}
+
+
+  
+}
+
diff --git a/tos/lib/net/zigbee/cc2420/CC2420Config.nc b/tos/lib/net/zigbee/cc2420/CC2420Config.nc
new file mode 100644 (file)
index 0000000..972f37a
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * An HAL abstraction of the ChipCon CC2420 radio. This abstraction
+ * deals specifically with radio configurations. All get() and set()
+ * commands are single-phase. After setting some values, a call to
+ * sync() is required for the changes to propagate to the cc2420
+ * hardware chip. This interface allows setting multiple parameters
+ * before calling sync().
+ *
+ * @author Jonathan Hui <jhui@archrock.com>
+ * @version $Revision$ $Date$
+ */
+
+interface CC2420Config {
+
+  /**
+   * Sync configuration changes with the radio hardware. This only
+   * applies to set commands below.
+   *
+   * @return SUCCESS if the request was accepted, FAIL otherwise.
+   */
+  command error_t sync();
+  event void syncDone( error_t error );
+
+  /**
+   * Change the channel of the radio, between 11 and 26
+   */
+  command uint8_t getChannel();
+  command void setChannel( uint8_t channel );
+
+  /**
+   * Change the short address of the radio.
+   */
+  async command uint16_t getShortAddr();
+  command void setShortAddr( uint16_t address );
+
+  /**
+   * Change the PAN address of the radio.
+   */
+  async command uint16_t getPanAddr();
+  command void setPanAddr( uint16_t address );
+
+  
+  /**
+   * @param on TRUE to turn address recognition on, FALSE to turn it off
+   */
+  command void setAddressRecognition(bool on);
+  
+  /**
+   * @return TRUE if address recognition is enabled
+   */
+  async command bool isAddressRecognitionEnabled();
+  
+  /**
+   * Sync must be called for acknowledgement changes to take effect
+   * @param enableAutoAck TRUE to enable auto acknowledgements
+   * @param hwAutoAck TRUE to default to hardware auto acks, FALSE to
+   *     default to software auto acknowledgements
+   */
+  command void setAutoAck(bool enableAutoAck, bool hwAutoAck);
+  
+  /**
+   * @return TRUE if hardware auto acks are the default, FALSE if software
+   *     acks are the default
+   */
+  async command bool isHwAutoAckDefault();
+  
+  /**
+   * @return TRUE if auto acks are enabled
+   */
+  async command bool isAutoAckEnabled();
+  
+}
index 14cb939aad8b80e4775a1dc5e167e24d040ba7cd..51708378655c3974f508be9e1b39cae9a0d065d2 100644 (file)
@@ -786,7 +786,7 @@ typedef enum{
     case S_RX_FCF:
       m_state = S_RX_PAYLOAD;
       
-      /*
+      
        * The destination address check here is not completely optimized. If you 
        * are seeing issues with dropped acknowledgements, try removing
        * the address check and decreasing SACK_HEADER_LENGTH to 2.
diff --git a/tos/lib/net/zigbee/ieee802154/includes/PrintfUART.h b/tos/lib/net/zigbee/ieee802154/includes/PrintfUART.h
deleted file mode 100644 (file)
index f19f13b..0000000
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- * Copyright (c) 2005
- *     The President and Fellows of Harvard College.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-/* 
- * Writes printf like output to the UART.  
- * This works only on the AVR and MSP430 Microcontrollers!
- * <p>
- * Note: For AVR we explicitly place the print statements in ROM; for
- * MSP430 this is done by default!  For AVR, if we don't place it
- * explicitely in ROM, the statements will go in RAM, which will
- * quickly cause a descent size program to run out of RAM.  By default
- * it doesn't disable the interupts; disabling the interupts when
- * writing to the UART, slows down/makes the mote quite unresponsive,
- * and can lead to problems!  If you wish to disable all printfs to
- * the UART, then comment the flag: <code>PRINTFUART_ENABLED</code>.
-
- * <p> <pre>
- * How to use:
- *   // (1) Call printfUART_init() from your initialization function 
- *   //     to initialize the UART
- *   printfUART_init();
- *   // (2) Set your UART client to the correct baud rate.  Look at 
- *   //     the comments in printfUART_init(), to figure out what 
- *   //     baud to use for your particular mote
- *
- *   // (3) Send printf statements like this:
- *   printfUART("Hello World, we are in year= %i\n", 2004);
- *
- * Examples and caveats:
- *   // (1) - If no parameters are passed, then the second quotes 
- *            are required because of how the macro is defined
- *   printfUART("Timer fired\n", ""); 
- *   // (2) - Must use curly braces in single section statements
- *   if (x < 3)
- *       {printfUART("The value of x is %i\n", x);}
- *   // (3) - Otherwise it more or less works like regular printf
- *   printfUART("\nThe value of x=%i, and y=%i\n", x, y); 
- * </pre>
- * <pre>URL: http://www.eecs.harvard.edu/~konrad/projects/motetrack</pre>
- * @author Konrad Lorincz
- * @version 2.0, January 5, 2005
- */
-#ifndef PRINTFUART_H
-#define PRINTFUART_H
-#include <stdarg.h>
-//#include <stdio.h>
-
-// Comment out the line below to DISABLE printf statements.
-//#define PRINTFUART_ENABLED
-
-
-// -------------------------------------------------------------------
-#ifdef PRINTFUART_ENABLED
-    #define DEBUGBUF_SIZE 256
-    char debugbuf[DEBUGBUF_SIZE];
-    char debugbufROMtoRAM[DEBUGBUF_SIZE];
-
-    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
-        #define printfUART(__format, __args...) {                  \
-            static const char strROM[] PROGMEM = __format;         \
-            strcpy_P((char*) &debugbufROMtoRAM, (PGM_P) &strROM);  \
-            sprintf(debugbuf, debugbufROMtoRAM, __args);           \
-            writedebug();                                          \
-        }   
-    #else  // assume MSP430 architecture (e.g. TelosA, TelosB, etc.)
-        #define printfUART(__format, __args...) {      \
-            sprintf(debugbuf, __format, __args);       \
-            writedebug();                              \
-        }   
-    #endif
-#else
-    #define printfUART(__format, __args...)
-    void printfUART_init() {}
-#endif
-
-#define NOprintfUART(__format, __args...)
-
-
-/** Used for terminating the program from a non-nesc file. Calling <code>exit(1)</code> 
- *  from a non-nesc file doesn't terminate the program immeditely
- */
-static int EXIT_PROGRAM = 0;  
-
-
-
-// -------------------------------------------------------------------
-#ifdef PRINTFUART_ENABLED
-
-/**
- * Initialize the UART port.  Call this from your startup routine.
- */
-#define printfUART_init() {atomic printfUART_init_private();}
-void printfUART_init_private()
-{
-    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2)
-        // 56K baud
-        outp(0,UBRR0H);
-        outp(15, UBRR0L);                              //set baud rate
-        outp((1<<U2X),UCSR0A);                         // Set UART double speed
-        outp(((1 << UCSZ1) | (1 << UCSZ0)) , UCSR0C);  // Set frame format: 8 data-bits, 1 stop-bit
-        inp(UDR0);
-        outp((1 << TXEN) ,UCSR0B);   // Enable uart reciever and transmitter
-
-    #else
-      #if defined(PLATFORM_MICA2DOT)  
-        // 19.2K baud
-        outp(0,UBRR0H);            // Set baudrate to 19.2 KBps
-        outp(12, UBRR0L);
-        outp(0,UCSR0A);            // Disable U2X and MPCM
-        outp(((1 << UCSZ1) | (1 << UCSZ0)) , UCSR0C);
-        inp(UDR0);
-        outp((1 << TXEN) ,UCSR0B);
-  
-      #else  // assume TelosA, TelosB, etc.
-        //9.6K baud
-        uint16_t l_br = 0;
-        uint8_t l_mctl = 0;
-        uint8_t l_ssel = 0;
-
-
-        TOSH_SEL_UTXD1_MODFUNC();
-        TOSH_SEL_URXD1_MODFUNC();
-
-
-        UCTL1 = SWRST;  
-        UCTL1 |= CHAR;  // 8-bit char, UART-mode
-    
-        U1RCTL &= ~URXEIE;  // even erroneous characters trigger interrupts
-
-        UCTL1 = SWRST;
-        UCTL1 |= CHAR;  // 8-bit char, UART-mode
-
-        if (l_ssel & 0x80) {
-            U1TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
-            U1TCTL |= (l_ssel & 0x7F); 
-        }
-        else {
-            U1TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
-            U1TCTL |= SSEL_ACLK; // use ACLK, assuming 32khz
-        }
-
-        if ((l_mctl != 0) || (l_br != 0)) {
-            U1BR0 = l_br & 0x0FF;
-            U1BR1 = (l_br >> 8) & 0x0FF;
-            U1MCTL = l_mctl;
-        }
-        else {
-            U1BR0 = 0x03;   // 9600 baud
-            U1BR1 = 0x00;
-            U1MCTL = 0x4A;
-        }
-      
-        ME2 &= ~USPIE1;   // USART1 SPI module disable
-        ME2 |= (UTXE1 | URXE1);   // USART1 UART module enable
-      
-        U1CTL &= ~SWRST;
-    
-        IFG2 &= ~(UTXIFG1 | URXIFG1);
-        IE2 &= ~(UTXIE1 | URXIE1);  // interrupt disabled
-
-      #endif
-    #endif
-}
-
-#if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
-#else // assume AVR architecture (e.g. TelosA, TelosB)
-    bool isTxIntrPending()
-    {
-        if (U1TCTL & TXEPT) {
-            return TRUE;
-        }
-        return FALSE;
-    }
-#endif
-
-/**
- * Outputs a char to the UART.
- */
-void UARTPutChar(char c)
-{
-    if (c == '\n')
-        UARTPutChar('\r');
-
-
-    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
-        loop_until_bit_is_set(UCSR0A, UDRE);
-        outb(UDR0,c);
-    #else // assume AVR architecture (e.g. TelosA, TelosB)
-        U1TXBUF = c;  
-        while( !isTxIntrPending() )  
-            continue;
-    #endif
-}
-
-/**
- * Outputs the entire debugbuf to the UART, or until it encounters '\0'.
- */
-void writedebug()
-{
-    uint16_t i = 0;
-    
-    while (debugbuf[i] != '\0' && i < DEBUGBUF_SIZE)
-        UARTPutChar(debugbuf[i++]);
-}
-
-
-
-/**
- * Simplified sprintf
- */
-#define SCRATCH 16
-int sprintf(uint8_t *buf, const uint8_t *format, ...)
-{
-    uint8_t scratch[SCRATCH];
-    uint8_t format_flag;
-    uint32_t u_val=0, base;//modified by Andre Cunha
-    uint8_t *ptr;
-    va_list ap;
-
-   //memset(scratch, 0, SCRATCH);
-       
-    buf[0] = '\0';  // KLDEBUG - fixes subtle bug ...
-    va_start (ap, format);
-    for (;;){
-        while ((format_flag = *format++) != '%'){      // Until '%' or '\0'
-            if (!format_flag) {va_end (ap); return (0);}
-            *buf = format_flag; buf++; *buf=0;
-        }
-
-        switch (format_flag = *format++){
-
-        case 'c':
-            format_flag = va_arg(ap,int);
-        default:
-            *buf = format_flag; buf++; *buf=0;
-            continue;
-        case 'S':
-        case 's':
-            ptr = va_arg(ap,char *);
-            strcat(buf, ptr);
-            continue;
-        case 'o':
-            base = 8;
-            *buf = '0'; buf++; *buf=0;
-            goto CONVERSION_LOOP;
-        case 'i':
-            if (((int)u_val) < 0){
-                u_val = - u_val;
-                *buf = '-'; buf++; *buf=0;
-            }
-                       base = 10;
-            goto CONVERSION_LOOP;
-            // no break -> run into next case
-                case 'd'://added by Andre Cunha
-            if (((int32_t)u_val) < 0){
-                u_val = - u_val;
-                *buf = '-'; buf++; *buf=0;
-            }
-            
-                       base = 10;
-            goto CONVERSION_LOOP32;
-        case 'u':
-            base = 10;
-            goto CONVERSION_LOOP;
-        case 'x':
-            base = 16;
-                       goto CONVERSION_LOOP;
-                       
-               case 'y'://unsigned int 32 bits hexadecimal//added by Andre Cunha
-            base = 16;
-                       goto CONVERSION_LOOP32;
-                       
-        CONVERSION_LOOP:
-            u_val = va_arg(ap,int);
-            ptr = scratch + SCRATCH;
-            *--ptr = 0;
-            do {
-                char ch = u_val % base + '0';
-                if (ch > '9')
-                    ch += 'a' - '9' - 1;
-                *--ptr = ch;
-                u_val /= base;
-            } while (u_val);
-            strcat(buf, ptr);
-            buf += strlen(ptr);
-                       break;
-                       
-               CONVERSION_LOOP32:
-            u_val = va_arg(ap,int32_t);
-            ptr = scratch + SCRATCH;
-            *--ptr = 0;
-            do {
-                char ch = u_val % base + '0';
-                if (ch > '9')
-                    ch += 'a' - '9' - 1;
-                *--ptr = ch;
-                u_val /= base;
-            } while (u_val);
-            strcat(buf, ptr);
-            buf += strlen(ptr);
-        }
-    }
-}
-
-
-#endif  // PRINTFUART_ENABLED
-// -------------------------------------------------------------------
-
-#endif  // PRINTFUART_H
-
diff --git a/tos/lib/net/zigbee/ieee802154/includes/printfUART.h b/tos/lib/net/zigbee/ieee802154/includes/printfUART.h
new file mode 100644 (file)
index 0000000..35a736f
--- /dev/null
@@ -0,0 +1,336 @@
+/*
+ * Copyright (c) 2005
+ *     The President and Fellows of Harvard College.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* 
+ * Writes printf like output to the UART.  
+ * This works only on the AVR and MSP430 Microcontrollers!
+ * <p>
+ * Note: For AVR we explicitly place the print statements in ROM; for
+ * MSP430 this is done by default!  For AVR, if we don't place it
+ * explicitely in ROM, the statements will go in RAM, which will
+ * quickly cause a descent size program to run out of RAM.  By default
+ * it doesn't disable the interupts; disabling the interupts when
+ * writing to the UART, slows down/makes the mote quite unresponsive,
+ * and can lead to problems!  If you wish to disable all printfs to
+ * the UART, then comment the flag: <code>PRINTFUART_ENABLED</code>.
+
+ * <p> <pre>
+ * How to use:
+ *   // (1) Call printfUART_init() from your initialization function 
+ *   //     to initialize the UART
+ *   printfUART_init();
+ *   // (2) Set your UART client to the correct baud rate.  Look at 
+ *   //     the comments in printfUART_init(), to figure out what 
+ *   //     baud to use for your particular mote
+ *
+ *   // (3) Send printf statements like this:
+ *   printfUART("Hello World, we are in year= %i\n", 2004);
+ *
+ * Examples and caveats:
+ *   // (1) - If no parameters are passed, then the second quotes 
+ *            are required because of how the macro is defined
+ *   printfUART("Timer fired\n", ""); 
+ *   // (2) - Must use curly braces in single section statements
+ *   if (x < 3)
+ *       {printfUART("The value of x is %i\n", x);}
+ *   // (3) - Otherwise it more or less works like regular printf
+ *   printfUART("\nThe value of x=%i, and y=%i\n", x, y); 
+ * </pre>
+ * <pre>URL: http://www.eecs.harvard.edu/~konrad/projects/motetrack</pre>
+ * @author Konrad Lorincz
+ * @version 2.0, January 5, 2005
+ */
+#ifndef PRINTFUART_H
+#define PRINTFUART_H
+#include <stdarg.h>
+//#include <stdio.h>
+
+// Comment out the line below to DISABLE printf statements.
+#define PRINTFUART_ENABLED
+
+
+// -------------------------------------------------------------------
+#ifdef PRINTFUART_ENABLED
+    #define DEBUGBUF_SIZE 256
+    char debugbuf[DEBUGBUF_SIZE];
+    char debugbufROMtoRAM[DEBUGBUF_SIZE];
+
+    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
+        #define printfUART(__format, __args...) {                  \
+            static const char strROM[] PROGMEM = __format;         \
+            strcpy_P((char*) &debugbufROMtoRAM, (PGM_P) &strROM);  \
+            sprintf(debugbuf, debugbufROMtoRAM, __args);           \
+            writedebug();                                          \
+        }   
+    #else  // assume MSP430 architecture (e.g. TelosA, TelosB, etc.)
+        #define printfUART(__format, __args...) {      \
+            sprintf(debugbuf, __format, __args);       \
+            writedebug();                              \
+        }   
+    #endif
+#else
+    #define printfUART(__format, __args...)
+    void printfUART_init() {}
+#endif
+
+#define NOprintfUART(__format, __args...)
+
+
+/** Used for terminating the program from a non-nesc file. Calling <code>exit(1)</code> 
+ *  from a non-nesc file doesn't terminate the program immeditely
+ */
+static int EXIT_PROGRAM = 0;  
+
+
+
+// -------------------------------------------------------------------
+#ifdef PRINTFUART_ENABLED
+
+/**
+ * Initialize the UART port.  Call this from your startup routine.
+ */
+#define printfUART_init() {atomic printfUART_init_private();}
+void printfUART_init_private()
+{
+    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2)
+        // 56K baud
+        outp(0,UBRR0H);
+        outp(15, UBRR0L);                              //set baud rate
+        outp((1<<U2X),UCSR0A);                         // Set UART double speed
+        outp(((1 << UCSZ1) | (1 << UCSZ0)) , UCSR0C);  // Set frame format: 8 data-bits, 1 stop-bit
+        inp(UDR0);
+        outp((1 << TXEN) ,UCSR0B);   // Enable uart reciever and transmitter
+
+    #else
+      #if defined(PLATFORM_MICA2DOT)  
+        // 19.2K baud
+        outp(0,UBRR0H);            // Set baudrate to 19.2 KBps
+        outp(12, UBRR0L);
+        outp(0,UCSR0A);            // Disable U2X and MPCM
+        outp(((1 << UCSZ1) | (1 << UCSZ0)) , UCSR0C);
+        inp(UDR0);
+        outp((1 << TXEN) ,UCSR0B);
+  
+      #else  // assume TelosA, TelosB, etc.
+        //9.6K baud
+        uint16_t l_br = 0;
+        uint8_t l_mctl = 0;
+        uint8_t l_ssel = 0;
+
+
+        TOSH_SEL_UTXD1_MODFUNC();
+        TOSH_SEL_URXD1_MODFUNC();
+
+
+        UCTL1 = SWRST;  
+        UCTL1 |= CHAR;  // 8-bit char, UART-mode
+    
+        U1RCTL &= ~URXEIE;  // even erroneous characters trigger interrupts
+
+        UCTL1 = SWRST;
+        UCTL1 |= CHAR;  // 8-bit char, UART-mode
+
+        if (l_ssel & 0x80) {
+            U1TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
+            U1TCTL |= (l_ssel & 0x7F); 
+        }
+        else {
+            U1TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
+            U1TCTL |= SSEL_ACLK; // use ACLK, assuming 32khz
+        }
+
+        if ((l_mctl != 0) || (l_br != 0)) {
+            U1BR0 = l_br & 0x0FF;
+            U1BR1 = (l_br >> 8) & 0x0FF;
+            U1MCTL = l_mctl;
+        }
+        else {
+            U1BR0 = 0x03;   // 9600 baud
+            U1BR1 = 0x00;
+            U1MCTL = 0x4A;
+        }
+      
+        ME2 &= ~USPIE1;   // USART1 SPI module disable
+        ME2 |= (UTXE1 | URXE1);   // USART1 UART module enable
+      
+        U1CTL &= ~SWRST;
+    
+        IFG2 &= ~(UTXIFG1 | URXIFG1);
+        IE2 &= ~(UTXIE1 | URXIE1);  // interrupt disabled
+
+      #endif
+    #endif
+}
+
+#if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
+#else // assume AVR architecture (e.g. TelosA, TelosB)
+    bool isTxIntrPending()
+    {
+        if (U1TCTL & TXEPT) {
+            return TRUE;
+        }
+        return FALSE;
+    }
+#endif
+
+/**
+ * Outputs a char to the UART.
+ */
+void UARTPutChar(char c)
+{
+    if (c == '\n')
+        UARTPutChar('\r');
+
+
+    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
+        loop_until_bit_is_set(UCSR0A, UDRE);
+        outb(UDR0,c);
+    #else // assume AVR architecture (e.g. TelosA, TelosB)
+        U1TXBUF = c;  
+        while( !isTxIntrPending() )  
+            continue;
+    #endif
+}
+
+/**
+ * Outputs the entire debugbuf to the UART, or until it encounters '\0'.
+ */
+void writedebug()
+{
+    uint16_t i = 0;
+    
+    while (debugbuf[i] != '\0' && i < DEBUGBUF_SIZE)
+        UARTPutChar(debugbuf[i++]);
+}
+
+
+
+/**
+ * Simplified sprintf
+ */
+#define SCRATCH 16
+int sprintf(uint8_t *buf, const uint8_t *format, ...)
+{
+    uint8_t scratch[SCRATCH];
+    uint8_t format_flag;
+    uint32_t u_val=0, base;//modified by Andre Cunha
+    uint8_t *ptr;
+    va_list ap;
+
+   //memset(scratch, 0, SCRATCH);
+       
+    buf[0] = '\0';  // KLDEBUG - fixes subtle bug ...
+    va_start (ap, format);
+    for (;;){
+        while ((format_flag = *format++) != '%'){      // Until '%' or '\0'
+            if (!format_flag) {va_end (ap); return (0);}
+            *buf = format_flag; buf++; *buf=0;
+        }
+
+        switch (format_flag = *format++){
+
+        case 'c':
+            format_flag = va_arg(ap,int);
+        default:
+            *buf = format_flag; buf++; *buf=0;
+            continue;
+        case 'S':
+        case 's':
+            ptr = va_arg(ap,char *);
+            strcat(buf, ptr);
+            continue;
+        case 'o':
+            base = 8;
+            *buf = '0'; buf++; *buf=0;
+            goto CONVERSION_LOOP;
+        case 'i':
+            if (((int)u_val) < 0){
+                u_val = - u_val;
+                *buf = '-'; buf++; *buf=0;
+            }
+                       base = 10;
+            goto CONVERSION_LOOP;
+            // no break -> run into next case
+                case 'd'://added by Andre Cunha
+            if (((int32_t)u_val) < 0){
+                u_val = - u_val;
+                *buf = '-'; buf++; *buf=0;
+            }
+            
+                       base = 10;
+            goto CONVERSION_LOOP32;
+        case 'u':
+            base = 10;
+            goto CONVERSION_LOOP;
+        case 'x':
+            base = 16;
+                       goto CONVERSION_LOOP;
+                       
+               case 'y'://unsigned int 32 bits hexadecimal//added by Andre Cunha
+            base = 16;
+                       goto CONVERSION_LOOP32;
+                       
+        CONVERSION_LOOP:
+            u_val = va_arg(ap,int);
+            ptr = scratch + SCRATCH;
+            *--ptr = 0;
+            do {
+                char ch = u_val % base + '0';
+                if (ch > '9')
+                    ch += 'a' - '9' - 1;
+                *--ptr = ch;
+                u_val /= base;
+            } while (u_val);
+            strcat(buf, ptr);
+            buf += strlen(ptr);
+                       break;
+                       
+               CONVERSION_LOOP32:
+            u_val = va_arg(ap,int32_t);
+            ptr = scratch + SCRATCH;
+            *--ptr = 0;
+            do {
+                char ch = u_val % base + '0';
+                if (ch > '9')
+                    ch += 'a' - '9' - 1;
+                *--ptr = ch;
+                u_val /= base;
+            } while (u_val);
+            strcat(buf, ptr);
+            buf += strlen(ptr);
+        }
+    }
+}
+
+
+#endif  // PRINTFUART_ENABLED
+// -------------------------------------------------------------------
+
+#endif  // PRINTFUART_H
+
diff --git a/tos/lib/net/zigbee/ieee802154/mac/Mac.nc b/tos/lib/net/zigbee/ieee802154/mac/Mac.nc
deleted file mode 100644 (file)
index 28da2de..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-
-#include <Timer.h>
-
-configuration Mac {
-
-
-               //MLME  
-               provides interface MLME_START;
-               provides interface MLME_SET;
-               provides interface MLME_GET;
-               
-               provides interface MLME_ASSOCIATE;
-               provides interface MLME_DISASSOCIATE;
-               
-               provides interface MLME_BEACON_NOTIFY;
-               provides interface MLME_GTS;
-               
-               provides interface MLME_ORPHAN;
-
-               provides interface MLME_SYNC;
-               provides interface MLME_SYNC_LOSS;
-               
-               provides interface MLME_RESET;
-               
-               provides interface MLME_SCAN;
-               
-               //MCPS
-               provides interface MCPS_DATA;
-               provides interface MCPS_PURGE;
-
-}
-implementation {
-
-       components MainC;
-       MainC.SoftwareInit -> MacM;
-
-       components LedsC;
-       components MacM;
-
-       components Phy;
-
-       components TimerAsyncC;
-       
-       MacM.TimerAsync ->TimerAsyncC;
-
-       MacM.Leds -> LedsC;
-       
-       
-       MacM.AMControl ->Phy.SplitControl;
-       
-       components HplCC2420PinsC as Pins;
-       MacM.CCA -> Pins.CCA;
-       
-       components RandomC;
-       MacM.Random -> RandomC;
-
-       components new TimerMilliC() as T_ackwait;
-       MacM.T_ackwait -> T_ackwait;
-       
-       components new TimerMilliC() as T_ResponseWaitTime;
-       MacM.T_ResponseWaitTime -> T_ResponseWaitTime;
-       
-       components new TimerMilliC() as T_ScanDuration;
-       MacM.T_ScanDuration -> T_ScanDuration;
-
-       components CC2420ReceiveC;
-       MacM.AddressFilter -> CC2420ReceiveC;
-
-       /*****************************************************/
-       /*                              INTERFACES                                               */
-       /*****************************************************/  
-       MacM.PD_DATA -> Phy.PD_DATA;
-       MacM.PLME_ED ->Phy.PLME_ED;
-       MacM.PLME_CCA -> Phy.PLME_CCA;
-       MacM.PLME_SET -> Phy.PLME_SET;
-       MacM.PLME_GET -> Phy.PLME_GET;
-       MacM.PLME_SET_TRX_STATE -> Phy.PLME_SET_TRX_STATE;
-
-
-       //MLME interfaces
-       MLME_START=MacM;
-
-       MLME_SET=MacM;
-       MLME_GET=MacM;
-       
-       MLME_ASSOCIATE=MacM;
-       MLME_DISASSOCIATE=MacM;
-       
-       MLME_BEACON_NOTIFY = MacM;
-       MLME_GTS=MacM;
-       
-       MLME_ORPHAN=MacM;
-       
-       MLME_SYNC=MacM;
-       MLME_SYNC_LOSS=MacM;
-       
-       MLME_RESET=MacM;
-       
-       MLME_SCAN=MacM;
-       
-       MCPS_DATA=MacM;
-       MCPS_PURGE=MacM;
-       
-       
-       
-       
-
-}
-
diff --git a/tos/lib/net/zigbee/ieee802154/mac/MacC.nc b/tos/lib/net/zigbee/ieee802154/mac/MacC.nc
new file mode 100644 (file)
index 0000000..f8262d2
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+
+#include <Timer.h>
+
+configuration MacC {
+
+
+               //MLME  
+               provides interface MLME_START;
+               provides interface MLME_SET;
+               provides interface MLME_GET;
+               
+               provides interface MLME_ASSOCIATE;
+               provides interface MLME_DISASSOCIATE;
+               
+               provides interface MLME_BEACON_NOTIFY;
+               provides interface MLME_GTS;
+               
+               provides interface MLME_ORPHAN;
+
+               provides interface MLME_SYNC;
+               provides interface MLME_SYNC_LOSS;
+               
+               provides interface MLME_RESET;
+               
+               provides interface MLME_SCAN;
+               
+               //MCPS
+               provides interface MCPS_DATA;
+               provides interface MCPS_PURGE;
+
+}
+implementation {
+
+       components MainC;
+       MainC.SoftwareInit -> MacP;
+
+       components LedsC;
+       components MacP;
+
+       components PhyC;
+
+       components TimerAsyncC;
+       
+       MacP.TimerAsync ->TimerAsyncC;
+
+       MacP.Leds -> LedsC;
+       
+       
+       MacP.AMControl ->PhyC.SplitControl;
+       
+       components HplCC2420PinsC as Pins;
+       MacP.CCA -> Pins.CCA;
+       
+       components RandomC;
+       MacP.Random -> RandomC;
+
+       components new TimerMilliC() as T_ackwait;
+       MacP.T_ackwait -> T_ackwait;
+       
+       components new TimerMilliC() as T_ResponseWaitTime;
+       MacP.T_ResponseWaitTime -> T_ResponseWaitTime;
+       
+       components new TimerMilliC() as T_ScanDuration;
+       MacP.T_ScanDuration -> T_ScanDuration;
+
+       components CC2420ReceiveC;
+       MacP.AddressFilter -> CC2420ReceiveC;
+
+       /*****************************************************/
+       /*                              INTERFACES                                               */
+       /*****************************************************/  
+       MacP.PD_DATA -> PhyC.PD_DATA;
+       MacP.PLME_ED ->PhyC.PLME_ED;
+       MacP.PLME_CCA -> PhyC.PLME_CCA;
+       MacP.PLME_SET -> PhyC.PLME_SET;
+       MacP.PLME_GET -> PhyC.PLME_GET;
+       MacP.PLME_SET_TRX_STATE -> PhyC.PLME_SET_TRX_STATE;
+
+
+       //MLME interfaces
+       MLME_START=MacP;
+
+       MLME_SET=MacP;
+       MLME_GET=MacP;
+       
+       MLME_ASSOCIATE=MacP;
+       MLME_DISASSOCIATE=MacP;
+       
+       MLME_BEACON_NOTIFY = MacP;
+       MLME_GTS=MacP;
+       
+       MLME_ORPHAN=MacP;
+       
+       MLME_SYNC=MacP;
+       MLME_SYNC_LOSS=MacP;
+       
+       MLME_RESET=MacP;
+       
+       MLME_SCAN=MacP;
+       
+       MCPS_DATA=MacP;
+       MCPS_PURGE=MacP;
+       
+       
+       
+       
+
+}
+
diff --git a/tos/lib/net/zigbee/ieee802154/mac/MacM.nc b/tos/lib/net/zigbee/ieee802154/mac/MacM.nc
deleted file mode 100644 (file)
index dc25d0f..0000000
+++ /dev/null
@@ -1,5379 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-
-#include <Timer.h>
-
-#include "printfUART.h"
-
-#include "frame_format.h"
-#include "phy_const.h"
-
-#include "mac_const.h"
-#include "mac_enumerations.h"
-
-#include "mac_func.h"
-
-module MacM {
-       provides interface Init;
-       
-       provides interface MLME_START;
-       provides interface MLME_SET;
-    provides interface MLME_GET;
-       
-       provides interface MLME_ASSOCIATE;
-       provides interface MLME_DISASSOCIATE;
-       
-       provides interface MLME_BEACON_NOTIFY;
-       provides interface MLME_GTS;
-       
-       provides interface MLME_ORPHAN;
-       
-       provides interface MLME_SYNC;
-       provides interface MLME_SYNC_LOSS;
-               
-       provides interface MLME_RESET;
-       
-       provides interface MLME_SCAN;
-       
-       //MCPS
-       provides interface MCPS_DATA;
-       provides interface MCPS_PURGE;
-               
-       
-       uses interface Timer<TMilli> as T_ackwait;      
-               
-       uses interface Timer<TMilli> as T_ResponseWaitTime;
-       
-       uses interface Timer<TMilli> as T_ScanDuration;
-       
-       uses interface Leds;
-       
-       uses interface SplitControl as AMControl;
-       
-       uses interface Random;
-       
-       uses interface GeneralIO as CCA;
-       
-       //uses interface Test_send;
-       
-       uses interface TimerAsync;
-       
-       uses interface PD_DATA;
-       
-       uses interface PLME_ED;
-       uses interface PLME_CCA;
-       uses interface PLME_SET;
-       uses interface PLME_GET;
-       uses interface PLME_SET_TRX_STATE;
-
-
-       uses interface AddressFilter;
-
-  
-}
-implementation {
-/*****************************************************/
-/*                             GENERAL                                  */
-/*****************************************************/  
-       /***************Variables*************************/
-       //local extended address
-       uint32_t aExtendedAddress0;
-       uint32_t aExtendedAddress1;
-
-       macPIB mac_PIB;
-
-//If the the MLME receives a start request the node becomes a pan coordinator
-       //and start transmiting beacons 
-       bool PANCoordinator = 0;
-       //(0 NO beacon transmission; 1 beacon transmission);
-       bool Beacon_enabled_PAN = 0;
-       
-       //(RESET) when the reset command arrives it checks whether or not to reset the PIB
-       bool SetDefaultPIB=0;
-       
-       //use security
-       bool SecurityEnable=0;
-       
-       //others
-       bool pending_reset=0;
-       
-       //transceiver status -every time the transceiver changes state this variable is updated
-       uint8_t trx_status;
-       
-       //defines the transmission
-       bool beacon_enabled=0;
-       
-       /***************Functions Definition***************/
-       
-       void init_MacPIB(); 
-       
-       uint8_t min(uint8_t val1, uint8_t val2);
-       
-       void init_MacCon();
-       
-       
-       task void signal_loss();
-       
-
-       void create_data_request_cmd();
-       void create_beacon_request_cmd();
-       void create_gts_request_cmd(uint8_t gts_characteristics);
-       
-       void build_ack(uint8_t sequence,uint8_t frame_pending);
-       
-       void create_data_frame(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions,uint8_t on_gts_slot,uint8_t pan);
-
-
-
-
-/*****************************************************/        
-/*                             Association                                      */
-/*****************************************************/ 
-       /***************Variables*************************/
-       uint8_t associating = 0;
-       uint8_t association_cmd_seq_num =0;
-       
-       /*association parameters*/
-       
-       uint8_t a_LogicalChannel;
-       uint8_t a_CoordAddrMode;
-       uint16_t a_CoordPANId;
-       uint32_t a_CoordAddress[2];
-       uint8_t a_CapabilityInformation;
-       bool a_securityenable;
-       
-       /***************Functions Definition***************/            
-       
-       void create_association_request_cmd(uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation);
-
-       error_t create_association_response_cmd(uint32_t DeviceAddress[],uint16_t shortaddress, uint8_t status);
-       
-       void create_disassociation_notification_cmd(uint32_t DeviceAddress[],uint8_t disassociation_reason);
-       
-       void process_dissassociation_notification(MPDU *pdu);
-
-/*****************************************************/
-/*                             Synchronization                                  */
-/*****************************************************/ 
-       /***************Variables*************************/
-       //(SYNC)the device will try to track the beacon ie enable its receiver just before the espected time of each beacon
-       bool TrackBeacon=0;
-       bool beacon_processed=0;
-       //beacon loss indication
-       uint8_t beacon_loss_reason;
-       
-       //(SYNC)the device will try to locate one beacon
-       bool findabeacon=0;
-       //(SYNC)number of beacons lost before sending a Beacon-Lost indication comparing to aMaxLostBeacons
-       uint8_t missed_beacons=0;
-       //boolean variable stating if the device is synchonized with the beacon or not
-       uint8_t on_sync=0;
-       
-       uint32_t parent_offset=0x00000000;
-
-
-/*****************************************************/
-/*                             GTS Variables                                    */
-/*****************************************************/  
-       /***************Variables*************************/
-       
-       uint8_t gts_request=0;
-       uint8_t gts_request_seq_num=0;
-       
-       bool gts_confirm;
-       
-       uint8_t GTS_specification;
-       bool GTSCapability=1;
-       
-       uint8_t final_CAP_slot=15;
-       
-       //GTS descriptor variables, coordinator usage only
-       GTSinfoEntryType GTS_db[7];
-       uint8_t GTS_descriptor_count=0;
-       uint8_t GTS_startslot=16;
-       uint8_t GTS_id=0x01;
-
-
-       //null gts descriptors
-       GTSinfoEntryType_null GTS_null_db[7];
-       
-       uint8_t GTS_null_descriptor_count=0;
-       //uint8_t GTS_null_id=0x01;
-       
-       //node GTS variables
-       // 1 GTS for transmit
-       uint8_t s_GTSss=0;           //send gts start slot
-       uint8_t s_GTS_length=0;          //send gts length
-       //1 GTS for receive
-       uint8_t r_GTSss=0;                       //receive gts start slot
-       uint8_t r_GTS_length=0;          //receive gts lenght
-       
-       //used to state that the device is on its transmit slot
-       uint8_t on_s_GTS=0;
-       //used to state that the device is on its receive slot
-       uint8_t on_r_GTS=0;
-       
-       //used to determine if the next time slot is used for transmission
-       uint8_t next_on_s_GTS=0;
-       //used to determine if the next time slot is used for reception
-       uint8_t next_on_r_GTS=0;
-       
-       //variable stating if the coordinator allow GTS allocations
-       uint8_t allow_gts=1;
-       
-       //COORDINATOR GTS BUFFER        
-       gts_slot_element gts_slot_list[7];
-       uint8_t available_gts_index[GTS_SEND_BUFFER_SIZE];
-       uint8_t available_gts_index_count;
-       
-       uint8_t coordinator_gts_send_pending_data=0;
-       uint8_t coordinator_gts_send_time_slot=0;
-       
-       //gts buffer used to store the gts messages both in COORDINATOR and NON COORDINATOR
-       norace MPDU gts_send_buffer[GTS_SEND_BUFFER_SIZE];
-       
-       //NON PAN COORDINATOR BUFFER
-       //buffering for sending
-       uint8_t gts_send_buffer_count=0;
-       uint8_t gts_send_buffer_msg_in=0;
-       uint8_t gts_send_buffer_msg_out=0;
-       uint8_t gts_send_pending_data=0;
-       
-
-       /***************Functions Definition***************/
-       
-       void process_gts_request(MPDU *pdu);    
-       void init_available_gts_index();
-       task void start_coordinator_gts_send();
-       
-       
-       //GTS FUNCTIONS
-       error_t remove_gts_entry(uint16_t DevAddressType);
-       error_t add_gts_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType);
-       error_t add_gts_null_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType);
-       
-       //increment the idle GTS for GTS deallocation purposes, not fully implemented yet
-       task void increment_gts_null();
-       
-       task void start_gts_send();
-       
-       
-       
-       //initialization functions
-       void init_gts_slot_list();
-       void init_GTS_null_db();
-       
-       void init_GTS_db();
-
-
-       uint32_t calculate_gts_expiration();
-       task void check_gts_expiration();
-
-
-/*****************************************************/
-/*                             CHANNEL SCAN Variables                           */
-/*****************************************************/ 
-       //current_channel
-       uint8_t current_channel=0;
-
-       /***************Variables*************************/
-       //ED-SCAN variables
-       
-       bool scanning_channels;
-       
-       uint32_t channels_to_scan;
-       uint8_t current_scanning=0;
-       //uint8_t scan_count=0;
-       uint8_t scanned_values[16];
-       uint8_t scan_type;
-       
-       SCAN_PANDescriptor scan_pans[16];
-       
-       uint16_t scan_duration;
-       
-       task void data_channel_scan_indication();
-       
-/*****************************************************/
-/*                             TIMER VARIABLES                                  */
-/*****************************************************/  
-       /***************Variables*************************/
-       uint32_t response_wait_time;
-       
-       //Beacon Interval
-       uint32_t BI;
-       //Superframe duration
-       uint32_t SD;
-       
-       //timer variables
-       uint32_t time_slot; //backoff boundary timer
-       uint32_t backoff;  //backoff timer
-       
-       //current number of backoffs in the active period
-       uint8_t number_backoff=1;
-       uint8_t number_time_slot=0;
-       
-       bool csma_slotted=0;
-/*****************************************************/
-/*                             CSMA VARIABLES                                   */
-/*****************************************************/        
-       /***************Variables*************************/     
-
-       //DEFERENCE CHANGE
-       uint8_t cca_deference = 0;
-       uint8_t backoff_deference = 0;
-       uint8_t check_csma_ca_backoff_send_conditions(uint32_t delay_backoffs);
-
-       //STEP 2
-       uint8_t delay_backoff_period;
-       bool csma_delay=0;
-       
-       bool csma_locate_backoff_boundary=0;
-       
-       bool csma_cca_backoff_boundary=0;
-       
-       //Although the receiver of the device is enabled during the channel assessment portion of this algorithm, the
-       //device shall discard any frames received during this time.
-       bool performing_csma_ca=0;
-       
-       //CSMA-CA variables
-       uint8_t BE; //backoff exponent
-       uint8_t CW; //contention window (number of backoffs to clear the channel)
-       uint8_t NB; //number of backoffs
-
-       /***************Functions Definition***************/    
-       
-       void init_csma_ca(bool slotted);
-       void perform_csma_ca();
-       task void perform_csma_ca_unslotted();
-       task void perform_csma_ca_slotted();
-       //task void start_csma_ca_slotted();
-       
-/*****************************************************/
-/*                             Indirect Transmission buffers            */
-/*****************************************************/
-       /***************Variables*************************/     
-       //indirect transmission buffer
-       norace indirect_transmission_element indirect_trans_queue[INDIRECT_BUFFER_SIZE];
-       //indirect transmission message counter
-       uint8_t indirect_trans_count=0;
-
-       /***************Functions Definition***************/    
-       
-       //function used to initialize the indirect transmission buffer
-       void init_indirect_trans_buffer();
-       //function used to search and send an existing indirect transmission message
-       void send_ind_trans_addr(uint32_t DeviceAddress[]);
-       //function used to remove an existing indirect transmission message
-       error_t remove_indirect_trans(uint8_t handler);
-       //function used to increment the transaction persistent time on each message
-       //if the transaction time expires the messages are discarded
-       void increment_indirect_trans();
-       
-/*****************************************************/
-/*                             RECEIVE buffers                           */
-/*****************************************************/  
-       /***************Variables*************************/
-       
-       //buffering variables
-       norace MPDU buffer_msg[RECEIVE_BUFFER_SIZE];
-       int current_msg_in=0;
-       int current_msg_out=0;
-       int buffer_count=0;
-
-       /***************Functions Definition***************/    
-       
-       task void data_indication();
-       
-       void indication_cmd(MPDU *pdu, int8_t ppduLinkQuality);
-       void indication_ack(MPDU *pdu, int8_t ppduLinkQuality);
-       void indication_data(MPDU *pdu, int8_t ppduLinkQuality);
-/*****************************************************/
-/*                             RECEPTION AND TRANSMISSION                                */
-/*****************************************************/  
-       
-       /***************Variables*************************/
-       
-       //buffering for sending
-       norace MPDUBuffer send_buffer[SEND_BUFFER_SIZE];
-       uint8_t send_buffer_count=0;
-       uint8_t send_buffer_msg_in=0;
-       uint8_t send_buffer_msg_out=0;
-       
-       //retransmission information
-       uint8_t send_ack_check;//ack requested in the transmitted frame
-       uint8_t retransmit_count;//retransmission count
-       uint8_t ack_sequence_number_check;//transmission sequence number
-       uint8_t send_retransmission;
-       uint8_t send_indirect_transmission;
-
-       uint8_t pending_request_data=0;
-       
-       uint8_t ackwait_period;
-       
-       uint8_t link_quality;
-       
-       norace ACK mac_ack;
-       ACK *mac_ack_ptr;
-       
-       uint32_t gts_expiration;
-
-       uint8_t I_AM_IN_CAP=0;
-       uint8_t I_AM_IN_CFP=0;
-       uint8_t I_AM_IN_IP=0;
-       
-       /***************Functions Definition***************/    
-       
-       task void send_frame_csma();
-       
-       uint8_t check_csma_ca_send_conditions(uint8_t frame_length,uint8_t frame_control1);
-
-       uint8_t check_gts_send_conditions(uint8_t frame_length);
-       
-       uint8_t calculate_ifs(uint8_t pk_length);
-
-
-
-/*****************************************************/
-/*                             BEACON MANAGEMENT                             */
-/*****************************************************/ 
-       /***************Variables*************************/
-       norace MPDU mac_beacon_txmpdu;
-       MPDU *mac_beacon_txmpdu_ptr;
-       
-       uint8_t *send_beacon_frame_ptr;
-       uint8_t send_beacon_length;
-
-       /***************Functions Definition***************/    
-       /*function to create the beacon*/
-       task void create_beacon();
-       /*function to process the beacon information*/
-       void process_beacon(MPDU *packet,uint8_t ppduLinkQuality);
-       
-
-/*****************************************************/
-/*                             Fault tolerance functions            */
-/*****************************************************/ 
-       
-       void create_coordinator_realignment_cmd(uint32_t device_extended0, uint32_t device_extended1, uint16_t device_short_address);
-
-       void create_orphan_notification();
-       
-       
-
-       void process_coordinator_realignment(MPDU *pdu);
-
-/***************************DEBUG FUNCTIONS******************************/
-/* This function are list functions with the purpose of debug, to use then uncomment the declatarion
-on top of this file*/
-/*
-       void list_mac_pib();
-       
-       void list_gts();
-       
-       void list_my_gts();
-       void list_gts_null();
-       */
-       //list all the handles in the indirect transmission buffer, debug purposes
-       void list_indirect_trans_buffer();      
-                       
-/***************************END DEBUG FUNCTIONS******************************/
-
-
-/***************** Init Commands ****************/
-  command error_t Init.init() {
-  
-  call AMControl.start();
-
-
-       //initialization of the beacon structure
-       mac_beacon_txmpdu_ptr = &mac_beacon_txmpdu;
-
-
-
-   atomic{
-       //inicialize the mac PIB
-       init_MacPIB();
-       
-       init_GTS_db();
-       
-       init_GTS_null_db();
-       
-       init_gts_slot_list();
-       
-       init_available_gts_index();
-       
-       aExtendedAddress0=TOS_NODE_ID;
-       aExtendedAddress1=TOS_NODE_ID;
-       
-       
-       call AddressFilter.set_address(mac_PIB.macShortAddress, aExtendedAddress0, aExtendedAddress1);
-
-       call AddressFilter.set_coord_address(mac_PIB.macCoordShortAddress, mac_PIB.macPANId);
-       
-       
-       
-       
-       init_indirect_trans_buffer();
-
-
-       }
-       
-       //beacon
-       mac_beacon_txmpdu_ptr = &mac_beacon_txmpdu;
-               
-       //ack
-       mac_ack_ptr = &mac_ack;
-       
-       //Other timers, sync timers units expressed in miliseconds
-       ackwait_period = ((mac_PIB.macAckWaitDuration * 4.0 ) / 250.0) * 3;
-
-       response_wait_time = ((aResponseWaitTime * 4.0) / 250.0) * 2;
-
-       atomic{
-       
-               
-               BI = aBaseSuperframeDuration * powf(2,mac_PIB.macBeaconOrder);
-               SD = aBaseSuperframeDuration * powf(2,mac_PIB.macSuperframeOrder);
-               
-               
-               //backoff_period
-               backoff = aUnitBackoffPeriod;
-               //backoff_period_boundary
-               
-               time_slot = SD / NUMBER_TIME_SLOTS;
-                       
-               call TimerAsync.set_enable_backoffs(1); 
-               call TimerAsync.set_backoff_symbols(backoff);
-               
-               call TimerAsync.set_bi_sd(BI,SD);
-               
-               call TimerAsync.start();
-       }
-
-
-printfUART_init();
-
-    return SUCCESS;
-  }
-
-  event void AMControl.startDone(error_t err) {
-    if (err == SUCCESS) {
-       
-       call TimerAsync.start();
-               
-       }
-    else {
-      call AMControl.start();
-    }
-  }
-
-  event void AMControl.stopDone(error_t err) {
-  }
-
-
-/*****************************************************/
-/*                             TIMERS FIRED                                             */
-/*****************************************************/ 
-
-async event error_t TimerAsync.before_bi_fired()
-{
-       ////printfUART("bbi %i\n",call TimerAsync.get_current_ticks());
-               
-       if (mac_PIB.macBeaconOrder != mac_PIB.macSuperframeOrder )
-       {
-               if ( Beacon_enabled_PAN == 1 )
-               {
-                       //
-                       //post set_trx();
-                       trx_status = PHY_TX_ON;
-                       call PLME_SET_TRX_STATE.request(PHY_TX_ON);
-               }
-               else
-               {
-                       //
-                       //post set_trx();
-                       trx_status = PHY_RX_ON;
-                       call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-               }
-       }
-       
-       //I_AM_IN_CAP = 1;
-       findabeacon = 1;
-               
-       return SUCCESS;
-}
-
-/*******************Timer BEACON INTERVAL******************/
-async event error_t TimerAsync.bi_fired()
-{
-       call Leds.led2On();
-       //call Test_send.send();
-       
-       I_AM_IN_CAP = 1;
-       I_AM_IN_IP = 0;
-       
-       ////printfUART("bi\n","");
-       
-       
-       if ( Beacon_enabled_PAN == 1 )
-       {
-               //the beacon is send directly without CSMA/CA
-               call PD_DATA.request(send_beacon_length,send_beacon_frame_ptr);
-       }
-
-       number_backoff =0;
-       number_time_slot=0;
-       
-       
-       //CHECK there is the need to wait a small amount of time before checking if the beacon as been processed or not
-       //possible solition, if it receives a packet stand by for confirmation it its a beacon
-       //The device must always receive the beacon
-       if (TrackBeacon == 1) 
-       {
-               if (beacon_processed==1) 
-               {
-                       beacon_processed=0;
-               }
-               else
-               {
-                       //dealocate all GTS
-                       //beacon loss
-
-                       on_sync =0;
-                       beacon_loss_reason = MAC_BEACON_LOSS;
-                       
-                       //TODO
-                       //post signal_loss();
-               }
-       }
-       
-       post send_frame_csma();
-
-       return SUCCESS;
-}
-
-/*******************Timer SUPERFRAME DURATION******************/
-async event error_t TimerAsync.sd_fired()
-{
-       call Leds.led2Off();
-
-       ////printfUART("sd\n","");
-
-       I_AM_IN_CFP = 0;
-       I_AM_IN_IP = 1;
-       
-       
-       number_backoff=0;
-       number_time_slot=0;
-       
-       
-       if (PANCoordinator == 0 && TYPE_DEVICE == ROUTER)
-       {
-               trx_status = PHY_RX_ON;
-       
-               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-       }
-       else
-       {
-               trx_status = PHY_RX_ON;
-               
-               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-               
-       }
-       
-       if (mac_PIB.macShortAddress==0xffff && TYPE_DEVICE == END_DEVICE)
-       {
-               trx_status = PHY_RX_ON;
-               
-               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-       }
-       
-       //trx_status = PHY_RX_ON;
-       //post set_trx();
-       /*
-               //turn the transceiver off
-       if (mac_PIB.macBeaconOrder != mac_PIB.macSuperframeOrder )
-       {
-               if ( mac_PIB.macRxOnWhenIdle == 0 && findabeacon == 0) 
-               {
-                       trx_status = PHY_TRX_OFF;
-                       post set_trx();
-               }
-               else
-               {
-                       trx_status = PHY_RX_ON;
-                       post set_trx();
-               }
-       }
-       //if the node is trying to synchronize
-               if (on_sync == 0 || mac_PIB.macPromiscuousMode == 1)
-       {
-               atomic{
-                       trx_status = PHY_RX_ON;
-                       post set_trx();
-               }
-       }
-       */
-       if (PANCoordinator == 1)
-       {
-               //increment the gts_null descriptors
-               atomic{
-                       
-                               //if (GTS_null_descriptor_count > 0) post increment_gts_null();
-                       
-                               //if (GTS_descriptor_count >0 ) post check_gts_expiration();
-                       
-                               //if (indirect_trans_count > 0) increment_indirect_trans();
-                               
-                               //creation of the beacon
-                               post create_beacon();
-               }
-               //trx_status = PHY_TRX_OFF;
-               //post set_trx();
-       }
-       else
-       {
-       //temporariamente aqui //atenção quando for para o cluster-tree Ã© preciso mudar para fora
-       //e necessario destinguir ZC de ZR (que tem que manter a sync com o respectivo pai)
-       if (on_sync == 0)
-       {
-               //sync not ok
-               
-               //findabeacon=1;
-               if (missed_beacons == aMaxLostBeacons)
-               {
-               
-                       //printfUART("sync_loss %i\n",missed_beacons);
-                       //out of sync
-                       post signal_loss();
-               }
-               ////printfUART("out_sync %i\n",missed_beacons);
-               missed_beacons++;
-               call Leds.led1Off();
-               
-       }
-       else
-       {
-               //sync ok
-               missed_beacons=0;
-       
-               on_sync=0;
-       }
-       
-       }
-
-       //trx_status = PHY_TRX_OFF;
-       //call PLME_SET_TRX_STATE.request(PHY_TRX_OFF);
-
-       return SUCCESS;
-}
-
-/*******************Timer BEFORE TIME SLOT FIRED******************/
-async event error_t TimerAsync.before_time_slot_fired()
-{
-       on_s_GTS=0;
-       on_r_GTS=0;
-       
-       if (next_on_s_GTS == 1)
-       {       
-               on_s_GTS=1;
-               next_on_s_GTS =0;
-               trx_status = PHY_TX_ON;
-               call PLME_SET_TRX_STATE.request(PHY_TX_ON);
-               //post set_trx();
-       }
-       
-       if(next_on_r_GTS == 1)
-       {
-               on_r_GTS=1;
-               next_on_r_GTS=0;
-               trx_status = PHY_RX_ON;
-               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-               //post set_trx();
-       }
-
-return SUCCESS;
-}
-/*******************Timer TIME SLOT FIRED******************/
-async event error_t TimerAsync.time_slot_fired()
-{
-       //reset the backoff counter and increment the slot boundary
-       number_backoff=0;
-       number_time_slot++;
-               
-       //verify is there is data to send in the GTS, and try to send it
-       if(PANCoordinator == 1 && GTS_db[15-number_time_slot].direction == 1 && GTS_db[15-number_time_slot].gts_id != 0)
-       {
-               //COORDINATOR SEND DATA
-               ////////////printfUART("bbck%i:%i:%i\n", (15-number_time_slot),GTS_db[15-number_time_slot].direction,gts_slot_list[15-number_time_slot].element_count);
-               
-               post start_coordinator_gts_send();
-                               
-       }
-       else
-       {
-               //DEVICE SEND DATA
-               if (number_time_slot == s_GTSss && gts_send_buffer_count > 0 && on_sync == 1)//(send_s_GTSss-send_s_GTS_len) 
-               {
-                               //current_time = call TimerAsync.get_total_tick_counter();
-                               post start_gts_send();
-               }               
-       }
-       
-       next_on_r_GTS =0;
-       next_on_s_GTS=0;
-       
-       
-       ////printfUART("ts%i %i %i\n", number_time_slot,s_GTSss,r_GTSss);
-       
-       
-       //verification if the time slot is entering the CAP
-       //GTS FIELDS PROCESSING
-       
-       if ((number_time_slot + 1) >= final_CAP_slot && (number_time_slot + 1) < 16)
-       {
-               I_AM_IN_CAP = 0;
-               I_AM_IN_CFP = 1;
-               
-               ////printfUART("bts %i\n",I_AM_IN_CAP, number_time_slot); 
-       
-       atomic{
-               
-               //verification of the next time slot
-               if(PANCoordinator == 1 && number_time_slot < 15)
-               {
-               //COORDINATOR verification of the next time slot
-                       if(GTS_db[14-number_time_slot].gts_id != 0x00 && GTS_db[14-number_time_slot].DevAddressType != 0x0000)
-                       {       
-                               if(GTS_db[14-number_time_slot].direction == 1 ) // device wants to receive
-                               {
-                                       next_on_s_GTS =1; //PAN coord mode
-                               }
-                               else
-                               {
-                                       next_on_r_GTS=1; //PAN coord mode
-                               }
-                       }       
-               }
-               else
-               {
-               //device verification of the next time slot
-                       if( (number_time_slot +1) == s_GTSss || (number_time_slot +1) == r_GTSss )
-                       {
-                               ////printfUART("s_GTSss: %i r_GTSss: %i\n", s_GTSss,r_GTSss);
-                               if((number_time_slot + 1) == s_GTSss)
-                               {       
-                                       ////printfUART("MY SEND SLOT \n", "");
-                                       next_on_s_GTS =1;
-                                       s_GTS_length --;
-                                       if (s_GTS_length != 0 )
-                                       {
-                                               s_GTSss++;
-                                       }
-                               }
-                               else                    
-                               {
-                                       //////////////printfUART("MY RECEIVE SLOT \n", "");
-                                       next_on_r_GTS =1;
-                                       r_GTS_length --;
-                                       if (r_GTS_length != 0 )
-                                       {
-                                               r_GTSss++;
-                                       }
-                               }                               
-                       }
-                       else
-                       {
-                               //idle
-                               next_on_s_GTS=0;
-                               next_on_r_GTS=0;
-                       }
-               }
-       }
-       }
-       
-return SUCCESS;
-}
-async event error_t TimerAsync.sfd_fired()
-{
-
-return SUCCESS;
-}
-
-/*******************Timer BACKOFF PERIOD******************/
-async event error_t TimerAsync.backoff_fired()
-{
-       //slotted CSMA/CA function
-       atomic{
-       
-               if( csma_locate_backoff_boundary == 1 )
-               {
-                       csma_locate_backoff_boundary=0;
-                       
-                       //post start_csma_ca_slotted();
-                       
-                       //DEFERENCE CHANGE
-                       if (backoff_deference == 0)
-                       {
-                               //normal situation
-                               delay_backoff_period = (call Random.rand16() & ((uint8_t)(powf(2,BE)) - 1));
-                               
-                               if (check_csma_ca_backoff_send_conditions((uint32_t) delay_backoff_period) == 1)
-                               {
-                                       backoff_deference = 1;
-                               }
-                               
-                       }
-                       else
-                       {
-                               backoff_deference = 0;
-                       }
-                       
-                       csma_delay=1;
-               }
-               if( csma_cca_backoff_boundary == 1 )
-                       post perform_csma_ca_slotted();
-       }
-       //CSMA/CA
-       atomic{
-               if(csma_delay == 1 )
-               {
-                       if (delay_backoff_period == 0)
-                       {
-                               if(csma_slotted == 0)
-                               {
-                                       post perform_csma_ca_unslotted();
-                               }
-                               else
-                               {
-                                       //CSMA/CA SLOTTED
-                                       csma_delay=0;
-                                       csma_cca_backoff_boundary=1;
-                               }
-                       }
-                       delay_backoff_period--;
-               }
-       }
-       number_backoff++;
-return SUCCESS;
-}
-
-/*******************T_ackwait**************************/
-  event void T_ackwait.fired() {
-  
-  //////////printfUART("Tfd \n", "");
-       
-       //call Leds.redToggle();
-
-       if (send_ack_check == 1)
-       {
-               retransmit_count++;
-               
-               if (retransmit_count == aMaxFrameRetries || send_indirect_transmission > 0)
-               {
-                               //check the type of data being send
-                               /*
-                               if (associating == 1)
-                               {
-                                       //printfUART("af ack\n", "");
-                                       associating=0;
-                                       signal MLME_ASSOCIATE.confirm(0x0000,MAC_NO_ACK);
-                               }
-                               */
-                               
-                       atomic{ 
-                               ////////////printfUART("TRANSMISSION FAIL\n",""); 
-                               //stardard procedure, if fail discard the packet
-                               atomic send_buffer_count --;
-                               send_buffer_msg_out++;
-                       
-                                       //failsafe
-                                       if(send_buffer_count > SEND_BUFFER_SIZE)
-                                       {
-                                               
-                                               atomic send_buffer_count =0;
-                                               send_buffer_msg_out=0;
-                                               send_buffer_msg_in=0;
-                                               
-                                       }
-                                       
-                                       
-                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                               send_buffer_msg_out=0;
-                                       
-                                       if (send_buffer_count > 0)
-                                               post send_frame_csma();
-                                               
-                                       send_ack_check=0;
-                                       retransmit_count=0;
-                                       ack_sequence_number_check=0;
-                               
-                               }
-               }
-               
-               ////////////printfUART("RETRY\n",""); 
-               //retransmissions
-               post send_frame_csma();
-       }
-    
-  }
-
-/*******************T_ResponseWaitTime**************************/
-  event void T_ResponseWaitTime.fired() {
-       //command response wait time
-       ////////////printfUART("T_ResponseWaitTime.fired\n", "");
-
-       if (associating == 1)
-       {
-               //printfUART("af rwt\n", "");
-               associating=0;
-               signal MLME_ASSOCIATE.confirm(0x0000,MAC_NO_DATA);
-               
-       }
-  
-  }
-
-/*****************************************************
-****************PD_DATA EVENTS***********************
-******************************************************/
-  async event error_t PD_DATA.confirm(uint8_t status) {
-
-
-    return SUCCESS;     
-  }
-/*****************************************************
-****************       PD_DATA     ********************
-******************************************************/ 
-
-async event error_t PD_DATA.indication(uint8_t psduLenght,uint8_t* psdu, int8_t ppduLinkQuality){
-               //if(I_AM_IN_CAP == 1 || I_AM_IN_CFP == 1 || mac_PIB.macShortAddress==0xffff || scanning_channels ==1 || findabeacon == 1)
-               //{
-                       if (buffer_count > RECEIVE_BUFFER_SIZE)
-                       {
-                               //call Leds.redToggle();
-                               //printfUART("full\n","");
-                       }
-                       else
-                       {
-               
-                               memcpy(&buffer_msg[current_msg_in],psdu,sizeof(MPDU));
-
-                               atomic{
-                                       current_msg_in++;
-                               
-                                       if ( current_msg_in == RECEIVE_BUFFER_SIZE ) 
-                                               current_msg_in = 0;
-               
-                                       buffer_count ++;
-                               }
-                               
-                               link_quality = ppduLinkQuality;
-                               
-                               if (scanning_channels ==1)
-                               {
-                                       //channel scan operation, accepts beacons only
-                                       post data_channel_scan_indication();
-                               
-                               }
-                               else
-                               {
-                               //normal operation
-                                       post data_indication();
-                               }
-                       }
-               //}
-               //else
-               //{
-               //      //printfUART("drop\n","");
-               //}
-
-return SUCCESS;
-}
-
-
-
-task void data_indication()
-{
-       //check all the conditions for a receiver packet
-    //pag 155
-       uint8_t link_qual;
-       
-       atomic link_qual = link_quality;
-
-       ////printfUART("data_indication\n","");
-       //////////printfUART("buf  %i %i\n",buffer_count,indirect_trans_count);
-
-       //Although the receiver of the device is enabled during the channel assessment portion of this algorithm, the
-       //device shall discard any frames received during this time.
-       //////////////printfUART("performing_csma_ca: %i\n",performing_csma_ca);
-       if (performing_csma_ca == 1)
-       {       
-               //////////////printfUART("REJ CSMA\n","");
-               atomic{ 
-                       buffer_count--;
-               
-                       current_msg_out++;
-               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
-                       current_msg_out = 0;
-                       }
-               
-               return;
-    }
-       
-       //while performing channel scan disable the packet reception
-       if ( scanning_channels == 1)
-       {       
-               atomic{ 
-                       buffer_count--;
-       
-                       current_msg_out++;
-               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
-                       current_msg_out = 0;
-                       }
-               return;
-       }       
-atomic{
-
-    //////printfUART("data ind %x %x %i\n",buffer_msg[current_msg_out].frame_control1,buffer_msg[current_msg_out].frame_control2,(buffer_msg[current_msg_out].frame_control2 & 0x7));
-       
-       //check the frame type of the received packet
-       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
-       {
-               
-                       case TYPE_DATA: ////printfUART("rd %i\n",buffer_msg[current_msg_out].seq_num);
-                                                       indication_data(&buffer_msg[current_msg_out],link_qual);
-                                                       break;
-                                                       
-                       case TYPE_ACK: ////printfUART("ra\n","");
-                                                       //ack_received = 1;
-                                                       indication_ack(&buffer_msg[current_msg_out],link_qual);
-                                                       
-                                                       break;
-                                                       
-                       case TYPE_CMD:  ////printfUART("rc\n","");
-                                                       indication_cmd(&buffer_msg[current_msg_out],link_qual);
-                                                       break;
-                       
-                       case TYPE_BEACON:
-                                                       
-                                                       ////printfUART("rb %i\n",buffer_msg[current_msg_out].seq_num);
-                                                       if (mac_PIB.macShortAddress == 0x0000) 
-                                                       {
-                                                               buffer_count--;
-                                                       }
-                                                       else
-                                                       {
-                                                               process_beacon(&buffer_msg[current_msg_out],link_qual);
-                                                               
-                                                       }
-
-                                                       break;
-                       default: 
-                                               atomic buffer_count--;
-                                               //////printfUART("Invalid frame type\n","");
-
-                                               break;
-       }
-       atomic{
-                       current_msg_out++;
-               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
-                       current_msg_out = 0;
-               }
-       }
-       return;
-}
-
-
-
-/*****************************************************
-****************PLME_ED EVENTS***********************
-******************************************************/ 
-event error_t PLME_CCA.confirm(uint8_t status){
-return SUCCESS;
-}
-   
-   
-event error_t PLME_SET.confirm(uint8_t status, uint8_t PIBAttribute){   
-return SUCCESS;
-}
-async event error_t PLME_SET_TRX_STATE.confirm(uint8_t status){
-
-return SUCCESS;
-}    
-   
-event error_t PLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue){
-   
-return SUCCESS;
-}    
-
-event error_t PLME_ED.confirm(uint8_t status,int8_t EnergyLevel){
-
-return SUCCESS;
-}
-
-/*******************************************************************************************************/
-/*******************************************************************************************************/
-/*******************************************************************************************************/
-/****************************************PACKET PROCESSING FUNCTIONS************************************/
-/*******************************************************************************************************/
-/*******************************************************************************************************/
-/*******************************************************************************************************/
-
-void process_beacon(MPDU *packet,uint8_t ppduLinkQuality)
-{
-
-       /*
-       ORGANIZE THE PROCESS BEACON FUNCION AS FOLLOWS.
-       1- GET THE BEACON ORDER
-       2- GET THE SUPERFRAME ORDER
-       3- GET THE FINAL CAP SLOT
-       4 - COMPUTE SD, BI, TS, BACKOFF PERIOD IN MILLISECONDS
-       
-       4- SYNCHRONIZE THE NODE BY DOING THE FOLLOWING
-               - SET A TIMER IN MS FOR THE FINAL TIME SLOT (SUPERFRAME DURATION) : IT EXPRIES AFTER SD - TX TIME - PROCESS TIME
-               - SET A TIMER IN MS FOR THE GTS IF ANY EXIST IT EXPRIES AFTER GTS_NBR * TIME_SLOT - TX TIME - PROCESS TIME 
-       */
-       uint32_t SO_EXPONENT;
-       uint32_t BO_EXPONENT;
-       int i=0;
-       uint16_t gts_descriptor_addr;
-       uint8_t data_count;
-       
-       uint8_t gts_directions;
-       uint8_t gts_des_count;
-       
-       uint8_t gts_ss;
-       uint8_t gts_l;
-       uint8_t dir;
-       uint8_t dir_mask;
-
-       //end gts variables
-
-       //function that processes the received beacon
-       beacon_addr_short *beacon_ptr;
-       
-       PANDescriptor pan_descriptor;
-
-       // beacon_trans_delay = (((packet->length(bytes) * 8.0) / 250.00(bits/s) ) / 0.34(s) (timer_granularity) ) (symbols)
-
-       //pending frames
-       uint8_t short_addr_pending=0;
-       uint8_t long_addr_pending=0;
-
-       //used in the synchronization
-       //uint32_t process_tick_counter; //symbols
-       
-       //uint32_t becon_trans_delay; //symbols
-       //uint32_t start_reset_ct; //number of clock ticks since the start of the beacon interval
-       
-       //used in the track beacon
-       beacon_processed = 1;
-       missed_beacons=0;
-       
-       //initializing pointer to data structure
-       beacon_ptr = (beacon_addr_short*) (packet->data);
-       
-       
-               //decrement buffer count
-       atomic buffer_count --;
-       
-       ////printfUART("Received Beacon\n","");
-       ////printfUART("rb panid: %x %x \n",beacon_ptr->source_address,mac_PIB.macCoordShortAddress);
-       ////////printfUART("My macPANID: %x\n",mac_PIB.macPANId);
-       
-       if( beacon_ptr->source_address != mac_PIB.macCoordShortAddress)
-       {
-               //
-               return;
-       }
-       ////printfUART("bea %i\n",call TimerAsync.get_current_ticks());
-       
-       /**********************************************************************************/
-       /*                                      PROCESSING THE SUPERFRAME STRUCTURE                                                       */
-       /**********************************************************************************/
-       
-       if (PANCoordinator == 0)
-       {
-               mac_PIB.macBeaconOrder = get_beacon_order(beacon_ptr->superframe_specification);
-               mac_PIB.macSuperframeOrder = get_superframe_order(beacon_ptr->superframe_specification);
-               
-               //mac_PIB.macCoordShortAddress = beacon_ptr->source_address;
-               
-               ////printfUART("BO,SO:%i %i\n",mac_PIB.macBeaconOrder,mac_PIB.macSuperframeOrder);
-               
-               //mac_PIB.macPANId = beacon_ptr->source_PAN_identifier;
-               
-               //beacon order check if it changed
-               if (mac_PIB.macSuperframeOrder == 0)
-               {
-                       SO_EXPONENT = 1;
-               }
-               else
-               {
-                       SO_EXPONENT = powf(2,mac_PIB.macSuperframeOrder);
-               }
-               
-               if ( mac_PIB.macBeaconOrder ==0)
-               {
-                       BO_EXPONENT =1;
-               }
-               else
-               {
-                               BO_EXPONENT = powf(2,mac_PIB.macBeaconOrder);
-               }
-               BI = aBaseSuperframeDuration * BO_EXPONENT; 
-               SD = aBaseSuperframeDuration * SO_EXPONENT; 
-               
-               //backoff_period
-               backoff = aUnitBackoffPeriod;
-               time_slot = SD / NUMBER_TIME_SLOTS;
-               
-               call TimerAsync.set_bi_sd(BI,SD);
-       }       
-               
-       /**********************************************************************************/
-       /*                                                      PROCESS GTS CHARACTERISTICS                                                       */
-       /**********************************************************************************/
-               allow_gts =1;
-       
-               //initializing the gts variables
-               s_GTSss=0;
-               s_GTS_length=0;
-               
-               r_GTSss=0;
-               r_GTS_length=0;
-               
-               /*
-               send_s_GTSss=0;  
-               send_r_GTSss=0; 
-               send_s_GTS_len=0;
-               send_r_GTS_len=0;
-               */
-               final_CAP_slot = 15;
-
-
-               gts_des_count = (packet->data[8] & 0x0f);
-               
-               data_count = 9;
-               
-               final_CAP_slot = 15 - gts_des_count;
-               
-               if (gts_des_count > 0 )
-               {
-               data_count = 10; //position of the current data count
-               //process descriptors
-               
-                       gts_directions = packet->data[9];
-                       
-                       ////printfUART("gts_directions:%x\n",gts_directions);
-                       
-                       for(i=0; i< gts_des_count; i++)
-                       {       
-                               gts_descriptor_addr = (uint16_t) packet->data[data_count];
-                                       
-                               ////printfUART("gts_des_addr:%x mac short:%x\n",gts_descriptor_addr,mac_PIB.macShortAddress);
-                               
-                               data_count = data_count+2;
-                               //check if it concerns me
-                               if (gts_descriptor_addr == mac_PIB.macShortAddress)
-                               {
-                                       //confirm the gts request
-                                       //////////////printfUART("packet->data[data_count]: %x\n",packet->data[data_count]);
-                                       //gts_ss = 15 - get_gts_descriptor_ss(packet->data[data_count]);
-                                       gts_ss = get_gts_descriptor_ss(packet->data[data_count]);
-                                       gts_l = get_gts_descriptor_len(packet->data[data_count]);
-
-                                       if ( i == 0 )
-                                       {
-                                               dir_mask=1;
-                                       }
-                                       else
-                                       {
-                                       
-                                                       dir_mask = powf(2,i);
-                                       }
-                                       //////////////printfUART("dir_mask: %x i: %x gts_directions: %x \n",dir_mask,i,gts_directions);
-                                       dir = ( gts_directions & dir_mask);
-                                       if (dir == 0)
-                                       {
-                                               s_GTSss=gts_ss;
-                                               s_GTS_length=gts_l;
-                                       }
-                                       else
-                                       {
-
-                                               r_GTSss=gts_ss;
-                                               r_GTS_length=gts_l;
-                                       }
-                                       
-                                       ////printfUART("PB gts_ss: %i gts_l: %i dir: %i \n",gts_ss,gts_l,dir);
-                                       //////////////printfUART("PB send_s_GTSss: %i send_s_GTS_len: %i\n",send_s_GTSss,send_s_GTS_len);
-                                       
-                                       if ( gts_l == 0 )
-                                       {
-                                               allow_gts=0;
-                                       }
-
-                                       if (gts_confirm == 1 && gts_l != 0)
-                                       {
-                                               //signal ok
-                                               ////printfUART("gts confirm \n","");
-                                               gts_confirm =0;
-                                               signal MLME_GTS.confirm(GTS_specification,MAC_SUCCESS);
-                                       }
-                                       else
-                                       {
-                                               //signal not ok
-                                               //////////////printfUART("gts not confirm \n","");
-                                               gts_confirm =0;
-                                               signal MLME_GTS.confirm(GTS_specification,MAC_DENIED);
-                                       }
-                                       
-                               }
-                               data_count++;   
-                       }
-               }
-       
-       /**********************************************************************************/
-       /*                                                      PROCESS PENDING ADDRESSES INFORMATION                             */
-       /**********************************************************************************/    
-               //this should pass to the network layer
-               
-               
-               short_addr_pending=get_number_short(packet->data[data_count]);
-               long_addr_pending=get_number_extended(packet->data[data_count]);
-               
-               ////////////printfUART("ADD COUNT %i %i\n",short_addr_pending,long_addr_pending);
-               
-               data_count++;
-               
-               if(short_addr_pending > 0)
-               {
-                       for(i=0;i < short_addr_pending;i++)
-                       {
-                               ////////////printfUART("PB %i %i\n",(uint16_t)packet->data[data_count],short_addr_pending);
-                               
-                               //if(packet->data[data_count] == (uint8_t)mac_PIB.macShortAddress && packet->data[data_count+1] == (uint8_t)(mac_PIB.macShortAddress >> 8) )
-                               if((uint16_t)packet->data[data_count] == mac_PIB.macShortAddress)
-                               {
-                                       
-                                       create_data_request_cmd();
-                               }
-                               data_count = data_count + 2;
-                       }
-               }
-               if(long_addr_pending > 0)
-               {
-                       for(i=0; i < long_addr_pending;i++)
-                       {
-                               if((uint32_t)packet->data[data_count] == aExtendedAddress0 && (uint32_t)packet->data[data_count + 4] == aExtendedAddress1)
-                               {
-                                       
-                                       data_count = data_count + 8;
-
-                               }
-                       
-                       }
-               }
-
-       /**********************************************************************************/
-       /*                              BUILD the PAN descriptor of the COORDINATOR                                               */
-       /**********************************************************************************/
-               
-               
-          //Beacon NOTIFICATION
-          //BUILD the PAN descriptor of the COORDINATOR
-               //assuming that the adress is short
-               pan_descriptor.CoordAddrMode = SHORT_ADDRESS;
-               pan_descriptor.CoordPANId = 0x0000;//beacon_ptr->source_PAN_identifier;
-               pan_descriptor.CoordAddress0=0x00000000;
-               pan_descriptor.CoordAddress1=mac_PIB.macCoordShortAddress;
-               pan_descriptor.LogicalChannel=current_channel;
-               //superframe specification field
-               pan_descriptor.SuperframeSpec = beacon_ptr->superframe_specification;
-               
-               pan_descriptor.GTSPermit=mac_PIB.macGTSPermit;
-               pan_descriptor.LinkQuality=0x00;
-               pan_descriptor.TimeStamp=0x000000;
-               pan_descriptor.SecurityUse=0;
-               pan_descriptor.ACLEntry=0x00;
-               pan_descriptor.SecurityFailure=0x00;
-          
-               //I_AM_IN_CAP = 1;
-          
-       /**********************************************************************************/
-       /*                                                              SYNCHRONIZING                                                                     */
-       /**********************************************************************************/
-
-       //processing time + beacon transmission delay
-       
-       //removed not used
-       //process_tick_counter = call TimerAsync.get_process_frame_tick_counter();
-       //removed not used      
-       //start_reset_ct = ((1000 * (packet->length * 8.0) / 250)) / 69.54;  //(process_tick_counter - receive_tick_counter);
-
-       if(PANCoordinator == 0)
-       {
-                       I_AM_IN_CAP = 1;
-                       I_AM_IN_IP = 0;
-                       
-                       //call Leds.yellowOn();
-                       call Leds.led2On();
-                       
-                       call Leds.led1On();
-                       
-                       if(findabeacon == 1)
-                       {
-                               ////printfUART("findabeacon\n", "");
-                               call TimerAsync.set_timers_enable(1);
-                               findabeacon =0;
-                       }
-                       
-                       //#ifdef PLATFORM_MICAZ
-                       //number_time_slot = call TimerAsync.reset_start(start_reset_ct+process_tick_counter+52);// //SOBI=3 52 //SOBI=0 15
-                       //#else
-                       
-                       //call TimerAsync.reset();
-                       
-                       number_time_slot = call TimerAsync.reset_start(75);   //95 old val sem print
-                                       
-                       // +process_tick_counter+52 //SOBI=3 52 //SOBI=0 
-                       //#endif
-                       on_sync=1;
-                       
-                       ////printfUART("sED\n", "");
-       }
-       signal MLME_BEACON_NOTIFY.indication((uint8_t)packet->seq_num,pan_descriptor,0, 0, mac_PIB.macBeaconPayloadLenght, packet->data);
-               
-return;
-}
-
-
-void process_gts_request(MPDU *pdu)
-{
-               error_t status;
-               cmd_gts_request *mac_gts_request;
-               
-               mac_gts_request= (cmd_gts_request*) &pdu->data;
-               
-atomic{                
-               if ( get_characteristic_type(mac_gts_request->gts_characteristics) == 1)
-               {
-               //allocation
-       
-       //process the gts request
-               status = add_gts_entry(get_gts_length(mac_gts_request->gts_characteristics),get_gts_direction(mac_gts_request->gts_characteristics),mac_gts_request->source_address);
-               
-               }
-               else
-               {
-               //dealocation
-       
-               status = remove_gts_entry(mac_gts_request->source_address);
-               }
-               
-               signal MLME_GTS.indication(mac_gts_request->source_address, mac_gts_request->gts_characteristics, 0, 0);
-               
-               }
-
-return;
-}
-/****************DATA indication functions******************/
-
-void indication_data(MPDU *pdu, int8_t ppduLinkQuality)
-{
-       uint8_t data_len;
-       
-       uint8_t payload[80];
-       uint8_t msdu_length=0;
-       
-       //int i;
-       
-       uint32_t SrcAddr[2];
-       uint32_t DstAddr[2];
-       
-       
-       //frame control variables
-       uint8_t source_address=0;
-       uint8_t destination_address=0;
-
-
-       dest_short *dest_short_ptr;
-       dest_long *dest_long_ptr;
-       
-       source_short *source_short_ptr;
-       source_long *source_long_ptr;
-
-       //implement the intra PAN data messages
-       //intra_pan_source_short *intra_pan_source_short_ptr;
-       //intra_pan_source_long *intra_pan_source_long_ptr;
-       
-       
-       source_address=get_fc2_source_addr(pdu->frame_control2);
-       destination_address=get_fc2_dest_addr(pdu->frame_control2);
-       
-       //decrement buffer count
-       atomic buffer_count --;
-       
-       SrcAddr[0]=0x00000000;
-       SrcAddr[1]=0x00000000;
-       DstAddr[0]=0x00000000;
-       DstAddr[1]=0x00000000;
-
-
-       ////printfUART("id %i %i \n",source_address,destination_address);
-
-
-       if ( get_fc1_intra_pan(pdu->frame_control1)== 0 )
-       {
-       //INTRA PAN
-               if (destination_address > 1 && source_address > 1)
-               {
-                       // Destination LONG - Source LONG       
-                       if (destination_address == LONG_ADDRESS && source_address == LONG_ADDRESS)
-                       {
-                               dest_long_ptr = (dest_long *) &pdu->data[0];
-                               source_long_ptr = (source_long *) &pdu->data[DEST_LONG_LEN];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
-                               {
-                                       ////////////printfUART("data rejected, ext destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               data_len = 20;
-                               
-                               
-                               DstAddr[1] = dest_long_ptr->destination_address0;
-                               DstAddr[0] =dest_long_ptr->destination_address1;
-                               
-                               SrcAddr[1] =source_long_ptr->source_address0;
-                               SrcAddr[0] =source_long_ptr->source_address1;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-                               
-                       }
-                       
-                       // Destination SHORT - Source LONG
-                       if ( destination_address == SHORT_ADDRESS && source_address == LONG_ADDRESS )
-                       {
-                               dest_short_ptr = (dest_short *) &pdu->data[0];
-                               source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
-                               {
-                                       ////////////printfUART("data rejected, short destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 14;
-                               
-                               DstAddr[0] =dest_short_ptr->destination_address;
-                               
-                               SrcAddr[1] =source_long_ptr->source_address0;
-                               SrcAddr[0] =source_long_ptr->source_address1;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-                       // Destination LONG - Source SHORT
-                       if ( destination_address == LONG_ADDRESS && source_address == SHORT_ADDRESS )
-                       {
-                               dest_long_ptr = (dest_long *) &pdu->data[0];
-                               source_short_ptr = (source_short *) &pdu->data[DEST_LONG_LEN];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
-                               {
-                                       ////////////printfUART("data rejected, ext destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 14;
-                               
-                               DstAddr[1] = dest_long_ptr->destination_address0;
-                               DstAddr[0] =dest_long_ptr->destination_address1;
-                               
-                               
-                               SrcAddr[0] =source_short_ptr->source_address;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-                       
-                       
-                       //Destination SHORT - Source SHORT
-                       if ( destination_address == SHORT_ADDRESS && source_address == SHORT_ADDRESS )  
-                       {
-                               dest_short_ptr = (dest_short *) &pdu->data[0];
-                               source_short_ptr = (source_short *) &pdu->data[DEST_SHORT_LEN];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
-                               {
-                                       ////printfUART("data rejected, short destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       ////printfUART("SH SH data rejected, wrong destination PAN %x\n",mac_PIB.macPANId ); 
-                                       return;
-                               }
-                               
-                               data_len = 8;
-                               
-                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                               {
-                                       build_ack(pdu->seq_num,0);
-                               }
-                               
-                               DstAddr[0] =dest_short_ptr->destination_address;
-                               
-                               SrcAddr[0] =source_short_ptr->source_address;
-                               
-                               msdu_length = (pdu->length - 5) - data_len;
-                               
-                               
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                       
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length,payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-               }
-               
-               /*********NO DESTINATION ADDRESS PRESENT ****************/
-               
-               if ( destination_address == 0 && source_address > 1 )
-               {
-                               
-                       if (source_address == LONG_ADDRESS)
-                       {//Source LONG
-                               source_long_ptr = (source_long *) &pdu->data[0];
-                               
-                               //If only source addressing fields are included in a data or MAC command frame, the frame shall be
-                               //accepted only if the device is a PAN coordinator and the source PAN identifier matches macPANId.
-                               if ( PANCoordinator==0 || source_long_ptr->source_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       ////////////printfUART("data rejected, im not pan\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 10;
-                               
-                               SrcAddr[1] =source_long_ptr->source_address0;
-                               SrcAddr[0] =source_long_ptr->source_address1;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address,(uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, 0x0000, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-                       else
-                       {//Source SHORT
-
-                               source_short_ptr = (source_short *) &pdu->data[0];
-                               //If only source addressing fields are included in a data or MAC command frame, the frame shall be
-                               //accepted only if the device is a PAN coordinator and the source PAN identifier matches macPANId.
-                               if ( PANCoordinator==0 || source_short_ptr->source_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       ////////////printfUART("data rejected, im not pan\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 4;
-
-                               
-                               SrcAddr[0] =source_short_ptr->source_address;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, 0x0000, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-               }
-               /*********NO SOURCE ADDRESS PRESENT ****************/
-               
-               if ( destination_address > 1 && source_address == 0 )
-               {
-                       if (destination_address == LONG_ADDRESS)
-                       {//Destination LONG
-                               dest_long_ptr = (dest_long *) &pdu->data[0];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
-                               {
-                                       ////////////printfUART("data rejected, ext destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 10;
-                               
-                               DstAddr[1] = dest_long_ptr->destination_address0;
-                               DstAddr[0] =dest_long_ptr->destination_address1;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                       
-                               signal MCPS_DATA.indication((uint16_t)source_address,0x0000, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-                       else
-                       {//Destination SHORT
-                               dest_short_ptr = (dest_short *) &pdu->data[0];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
-                               {
-                                       ////////////printfUART("data rejected, short destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 4;
-                               
-                               DstAddr[0] =dest_short_ptr->destination_address;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address,0x0000, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                               data_len = 4;
-                       }
-               }
-               
-       }
-       else
-       {
-       //intra_pan == 1
-       
-       
-       
-       }
-       
-       
-return;
-}
-
-void indication_cmd(MPDU *pdu, int8_t ppduLinkQuality)
-{
-               uint8_t cmd_type;
-               //uint8_t pk_ptr;
-               uint8_t addressing_fields_length=0;
-               
-               uint32_t SrcAddr[2];
-               //uint32_t DstAddr[2];//NOT USED SO FAR
-               
-               //frame control variables
-               uint8_t source_address=0;
-               uint8_t destination_address=0;
-       
-               //NOT USED SO FAR
-               //dest_short *dest_short_ptr;
-               //dest_long *dest_long_ptr;
-               //NOT USED SO FAR
-               //source_short *source_short_ptr;
-               source_long *source_long_ptr;
-               
-               dest_short *dest_short_ptr;
-               dest_long *dest_long_ptr;
-               
-               //CHECK IMPLEMENT
-               //intra_pan_source_short *intra_pan_source_short_ptr; 
-               //intra_pan_source_long *intra_pan_source_long_ptr;
-               
-               destination_address=get_fc2_dest_addr(pdu->frame_control2);
-               source_address=get_fc2_source_addr(pdu->frame_control2);
-               
-               //decrement buffer count
-               atomic buffer_count --;
-               
-               switch(destination_address)
-               {
-                       case LONG_ADDRESS: addressing_fields_length = DEST_LONG_LEN;
-                                                               dest_long_ptr = (dest_long *) &pdu->data[0];
-                                                               if(dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1)
-                                                               {
-                                                                       //printfUART("NOT FOR ME","");
-                                                                       return;
-                                                               }
-                                                               
-                                                               break;
-                       case SHORT_ADDRESS: addressing_fields_length = DEST_SHORT_LEN;
-                                                               dest_short_ptr= (dest_short *) &pdu->data[0];
-                                                               //destination command not for me
-                                                               if (dest_short_ptr->destination_address != mac_PIB.macShortAddress && dest_short_ptr->destination_address !=0xffff)
-                                                               {
-                                                                       //printfUART("NOT FOR ME","");
-                                                                       ////////////printfUART("NOT FOR ME %x me %e\n", dest_short_ptr->destination_address,mac_PIB.macShortAddress); 
-                                                                       return;
-                                                               }
-                                                               break;
-               }
-               switch(source_address)
-               {
-                       case LONG_ADDRESS: addressing_fields_length = addressing_fields_length + SOURCE_LONG_LEN;
-                                                               break;
-                       case SHORT_ADDRESS: addressing_fields_length = addressing_fields_length + SOURCE_SHORT_LEN;
-                                                               break;
-               }
-
-               cmd_type = pdu->data[addressing_fields_length];
-               
-                               
-               switch(cmd_type)
-               {
-               
-               case CMD_ASSOCIATION_REQUEST:   
-                                                                       //check if association is allowed, if not discard the frame             
-                                                                       
-                                                                       ////////printfUART("CMD_ASSOCIATION_REQUEST \n", "");
-                                                                       
-                                                                               
-                                                                                       if (mac_PIB.macAssociationPermit == 0 )
-                                                                                       {
-                                                                                               ////////////printfUART("Association not alowed\n", "");
-                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                                               {
-                                                                                                       build_ack(pdu->seq_num,0);
-                                                                                               }
-                                                                                               return;
-                                                                                       }
-                                                                                       
-                                                                                       if ( PANCoordinator==0 )
-                                                                                       {
-                                                                                               ////////////printfUART("i´m not a pan\n", ""); 
-                                                                                               return;
-                                                                                       }
-                                                                       atomic{
-                                                                                       source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
-                                                                                       
-                                                                                       SrcAddr[1] =source_long_ptr->source_address0;
-                                                                                       SrcAddr[0] =source_long_ptr->source_address1;
-                                                                                       
-                                                                                       
-                                                                                       signal MLME_ASSOCIATE.indication(SrcAddr, pdu->data[addressing_fields_length+1] , 0, 0);
-
-                                                                                       }
-                                                                                       
-                                                                                       if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                                       {
-                                                                                               build_ack(pdu->seq_num,1);
-                                                                                       }       
-
-                                                                                       
-                                                                       break;
-               
-               case CMD_ASSOCIATION_RESPONSE: atomic{
-                                                                                               //printfUART("CMD_ASSOCIATION_RESPONSE\n", ""); 
-                                                                                               
-                                                                                               associating =0;
-                                                                                               call T_ResponseWaitTime.stop();
-                                                                                               
-                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                                               {
-                                                                                                       build_ack(pdu->seq_num,0);
-                                                                                               }
-                                                                                       
-                                                                                               signal MLME_ASSOCIATE.confirm((uint16_t)(pdu->data[addressing_fields_length+1] + (pdu->data[addressing_fields_length+2] << 8)), pdu->data[addressing_fields_length+3]);
-                                                                                               }
-                                                                               break;
-
-               case CMD_DISASSOCIATION_NOTIFICATION:   ////////////printfUART("Received CMD_DISASSOCIATION_NOTIFICATION\n", ""); 
-                                                                                               
-                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                                               {
-                                                                                                       build_ack(pdu->seq_num,0);
-                                                                                               }
-                                                                                               
-                                                                                               process_dissassociation_notification(pdu);
-                                                                                               break;
-               case CMD_DATA_REQUEST: 
-                                                               ////printfUART("CMD_DATA_REQUEST\n", ""); 
-                                                                       ////////printfUART("DR\n", "");
-                                                                       if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                       {
-                                                                               //TODO
-                                                                               //Problems with consecutive reception of messages
-                                                                               
-                                                                               //build_ack(pdu->seq_num,0);
-                                                                       }
-                                                                       
-                                                                       //cmd_data_request_0_3_reception = (cmd_data_request_0_3 *) pdu->data;
-                                                                       
-                                                                       source_long_ptr = (source_long *) &pdu->data[0];
-                                                                                       
-                                                                       SrcAddr[1] =source_long_ptr->source_address0;
-                                                                       SrcAddr[0] =source_long_ptr->source_address1;
-                                                                       
-                                                                       send_ind_trans_addr(SrcAddr);
-
-                                                               break;
-               case CMD_PANID_CONFLICT:
-                                                               break;
-                                                               
-               case CMD_ORPHAN_NOTIFICATION:
-                                                                       ////printfUART("CMD_ORPHAN_NOTIFICATION\n", ""); 
-                                                                       
-                                                                       source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
-                                                                                       
-                                                                       SrcAddr[1] =source_long_ptr->source_address0;
-                                                                       SrcAddr[0] =source_long_ptr->source_address1;
-                                                                       
-                                                                       signal MLME_ORPHAN.indication(SrcAddr, 0x00,0x00);
-                                                               
-               
-                                                               break;
-               case CMD_BEACON_REQUEST:
-                                                               break;
-               case CMD_COORDINATOR_REALIGNMENT:
-                                                                       //printfUART("CMD_COORDINATOR_REALIGNMENT\n", ""); 
-                                                                       
-                                                                       process_coordinator_realignment(pdu);
-                                                                       
-                                                               break;
-               case CMD_GTS_REQUEST:   
-                                                               //////////////printfUART("Received CMD_GTS_REQUEST\n", ""); 
-                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                               {
-                                                                       build_ack(pdu->seq_num,0);
-                                                               }
-                                                               process_gts_request(pdu);
-                                                               break;
-               default: break;
-
-               }
-
-return;
-}
-
-void indication_ack(MPDU *pdu, int8_t ppduLinkQuality)
-{
-       //decrement buffer count
-
-       atomic buffer_count --;
-
-       //////////////printfUART("ACK Received\n",""); 
-       
-       atomic{
-                       if (send_ack_check == 1 && ack_sequence_number_check == pdu->seq_num)
-                       {
-                               //transmission SUCCESS
-                               call T_ackwait.stop();
-                               
-                               send_buffer_count --;
-                               send_buffer_msg_out++;
-                               
-                               //failsafe
-                               if(send_buffer_count > SEND_BUFFER_SIZE)
-                               {
-                                       send_buffer_count =0;
-                                       send_buffer_msg_out=0;
-                                       send_buffer_msg_in=0;
-                               }
-                               
-                               if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                       send_buffer_msg_out=0;
-                               
-                               //received an ack for the association request
-                               if( associating == 1 && association_cmd_seq_num == pdu->seq_num )
-                               {
-                                       ////////////printfUART("ASSOC ACK\n",""); 
-                                       call T_ResponseWaitTime.startOneShot(response_wait_time);
-                                       //call T_ResponseWaitTime.start(TIMER_ONE_SHOT, response_wait_time);
-                               }
-                               
-                               if (gts_request == 1 && gts_request_seq_num == pdu->seq_num)
-                               {
-                               
-                                       call T_ResponseWaitTime.startOneShot(response_wait_time);
-                                       //call T_ResponseWaitTime.start(TIMER_ONE_SHOT, response_wait_time);
-                               }
-                               
-                               ////////////printfUART("TRANSMISSION SUCCESS\n",""); 
-
-                               if (send_indirect_transmission > 0 )
-                               {       //the message send was indirect
-                                       //remove the message from the indirect transmission queue
-                                       indirect_trans_queue[send_indirect_transmission-1].handler=0x00;
-                                       indirect_trans_count--;
-                                       ////////////printfUART("SU id:%i ct:%i\n", send_indirect_transmission,indirect_trans_count);
-                               }
-                               
-                               send_ack_check=0;
-                               retransmit_count=0;
-                               ack_sequence_number_check=0;
-                               
-                               
-                               if (send_buffer_count > 0)
-                                       post send_frame_csma();
-                               
-                               
-                       }
-               }
-       
-                       //CHECK
-               if (get_fc1_frame_pending(pdu->frame_control1) == 1 && pending_request_data ==1)// && associating == 1
-               {               
-                               ////////////printfUART("Frame_pending\n",""); 
-                               pending_request_data=0;
-                               create_data_request_cmd();
-               }
-               
-               //GTS mechanism, after the confirmation of the GTS request, must check if the beacon has the gts
-               /*
-               if (gts_ack == 1)
-               {
-                       gts_ack=0;
-                       gts_confirm=1;
-                       call T_ResponseWaitTime.stop();
-               
-               }
-       */
-               if(gts_send_pending_data==1)
-                       post start_gts_send();
-               
-               if(coordinator_gts_send_pending_data==1 && coordinator_gts_send_time_slot == number_time_slot)
-                       post start_coordinator_gts_send();
-       
-return;
-}
-
-
-void process_dissassociation_notification(MPDU *pdu)
-{
-atomic{
-               cmd_disassociation_notification *mac_disassociation_notification;
-               
-               //creation of a pointer to the disassociation notification structure
-               mac_disassociation_notification = (cmd_disassociation_notification*) pdu->data;                                                                 
-
-               signal MLME_DISASSOCIATE.indication(&mac_disassociation_notification->source_address0, mac_disassociation_notification->disassociation_reason, 0, 0);
-               }
-
-return;
-}
-
-
-
-
-void process_coordinator_realignment(MPDU *pdu)
-{
-
-atomic{
-       cmd_coord_realignment *cmd_realignment = 0;
-       
-       dest_long *dest_long_ptr=0;
-       source_short *source_short_ptr=0;
-
-       cmd_realignment = (cmd_coord_realignment*) &pdu->data[DEST_LONG_LEN + SOURCE_SHORT_LEN];
-       
-       //creation of a pointer the addressing structures
-       dest_long_ptr = (dest_long *) &pdu->data[0];
-       source_short_ptr = (source_short *) &pdu->data[DEST_LONG_LEN];
-               
-       mac_PIB.macCoordShortAddress = ((cmd_realignment->coordinator_short_address0 << 8) | cmd_realignment->coordinator_short_address0 );
-       mac_PIB.macShortAddress = cmd_realignment->short_address;
-       
-       
-       //printfUART("PCR %i %i\n",mac_PIB.macCoordShortAddress,mac_PIB.macShortAddress); 
-       
-       }
-return;
-}
-
-
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/************************              BUILD FRAMES FUNCTIONS                          **********************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-
-
-task void create_beacon()
-{
-       int i=0;
-       uint8_t packet_length = 25;
-       int data_count=0;
-       int pending_data_index=0;
-       MPDU* pkt_ptr=0;
-       //pending frames
-       uint8_t short_addr_pending=0;
-       uint8_t long_addr_pending=0;
-               
-       uint8_t gts_directions=0x00;
-       
-       uint16_t frame_control;
-
-       
-       atomic{
-               
-               beacon_addr_short *mac_beacon_addr_short_ptr;
-               //mac_beacon_addr_short_ptr = (beacon_addr_short*) &mac_txmpdu.data[0];
-               mac_beacon_addr_short_ptr = (beacon_addr_short*) &mac_beacon_txmpdu.data[0];
-               //call PLME_SET_TRX_STATE.request(PHY_TX_ON);
-               
-               mac_beacon_txmpdu_ptr->length = 15;
-               
-               frame_control = set_frame_control(TYPE_BEACON,0,0,0,1,SHORT_ADDRESS,SHORT_ADDRESS);
-               
-               mac_beacon_txmpdu_ptr->frame_control1 = (uint8_t)( frame_control);
-               
-               mac_beacon_txmpdu_ptr->frame_control2 = (uint8_t)( frame_control >> 8);
-               
-               //mac_beacon_txmpdu_ptr->frame_control = set_frame_control(TYPE_BEACON,0,0,0,1,SHORT_ADDRESS,SHORT_ADDRESS);
-               mac_beacon_txmpdu_ptr->seq_num = mac_PIB.macBSN;
-               mac_PIB.macBSN++;
-               
-               
-               //relocation error
-               mac_beacon_addr_short_ptr->destination_PAN_identifier= mac_PIB.macPANId;
-               //relocation error
-               mac_beacon_addr_short_ptr->destination_address = 0xffff;
-               //relocation error
-               mac_beacon_addr_short_ptr->source_address = mac_PIB.macShortAddress;
-               if (mac_PIB.macShortAddress == 0x0000)
-               {       //the device is the PAN Coordinator
-                       mac_beacon_addr_short_ptr->superframe_specification = set_superframe_specification(mac_PIB.macBeaconOrder,(uint8_t)mac_PIB.macSuperframeOrder,final_CAP_slot,0,1,mac_PIB.macAssociationPermit);
-               }
-               else
-               {
-                       mac_beacon_addr_short_ptr->superframe_specification = set_superframe_specification(mac_PIB.macBeaconOrder,(uint8_t)mac_PIB.macSuperframeOrder,final_CAP_slot,0,1,mac_PIB.macAssociationPermit);
-               }
-               
-               mac_beacon_txmpdu_ptr->data[8] = set_gts_specification(GTS_descriptor_count,mac_PIB.macGTSPermit);
-               
-               mac_beacon_txmpdu_ptr->data[9] = set_pending_address_specification(short_addr_pending,long_addr_pending);
-               
-               data_count = 9;
-               packet_length = 15;
-               
-               
-               //BUILDING the GTS DESCRIPTORS
-               if( (GTS_descriptor_count + GTS_null_descriptor_count) > 0 )
-               {
-                       data_count++;
-                                       
-                       for(i=0; i< 7 ; i++)
-                       {
-                               if( GTS_db[i].gts_id != 0x00 && GTS_db[i].DevAddressType != 0x0000) 
-                               {
-                                       
-                                       mac_beacon_txmpdu_ptr->data[data_count] = GTS_db[i].DevAddressType;
-                                       //////////////printfUART("B gts %i\n", (GTS_db[i].DevAddressType >> 8 ) ); 
-                                       
-                                       data_count++;
-                                       mac_beacon_txmpdu_ptr->data[data_count] = (GTS_db[i].DevAddressType >> 8 );
-                                       //////////////printfUART("B gts %i\n",  GTS_db[i].DevAddressType ); 
-                                       
-                                       data_count++;
-                                       
-                                       mac_beacon_txmpdu_ptr->data[data_count] = set_gts_descriptor(15-i,GTS_db[i].length);
-                                       data_count++;
-                                       //////printfUART("B gts %i\n", set_gts_descriptor(GTS_db[i].starting_slot,GTS_db[i].length) ); 
-                                       
-                                       packet_length = packet_length + 3;
-                                       
-                                       if ( GTS_db[i].direction == 1 )
-                                       {
-                                               gts_directions = gts_directions | (1 << i); 
-                                       }
-                                       else
-                                       {
-                                               gts_directions = gts_directions | (0 << i); 
-                                       }
-                                       //////printfUART("dir %i\n", gts_directions); 
-                               }
-                       }
-                       mac_beacon_txmpdu_ptr->data[9] = gts_directions;
-                       //CHECK
-                       packet_length++;
-                       //BUILDING the NULL GTS DESCRIPTORS
-                       if ( GTS_null_descriptor_count > 0 )
-                       {
-                               for(i=0; i< 7 ; i++)
-                               {
-                                       if( GTS_null_db[i].DevAddressType != 0x0000) 
-                                       {
-                                               mac_beacon_txmpdu_ptr->data[data_count] = GTS_null_db[i].DevAddressType;
-                                               //////////////printfUART("B gts %i\n", (GTS_db[i].DevAddressType >> 8 ) ); 
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count] = (GTS_null_db[i].DevAddressType >> 8 );
-                                               //////////////printfUART("B gts %i\n",  GTS_db[i].DevAddressType ); 
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count] = 0x00;
-                                               data_count++;
-                                               //////////////printfUART("B gts %i\n", set_gts_descriptor(GTS_db[i].starting_slot,GTS_db[i].length) ); 
-                                               packet_length = packet_length +3;
-                                       }
-                               }
-                       }
-                       //resetting the GTS specification field
-                       mac_beacon_txmpdu_ptr->data[8] = set_gts_specification(GTS_descriptor_count + GTS_null_descriptor_count,mac_PIB.macGTSPermit);
-                       
-
-               }
-
-                       pending_data_index = data_count;
-                       data_count++;
-               //IMPLEMENT PENDING ADDRESSES
-               //temporary
-               //indirect_trans_count =0;
-               
-               if (indirect_trans_count > 0 )
-               {
-                               //IMPLEMENT THE PENDING ADDRESSES CONSTRUCTION
-
-                       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-                       {
-                               if (indirect_trans_queue[i].handler > 0x00)
-                               {
-                                       pkt_ptr = (MPDU *)&indirect_trans_queue[i].frame;
-                                       //ADD INDIRECT TRANSMISSION DESCRIPTOR
-                                       if(get_fc2_dest_addr(pkt_ptr->frame_control2) == SHORT_ADDRESS)
-                                       {
-                                               short_addr_pending++;
-                                               packet_length = packet_length + 2;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[2];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[3];
-                                               data_count++;
-                                       }
-                               }
-                       }
-                       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-                       {
-                               if (indirect_trans_queue[i].handler > 0x00)
-                               {
-                                       if(get_fc2_dest_addr(pkt_ptr->frame_control2) == LONG_ADDRESS)
-                                       {
-                                               long_addr_pending++;
-                                               packet_length = packet_length + 8;
-
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[0];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[1];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[2];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[3];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[4];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[5];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[6];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[7];
-                                               data_count++;
-                                               
-                                       }
-                               }
-                       }
-                               
-               }
-               mac_beacon_txmpdu_ptr->data[pending_data_index] = set_pending_address_specification(short_addr_pending,long_addr_pending);
-               
-               
-               //adding the beacon payload
-               if (mac_PIB.macBeaconPayloadLenght > 0 )
-               {
-                       for (i=0;i < mac_PIB.macBeaconPayloadLenght;i++)
-                       {
-                               mac_beacon_txmpdu_ptr->data[data_count] = mac_PIB.macBeaconPayload[i];
-                               data_count++;
-                               packet_length++;
-                       }
-               
-               
-               }
-               
-               //short_addr_pending=0;
-               //long_addr_pending=0;
-               
-               mac_beacon_txmpdu_ptr->length = packet_length;
-               
-               send_beacon_length = packet_length;
-               
-               send_beacon_frame_ptr = (uint8_t*)mac_beacon_txmpdu_ptr;
-               }
-}
-
-
-void create_data_frame(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions,uint8_t on_gts_slot,uint8_t pan)
-{
-       
-       int i_indirect_trans=0;
-
-       dest_short *dest_short_ptr;
-       dest_long *dest_long_ptr;
-       
-       source_short *source_short_ptr;
-       source_long *source_long_ptr;
-
-       //intra_pan_source_short *intra_pan_source_short_ptr;
-       //intra_pan_source_long *intra_pan_source_long_ptr;
-       
-       //CHECK
-       uint8_t intra_pan=0;
-       uint8_t data_len=0;
-       
-       uint8_t current_gts_element_count=0;
-       
-       MPDU *frame_pkt=0;
-       
-       uint16_t frame_control;
-       
-       ////printfUART("create df\n","");
-       
-       //decision of the buffer where to store de packet creation
-       if (on_gts_slot > 0 )
-       {
-       
-               if (PANCoordinator == 1)
-               {
-               //setting the coordinator gts frame pointer
-                       
-                       //get the number of frames in the gts_slot_list
-                       atomic current_gts_element_count = gts_slot_list[15-on_gts_slot].element_count;
-                       
-                       ////////////printfUART("element count %i\n",gts_slot_list[15-on_gts_slot].element_count);
-                       
-                       if (current_gts_element_count  == GTS_SEND_BUFFER_SIZE || available_gts_index_count == 0)
-                       {
-                               ////////////printfUART("FULL\n","");
-                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
-                               return;
-                       }
-                       else
-                       {
-                               frame_pkt = (MPDU *) &gts_send_buffer[available_gts_index[available_gts_index_count]];
-                       }
-                       
-               }
-               else
-               {
-               //setting the device gts frame pointer
-                       //////////////printfUART("start creation %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
-               
-                       if(gts_send_buffer_count == GTS_SEND_BUFFER_SIZE)
-                       {
-                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
-                               return;
-                       }
-                       if (gts_send_buffer_msg_in == GTS_SEND_BUFFER_SIZE)
-                               gts_send_buffer_msg_in=0;
-                       
-                               frame_pkt = (MPDU *) &gts_send_buffer[gts_send_buffer_msg_in];
-               
-               }
-       }
-       else
-       {
-       
-               if ( get_txoptions_indirect_transmission(TxOptions) == 1)
-               {
-                       
-                       //CREATE THE INDIRECT TRANSMISSION PACKET POINTER
-                       //check if the is enough space to store the indirect transaction
-                       if (indirect_trans_count == INDIRECT_BUFFER_SIZE)
-                       {
-                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
-                               ////////////printfUART("buffer full %i\n", indirect_trans_count);
-                               return;
-                       }
-                       
-                       for(i_indirect_trans=0;i_indirect_trans<INDIRECT_BUFFER_SIZE;i_indirect_trans++)
-                       {
-                               if (indirect_trans_queue[i_indirect_trans].handler == 0x00)
-                               {
-                                       frame_pkt = (MPDU *) &indirect_trans_queue[i_indirect_trans].frame;
-                                       break;
-                               }
-                       }
-                       
-                       
-               }
-               else
-               {
-                       //CREATE NORMAL TRANSMISSION PACKET POINTER
-                               //////printfUART("sb  %i\n", send_buffer_count);
-                       atomic{
-                               if ((send_buffer_count +1) > SEND_BUFFER_SIZE)  
-                                       return;
-                       
-                               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                                       send_buffer_msg_in=0;
-               
-                               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-                               }
-               }
-       }
-       
-atomic{
-
-       if (intra_pan == 0 )
-       {
-       
-               if ( DstAddrMode > 1 && SrcAddrMode > 1 )
-               {
-                       // Destination LONG - Source LONG       
-                       if (DstAddrMode == LONG_ADDRESS && SrcAddrMode == LONG_ADDRESS)
-                       {
-                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-                               source_long_ptr = (source_long *) &frame_pkt->data[DEST_LONG_LEN];
-                               
-                               dest_long_ptr->destination_PAN_identifier=DestPANId;
-                               dest_long_ptr->destination_address0=DstAddr[1];
-                               dest_long_ptr->destination_address1=DstAddr[0];
-                               
-                               source_long_ptr->source_PAN_identifier=SrcPANId;
-                               source_long_ptr->source_address0=SrcAddr[1];
-                               source_long_ptr->source_address1=SrcAddr[0];
-                               
-                               data_len = 20;
-                       }
-                       
-                       // Destination SHORT - Source LONG
-                       if ( DstAddrMode == SHORT_ADDRESS && SrcAddrMode == LONG_ADDRESS )
-                       {
-                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-                               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
-                               
-                               dest_short_ptr->destination_PAN_identifier=DestPANId;
-                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
-                               
-                               source_long_ptr->source_PAN_identifier=SrcPANId;
-                               source_long_ptr->source_address0=SrcAddr[1];
-                               source_long_ptr->source_address1=SrcAddr[0];
-                               
-                               data_len = 14;
-                       }
-                       // Destination LONG - Source SHORT
-                       if ( DstAddrMode == LONG_ADDRESS && SrcAddrMode == SHORT_ADDRESS )
-                       {
-                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-                               source_short_ptr = (source_short *) &frame_pkt->data[DEST_LONG_LEN];
-                               
-                               dest_long_ptr->destination_PAN_identifier=DestPANId;
-                               dest_long_ptr->destination_address0=DstAddr[1];
-                               dest_long_ptr->destination_address1=DstAddr[0];
-                               
-                               source_short_ptr->source_PAN_identifier=SrcPANId;
-                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
-                               
-                               data_len = 14;
-                       }
-                       
-                       
-                       //Destination SHORT - Source SHORT
-                       if ( DstAddrMode == SHORT_ADDRESS && SrcAddrMode == SHORT_ADDRESS )     
-                       {
-                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-                               source_short_ptr = (source_short *) &frame_pkt->data[DEST_SHORT_LEN];
-                               
-                               dest_short_ptr->destination_PAN_identifier=DestPANId;
-                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
-                               
-                               source_short_ptr->source_PAN_identifier=SrcPANId;
-                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
-                               
-                               data_len = 8;
-                       }
-               }
-               
-               if ( DstAddrMode == 0 && SrcAddrMode > 1 )
-               {
-                               
-                       if (SrcAddrMode == LONG_ADDRESS)
-                       {//Source LONG
-                               source_long_ptr = (source_long *) &frame_pkt->data[0];
-                               
-                               source_long_ptr->source_PAN_identifier=SrcPANId;
-                               source_long_ptr->source_address0=SrcAddr[1];
-                               source_long_ptr->source_address1=SrcAddr[0];
-                               
-                               data_len = 10;
-                       }
-                       else
-                       {//Source SHORT
-
-                               source_short_ptr = (source_short *) &frame_pkt->data[0];
-                               
-                               source_short_ptr->source_PAN_identifier=SrcPANId;
-                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
-                               
-                               data_len = 4;
-                       }
-               }
-               
-               if ( DstAddrMode > 1 && SrcAddrMode == 0 )
-               {
-                       if (DstAddrMode == LONG_ADDRESS)
-                       {//Destination LONG
-                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-               
-                               dest_long_ptr->destination_PAN_identifier=DestPANId;
-                               dest_long_ptr->destination_address0=DstAddr[1];
-                               dest_long_ptr->destination_address1=DstAddr[0];
-
-                               data_len = 10;
-                       }
-                       else
-                       {//Destination SHORT
-                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-
-                               dest_short_ptr->destination_PAN_identifier=DestPANId;
-                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
-                               
-                               data_len = 4;
-                       }
-               }
-       }
-       else
-       {
-       //intra_pan == 1
-
-       }
-               
-               memcpy(&frame_pkt->data[data_len],&msdu[0],msduLength*sizeof(uint8_t));
-               
-               if(on_gts_slot > 0)
-               {
-                       //preparing a GTS transmission
-                       
-                       //////////////printfUART("GTS send slt: %i count %i %u\n",on_gts_slot,gts_slot_list[15-on_gts_slot].element_count,mac_PIB.macDSN);
-                       frame_pkt->length = data_len + msduLength + MPDU_HEADER_LEN;
-                       
-                       frame_control = set_frame_control(TYPE_DATA,0,0,1,intra_pan,DstAddrMode,SrcAddrMode);
-                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-                       
-                       frame_pkt->seq_num = mac_PIB.macDSN;
-                       mac_PIB.macDSN++;
-                                               
-                       //ADDING DATA TO THE GTS BUFFER
-                       atomic{
-                                       if (PANCoordinator == 1)
-                                       {
-                                               gts_slot_list[15-on_gts_slot].element_count ++;
-                                               gts_slot_list[15-on_gts_slot].gts_send_frame_index[gts_slot_list[15-on_gts_slot].element_in] = available_gts_index[available_gts_index_count];
-                                               //gts_slot_list[15-on_gts_slot].length = frame_pkt->length;
-                                               
-                                               gts_slot_list[15-on_gts_slot].element_in ++;
-                                               
-                                               if (gts_slot_list[15-on_gts_slot].element_in == GTS_SEND_BUFFER_SIZE)
-                                                       gts_slot_list[15-on_gts_slot].element_in=0;
-                                               
-                                               available_gts_index_count --;
-                                               
-                                               //current_gts_pending_frame++;
-                                       }
-                                       else
-                                       {
-                                               gts_send_buffer_count++;
-                                               gts_send_buffer_msg_in++;
-                                               //////////////printfUART("end c %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
-                                       }
-                       }
-               }
-               else
-               {
-                       ////////////printfUART("CSMA send %i\n", get_txoptions_ack(TxOptions));
-                       frame_pkt->length = data_len + msduLength + MPDU_HEADER_LEN;
-                       //frame_pkt->frame_control = set_frame_control(TYPE_DATA,0,0,get_txoptions_ack(TxOptions),intra_pan,DstAddrMode,SrcAddrMode);
-                       
-                       frame_control = set_frame_control(TYPE_DATA,0,0,get_txoptions_ack(TxOptions),intra_pan,DstAddrMode,SrcAddrMode);
-                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-                       
-                       frame_pkt->seq_num = mac_PIB.macDSN;
-                       
-                       ////////printfUART("sqn %i\n", mac_PIB.macDSN);
-                       
-                       mac_PIB.macDSN++;
-                       
-                       if ( get_txoptions_indirect_transmission(TxOptions) == 1)
-                       {
-                                       indirect_trans_queue[i_indirect_trans].handler = indirect_trans_count + 1;
-                                       indirect_trans_queue[i_indirect_trans].transaction_persistent_time = 0x0000;
-       
-                                       indirect_trans_count++;
-       
-                                       ////////////printfUART("ADDED HDL: %i ADDR: %i\n",indirect_trans_count,DstAddr[1]); 
-                       }
-                       else
-                       {
-                                       //enable retransmissions
-                                       send_buffer[send_buffer_msg_in].retransmission = 1;
-                                       send_buffer[send_buffer_msg_in].indirect = 0;
-                                       
-                                       send_buffer_count++;
-                                       
-                                       send_buffer_msg_in++;
-                                       
-                                       post send_frame_csma();
-                       }
-                       
-               }
-               
-       }
-return;
-}
-
-
-error_t create_association_response_cmd(uint32_t DeviceAddress[],uint16_t shortaddress, uint8_t status)
-{
-
-       cmd_association_response *mac_association_response;
-       dest_long *dest_long_ptr;
-       source_long *source_long_ptr;
-       
-       int i=0;
-       
-       MPDU *frame_pkt=0;
-       
-       uint16_t frame_control;
-       
-       //atomic{
-       /*
-                       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-       */
-       
-       //check if the is enough space to store the indirect transaction
-       if (indirect_trans_count == INDIRECT_BUFFER_SIZE)
-       {
-               //printfUART("i full","");
-               return MAC_TRANSACTION_OVERFLOW;
-       }
-       
-       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-       {
-               if (indirect_trans_queue[i].handler == 0x00)
-               {
-                       //memcpy(&indirect_trans_queue[i].frame,frame_ptr,sizeof(MPDU));
-                       frame_pkt = (MPDU *) &indirect_trans_queue[i].frame;
-                       //printfUART("found slot","");
-                       break;
-               }
-       }
-       
-       //creation of a pointer to the association response structure
-       dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-       source_long_ptr = (source_long *) &frame_pkt->data[DEST_LONG_LEN];
-       
-       mac_association_response = (cmd_association_response *) &frame_pkt->data[DEST_LONG_LEN + SOURCE_LONG_LEN];                                                                      
-       
-       frame_pkt->length = 29;
-       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
-       
-       frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
-       
-       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-       
-       frame_pkt->seq_num = mac_PIB.macDSN;
-       mac_PIB.macDSN++;
-       
-       dest_long_ptr->destination_PAN_identifier = mac_PIB.macPANId;
-
-       dest_long_ptr->destination_address0 = DeviceAddress[1];
-       dest_long_ptr->destination_address1 = DeviceAddress[0];
-       
-       source_long_ptr->source_PAN_identifier = mac_PIB.macPANId;
-       
-       source_long_ptr->source_address0 = aExtendedAddress0;
-       source_long_ptr->source_address1 = aExtendedAddress1;
-
-       mac_association_response->command_frame_identifier = CMD_ASSOCIATION_RESPONSE;
-       
-       //mac_association_response->short_address = shortaddress;
-       mac_association_response->short_address1 = (uint8_t)(shortaddress);
-       mac_association_response->short_address2 = (uint8_t)(shortaddress >> 8);
-
-
-       mac_association_response->association_status = status;
-/*
-
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-                       }       
-               post send_frame_csma();
-*/
-       //printfUART("ASS RESP S: %i\n",shortaddress); 
-
-       indirect_trans_queue[i].handler = indirect_trans_count+1;
-
-       indirect_trans_queue[i].transaction_persistent_time = 0x0000;
-       
-       indirect_trans_count++;
-       
-       //printfUART("IAD\n", "");
-
-return MAC_SUCCESS;
-}
-
-
-void create_association_request_cmd(uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation)
-{
-atomic{
-
-               cmd_association_request *cmd_association_request_ptr;
-               dest_short *dest_short_ptr;
-               source_long *source_long_ptr;
-       
-               MPDU *frame_pkt=0;
-               
-               uint16_t frame_control;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-               
-               //creation of a pointer to the association response structure
-               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
-               
-               cmd_association_request_ptr = (cmd_association_request *) &send_buffer[send_buffer_msg_in].data[DEST_SHORT_LEN + SOURCE_LONG_LEN];
-               
-               frame_pkt->length = 21;
-               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,SHORT_ADDRESS,LONG_ADDRESS);
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,1,0,SHORT_ADDRESS,LONG_ADDRESS);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               association_cmd_seq_num =  mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               dest_short_ptr->destination_PAN_identifier = CoordPANId; //mac_PIB.macPANId;
-               
-               if (CoordAddrMode == SHORT_ADDRESS )
-               {
-                       dest_short_ptr->destination_address = (uint16_t)(CoordAddress[1] & 0x000000ff) ;  //mac_PIB.macPANId;
-               }
-               else
-               {
-               //CHECK
-               
-               //implement the long address version
-               
-               }
-               
-               source_long_ptr->source_PAN_identifier = 0xffff;
-               
-               source_long_ptr->source_address0 = aExtendedAddress0;
-               source_long_ptr->source_address1 = aExtendedAddress1;
-               
-               cmd_association_request_ptr->command_frame_identifier = CMD_ASSOCIATION_REQUEST;
-               
-               cmd_association_request_ptr->capability_information = CapabilityInformation;
-
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               pending_request_data=1;
-               
-               //////printfUART("Association request %i %i \n", send_buffer_count,send_buffer_msg_in);
-               
-               
-               post send_frame_csma();
-
-       }
-return;
-}
-
-void create_data_request_cmd()
-{
-       ////////////printfUART("create_data_request_cmd\n", ""); 
-
-atomic{
-               //dest_short *dest_short_ptr;
-               source_long *source_long_ptr;
-
-               
-               MPDU *frame_pkt;
-               
-               uint16_t frame_control;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-       
-       
-               source_long_ptr= (source_long *) &send_buffer[send_buffer_msg_in].data[0];
-       
-               //creation of a pointer to the association response structure
-               //dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-               source_long_ptr = (source_long *) &frame_pkt->data[0];
-       
-       
-               frame_pkt->length = 16;                                                 
-               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,LONG_ADDRESS);   //dest | source
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,LONG_ADDRESS);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               
-               source_long_ptr->source_PAN_identifier = mac_PIB.macPANId;
-               
-               source_long_ptr->source_address0 = aExtendedAddress0;//aExtendedAddress0;
-               source_long_ptr->source_address1 = aExtendedAddress1;
-               
-               //command_frame_identifier = CMD_DATA_REQUEST;
-               frame_pkt->data[SOURCE_LONG_LEN]=CMD_DATA_REQUEST;
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-                               
-               post send_frame_csma();
-               
-               
-               }
-return;
-}
-
-void create_beacon_request_cmd()
-{
-
-atomic{
-               cmd_beacon_request *mac_beacon_request;
-       
-               MPDU *frame_pkt;
-               
-               uint16_t frame_control;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-       
-               mac_beacon_request= (cmd_beacon_request*) &send_buffer[send_buffer_msg_in].data;
-       
-               frame_pkt->length = 10;                                                 
-               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);   //dest | source
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               mac_beacon_request->destination_PAN_identifier = 0xffff;
-               
-               mac_beacon_request->destination_address = 0xffff;
-       
-               mac_beacon_request->command_frame_identifier = CMD_BEACON_REQUEST;
-               
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               post send_frame_csma();
-
-               }
-
-return;
-}
-
-void create_orphan_notification()
-{
-
-       atomic{
-       
-               cmd_default *cmd_orphan_notification=0;
-               
-               dest_short *dest_short_ptr=0;
-               source_long *source_long_ptr=0;
-
-               MPDU *frame_pkt=0;
-                       
-               uint16_t frame_control=0;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-               
-               frame_pkt->length = 20;                                                 
-                               
-               cmd_orphan_notification = (cmd_default*) &send_buffer[send_buffer_msg_in].data[DEST_SHORT_LEN + SOURCE_LONG_LEN];
-               
-               //creation of a pointer the addressing structures
-               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
-               
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,LONG_ADDRESS);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               
-               dest_short_ptr->destination_PAN_identifier = 0xffff; //mac_PIB.macPANId;
-               
-               dest_short_ptr->destination_address = 0xffff ;  //mac_PIB.macPANId;
-               
-               source_long_ptr->source_PAN_identifier = 0xffff;
-               
-               source_long_ptr->source_address0 = aExtendedAddress0;
-               source_long_ptr->source_address1 = aExtendedAddress1;
-                               
-               
-               cmd_orphan_notification->command_frame_identifier = CMD_ORPHAN_NOTIFICATION;
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               post send_frame_csma();
-       }
-
-return;
-}
-
-
-void create_coordinator_realignment_cmd(uint32_t device_extended0, uint32_t device_extended1, uint16_t device_short_address)
-{
-
-atomic{
-
-       cmd_coord_realignment *cmd_realignment =0;
-       
-       dest_long *dest_long_ptr=0;
-       source_short *source_short_ptr=0;
-       
-       MPDU *frame_pkt=0;
-       
-       uint16_t frame_control=0;
-       
-       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-               send_buffer_msg_in=0;
-
-       frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-       
-       frame_pkt->length = 27;                                                 
-       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);   //dest | source
-       
-       cmd_realignment = (cmd_coord_realignment*) &send_buffer[send_buffer_msg_in].data[DEST_LONG_LEN + SOURCE_SHORT_LEN];
-       
-       //creation of a pointer the addressing structures
-       dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-       source_short_ptr = (source_short *) &frame_pkt->data[DEST_LONG_LEN];
-
-       
-       frame_control = set_frame_control(TYPE_CMD,0,0,0,0,LONG_ADDRESS,SHORT_ADDRESS);
-       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-       frame_pkt->seq_num = mac_PIB.macDSN;
-       
-       mac_PIB.macDSN++;
-       
-       dest_long_ptr->destination_PAN_identifier = 0xffff;
-       dest_long_ptr->destination_address0 = device_extended0;
-       dest_long_ptr->destination_address1 = device_extended1;
-       
-       source_short_ptr->source_PAN_identifier = mac_PIB.macPANId;
-       source_short_ptr->source_address = mac_PIB.macCoordShortAddress;
-       
-       
-       cmd_realignment->command_frame_identifier = CMD_COORDINATOR_REALIGNMENT;
-       
-       mac_PIB.macPANId = 0x1234;
-       
-       mac_PIB.macCoordShortAddress =0x0000;
-       
-       cmd_realignment->PAN_identifier0 = (mac_PIB.macPANId);
-       cmd_realignment->PAN_identifier1 = (mac_PIB.macPANId >> 8);
-
-       cmd_realignment->coordinator_short_address0 = (mac_PIB.macCoordShortAddress);
-       cmd_realignment->coordinator_short_address1 = (mac_PIB.macCoordShortAddress >> 8);
-       
-       cmd_realignment->logical_channel = LOGICAL_CHANNEL;
-       cmd_realignment->short_address = device_short_address;
-
-       
-       //increment the send buffer variables
-       send_buffer_count++;
-       send_buffer_msg_in++;
-       
-       post send_frame_csma();
-
-       }
-
-return;
-}
-
-
-void create_gts_request_cmd(uint8_t gts_characteristics)
-{
-atomic{
-               cmd_gts_request *mac_gts_request;
-               
-               MPDU *frame_pkt;
-               
-               uint16_t frame_control;
-               //////printfUART("create_gts_request_cmd\n", "");
-               
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-               
-               mac_gts_request= (cmd_gts_request*) &send_buffer[send_buffer_msg_in].data;
-
-               frame_pkt->length = 11;
-       
-               if ( get_characteristic_type(gts_characteristics) != 0 )
-               {   
-                       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);   //dest | source
-               
-                       frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS); 
-                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               }
-               else
-               {       
-                       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);
-                       
-                       frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);
-                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               }
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               gts_request_seq_num = frame_pkt->seq_num;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               //mac_gts_request->source_PAN_identifier = 0x0001;
-               mac_gts_request->source_PAN_identifier = mac_PIB.macPANId;
-               
-               mac_gts_request->source_address = mac_PIB.macShortAddress;
-       
-               mac_gts_request->command_frame_identifier = CMD_GTS_REQUEST;
-               
-               //mac_gts_request->gts_characteristics = set_gts_characteristics(2,1,1);
-               mac_gts_request->gts_characteristics =gts_characteristics;
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               post send_frame_csma();
-               
-               }
-
-return;
-}
-
-void create_disassociation_notification_cmd(uint32_t DeviceAddress[],uint8_t disassociation_reason)
-{
-
-       atomic{
-               cmd_disassociation_notification *mac_disassociation_notification;
-               MPDU *frame_pkt;
-               
-               uint16_t frame_control;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-               
-               //creation of a pointer to the disassociation notification structure
-               mac_disassociation_notification = (cmd_disassociation_notification*) &send_buffer[send_buffer_msg_in].data;                                                             
-               
-               
-               frame_pkt->length = 27;
-               
-               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               mac_disassociation_notification->destination_PAN_identifier = mac_PIB.macPANId;
-
-               mac_disassociation_notification->destination_address0 = DeviceAddress[0];
-               mac_disassociation_notification->destination_address1 = DeviceAddress[1];
-       
-               mac_disassociation_notification->source_PAN_identifier = mac_PIB.macPANId;
-       
-               mac_disassociation_notification->source_address0 = aExtendedAddress0;
-               mac_disassociation_notification->source_address1 = aExtendedAddress1;
-       
-               mac_disassociation_notification->command_frame_identifier = CMD_DISASSOCIATION_NOTIFICATION;
-               
-               mac_disassociation_notification->disassociation_reason = disassociation_reason;
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               post send_frame_csma();
-
-       }
-return;
-}
-
-
-
-void build_ack(uint8_t sequence,uint8_t frame_pending)
-{
-       uint16_t frame_control;
-       atomic{
-                       mac_ack_ptr->length = ACK_LENGTH;
-                       //mac_ack_ptr->frame_control = set_frame_control(TYPE_ACK,0,frame_pending,0,0,0,0);
-                       
-                       frame_control = set_frame_control(TYPE_ACK,0,frame_pending,0,0,0,0);
-                       mac_ack_ptr->frame_control1 =(uint8_t)( frame_control);
-                       mac_ack_ptr->frame_control2 =(uint8_t)( frame_control >> 8);
-                       
-                       mac_ack_ptr->seq_num = sequence;
-                       
-                       call PD_DATA.request(mac_ack_ptr->length,(uint8_t*)mac_ack_ptr);
-       }
-}
-
-
-
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/************************              INTERFACES PROVIDED                     **********************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-
-/*********************************************************/
-/**************MLME_SCAN********************************/
-/*********************************************************/
-
-task void data_channel_scan_indication()
-{
-       uint8_t link_qual;
-       
-       beacon_addr_short *beacon_ptr;
-       
-       ////printfUART("data_channel_scan_indication\n","");
-
-       atomic link_qual = link_quality;
-
-       atomic buffer_count--;
-
-       switch(scan_type)
-       {
-               case ED_SCAN: 
-                                               if (scanned_values[current_scanning-1] < link_qual)
-                                                               scanned_values[current_scanning-1] = link_qual;
-                                               break;
-               
-               case ACTIVE_SCAN:break;
-                                       
-               case PASSIVE_SCAN: 
-                                                       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
-                                                       {
-                                                               case TYPE_BEACON:
-                                                               printfUART("3 ps rb\n","");
-                                                               beacon_ptr = (beacon_addr_short*) (&buffer_msg[current_msg_out].data);
-
-                                                               //Beacon NOTIFICATION
-                                                               //BUILD the PAN descriptor of the COORDINATOR
-                                                               //assuming that the adress is short
-                                                               scan_pans[current_scanning-1].CoordPANId = beacon_ptr->destination_PAN_identifier;
-                                                               scan_pans[current_scanning-1].CoordAddress=beacon_ptr->source_address;
-                                                               scan_pans[current_scanning-1].LogicalChannel=current_channel;
-                                                               //superframe specification field
-                                                               scan_pans[current_scanning-1].SuperframeSpec = beacon_ptr->superframe_specification;
-                                                               
-                                                               if (scan_pans[current_scanning-1].lqi < link_qual)
-                                                               scan_pans[current_scanning-1].lqi = link_qual;
-                                                       
-                                                               break;
-                                                               
-                                                               default: break;
-                                                       //atomic buffer_count--;
-                                                       //////////////printfUART("Invalid frame type\n","");
-
-                                                       }
-                                                       break;
-               case ORPHAN_SCAN: 
-                                                       ////printfUART("osrm\n","");
-                                                       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
-                                                       {
-                                                               case TYPE_CMD:
-                                                                               ////printfUART("received cmd\n","");
-                                                                               if (buffer_msg[current_msg_out].data[SOURCE_SHORT_LEN+ DEST_LONG_LEN] == CMD_COORDINATOR_REALIGNMENT)
-                                                                               {       
-                                                                                       //printfUART("pf\n","");
-                                                                                       atomic scanning_channels = 0;
-                                                                                       call T_ScanDuration.stop();
-                                                                                       process_coordinator_realignment(&buffer_msg[current_msg_out]);
-                                                                                       
-                                                                               }
-                                                                               
-                                                                               break;
-                                                       default: break;
-                                                       }
-                                                       break;
-               
-       }
-       
-       atomic{
-                       current_msg_out++;
-               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
-                       current_msg_out = 0;
-               }
-return;
-}
-/*******************T_ScanDuration**************************/
-event void T_ScanDuration.fired() {
-
-       current_scanning++;
-       
-       printfUART("cs%i c%i\n",current_scanning,(0x0A + current_scanning));
-                                               
-       call PLME_SET.request(PHYCURRENTCHANNEL, (0x0A + current_scanning));
-
-       current_channel = (0x0A + current_scanning);
-       
-
-       if (current_scanning == 16 )
-       {
-               ////printfUART("scan end\n","");
-               
-               atomic scanning_channels = 0;
-               
-               switch(scan_type)
-               {
-                       case ED_SCAN: 
-                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , scanned_values,0x00);
-                                                       break;
-                       
-                       case ACTIVE_SCAN:break;
-
-                       case PASSIVE_SCAN: 
-                                                       //event result_t confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[]);
-                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , 0x00, scan_pans);
-                                                       break;
-                       
-                       case ORPHAN_SCAN: 
-                                                       //orphan scan
-                                                       //send opphan command on every channel directed to the current PAN coordinator
-                                                       //printfUART("oph s end not found\n","");
-                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , 0x00, scan_pans);
-                                                       
-                                                       break;
-               }
-       }
-       else
-       {
-               switch(scan_type)
-               {
-                       case ORPHAN_SCAN:       //printfUART("con\n","");
-                                                               create_orphan_notification();
-                                                               break;
-               }
-               
-               call T_ScanDuration.startOneShot(scan_duration);
-       }
-  
-}
-
-
-
-command error_t MLME_SCAN.request(uint8_t ScanType, uint32_t ScanChannels, uint8_t ScanDuration)
-{
-//pag 93
-       //printfUART("MLME_SCAN.request\n", ""); 
-               
-       atomic scanning_channels = 1;
-       scan_type = ScanType;
-       channels_to_scan = ScanChannels;
-       
-       atomic current_scanning=0;
-       
-       
-       switch(ScanType)
-       {
-               //ED SCAN only FFD                      
-               case ED_SCAN:   
-                                       call TimerAsync.set_timers_enable(0x00);
-                                       /*
-                               
-                                       scanning_channels = 1;
-                                       scan_type = ScanType;
-                                       current_scanning=0;
-                                       scan_count=0;
-                                       channels_to_scan = ScanChannels;
-                                       scan_duration = ((aBaseSuperframeDuration * pow(2,ScanDuration)) * 4.0) / 250.0;
-                                       
-                                       ////////////printfUART("channels_to_scan %y scan_duration %y\n", channels_to_scan,scan_duration); 
-                                       
-                                       call T_ed_scan.start(TIMER_REPEAT,1);
-                                       
-                                       call T_scan_duration.start(TIMER_ONE_SHOT,scan_duration);       
-                                       */
-                                       
-                                       
-                                       //calculate the scan_duration in miliseconds
-                                       //#ifdef PLATFORM_MICAZ
-                                               scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
-                                       //#else
-                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
-                                       //#endif
-                       //scan_duration = 2000;
-                                       
-                                       call T_ScanDuration.startOneShot(scan_duration);
-                                       
-                                       ////printfUART("channels_to_scan %y scan_duration %y\n", channels_to_scan,scan_duration); 
-                                       break;
-               //active scan only FFD
-               case ACTIVE_SCAN:
-                                       call TimerAsync.set_timers_enable(0x00);
-                                       break;
-               //passive scan
-               case PASSIVE_SCAN:      
-                                       call TimerAsync.set_timers_enable(0x00);
-                                                       
-                                       //calculate the scan_duration in miliseconds
-                                       //#ifdef PLATFORM_MICAZ
-                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
-                                       //#else
-                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
-                                       //#endif
-                                       
-                                       
-                                       //defines the time (miliseconds) that the device listen in each channel
-                                       scan_duration = 2000;
-                                       
-                                       //printfUART("channels_to_scan %y scan_duration %i\n", channels_to_scan,scan_duration); 
-                                       
-                                       call T_ScanDuration.startOneShot(scan_duration);
-                                       
-                                       ////printfUART("channels_to_scan %y scan_duration %i\n", channels_to_scan,scan_duration); 
-                                       
-                                       //atomic trx_status = PHY_RX_ON;
-                                       //call PLME_SET_TRX_STATE.request(PHY_RX_ON); 
-               
-               
-               
-                                       break;
-               //orphan scan
-               case ORPHAN_SCAN:
-               
-                                       call TimerAsync.set_timers_enable(0x01);
-                                       
-                                   scan_duration = 4000;
-                                       
-                                       //printfUART("orphan cts %y sdur %i\n", channels_to_scan,scan_duration); 
-                                       
-                                       call T_ScanDuration.startOneShot(scan_duration);
-
-                                       break;
-       
-               default:
-                                       break;
-       }
-
-return SUCCESS;
-}
-
-
-
-/*********************************************************/
-/**************MLME_ORPHAN********************************/
-/*********************************************************/
-
-command error_t MLME_ORPHAN.response(uint32_t OrphanAddress[1],uint16_t ShortAddress,uint8_t AssociatedMember, uint8_t security_enabled)
-{
-
-       if (AssociatedMember==0x01)
-       {
-               create_coordinator_realignment_cmd(OrphanAddress[0], OrphanAddress[1], ShortAddress);
-       }
-       
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_SYNC********************************/
-/*********************************************************/
-
-
-command error_t MLME_SYNC.request(uint8_t logical_channel,uint8_t track_beacon)
-{
-
-call PLME_SET.request(PHYCURRENTCHANNEL,LOGICAL_CHANNEL);      
-       //call PLME_SET.request(PHYCURRENTCHANNEL,logical_channel);     
-       
-       call TimerAsync.set_timers_enable(0x01);
-       
-       //printfUART("sync req\n", ""); 
-       
-       atomic findabeacon = 1;
-
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_RESET********************************/
-/*********************************************************/
-
-
-command error_t MLME_RESET.request(uint8_t set_default_PIB)
-{
-
-
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_GTS***********************************/
-/*********************************************************/
-
-command error_t MLME_GTS.request(uint8_t GTSCharacteristics, bool security_enable)
-{
-
-       //uint32_t wait_time;
-       //if there is no short address asigned the node cannot send a GTS request
-       if (mac_PIB.macShortAddress == 0xffff)
-                       signal MLME_GTS.confirm(GTSCharacteristics,MAC_NO_SHORT_ADDRESS);
-       
-       //gts_ack=1;
-       
-       gts_request =1;
-       
-       create_gts_request_cmd(GTSCharacteristics);
-
-return SUCCESS;
-}
-
-
-/*********************************************************/
-/**************MLME_START*********************************/
-/*********************************************************/
-
-command error_t MLME_START.request(uint32_t PANId, uint8_t LogicalChannel, uint8_t beacon_order, uint8_t superframe_order,bool pan_coodinator,bool BatteryLifeExtension,bool CoordRealignment,bool securityenable,uint32_t StartTime)
-{
-
-       uint32_t BO_EXPONENT;
-       uint32_t SO_EXPONENT;
-
-       //////////printfUART("MLME_START.request\n", "");
-       //pag 102
-       atomic {
-       PANCoordinator=1;
-       Beacon_enabled_PAN=1;
-       //TEST
-       //atomic mac_PIB.macShortAddress = 0x0000;
-
-
-               if ( mac_PIB.macShortAddress == 0xffff)
-               {
-               
-                       signal MLME_START.confirm(MAC_NO_SHORT_ADDRESS);
-                       return SUCCESS;
-               }
-               else
-               {
-                       atomic mac_PIB.macBeaconOrder = beacon_order;
-                       
-                       if (beacon_order == 15) 
-                               atomic mac_PIB.macSuperframeOrder = 15;
-                       else
-                               atomic mac_PIB.macSuperframeOrder = superframe_order;
-               
-               
-                       //PANCoordinator is set to TRUE
-                       if (pan_coodinator == 1)
-                       {
-                               atomic mac_PIB.macPANId = PANId;
-                               call PLME_SET.request(PHYCURRENTCHANNEL,LogicalChannel);
-                       }
-                       if (CoordRealignment == 1)
-                       {
-                               //generates and broadcasts a coordinator realignment command containing the new PANId and LogicalChannels
-                       }
-                       if (securityenable == 1)
-                       {
-                       //security parameters
-                       }
-               }
-       
-               if (mac_PIB.macSuperframeOrder == 0)
-                       SO_EXPONENT = 1;
-               else
-               {
-                       SO_EXPONENT = powf(2,mac_PIB.macSuperframeOrder);
-               
-               }
-               if ( mac_PIB.macBeaconOrder == 0)
-                       BO_EXPONENT = 1;
-               else
-               {
-                       BO_EXPONENT = powf(2,mac_PIB.macBeaconOrder);
-               
-               }       
-       }
-       
-       BI = aBaseSuperframeDuration * BO_EXPONENT; 
-               
-       SD = aBaseSuperframeDuration * SO_EXPONENT; 
-       //backoff_period
-       backoff = aUnitBackoffPeriod;
-
-       
-       atomic time_slot = SD / NUMBER_TIME_SLOTS;
-
-       call TimerAsync.set_backoff_symbols(backoff);
-
-       call TimerAsync.set_bi_sd(BI,SD);
-       
-       atomic{
-       
-               call TimerAsync.set_timers_enable(0x01);
-               
-               call TimerAsync.reset();
-               
-       }
-               
-       signal MLME_START.confirm(MAC_SUCCESS);
-
-       return SUCCESS;
-}
-
-/*************************************************************/
-/**************MLME_ASSOCIATE*********************************/
-/*************************************************************/
-
-command error_t MLME_ASSOCIATE.request(uint8_t LogicalChannel,uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation,bool securityenable)
-{
-       //update current channel
-       //call PLME_SET.request(PHYCURRENTCHANNEL,LogicalChannel);
-       
-       
-       printfUART("MLME_ASSOCIATE.request %x %x\n", mac_PIB.macPANId,mac_PIB.macCoordShortAddress);
-       //updates the PAN ID
-       atomic{ 
-               mac_PIB.macPANId = CoordPANId;
-               mac_PIB.macCoordShortAddress = (uint16_t)(CoordAddress[1] & 0x000000ff);
-               }
-               
-               
-       associating=1; //boolean variable stating that the device is trying to associate
-       
-       call TimerAsync.set_timers_enable(1);
-       
-       //the channel selection is made during the SynC procedure
-       //call PLME_SET.request(PHYCURRENTCHANNEL, LogicalChannel);
-
-       current_channel = LogicalChannel;
-       
-       ////printfUART("SELECTED cord id %i\n", mac_PIB.macPANId);
-       ////printfUART("CoordAddress %i\n", mac_PIB.macCoordShortAddress);
-       ////printfUART("LogicalChannel %i\n", LogicalChannel);
-       ////printfUART("Cordaddr %i\n",CoordAddress[0]);
-       ////printfUART("Cordaddr %i\n",CoordAddress[1]);
-       /*
-
-       a_CoordAddrMode = CoordAddrMode;
-       a_CoordPANId=CoordPANId;
-       a_CoordAddress[0]=CoordAddress[0];
-       a_CoordAddress[1]=CoordAddress[1];
-       a_CapabilityInformation=CapabilityInformation;
-       a_securityenable=securityenable;
-       */
-       create_association_request_cmd(CoordAddrMode,CoordPANId,CoordAddress,CapabilityInformation);
-       
-       return SUCCESS;
-}
-
-command error_t MLME_ASSOCIATE.response(uint32_t DeviceAddress[], uint16_t AssocShortAddress, uint8_t status, bool securityenable)
-{
-       
-       error_t status_response;
-       
-       ////////printfUART("MAR\n", "");
-       
-       status_response = create_association_response_cmd(DeviceAddress,AssocShortAddress,status);
-       //////////////printfUART("MLME_ASSOCIATE.response\n", "");
-
-
-return SUCCESS;
-}
-
-/*************************************************************/
-/**************MLME_DISASSOCIATE*********************************/
-/*************************************************************/
-
-command error_t MLME_DISASSOCIATE.request(uint32_t DeviceAddress[], uint8_t disassociate_reason, bool securityenable)
-{
-       create_disassociation_notification_cmd(DeviceAddress,disassociate_reason);
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_GET***********************************/
-/*********************************************************/
-command error_t MLME_GET.request(uint8_t PIBAttribute)
-{
-
-       switch(PIBAttribute)
-       {
-               case MACACKWAITDURATION :               signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAckWaitDuration);
-                                                                               break;
-               case MACASSOCIATIONPERMIT:      signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAssociationPermit);
-                                                                               break;
-               case MACAUTOREQUEST :                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAutoRequest);
-                                                                               break;
-               case MACBATTLIFEEXT:                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBattLifeExt);
-                                                                               break;
-               case MACBATTLIFEEXTPERIODS:             signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBattLifeExtPeriods);
-                                                                               break;
-               case MACBEACONPAYLOAD:                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute, mac_PIB.macBeaconPayload);
-                                                                               break;
-               case MACMAXBEACONPAYLOADLENGTH: signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBeaconPayloadLenght);
-                                                                               break;
-               case MACBEACONORDER:                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBeaconOrder);
-                                                                               break;
-               case MACBEACONTXTIME:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *)&mac_PIB.macBeaconTxTime);
-                                                                               break;
-               case MACBSN:                                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBSN);
-                                                                               break;
-               case MACCOORDEXTENDEDADDRESS:   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macCoordExtendedAddress0);
-                                                                               break;
-               case MACCOORDSHORTADDRESS:              signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macCoordShortAddress);
-                                                                               break;
-               case MACDSN:                                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macDSN);
-                                                                               break;
-               case MACGTSPERMIT:                              signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macGTSPermit);
-                                                                               break;
-               case MACMAXCSMABACKOFFS:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macMaxCSMABackoffs);
-                                                                               break;
-               case MACMINBE:                                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macMinBE);
-                                                                               break;
-               case MACPANID:                                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macPANId);
-                                                                               break;
-               case MACPROMISCUOUSMODE:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macPromiscuousMode);
-                                                                               break;
-               case MACRXONWHENIDLE:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macRxOnWhenIdle);
-                                                                               break;
-               case MACSHORTADDRESS:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macShortAddress);
-                                                                               break;
-               case MACSUPERFRAMEORDER:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macSuperframeOrder);
-                                                                               break;
-               case MACTRANSACTIONPERSISTENCETIME:     signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macTransactionPersistenceTime);
-                                                                                       break;
-                                                                                       
-               default:                                                signal MLME_GET.confirm(MAC_UNSUPPORTED_ATTRIBUTE,PIBAttribute,0x00);
-                                                                               break;
-       }
-
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_SET***********************************/
-/*********************************************************/
-command error_t MLME_SET.request(uint8_t PIBAttribute,uint8_t PIBAttributeValue[])
-{
-
-//int i;
-
-////printfUART("set %i\n",PIBAttribute);
-
-atomic{
-
-       switch(PIBAttribute)
-       {
-       
-       
-               case MACACKWAITDURATION :               mac_PIB.macAckWaitDuration = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macAckWaitDuration: %x\n",mac_PIB.macAckWaitDuration);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                       
-               case MACASSOCIATIONPERMIT:      if ((uint8_t)PIBAttributeValue[1] == 0x00)
-                                                                               {
-                                                                                       mac_PIB.macAssociationPermit = 0x00;
-                                                                               }
-                                                                               else
-                                                                               {
-                                                                                       mac_PIB.macAssociationPermit = 0x01;
-                                                                               }
-                                                                               //////////printfUART("mac_PIB.macAssociationPermit: %i %y\n",mac_PIB.macAssociationPermit,PIBAttributeValue[1]);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACAUTOREQUEST :                   mac_PIB.macAutoRequest = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macAutoRequest: %i\n",mac_PIB.macAutoRequest);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACBATTLIFEEXT:                    mac_PIB.macBattLifeExt = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macBattLifeExt %i\n",mac_PIB.macBattLifeExt);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACBATTLIFEEXTPERIODS:             mac_PIB.macBattLifeExtPeriods = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macBattLifeExtPeriods %i\n",mac_PIB.macBattLifeExtPeriods);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACBEACONPAYLOAD:                  /*for(i=0;i < mac_PIB.macBeaconPayloadLenght;i++) 
-                                                                               {
-                                                                                       mac_PIB.macBeaconPayload[i] = PIBAttributeValue[i];
-                                                                               }*/
-                                                                       
-                                                                               memcpy(&PIBAttributeValue[0],&mac_PIB.macBeaconPayload[0],mac_PIB.macBeaconPayloadLenght * sizeof(uint8_t));
-                                                                               
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                               
-               case MACMAXBEACONPAYLOADLENGTH: mac_PIB.macBeaconPayloadLenght = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macBeaconPayloadLenght %i\n",mac_PIB.macBeaconPayloadLenght);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACBEACONORDER:                    mac_PIB.macBeaconOrder = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macBeaconOrder %i\n",mac_PIB.macBeaconOrder);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACBEACONTXTIME:                   mac_PIB.macBeaconTxTime =PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macBeaconTxTime %i\n",mac_PIB.macBeaconTxTime);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACBSN:                                    mac_PIB.macBSN = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macBSN %i\n",mac_PIB.macBSN);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-
-               case MACCOORDEXTENDEDADDRESS:   //mac_PIB.macCoordExtendedAddress0 = ((PIBAttributeValue[0] >> 24) | (PIBAttributeValue[1] >> 16) | (PIBAttributeValue[2] >> 8) | (PIBAttributeValue[3])) ;
-                                                                               //mac_PIB.macCoordExtendedAddress1 = ((PIBAttributeValue[4] >> 24) | (PIBAttributeValue[5] >> 16) | (PIBAttributeValue[6] >> 8) | (PIBAttributeValue[7]));
-
-                                                                               ////////////printfUART("mac_PIB.macCoordExtendedAddress0 %y\n",mac_PIB.macCoordExtendedAddress0);
-                                                                               ////////////printfUART("mac_PIB.macCoordExtendedAddress1 %y\n",mac_PIB.macCoordExtendedAddress1);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-                                                                       
-               case MACCOORDSHORTADDRESS:              mac_PIB.macCoordShortAddress= ((PIBAttributeValue[0] << 8) |PIBAttributeValue[1]);
-                                                                               ////printfUART("mac_PIB.macCoordShortAddress: %x\n",mac_PIB.macCoordShortAddress);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               
-               case MACDSN:                                    mac_PIB.macDSN = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macDSN: %x\n",mac_PIB.macDSN);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACGTSPERMIT:                              mac_PIB.macGTSPermit = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macGTSPermit: %x\n",mac_PIB.macGTSPermit);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACMAXCSMABACKOFFS:                mac_PIB.macMaxCSMABackoffs = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macMaxCSMABackoffs: %x\n",mac_PIB.macMaxCSMABackoffs);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACMINBE:                                  mac_PIB.macMinBE = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macMinBE: %x\n",mac_PIB.macMinBE);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               
-               case MACPANID:                                  mac_PIB.macPANId = ((PIBAttributeValue[0] << 8)| PIBAttributeValue[1]);
-                                                                               ////printfUART("mac_PIB.macPANId: %x\n",mac_PIB.macPANId);
-                                                                               
-                                                                               
-                                                                               call AddressFilter.set_coord_address(mac_PIB.macCoordShortAddress, mac_PIB.macPANId);
-                                                                               
-                                                                               
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               
-               case MACPROMISCUOUSMODE:                mac_PIB.macPromiscuousMode = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macPromiscuousMode: %x\n",mac_PIB.macPromiscuousMode);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACRXONWHENIDLE:                   mac_PIB.macRxOnWhenIdle = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macRxOnWhenIdle: %x\n",mac_PIB.macRxOnWhenIdle);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-                                                                               
-               case MACSHORTADDRESS:                   mac_PIB.macShortAddress = ((PIBAttributeValue[0] << 8) |PIBAttributeValue[1]);
-                                                                               ////printfUART("mac_PIB.macShortAddress: %y\n",mac_PIB.macShortAddress);
-                                                                               
-                                                                               call AddressFilter.set_address(mac_PIB.macShortAddress, aExtendedAddress0, aExtendedAddress0);
-                                                                               
-                                                                               
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACSUPERFRAMEORDER:                mac_PIB.macSuperframeOrder = PIBAttributeValue[0];
-                                                                               ////////////printfUART("mac_PIB.macSuperframeOrder: %x\n",mac_PIB.macSuperframeOrder);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACTRANSACTIONPERSISTENCETIME:      mac_PIB.macTransactionPersistenceTime = PIBAttributeValue[0];
-                                                                                        ////////////printfUART("mac_PIB.macTransactionPersistenceTime: %y\n",mac_PIB.macTransactionPersistenceTime);
-                                                                                        signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                                        break;
-                                                                                       
-               default:                                                signal MLME_SET.confirm(MAC_UNSUPPORTED_ATTRIBUTE,PIBAttribute);
-                                                                               break;
-                                                                               
-               
-       }
-
-}
-
-return SUCCESS;
-}
-/*************************************************************/
-/**************        MCPS - DATA         *******************/
-/*************************************************************/
-
-command error_t MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions)
-{
-       int i;
-       //uint8_t valid_gts=0;
-       uint32_t total_ticks;
-       
-       ////////printfUART("MCPS_DATA.request\n", ""); 
-       //check conditions on page 58
-       
-       //atomic mac_PIB.macShortAddress = TOS_LOCAL_ADDRESS;
-       
-       /*
-       ////printfUART("SrcAddrMode %x\n", SrcAddrMode);
-       ////printfUART("SrcPANId %x\n", SrcPANId);
-       ////printfUART("SrcAddr %x\n", SrcAddr[0]);
-       ////printfUART("SrcAddr %x\n", SrcAddr[1]);
-       ////printfUART("DstAddrMode %x\n", DstAddrMode);
-       ////printfUART("DestPANId %x\n", DestPANId);
-       ////printfUART("DstAddr %x\n", DstAddr[0]);
-       ////printfUART("DstAddr %x\n", DstAddr[1]);
-       ////printfUART("msduLength %x\n", msduLength);
-       ////printfUART("msduHandle %x\n", msduHandle);
-       ////printfUART("TxOptions %x\n", TxOptions);
-               */
-       
-       atomic{
-       
-       if (mac_PIB.macShortAddress == 0xffff)
-               return FAIL;
-       }
-       
-       if(PANCoordinator == 1)
-       {
-       //PAN COORDINATOR OPERATION
-               //////////////printfUART("GTS TRANS: %i TxOptions: %u dest:%u\n", get_txoptions_gts(TxOptions),TxOptions,DstAddr[1]); 
-               
-               if (get_txoptions_gts(TxOptions) == 1)
-               {
-               //GTS TRANSMISSION
-                       for (i=0 ; i < 7 ; i++)
-                       {
-                               //SEARCH FOR A VALID GTS
-                               if ( GTS_db[i].DevAddressType == (uint16_t)DstAddr[1] && GTS_db[i].direction == 1 && GTS_db[i].gts_id != 0)
-                               {
-                                       
-                               //atomic{
-                                               //////////////printfUART("BUFFER UNTIL GTS SLOT n: %i ss: %i\n",number_time_slot,GTS_db[valid_gts].starting_slot);
-                                               create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,GTS_db[i].starting_slot,1);
-                                       //}
-                                       return SUCCESS;
-                                       break;
-                               }
-                       }
-                       signal MCPS_DATA.confirm(msduHandle, MAC_INVALID_GTS);
-                       return FAIL;
-               }
-               else
-               {
-               //NORMAL/INDIRECT TRANSMISSION
-               
-                       //////////////printfUART("IND TRANS: %i TxOptions: %u\n", get_txoptions_indirect_transmission(TxOptions),TxOptions);
-                       //check if its an indirect transmission
-                       //if ( get_txoptions_indirect_transmission(TxOptions) == 1)
-                       //{
-                               //INDIRECT TRANSMISSION
-                               
-                               //////////////printfUART("CREATE INDIRECT TRANSMISSION\n","");
-                               
-                               
-                               
-                               
-                       //}
-                       //else
-                       //{
-                               //NORMAL TRANSMISSION
-                               ////printfUART("SEND NO GTS NO IND\n","");
-                               create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,0,0);
-                       //}
-               }
-       }
-       else
-       {
-       //NON PAN COORDINATOR OPERATION
-               atomic{
-                               
-                               //////////////printfUART("sslot: %i ini %i\n",s_GTSss,init_s_GTSss);
-                               //check if it a gts transmission
-                               if (get_txoptions_gts(TxOptions) == 1)
-                               {
-                               //GTS TRANSMISSION
-                                       if (s_GTSss == 0x00)
-                                       {
-                                               //////////////printfUART("NO VALID GTS \n","");
-                                               signal MCPS_DATA.confirm(msduHandle, MAC_INVALID_GTS);
-                                       }
-                                       else
-                                       {
-                                                       total_ticks = call TimerAsync.get_total_tick_counter();
-                                                       msdu[0] =(uint8_t)(total_ticks >> 0 );
-                                                       msdu[1] =(uint8_t)(total_ticks >> 8);
-                                                       msdu[2] =(uint8_t)(total_ticks >> 16);
-                                                       msdu[3] =(uint8_t)(total_ticks >> 24);
-                                                       
-                                                       if (on_sync == 1 && s_GTSss > 0)
-                                                       create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,s_GTSss,0);
-                                       }
-                               }
-                               else
-                               {
-                               //NORMAL TRANSMISSION
-                                       //printfUART("TRnsm\n","");
-                                       create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,0,0);
-                               }
-                       }
-       }
-       return SUCCESS;
-}
-
-
-
-
-/*************************************************************/
-/**************        MCPS - PURGE         *******************/
-/*************************************************************/
-
-command error_t MCPS_PURGE.request(uint8_t msduHandle)
-{
-
-
-
-return SUCCESS;
-}
-
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/************************              OTHER FUNCTIONS                         **********************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-
-task void signal_loss()
-{
-       //TODO
-       atomic signal MLME_SYNC_LOSS.indication(beacon_loss_reason); //MAC_BEACON_LOSS
-       return;
-}
-
-//inicialization of the mac constants
-void init_MacCon()
-{
-/*****************************************************/
-/*                             Boolean Variables                                        */
-/*****************************************************/  
-PANCoordinator = 0;
-//(0 NO beacon transmission; 1 beacon transmission);
-Beacon_enabled_PAN = 0;
-//(SYNC)the device will try to track the beacon ie enable its receiver just before the espected time of each beacon
-TrackBeacon=0;
-//(SYNC)the device will try to locate one beacon
-findabeacon=0;
-//(RESET) when the reset command arrives it checks whether or not to reset the PIB
-SetDefaultPIB=0;
-/*****************************************************/
-/*                             Integer Variables                                        */
-/*****************************************************/  
-/*
-//Beacon Interval
-uint32_t BI;
-//Superframe duration
-uint32_t SD;
-*/
-//(SYNC)number of beacons lost before sending a Beacon-Lost indication comparing to aMaxLostBeacons
-missed_beacons=0;
-//current_channel
-current_channel=0;
-
-
-/*****************************************************/
-/*                             Other Variables                                  */
-/*****************************************************/ 
-pending_reset=0;
-
-}
-
-//inicialization of the mac PIB
-void init_MacPIB()
-{
-
-atomic{
-       //mac PIB default values
-       
-       //mac_PIB.macAckWaitDuration = 54; OLD VALUE//Number os symbols to wait for an acknowledgment
-       mac_PIB.macAckWaitDuration = 65;
-       
-       mac_PIB.macAssociationPermit = 1; //1 - PAN allowing associations
-       mac_PIB.macAutoRequest = 1; //indication if a device automatically sends a data request command if address is listed in the beacon frame
-       
-       mac_PIB.macBattLifeExt= 0; //batery life extension CSMA-CA
-       
-       mac_PIB.macBattLifeExtPeriods=6;
-       //mac_PIB.macBeaconPayload; //payload of the beacon
-       mac_PIB.macBeaconPayloadLenght=0; //beacon payload lenght
-       
-       mac_PIB.macBeaconTxTime=(0xffffff << 24); //*****
-       
-       
-       mac_PIB.macBSN=call Random.rand16(); //sequence number of the beacon frame
-       
-       
-       mac_PIB.macCoordExtendedAddress0 = 0x00000000; //64bits address of the coordinator with witch the device is associated
-       mac_PIB.macCoordExtendedAddress1 = 0x00000000;
-       
-       mac_PIB.macCoordShortAddress = 0x0000; //16bits address of the coordinator with witch the device is associated
-       
-       /*
-       if (DEVICE_DEPTH == 0x01)
-               mac_PIB.macCoordShortAddress =D1_PAN_SHORT;
-       if (DEVICE_DEPTH == 0x02)
-               mac_PIB.macCoordShortAddress =D2_PAN_SHORT;
-       if (DEVICE_DEPTH == 0x03)
-               mac_PIB.macCoordShortAddress =D3_PAN_SHORT;
-       if (DEVICE_DEPTH == 0x04)
-               mac_PIB.macCoordShortAddress =D4_PAN_SHORT;
-       */
-       
-       mac_PIB.macDSN=call Random.rand16(); //sequence number of the transmited data or MAC command frame
-       
-       //alowing gts requests (used in beacon)
-       mac_PIB.macGTSPermit=1; //
-       
-       //Number of maximum CSMA backoffs
-       mac_PIB.macMaxCSMABackoffs=4;
-       mac_PIB.macMinBE=0;
-       
-       //mac_PIB.macPANId=0xffff; //16bits identifier of the PAN on witch this device is operating
-       mac_PIB.macPANId = MAC_PANID;
-       
-       mac_PIB.macPromiscuousMode=0;
-       mac_PIB.macRxOnWhenIdle=0;
-       //mac_PIB.macShortAddress=TOS_LOCAL_ADDRESS; //16bits short address
-       mac_PIB.macShortAddress=0xffff;
-
-
-       mac_PIB.macBeaconOrder=7;  //specification of how often the coordinator transmits a beacon
-       mac_PIB.macSuperframeOrder=3;
-       
-       //default mac_PIB.macTransactionPersistenceTime=0x01f4;
-       mac_PIB.macTransactionPersistenceTime=0x0010;
-       
-       //*******************************************
-
-       }
-}
-
-//////////////////////////////////////////////////////////////
-////////////////////////CSMA-CA functions////////////////////
-/////////////////////////////////////////////////////////////
-
-/*****************************************************/
-/*                             SEND FRAME FUNCTION                      */
-/*****************************************************/ 
-
-task void send_frame_csma()
-{
-       atomic{
-       
-               //
-               /////printfUART("I_AM_IN_IP %i %i\n",I_AM_IN_IP,send_buffer_count);
-       
-               if ((send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE && performing_csma_ca == 0) || I_AM_IN_IP != 0)
-               {
-                       //////printfUART("sf %i\n",send_buffer_count);
-                       ////////printfUART("peform\n","");
-                       
-                       performing_csma_ca = 1;
-
-                       perform_csma_ca();
-               }
-               else
-               {
-                       ////printfUART("NOT SEND\n","");
-               }
-
-               
-       }
-       
-}
-
-
-task void perform_csma_ca_slotted()
-{
-       uint8_t random_interval;
-       
-               
-               
-               //DEFERENCE CHANGE
-               if (check_csma_ca_send_conditions(send_buffer[send_buffer_msg_out].length,send_buffer[send_buffer_msg_out].frame_control1) == 1 )
-               {
-                       cca_deference = 0;
-               }
-               else
-               {
-                       //nao e necessario
-                       cca_deference = 1;
-                       return;
-               }
-               
-       atomic{
-               ////printfUART("CCA: %i\n", call CCA.get()) ;
-       
-               if(call CCA.get() == CCA_BUSY )
-               {
-                       //////////////printfUART("CCA: 1\n", "") ;
-                       //STEP 5
-                       CW--;
-                       if (CW == 0 )
-                       {
-                               //send functions
-                               csma_cca_backoff_boundary =0;
-                                       
-                                       ////////printfUART("rts %i\n",get_ack_request(send_buffer[send_buffer_msg_out].frame_control));
-
-                                               //verify if the message must be ack
-                                               if ( get_fc1_ack_request(send_buffer[send_buffer_msg_out].frame_control1) == 1 )
-                                               {
-                                                       send_ack_check=1;
-                                                       ack_sequence_number_check=send_buffer[send_buffer_msg_out].seq_num;     
-                                                       //verify retransmission
-                                                       send_retransmission = send_buffer[send_buffer_msg_out].retransmission;
-                                                       //verify if its an indirect transmission
-                                                       send_indirect_transmission = send_buffer[send_buffer_msg_out].indirect;
-                                                       //SEND WITH ACK_REQUEST
-                                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
-                                                       
-                                                       ////////printfUART("out ck\n","");
-                                                       
-                                                       
-                                                       call T_ackwait.startOneShot(ackwait_period);
-                                               }
-                                               else
-                                               {
-                                               
-                                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
-                                                       
-                                                       send_buffer_count --;
-                                                       send_buffer_msg_out++;
-                                               
-                                                       //failsafe
-                                                       if(send_buffer_count > SEND_BUFFER_SIZE)
-                                                       {
-                                                               send_buffer_count =0;
-                                                               send_buffer_msg_out=0;
-                                                               send_buffer_msg_in=0;
-                                                       }
-                                                       
-                                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                                               send_buffer_msg_out=0;
-                                                       
-                                                       if (send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE)
-                                                               post send_frame_csma();
-                                                       
-                                                       ////printfUART("sk %i\n",send_buffer_count);
-                                                       
-                                                       //////////printfUART("%i %i %i\n",send_buffer_count,send_buffer_msg_in,send_buffer_msg_out);
-                                               }
-                                       
-                               performing_csma_ca = 0;
-                       }
-               }
-               else
-               {
-                       //CHECK NOT USED
-                       //csma_backoff_counter++;
-                       //csma_backoff_counter_inst++;
-
-                       if (NB < mac_PIB.macMaxCSMABackoffs)
-                       {
-                               ////////////printfUART("NB:%i BE:%i L CW: %i\n",NB,BE,CW);
-                               //STEP 4
-                               CW = 2;
-                               NB++;
-                               BE = min(BE+1,aMaxBE);
-                               
-                               //STEP 2
-                               //random_interval = pow(2,BE) - 1;
-                               
-                               //delay_backoff_period = (call Random.rand() & random_interval);
-                               //verification of the backoff_deference
-                               //DEFERENCE CHANGE
-                               if (backoff_deference == 0)
-                               {
-                                       random_interval = powf(2,BE) - 1;
-                                       delay_backoff_period = (call Random.rand16() & random_interval );
-                                               
-                                       if (check_csma_ca_backoff_send_conditions((uint32_t) delay_backoff_period) == 1)
-                                       {
-                                                       backoff_deference = 1;
-                                       }
-                               }
-                               else
-                               {
-                                       backoff_deference = 0;
-                               }
-                               
-                               
-                               //delay_backoff_period=0;
-                               
-                               ////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
-                               csma_delay=1;
-                       }
-                       else
-                       {
-                               //CSMA/CA FAIL
-                               csma_delay=0;
-                               csma_cca_backoff_boundary=0;
-                               
-                               send_buffer_count --;
-                               send_buffer_msg_out++;
-                       
-                               //failsafe
-                               if(send_buffer_count > SEND_BUFFER_SIZE)
-                               {
-                                       send_buffer_count =0;
-                                       send_buffer_msg_out=0;
-                                       send_buffer_msg_in=0;
-                               }
-                               
-                               if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                       send_buffer_msg_out=0;
-                               
-                               if (send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE)
-                                       post send_frame_csma();
-                                       
-                               performing_csma_ca = 0;
-                               
-                               ////printfUART("SLOTTED FAIL\n","");
-                               /*
-                               if(associating == 1)
-                               {
-                                       associating=0;
-                                       signal MLME_ASSOCIATE.confirm(0x0000,MAC_CHANNEL_ACCESS_FAILURE);
-                               }*/
-                       }
-               }
-       }
-return;
-}
-
-task void perform_csma_ca_unslotted()
-{
-       uint8_t random_interval;
-       
-       atomic{
-               if (NB < mac_PIB.macMaxCSMABackoffs)
-               {
-                       //STEP 3
-                       //perform CCA
-                       ////////////printfUART("CCA: %i\n", TOSH_READ_CC_CCA_PIN()) ;
-                       
-                       //if CCA is clear send message
-                       if(call CCA.get() == CCA_BUSY)
-                       {
-                               //send functions
-                               ////////////printfUART("UNSLOTTED SUCCESS\n","");
-                               atomic{
-                               csma_delay =0;
-                               
-
-                                               
-                               if (check_csma_ca_send_conditions(send_buffer[send_buffer_msg_out].length,send_buffer[send_buffer_msg_out].frame_control1) == 1 )
-                               {
-                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
-                                       
-                                       send_buffer_count --;
-                                       send_buffer_msg_out++;
-                               
-                                       //failsafe
-                                       if(send_buffer_count > SEND_BUFFER_SIZE)
-                                       {
-                                               send_buffer_count =0;
-                                               send_buffer_msg_out=0;
-                                               send_buffer_msg_in=0;
-                                       }
-                               
-                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                               send_buffer_msg_out=0;
-                               }
-                                       
-                               
-                               performing_csma_ca =0;
-
-                               }
-                               return; //SUCCESS
-                       
-                       }
-
-                       //CCA is not clear, perform new iteration of the CSMA/CA UNSLOTTED
-                       
-                       //STEP 4
-                       NB++;
-                       BE = min(BE+1,aMaxBE);
-               
-                       ////////////printfUART("NB:%i BE:%i\n",NB,BE);
-                       
-                       //STEP 2
-                       //#ifdef PLATFORM_MICAZ
-                               random_interval = powf(2,BE) - 1;
-                       //#else
-                       //      random_interval = powf(2,BE) - 1;
-                       //#endif
-                       delay_backoff_period = (call Random.rand16() & random_interval );
-                       //delay_backoff_period=1;
-                       csma_delay=1;
-                       
-                       //////////////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
-               }
-               else
-               {
-                       atomic csma_delay=0;
-                       ////////////printfUART("UNSLOTTED FAIL\n","");
-               }
-       }
-return;
-}
-
-
-void perform_csma_ca()
-{
-       uint8_t random_interval;
-       csma_slotted=1;
-       //STEP 1
-       if (csma_slotted == 0 )
-       {
-               atomic{
-                       //UNSLOTTED version
-                       init_csma_ca(csma_slotted);
-                       //STEP 2
-                       random_interval = powf(2,BE) - 1;
-                       delay_backoff_period = (call Random.rand16() & random_interval );
-                       
-                       csma_delay=1;
-                       ////////////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
-               }
-               return;
-       }
-       else
-       {
-               //SLOTTED version
-               atomic{
-                       //DEFERENCE CHANGE
-                       if (cca_deference==0)
-                       {
-                               init_csma_ca(csma_slotted);
-                               if (mac_PIB.macBattLifeExt == 1 )
-                               {
-                                       BE = min(2,     mac_PIB.macMinBE);
-                               }
-                               else
-                               {
-                                       BE = mac_PIB.macMinBE;
-                               }
-                               csma_locate_backoff_boundary = 1;
-                       }
-                       else
-                       {
-                               cca_deference = 0;
-                               csma_delay=0;
-                               csma_locate_backoff_boundary=0;
-                               csma_cca_backoff_boundary = 1;
-                       
-                       }
-               }
-               return;
-       }
-}
-
-
-uint8_t min(uint8_t val1, uint8_t val2)
-{
-       if (val1 < val2)
-       {
-               return val1;
-       }
-       else
-       {
-               return val2;
-       }
-}
-
-void init_csma_ca(bool slotted)
-{
-
-//initialization of the CSMA/CA protocol variables
-       //////////////printfUART("init_csma_ca\n", "") ;
-       
-       csma_delay=0;
-       
-       if (slotted == 0 )
-       {
-               NB=0;
-               BE=mac_PIB.macMinBE;
-       }
-       else
-       {
-               NB=0;
-               CW=2;
-               
-               csma_cca_backoff_boundary=0;
-               csma_locate_backoff_boundary=0;
-       }
-
-return;
-}
-
-
-uint8_t calculate_ifs(uint8_t pk_length)
-{
-       if (pk_length > aMaxSIFSFrameSize)
-               return aMinLIFSPeriod; // + ( ((pk_length * 8) / 250.00) / 0.34 );
-       else
-               return aMinSIFSPeriod; // + ( ((pk_length * 8) / 250.00) / 0.34 );
-}
-
-uint32_t calculate_gts_expiration()
-{
-       uint32_t exp_res;
-       if( mac_PIB.macBeaconOrder > 9 )
-               exp_res= 1;
-       else
-       {
-               //#ifdef PLATFORM_MICAZ
-                       exp_res= powf(2,(8-mac_PIB.macBeaconOrder));
-               //#else
-               //      exp_res= powf(2,(8-mac_PIB.macBeaconOrder));
-               //#endif
-       }       
-       ////////////printfUART("alculat %i\n",exp_res ) ;
-       return exp_res;
-}
-
-uint8_t check_csma_ca_send_conditions(uint8_t frame_length,uint8_t frame_control1)
-{
-       uint8_t ifs_symbols;
-       uint32_t frame_tx_time;
-       uint32_t remaining_gts_duration;
-       
-       
-       ifs_symbols=calculate_ifs(frame_length);
-       //wait_ifs=1;
-       //call TimerAsync.set_ifs_symbols(ifs_symbols);
-       
-       //////////////printfUART("ifs_symbols %i\n",ifs_symbols ) ;
-       
-       if (get_fc1_ack_request(frame_control1) == 1 )
-               frame_tx_time =  frame_length + ACK_LENGTH + aTurnaroundTime + ifs_symbols;
-       else
-               frame_tx_time =  frame_length + ifs_symbols;
-               
-       atomic remaining_gts_duration = time_slot - ( call TimerAsync.get_current_number_backoff_on_time_slot() * aUnitBackoffPeriod);
-       
-       //////////////printfUART("frame_tx %d remaing %d\n",frame_tx_time,remaining_gts_duration ) ;
-       
-       if (frame_tx_time < remaining_gts_duration)
-               return 1;
-       else
-               return 0;
-
-}
-
-//DEFERENCE CHANGE
-uint8_t check_csma_ca_backoff_send_conditions(uint32_t delay_backoffs)
-{
-
-       uint32_t number_of_sd_ticks=0;
-       uint32_t current_ticks=0;
-       uint32_t ticks_remaining =0;
-       uint32_t number_of_backoffs_remaining =0;
-       
-       number_of_sd_ticks = call TimerAsync.get_sd_ticks();
-       
-       current_ticks = call TimerAsync.get_current_ticks();
-       
-       ticks_remaining = number_of_sd_ticks - current_ticks;
-       
-       number_of_backoffs_remaining = ticks_remaining / 5;
-       
-       if (number_of_backoffs_remaining > delay_backoffs)
-               return 0;
-       else
-               return 1;
-
-
-
-}
-
-uint8_t check_gts_send_conditions(uint8_t frame_length)
-{
-       uint8_t ifs_symbols;
-       uint32_t frame_tx_time;
-       uint32_t remaining_gts_duration;
-       
-
-       ifs_symbols=calculate_ifs(frame_length);
-       //wait_ifs=1;
-       //call TimerAsync.set_ifs_symbols(ifs_symbols);
-       
-       //////////////printfUART("ifs_symbols %i\n",ifs_symbols ) ;
-       
-       frame_tx_time =  frame_length + ACK_LENGTH + aTurnaroundTime + ifs_symbols;
-       
-       remaining_gts_duration = time_slot - ( call TimerAsync.get_current_number_backoff_on_time_slot() * aUnitBackoffPeriod);
-       
-       //////////////printfUART("frame_tx %d remaing %d\n",frame_tx_time,remaining_gts_duration ) ;
-       
-       if (frame_tx_time < remaining_gts_duration)
-               return 1;
-       else
-               return 0;
-}
-
-//////////////////////////////////////////////////////////////
-////////////////////////GTS functions////////////////////////
-/////////////////////////////////////////////////////////////
-
-void init_GTS_db()
-{
-       //initialization of the GTS database
-       int i;
-atomic{
-               for (i=0 ; i < 7 ; i++)
-               {
-                       GTS_db[i].gts_id=0x00;
-                       GTS_db[i].starting_slot=0x00;
-                       GTS_db[i].length=0x00;
-                       GTS_db[i].direction=0x00;
-                       GTS_db[i].DevAddressType=0x0000;
-               
-               }
-       }
-return;
-}
-
-error_t remove_gts_entry(uint16_t DevAddressType)
-{
-       uint8_t r_lenght=0;
-       //int r_start_slot=7;
-       int i;
-       
-       atomic{
-               for (i=0; i < 7 ; i++)
-               {
-                       if( GTS_db[i].DevAddressType == DevAddressType )
-                       {
-                               
-                               r_lenght = GTS_db[i].length;
-                               //r_start_slot = i;
-                               //delete the values
-                               GTS_db[i].gts_id=0x00;
-                               GTS_db[i].starting_slot=0x00;
-                               GTS_db[i].length=0x00;
-                               GTS_db[i].direction=0x00;
-                               GTS_db[i].DevAddressType=0x0000;
-                               GTS_db[i].expiration=0x00;
-                               
-                               //////////////printfUART("GTS Entry removed dev:%i len:%i pos %i\n", DevAddressType,r_lenght,i);
-                               GTS_startslot = GTS_startslot + r_lenght;
-                               GTS_descriptor_count--;
-                               final_CAP_slot = final_CAP_slot + r_lenght;
-                       }
-                       
-                       if ( r_lenght > 0)
-                       {
-                               if ( GTS_db[i].gts_id != 0x00 && GTS_db[i].DevAddressType !=0x0000)
-                               {                               
-                                       GTS_db[i-r_lenght].gts_id = GTS_db[i].gts_id;
-                                       GTS_db[i-r_lenght].starting_slot = i-r_lenght;
-                                       GTS_db[i-r_lenght].length = GTS_db[i].length;
-                                       GTS_db[i-r_lenght].direction = GTS_db[i].direction;
-                                       GTS_db[i-r_lenght].DevAddressType = GTS_db[i].DevAddressType;
-                                       GTS_db[i-r_lenght].expiration = GTS_db[i].expiration;
-                                       
-                                       //delete the values
-                                       GTS_db[i].gts_id=0x00;
-                                       GTS_db[i].starting_slot=0x00;
-                                       GTS_db[i].length=0x00;
-                                       GTS_db[i].direction=0x00;
-                                       GTS_db[i].DevAddressType=0x0000;
-                                       GTS_db[i].expiration=0x00;
-                                       
-                                       //////////////printfUART("UPDATED\n","" );
-                               }
-                       }
-               }
-       }
-return SUCCESS;
-}
-
-error_t add_gts_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType)
-{
-       int i;
-       //////////////printfUART("ADDING gts_length: %i\n", gts_length); 
-       //////////////printfUART("dir: %i\n", direction); 
-       //////////////printfUART("addr: %i\n", DevAddressType);
-
-       //check aMinCAPLength
-       if ( (GTS_startslot - gts_length) < 5 )
-       {
-               //////////////printfUART("ADD FAIL%i\n", ""); 
-               
-       }
-       
-       //if it has more than 7 timeslots alocated
-       if ( (GTS_startslot -gts_length) < 9 )
-       {
-               return FAIL;
-       }
-       
-       //check if the address already exists in the GTS list
-       for (i=0 ; i < 7 ; i++)
-       {
-               if ( GTS_db[i].DevAddressType == DevAddressType && GTS_db[i].direction == direction && GTS_db[i].gts_id > 0)
-               {
-                       //////////////printfUART("ALREADY ADDED\n", ""); 
-                       return FAIL;
-               }
-               if ( GTS_null_db[i].DevAddressType == DevAddressType && GTS_null_db[i].gts_id > 0)
-               {
-                       //////////////printfUART("REJECTED\n", ""); 
-                       return FAIL;
-               }
-               
-               
-       }
-       
-atomic{        
-       
-       //////////////printfUART("GTS_startslot: %i\n", GTS_startslot); 
-       GTS_startslot = GTS_startslot - gts_length;
-
-       GTS_db[15-GTS_startslot].gts_id=GTS_id;
-       GTS_db[15-GTS_startslot].starting_slot=GTS_startslot;
-       GTS_db[15-GTS_startslot].length=gts_length;
-       GTS_db[15-GTS_startslot].direction=direction;
-       GTS_db[15-GTS_startslot].DevAddressType=DevAddressType;
-       GTS_db[15-GTS_startslot].expiration=0x00;
-
-       //////////////printfUART("GTS Entry added start:%i len:%i\n", GTS_startslot,gts_length); 
-       
-       GTS_id++;
-       GTS_descriptor_count++;
-       
-       final_CAP_slot = final_CAP_slot - gts_length;
-       
-       }
-       return SUCCESS;
-}
-
-
-//GTS null functions
-void init_GTS_null_db()
-{
-       //initialization of the GTS database
-       int i;
-       atomic{
-               for (i=0 ; i < 7 ; i++)
-               {
-                       GTS_null_db[i].gts_id=0x00;
-                       GTS_null_db[i].starting_slot=0x00;
-                       GTS_null_db[i].length=0x00;
-                       //GTS_null_db[i].direction=0x00;
-                       GTS_null_db[i].DevAddressType=0x0000;
-                       GTS_null_db[i].persistencetime=0x00;
-               }
-       }
-return;
-}
-
-
-error_t add_gts_null_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType)
-{
-       int i;
-               
-       //check if the address already exists in the GTS list
-       for (i=0 ; i < 7 ; i++)
-       {
-               if ( GTS_null_db[i].DevAddressType == DevAddressType && GTS_null_db[i].gts_id > 0)
-               {
-                       //////////////printfUART("ALREADY ADDED null\n", ""); 
-                       return FAIL;
-               }
-       }
-       
-       for (i=0 ; i < 7 ; i++)
-       {
-               if ( GTS_null_db[i].DevAddressType==0x0000 && GTS_null_db[i].gts_id == 0x00)
-               {
-                       GTS_null_db[i].gts_id=GTS_id;
-                       GTS_null_db[i].starting_slot=0x00;
-                       GTS_null_db[i].length=0x00;
-                       //GTS_null_db[i].direction=0x00;
-                       GTS_null_db[i].DevAddressType=DevAddressType;
-                       GTS_null_db[i].persistencetime=0x00;
-                       
-                       
-                       //////////////printfUART("GTS null Entry added addr:%x\n", DevAddressType); 
-                       
-                       GTS_id++;
-                       GTS_null_descriptor_count++;
-                       
-               return SUCCESS;
-               }
-       }
-
-       
-return FAIL;   
-}
-
-task void increment_gts_null()
-{
-       int i;
-       
-       //////////////printfUART("init inc\n",""); 
-atomic{
-       for (i=0 ; i < 7 ; i++)
-       {
-               if ( GTS_null_db[i].DevAddressType != 0x0000 && GTS_null_db[i].gts_id != 0x00)
-               {
-                       //////////////printfUART("increm %x\n", GTS_null_db[i].DevAddressType); 
-                       GTS_null_db[i].persistencetime++;
-               
-               }
-               
-               if ( GTS_null_db[i].persistencetime > (aGTSDescPersistenceTime -1)  )
-               {
-                       GTS_null_db[i].gts_id=0x00;
-                       GTS_null_db[i].starting_slot=0x00;
-                       GTS_null_db[i].length=0x00;
-                       //GTS_null_db[i].direction=0x00;
-                       GTS_null_db[i].DevAddressType=0x0000;
-                       GTS_null_db[i].persistencetime=0x00;
-                       
-                       //////////////printfUART("GTS null removed addr:%x\n", GTS_null_db[i].DevAddressType); 
-               
-                       atomic GTS_null_descriptor_count--;
-               }
-                       
-       }
-       
-       }
-//////////////printfUART("end inc\n",""); 
-return;
-}
-
-task void check_gts_expiration()
-{
-       int i;
-//////////////printfUART("init exp\n",""); 
-atomic{        
-       atomic gts_expiration=calculate_gts_expiration();
-       //////////////printfUART("gts_expiration:%i\n", gts_expiration); 
-       atomic gts_expiration=2;
-       //////////////printfUART("gts_expiration:%i\n", gts_expiration); 
-       
-       for (i=0 ; i < 7 ; i++)
-       {
-               
-               if ( GTS_db[i].DevAddressType != 0x0000 && GTS_db[i].gts_id != 0x00)
-               {
-                       if( GTS_db[i].expiration == (gts_expiration + 1) && GTS_db[i].direction ==0x00)
-                       {
-                               //////////////printfUART("GTS expired addr:%x\n", GTS_null_db[i].DevAddressType); 
-                               //remove gts, indicate on the gts null list
-                               atomic{
-                               
-                                       add_gts_null_entry(GTS_db[i].length,GTS_db[i].direction,GTS_db[i].DevAddressType);
-                                       
-                                       remove_gts_entry(GTS_db[i].DevAddressType);
-                               }
-                       }
-                       else
-                       {
-                               atomic GTS_db[i].expiration ++;
-                       }
-               }
-       }
-       
-       
-       }
-       //////////////printfUART("end exp\n",""); 
-return;
-}
-
-void init_available_gts_index()
-       {
-               int i=0;
-               atomic{
-                       available_gts_index_count = GTS_SEND_BUFFER_SIZE;
-                       for(i=0;i < GTS_SEND_BUFFER_SIZE;i++)
-                       {
-                               available_gts_index[i]=i;
-                       }
-               }
-               return;
-       }
-/*****************************GTS BUFFER******************************/
-void init_gts_slot_list()
-{
-       int i=0;
-       for(i=0;i<7;i++)
-       {
-               gts_slot_list[i].element_count = 0x00;
-               gts_slot_list[i].element_in = 0x00;
-               gts_slot_list[i].element_out = 0x00;
-       }
-}
-
-
-task void start_coordinator_gts_send()
-{
-atomic{
-
-       coordinator_gts_send_pending_data =0;
-       
-       if(gts_slot_list[15-number_time_slot].element_count > 0)
-       {
-               if (check_gts_send_conditions(gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length) == 1 )
-               {
-                       
-                       gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length = gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length -2;
-                       
-                       call PD_DATA.request(gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length,(uint8_t *)&gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]]);
-       
-                       available_gts_index_count++;
-                       available_gts_index[available_gts_index_count] = gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out];
-                       
-                       gts_slot_list[15-number_time_slot].element_count--;
-                       gts_slot_list[15-number_time_slot].element_out++;
-                       
-                       if (gts_slot_list[15-number_time_slot].element_out == GTS_SEND_BUFFER_SIZE)
-                               gts_slot_list[15-number_time_slot].element_out=0;
-
-                       if(gts_slot_list[15-number_time_slot].element_count > 0 )
-                       {
-                               coordinator_gts_send_pending_data =1;
-                               coordinator_gts_send_time_slot = number_time_slot;
-                       }
-               }
-       }
-}
-return;
-}
-
-task void start_gts_send()
-{
-
-       atomic{
-       gts_send_pending_data = 0;
-       
-       if(gts_send_buffer_count > 0)
-       {
-               if (check_gts_send_conditions(gts_send_buffer[gts_send_buffer_msg_out].length) == 1 )
-               {
-
-                       gts_send_buffer[gts_send_buffer_msg_out].length = gts_send_buffer[gts_send_buffer_msg_out].length -2;
-
-                       call PD_DATA.request(gts_send_buffer[gts_send_buffer_msg_out].length,(uint8_t *)&gts_send_buffer[gts_send_buffer_msg_out]);
-       
-                       gts_send_buffer_count --;
-                       gts_send_buffer_msg_out++;
-
-                       if (gts_send_buffer_msg_out == GTS_SEND_BUFFER_SIZE)
-                               gts_send_buffer_msg_out=0;
-
-                       //////////////printfUART("after send %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
-                       
-                       if (gts_send_buffer_count > 0)
-                               gts_send_pending_data = 1;      
-               }
-       }
-
-}
-return;
-}
-
-//////////////////////////////////////////////////////////////
-//////////Indirect transmission functions////////////////////
-/////////////////////////////////////////////////////////////
-
-void init_indirect_trans_buffer()
-{
-       int i;
-       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-       {
-               indirect_trans_queue[i].handler = 0x00;
-               indirect_trans_count=0;
-       }
-
-return;
-}
-
-
-error_t remove_indirect_trans(uint8_t handler)
-{
-
-       int i;
-       uint8_t removed_ok=0;
-       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-       {
-               if (indirect_trans_queue[i].handler == handler)
-               {
-                       indirect_trans_queue[i].handler = 0x00;
-                       removed_ok = 1;
-                       indirect_trans_count--;
-                       break;
-               }
-       }
-
-       if (removed_ok == 0) 
-       {
-               return MAC_INVALID_HANDLE;
-       }
-       else
-       {
-               return SUCCESS;
-       }
-}
-
-
-void increment_indirect_trans()
-{
-       int i;
-       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-       {
-               if (indirect_trans_queue[i].handler != 0x00)
-               {
-                       indirect_trans_queue[i].transaction_persistent_time++;
-                       if (indirect_trans_queue[i].transaction_persistent_time == mac_PIB.macTransactionPersistenceTime )
-                               remove_indirect_trans(indirect_trans_queue[i].handler);
-               }
-       }
-
-return;
-}
-
-void send_ind_trans_addr(uint32_t DeviceAddress[])
-{
-       
-       uint8_t destination_address=0;
-       
-       dest_short *dest_short_ptr =0;
-       dest_long *dest_long_ptr=0;
-       
-       int i=0;
-       MPDU *frame_ptr=0;
-       
-       ////printfUART("send_ind_trans_addr DeviceAddress0: %y DeviceAddress1: %y \n",DeviceAddress[0],DeviceAddress[1]);
-
-    //list_indirect_trans_buffer();
-
-               for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-               {
-                       if (indirect_trans_queue[i].handler > 0x00)
-                       {
-                               frame_ptr = (MPDU *)indirect_trans_queue[i].frame;
-                               destination_address=get_fc2_dest_addr(frame_ptr->frame_control2);
-                               
-                               switch(destination_address)
-                               {
-                                       case LONG_ADDRESS: dest_long_ptr = (dest_long *) frame_ptr->data;
-                                                                               break;
-                                       case SHORT_ADDRESS: dest_short_ptr = (dest_short *) frame_ptr->data;                                                            
-                                                                               break;
-                               }
-                               
-                               //check the full address
-                               
-                               if ( (dest_long_ptr->destination_address0 == DeviceAddress[1] && dest_long_ptr->destination_address1 == DeviceAddress[0]) || ( dest_short_ptr->destination_address == (uint16_t)DeviceAddress[0] ))
-                               {
-                                       
-                                       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                                               send_buffer_msg_in=0;
-                                               
-                                       memcpy(&send_buffer[send_buffer_msg_in],(MPDU *) &indirect_trans_queue[i].frame,sizeof(MPDU));
-                                       
-                                       //enable retransmissions
-                                       send_buffer[send_buffer_msg_in].retransmission =0;
-                                       send_buffer[send_buffer_msg_in].indirect = i + 1;
-                                       
-                                       //check upon reception
-                                       indirect_trans_queue[i].handler=0x00;
-                                       //verify temporary error on the association request
-                                       
-                                       indirect_trans_count--;
-                                       if(indirect_trans_count > INDIRECT_BUFFER_SIZE )
-                                       {
-                                               indirect_trans_count=0;
-                                       }
-                                       
-                                       atomic send_buffer_count++;
-                                       atomic send_buffer_msg_in++;
-                       
-                                       post send_frame_csma();
-                                       
-                                       ////printfUART("i send\n","");
-                                       
-                                       return;
-                               }
-                       }
-               }
-               ////printfUART("i not found","");
-
-       
-return;
-} 
-
-/***************************DEBUG FUNCTIONS******************************/
-/* This function are list functions with the purpose of debug, to use then uncomment the declatarion
-on top of this file*/
-/*
-
-void list_mac_pib()
-{
-////////////printfUART("mac_PIB.macAckWaitDuration: %x\n",mac_PIB.macAckWaitDuration);
-////////////printfUART("mac_PIB.macAssociationPermit: %i\n",mac_PIB.macAssociationPermit);
-////////////printfUART("mac_PIB.macAutoRequest: %i\n",mac_PIB.macAutoRequest);
-////////////printfUART("mac_PIB.macBattLifeExt %i\n",mac_PIB.macBattLifeExt);
-////////////printfUART("mac_PIB.macBattLifeExtPeriods %i\n",mac_PIB.macBattLifeExtPeriods);
-//beacon payload
-////////////printfUART("mac_PIB.macBeaconPayloadLenght %i\n",mac_PIB.macBeaconPayloadLenght);
-////////////printfUART("mac_PIB.macBeaconOrder %i\n",mac_PIB.macBeaconOrder);
-////////////printfUART("mac_PIB.macBeaconTxTime %i\n",mac_PIB.macBeaconTxTime);
-////////////printfUART("mac_PIB.macBSN %i\n",mac_PIB.macBSN);
-////////////printfUART("mac_PIB.macCoordExtendedAddress0 %y\n",mac_PIB.macCoordExtendedAddress0);
-////////////printfUART("mac_PIB.macCoordExtendedAddress1 %y\n",mac_PIB.macCoordExtendedAddress1);
-////////////printfUART("mac_PIB.macCoordShortAddress: %x\n",mac_PIB.macCoordShortAddress);
-////////////printfUART("mac_PIB.macDSN: %x\n",mac_PIB.macDSN);
-////////////printfUART("mac_PIB.macGTSPermit: %x\n",mac_PIB.macGTSPermit);
-////////////printfUART("mac_PIB.macMaxCSMABackoffs: %x\n",mac_PIB.macMaxCSMABackoffs);
-////////////printfUART("mac_PIB.macMinBE: %x\n",mac_PIB.macMinBE);
-////////////printfUART("mac_PIB.macPANId: %x\n",mac_PIB.macPANId);
-////////////printfUART("mac_PIB.macPromiscuousMode: %x\n",mac_PIB.macPromiscuousMode);
-////////////printfUART("mac_PIB.macRxOnWhenIdle: %x\n",mac_PIB.macRxOnWhenIdle);
-////////////printfUART("mac_PIB.macShortAddress: %y\n",mac_PIB.macShortAddress);
-////////////printfUART("mac_PIB.macSuperframeOrder: %x\n",mac_PIB.macSuperframeOrder);
-////////////printfUART("mac_PIB.macTransactionPersistenceTime: %y\n",mac_PIB.macTransactionPersistenceTime);
-
-return;
-}
-
-void list_gts()
-{
-       int i;
-       ////////////printfUART("GTS list%i\n", GTS_descriptor_count); 
-       
-       for (i=0; i< 7;i++)
-       {
-               ////////////printfUART("GTSID: %i",GTS_db[i].gts_id);   
-               ////////////printfUART("start slot: %i",GTS_db[i].starting_slot);
-               ////////////printfUART("lenght: %i",GTS_db[i].length);  
-               ////////////printfUART("dir: %i",GTS_db[i].direction);  
-               ////////////printfUART("DevAddressType: %i",GTS_db[i].DevAddressType);
-               ////////////printfUART("expiration: %i \n",GTS_db[i].expiration);
-       }
-       
-}
-
-void list_my_gts()
-{
-atomic{
-               ////////////printfUART("SEND GTS s_GTSss: %i s_GTS_length: %i\n",s_GTSss,s_GTS_length);         
-               
-               ////////////printfUART("RECEIVE GTS r_GTSss: %i r_GTS_length: %i\n",r_GTSss,r_GTS_length); 
-}
-}
-*/
-
-void list_indirect_trans_buffer()
-{
-       int i;
-       //printfUART("indirect_trans_count %i\n", indirect_trans_count); 
-       
-       for (i=0; i< INDIRECT_BUFFER_SIZE;i++)
-       {
-               //printfUART("hand: %i \n",indirect_trans_queue[i].handler); 
-               
-               ////printfUART("start slot: %i",GTS_db[i].starting_slot);
-
-       }
-       
-}
-/*
-void list_gts_null()
-{
-       int i;
-       ////////////printfUART("GTS null list%i\n", GTS_null_descriptor_count); 
-       
-       for (i=0; i< GTS_null_descriptor_count;i++)
-       {
-               //////////////printfUART("GTSID: %i",GTS_null_db[i].gts_id);    
-               ////////////printfUART("start slot: %i",GTS_null_db[i].starting_slot);
-               ////////////printfUART("lenght: %i",GTS_null_db[i].length);     
-               //////////////printfUART("dir: %i",GTS_null_db[i].direction);   
-               ////////////printfUART("DevAddressType: %i \n",GTS_null_db[i].DevAddressType); 
-               ////////////printfUART("persistencetime: %i \n",GTS_null_db[i].persistencetime); 
-       }
-       
-}
-
-*/
-
-
-}
-
diff --git a/tos/lib/net/zigbee/ieee802154/mac/MacP.nc b/tos/lib/net/zigbee/ieee802154/mac/MacP.nc
new file mode 100644 (file)
index 0000000..ab2ca9b
--- /dev/null
@@ -0,0 +1,5379 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+
+#include <Timer.h>
+
+#include "printfUART.h"
+
+#include "frame_format.h"
+#include "phy_const.h"
+
+#include "mac_const.h"
+#include "mac_enumerations.h"
+
+#include "mac_func.h"
+
+module MacP {
+       provides interface Init;
+       
+       provides interface MLME_START;
+       provides interface MLME_SET;
+    provides interface MLME_GET;
+       
+       provides interface MLME_ASSOCIATE;
+       provides interface MLME_DISASSOCIATE;
+       
+       provides interface MLME_BEACON_NOTIFY;
+       provides interface MLME_GTS;
+       
+       provides interface MLME_ORPHAN;
+       
+       provides interface MLME_SYNC;
+       provides interface MLME_SYNC_LOSS;
+               
+       provides interface MLME_RESET;
+       
+       provides interface MLME_SCAN;
+       
+       //MCPS
+       provides interface MCPS_DATA;
+       provides interface MCPS_PURGE;
+               
+       
+       uses interface Timer<TMilli> as T_ackwait;      
+               
+       uses interface Timer<TMilli> as T_ResponseWaitTime;
+       
+       uses interface Timer<TMilli> as T_ScanDuration;
+       
+       uses interface Leds;
+       
+       uses interface SplitControl as AMControl;
+       
+       uses interface Random;
+       
+       uses interface GeneralIO as CCA;
+       
+       //uses interface Test_send;
+       
+       uses interface TimerAsync;
+       
+       uses interface PD_DATA;
+       
+       uses interface PLME_ED;
+       uses interface PLME_CCA;
+       uses interface PLME_SET;
+       uses interface PLME_GET;
+       uses interface PLME_SET_TRX_STATE;
+
+
+       uses interface AddressFilter;
+
+  
+}
+implementation {
+/*****************************************************/
+/*                             GENERAL                                  */
+/*****************************************************/  
+       /***************Variables*************************/
+       //local extended address
+       uint32_t aExtendedAddress0;
+       uint32_t aExtendedAddress1;
+
+       macPIB mac_PIB;
+
+//If the the MLME receives a start request the node becomes a pan coordinator
+       //and start transmiting beacons 
+       bool PANCoordinator = 0;
+       //(0 NO beacon transmission; 1 beacon transmission);
+       bool Beacon_enabled_PAN = 0;
+       
+       //(RESET) when the reset command arrives it checks whether or not to reset the PIB
+       bool SetDefaultPIB=0;
+       
+       //use security
+       bool SecurityEnable=0;
+       
+       //others
+       bool pending_reset=0;
+       
+       //transceiver status -every time the transceiver changes state this variable is updated
+       uint8_t trx_status;
+       
+       //defines the transmission
+       bool beacon_enabled=0;
+       
+       /***************Functions Definition***************/
+       
+       void init_MacPIB(); 
+       
+       uint8_t min(uint8_t val1, uint8_t val2);
+       
+       void init_MacCon();
+       
+       
+       task void signal_loss();
+       
+
+       void create_data_request_cmd();
+       void create_beacon_request_cmd();
+       void create_gts_request_cmd(uint8_t gts_characteristics);
+       
+       void build_ack(uint8_t sequence,uint8_t frame_pending);
+       
+       void create_data_frame(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions,uint8_t on_gts_slot,uint8_t pan);
+
+
+
+
+/*****************************************************/        
+/*                             Association                                      */
+/*****************************************************/ 
+       /***************Variables*************************/
+       uint8_t associating = 0;
+       uint8_t association_cmd_seq_num =0;
+       
+       /*association parameters*/
+       
+       uint8_t a_LogicalChannel;
+       uint8_t a_CoordAddrMode;
+       uint16_t a_CoordPANId;
+       uint32_t a_CoordAddress[2];
+       uint8_t a_CapabilityInformation;
+       bool a_securityenable;
+       
+       /***************Functions Definition***************/            
+       
+       void create_association_request_cmd(uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation);
+
+       error_t create_association_response_cmd(uint32_t DeviceAddress[],uint16_t shortaddress, uint8_t status);
+       
+       void create_disassociation_notification_cmd(uint32_t DeviceAddress[],uint8_t disassociation_reason);
+       
+       void process_dissassociation_notification(MPDU *pdu);
+
+/*****************************************************/
+/*                             Synchronization                                  */
+/*****************************************************/ 
+       /***************Variables*************************/
+       //(SYNC)the device will try to track the beacon ie enable its receiver just before the espected time of each beacon
+       bool TrackBeacon=0;
+       bool beacon_processed=0;
+       //beacon loss indication
+       uint8_t beacon_loss_reason;
+       
+       //(SYNC)the device will try to locate one beacon
+       bool findabeacon=0;
+       //(SYNC)number of beacons lost before sending a Beacon-Lost indication comparing to aMaxLostBeacons
+       uint8_t missed_beacons=0;
+       //boolean variable stating if the device is synchonized with the beacon or not
+       uint8_t on_sync=0;
+       
+       uint32_t parent_offset=0x00000000;
+
+
+/*****************************************************/
+/*                             GTS Variables                                    */
+/*****************************************************/  
+       /***************Variables*************************/
+       
+       uint8_t gts_request=0;
+       uint8_t gts_request_seq_num=0;
+       
+       bool gts_confirm;
+       
+       uint8_t GTS_specification;
+       bool GTSCapability=1;
+       
+       uint8_t final_CAP_slot=15;
+       
+       //GTS descriptor variables, coordinator usage only
+       GTSinfoEntryType GTS_db[7];
+       uint8_t GTS_descriptor_count=0;
+       uint8_t GTS_startslot=16;
+       uint8_t GTS_id=0x01;
+
+
+       //null gts descriptors
+       GTSinfoEntryType_null GTS_null_db[7];
+       
+       uint8_t GTS_null_descriptor_count=0;
+       //uint8_t GTS_null_id=0x01;
+       
+       //node GTS variables
+       // 1 GTS for transmit
+       uint8_t s_GTSss=0;           //send gts start slot
+       uint8_t s_GTS_length=0;          //send gts length
+       //1 GTS for receive
+       uint8_t r_GTSss=0;                       //receive gts start slot
+       uint8_t r_GTS_length=0;          //receive gts lenght
+       
+       //used to state that the device is on its transmit slot
+       uint8_t on_s_GTS=0;
+       //used to state that the device is on its receive slot
+       uint8_t on_r_GTS=0;
+       
+       //used to determine if the next time slot is used for transmission
+       uint8_t next_on_s_GTS=0;
+       //used to determine if the next time slot is used for reception
+       uint8_t next_on_r_GTS=0;
+       
+       //variable stating if the coordinator allow GTS allocations
+       uint8_t allow_gts=1;
+       
+       //COORDINATOR GTS BUFFER        
+       gts_slot_element gts_slot_list[7];
+       uint8_t available_gts_index[GTS_SEND_BUFFER_SIZE];
+       uint8_t available_gts_index_count;
+       
+       uint8_t coordinator_gts_send_pending_data=0;
+       uint8_t coordinator_gts_send_time_slot=0;
+       
+       //gts buffer used to store the gts messages both in COORDINATOR and NON COORDINATOR
+       norace MPDU gts_send_buffer[GTS_SEND_BUFFER_SIZE];
+       
+       //NON PAN COORDINATOR BUFFER
+       //buffering for sending
+       uint8_t gts_send_buffer_count=0;
+       uint8_t gts_send_buffer_msg_in=0;
+       uint8_t gts_send_buffer_msg_out=0;
+       uint8_t gts_send_pending_data=0;
+       
+
+       /***************Functions Definition***************/
+       
+       void process_gts_request(MPDU *pdu);    
+       void init_available_gts_index();
+       task void start_coordinator_gts_send();
+       
+       
+       //GTS FUNCTIONS
+       error_t remove_gts_entry(uint16_t DevAddressType);
+       error_t add_gts_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType);
+       error_t add_gts_null_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType);
+       
+       //increment the idle GTS for GTS deallocation purposes, not fully implemented yet
+       task void increment_gts_null();
+       
+       task void start_gts_send();
+       
+       
+       
+       //initialization functions
+       void init_gts_slot_list();
+       void init_GTS_null_db();
+       
+       void init_GTS_db();
+
+
+       uint32_t calculate_gts_expiration();
+       task void check_gts_expiration();
+
+
+/*****************************************************/
+/*                             CHANNEL SCAN Variables                           */
+/*****************************************************/ 
+       //current_channel
+       uint8_t current_channel=0;
+
+       /***************Variables*************************/
+       //ED-SCAN variables
+       
+       bool scanning_channels;
+       
+       uint32_t channels_to_scan;
+       uint8_t current_scanning=0;
+       //uint8_t scan_count=0;
+       uint8_t scanned_values[16];
+       uint8_t scan_type;
+       
+       SCAN_PANDescriptor scan_pans[16];
+       
+       uint16_t scan_duration;
+       
+       task void data_channel_scan_indication();
+       
+/*****************************************************/
+/*                             TIMER VARIABLES                                  */
+/*****************************************************/  
+       /***************Variables*************************/
+       uint32_t response_wait_time;
+       
+       //Beacon Interval
+       uint32_t BI;
+       //Superframe duration
+       uint32_t SD;
+       
+       //timer variables
+       uint32_t time_slot; //backoff boundary timer
+       uint32_t backoff;  //backoff timer
+       
+       //current number of backoffs in the active period
+       uint8_t number_backoff=1;
+       uint8_t number_time_slot=0;
+       
+       bool csma_slotted=0;
+/*****************************************************/
+/*                             CSMA VARIABLES                                   */
+/*****************************************************/        
+       /***************Variables*************************/     
+
+       //DEFERENCE CHANGE
+       uint8_t cca_deference = 0;
+       uint8_t backoff_deference = 0;
+       uint8_t check_csma_ca_backoff_send_conditions(uint32_t delay_backoffs);
+
+       //STEP 2
+       uint8_t delay_backoff_period;
+       bool csma_delay=0;
+       
+       bool csma_locate_backoff_boundary=0;
+       
+       bool csma_cca_backoff_boundary=0;
+       
+       //Although the receiver of the device is enabled during the channel assessment portion of this algorithm, the
+       //device shall discard any frames received during this time.
+       bool performing_csma_ca=0;
+       
+       //CSMA-CA variables
+       uint8_t BE; //backoff exponent
+       uint8_t CW; //contention window (number of backoffs to clear the channel)
+       uint8_t NB; //number of backoffs
+
+       /***************Functions Definition***************/    
+       
+       void init_csma_ca(bool slotted);
+       void perform_csma_ca();
+       task void perform_csma_ca_unslotted();
+       task void perform_csma_ca_slotted();
+       //task void start_csma_ca_slotted();
+       
+/*****************************************************/
+/*                             Indirect Transmission buffers            */
+/*****************************************************/
+       /***************Variables*************************/     
+       //indirect transmission buffer
+       norace indirect_transmission_element indirect_trans_queue[INDIRECT_BUFFER_SIZE];
+       //indirect transmission message counter
+       uint8_t indirect_trans_count=0;
+
+       /***************Functions Definition***************/    
+       
+       //function used to initialize the indirect transmission buffer
+       void init_indirect_trans_buffer();
+       //function used to search and send an existing indirect transmission message
+       void send_ind_trans_addr(uint32_t DeviceAddress[]);
+       //function used to remove an existing indirect transmission message
+       error_t remove_indirect_trans(uint8_t handler);
+       //function used to increment the transaction persistent time on each message
+       //if the transaction time expires the messages are discarded
+       void increment_indirect_trans();
+       
+/*****************************************************/
+/*                             RECEIVE buffers                           */
+/*****************************************************/  
+       /***************Variables*************************/
+       
+       //buffering variables
+       norace MPDU buffer_msg[RECEIVE_BUFFER_SIZE];
+       int current_msg_in=0;
+       int current_msg_out=0;
+       int buffer_count=0;
+
+       /***************Functions Definition***************/    
+       
+       task void data_indication();
+       
+       void indication_cmd(MPDU *pdu, int8_t ppduLinkQuality);
+       void indication_ack(MPDU *pdu, int8_t ppduLinkQuality);
+       void indication_data(MPDU *pdu, int8_t ppduLinkQuality);
+/*****************************************************/
+/*                             RECEPTION AND TRANSMISSION                                */
+/*****************************************************/  
+       
+       /***************Variables*************************/
+       
+       //buffering for sending
+       norace MPDUBuffer send_buffer[SEND_BUFFER_SIZE];
+       uint8_t send_buffer_count=0;
+       uint8_t send_buffer_msg_in=0;
+       uint8_t send_buffer_msg_out=0;
+       
+       //retransmission information
+       uint8_t send_ack_check;//ack requested in the transmitted frame
+       uint8_t retransmit_count;//retransmission count
+       uint8_t ack_sequence_number_check;//transmission sequence number
+       uint8_t send_retransmission;
+       uint8_t send_indirect_transmission;
+
+       uint8_t pending_request_data=0;
+       
+       uint8_t ackwait_period;
+       
+       uint8_t link_quality;
+       
+       norace ACK mac_ack;
+       ACK *mac_ack_ptr;
+       
+       uint32_t gts_expiration;
+
+       uint8_t I_AM_IN_CAP=0;
+       uint8_t I_AM_IN_CFP=0;
+       uint8_t I_AM_IN_IP=0;
+       
+       /***************Functions Definition***************/    
+       
+       task void send_frame_csma();
+       
+       uint8_t check_csma_ca_send_conditions(uint8_t frame_length,uint8_t frame_control1);
+
+       uint8_t check_gts_send_conditions(uint8_t frame_length);
+       
+       uint8_t calculate_ifs(uint8_t pk_length);
+
+
+
+/*****************************************************/
+/*                             BEACON MANAGEMENT                             */
+/*****************************************************/ 
+       /***************Variables*************************/
+       norace MPDU mac_beacon_txmpdu;
+       MPDU *mac_beacon_txmpdu_ptr;
+       
+       uint8_t *send_beacon_frame_ptr;
+       uint8_t send_beacon_length;
+
+       /***************Functions Definition***************/    
+       /*function to create the beacon*/
+       task void create_beacon();
+       /*function to process the beacon information*/
+       void process_beacon(MPDU *packet,uint8_t ppduLinkQuality);
+       
+
+/*****************************************************/
+/*                             Fault tolerance functions            */
+/*****************************************************/ 
+       
+       void create_coordinator_realignment_cmd(uint32_t device_extended0, uint32_t device_extended1, uint16_t device_short_address);
+
+       void create_orphan_notification();
+       
+       
+
+       void process_coordinator_realignment(MPDU *pdu);
+
+/***************************DEBUG FUNCTIONS******************************/
+/* This function are list functions with the purpose of debug, to use then uncomment the declatarion
+on top of this file*/
+/*
+       void list_mac_pib();
+       
+       void list_gts();
+       
+       void list_my_gts();
+       void list_gts_null();
+       */
+       //list all the handles in the indirect transmission buffer, debug purposes
+       void list_indirect_trans_buffer();      
+                       
+/***************************END DEBUG FUNCTIONS******************************/
+
+
+/***************** Init Commands ****************/
+  command error_t Init.init() {
+  
+  call AMControl.start();
+
+
+       //initialization of the beacon structure
+       mac_beacon_txmpdu_ptr = &mac_beacon_txmpdu;
+
+
+
+   atomic{
+       //inicialize the mac PIB
+       init_MacPIB();
+       
+       init_GTS_db();
+       
+       init_GTS_null_db();
+       
+       init_gts_slot_list();
+       
+       init_available_gts_index();
+       
+       aExtendedAddress0=TOS_NODE_ID;
+       aExtendedAddress1=TOS_NODE_ID;
+       
+       
+       call AddressFilter.set_address(mac_PIB.macShortAddress, aExtendedAddress0, aExtendedAddress1);
+
+       call AddressFilter.set_coord_address(mac_PIB.macCoordShortAddress, mac_PIB.macPANId);
+       
+       
+       
+       
+       init_indirect_trans_buffer();
+
+
+       }
+       
+       //beacon
+       mac_beacon_txmpdu_ptr = &mac_beacon_txmpdu;
+               
+       //ack
+       mac_ack_ptr = &mac_ack;
+       
+       //Other timers, sync timers units expressed in miliseconds
+       ackwait_period = ((mac_PIB.macAckWaitDuration * 4.0 ) / 250.0) * 3;
+
+       response_wait_time = ((aResponseWaitTime * 4.0) / 250.0) * 2;
+
+       atomic{
+       
+               
+               BI = aBaseSuperframeDuration * powf(2,mac_PIB.macBeaconOrder);
+               SD = aBaseSuperframeDuration * powf(2,mac_PIB.macSuperframeOrder);
+               
+               
+               //backoff_period
+               backoff = aUnitBackoffPeriod;
+               //backoff_period_boundary
+               
+               time_slot = SD / NUMBER_TIME_SLOTS;
+                       
+               call TimerAsync.set_enable_backoffs(1); 
+               call TimerAsync.set_backoff_symbols(backoff);
+               
+               call TimerAsync.set_bi_sd(BI,SD);
+               
+               call TimerAsync.start();
+       }
+
+
+printfUART_init();
+
+    return SUCCESS;
+  }
+
+  event void AMControl.startDone(error_t err) {
+    if (err == SUCCESS) {
+       
+       call TimerAsync.start();
+               
+       }
+    else {
+      call AMControl.start();
+    }
+  }
+
+  event void AMControl.stopDone(error_t err) {
+  }
+
+
+/*****************************************************/
+/*                             TIMERS FIRED                                             */
+/*****************************************************/ 
+
+async event error_t TimerAsync.before_bi_fired()
+{
+       ////printfUART("bbi %i\n",call TimerAsync.get_current_ticks());
+               
+       if (mac_PIB.macBeaconOrder != mac_PIB.macSuperframeOrder )
+       {
+               if ( Beacon_enabled_PAN == 1 )
+               {
+                       //
+                       //post set_trx();
+                       trx_status = PHY_TX_ON;
+                       call PLME_SET_TRX_STATE.request(PHY_TX_ON);
+               }
+               else
+               {
+                       //
+                       //post set_trx();
+                       trx_status = PHY_RX_ON;
+                       call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+               }
+       }
+       
+       //I_AM_IN_CAP = 1;
+       findabeacon = 1;
+               
+       return SUCCESS;
+}
+
+/*******************Timer BEACON INTERVAL******************/
+async event error_t TimerAsync.bi_fired()
+{
+       call Leds.led2On();
+       //call Test_send.send();
+       
+       I_AM_IN_CAP = 1;
+       I_AM_IN_IP = 0;
+       
+       ////printfUART("bi\n","");
+       
+       
+       if ( Beacon_enabled_PAN == 1 )
+       {
+               //the beacon is send directly without CSMA/CA
+               call PD_DATA.request(send_beacon_length,send_beacon_frame_ptr);
+       }
+
+       number_backoff =0;
+       number_time_slot=0;
+       
+       
+       //CHECK there is the need to wait a small amount of time before checking if the beacon as been processed or not
+       //possible solition, if it receives a packet stand by for confirmation it its a beacon
+       //The device must always receive the beacon
+       if (TrackBeacon == 1) 
+       {
+               if (beacon_processed==1) 
+               {
+                       beacon_processed=0;
+               }
+               else
+               {
+                       //dealocate all GTS
+                       //beacon loss
+
+                       on_sync =0;
+                       beacon_loss_reason = MAC_BEACON_LOSS;
+                       
+                       //TODO
+                       //post signal_loss();
+               }
+       }
+       
+       post send_frame_csma();
+
+       return SUCCESS;
+}
+
+/*******************Timer SUPERFRAME DURATION******************/
+async event error_t TimerAsync.sd_fired()
+{
+       call Leds.led2Off();
+
+       ////printfUART("sd\n","");
+
+       I_AM_IN_CFP = 0;
+       I_AM_IN_IP = 1;
+       
+       
+       number_backoff=0;
+       number_time_slot=0;
+       
+       
+       if (PANCoordinator == 0 && TYPE_DEVICE == ROUTER)
+       {
+               trx_status = PHY_RX_ON;
+       
+               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+       }
+       else
+       {
+               trx_status = PHY_RX_ON;
+               
+               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+               
+       }
+       
+       if (mac_PIB.macShortAddress==0xffff && TYPE_DEVICE == END_DEVICE)
+       {
+               trx_status = PHY_RX_ON;
+               
+               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+       }
+       
+       //trx_status = PHY_RX_ON;
+       //post set_trx();
+       /*
+               //turn the transceiver off
+       if (mac_PIB.macBeaconOrder != mac_PIB.macSuperframeOrder )
+       {
+               if ( mac_PIB.macRxOnWhenIdle == 0 && findabeacon == 0) 
+               {
+                       trx_status = PHY_TRX_OFF;
+                       post set_trx();
+               }
+               else
+               {
+                       trx_status = PHY_RX_ON;
+                       post set_trx();
+               }
+       }
+       //if the node is trying to synchronize
+               if (on_sync == 0 || mac_PIB.macPromiscuousMode == 1)
+       {
+               atomic{
+                       trx_status = PHY_RX_ON;
+                       post set_trx();
+               }
+       }
+       */
+       if (PANCoordinator == 1)
+       {
+               //increment the gts_null descriptors
+               atomic{
+                       
+                               //if (GTS_null_descriptor_count > 0) post increment_gts_null();
+                       
+                               //if (GTS_descriptor_count >0 ) post check_gts_expiration();
+                       
+                               //if (indirect_trans_count > 0) increment_indirect_trans();
+                               
+                               //creation of the beacon
+                               post create_beacon();
+               }
+               //trx_status = PHY_TRX_OFF;
+               //post set_trx();
+       }
+       else
+       {
+       //temporariamente aqui //aten��o quando for para o cluster-tree ï¿½ preciso mudar para fora
+       //e necessario destinguir ZC de ZR (que tem que manter a sync com o respectivo pai)
+       if (on_sync == 0)
+       {
+               //sync not ok
+               
+               //findabeacon=1;
+               if (missed_beacons == aMaxLostBeacons)
+               {
+               
+                       //printfUART("sync_loss %i\n",missed_beacons);
+                       //out of sync
+                       post signal_loss();
+               }
+               ////printfUART("out_sync %i\n",missed_beacons);
+               missed_beacons++;
+               call Leds.led1Off();
+               
+       }
+       else
+       {
+               //sync ok
+               missed_beacons=0;
+       
+               on_sync=0;
+       }
+       
+       }
+
+       //trx_status = PHY_TRX_OFF;
+       //call PLME_SET_TRX_STATE.request(PHY_TRX_OFF);
+
+       return SUCCESS;
+}
+
+/*******************Timer BEFORE TIME SLOT FIRED******************/
+async event error_t TimerAsync.before_time_slot_fired()
+{
+       on_s_GTS=0;
+       on_r_GTS=0;
+       
+       if (next_on_s_GTS == 1)
+       {       
+               on_s_GTS=1;
+               next_on_s_GTS =0;
+               trx_status = PHY_TX_ON;
+               call PLME_SET_TRX_STATE.request(PHY_TX_ON);
+               //post set_trx();
+       }
+       
+       if(next_on_r_GTS == 1)
+       {
+               on_r_GTS=1;
+               next_on_r_GTS=0;
+               trx_status = PHY_RX_ON;
+               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+               //post set_trx();
+       }
+
+return SUCCESS;
+}
+/*******************Timer TIME SLOT FIRED******************/
+async event error_t TimerAsync.time_slot_fired()
+{
+       //reset the backoff counter and increment the slot boundary
+       number_backoff=0;
+       number_time_slot++;
+               
+       //verify is there is data to send in the GTS, and try to send it
+       if(PANCoordinator == 1 && GTS_db[15-number_time_slot].direction == 1 && GTS_db[15-number_time_slot].gts_id != 0)
+       {
+               //COORDINATOR SEND DATA
+               ////////////printfUART("bbck%i:%i:%i\n", (15-number_time_slot),GTS_db[15-number_time_slot].direction,gts_slot_list[15-number_time_slot].element_count);
+               
+               post start_coordinator_gts_send();
+                               
+       }
+       else
+       {
+               //DEVICE SEND DATA
+               if (number_time_slot == s_GTSss && gts_send_buffer_count > 0 && on_sync == 1)//(send_s_GTSss-send_s_GTS_len) 
+               {
+                               //current_time = call TimerAsync.get_total_tick_counter();
+                               post start_gts_send();
+               }               
+       }
+       
+       next_on_r_GTS =0;
+       next_on_s_GTS=0;
+       
+       
+       ////printfUART("ts%i %i %i\n", number_time_slot,s_GTSss,r_GTSss);
+       
+       
+       //verification if the time slot is entering the CAP
+       //GTS FIELDS PROCESSING
+       
+       if ((number_time_slot + 1) >= final_CAP_slot && (number_time_slot + 1) < 16)
+       {
+               I_AM_IN_CAP = 0;
+               I_AM_IN_CFP = 1;
+               
+               ////printfUART("bts %i\n",I_AM_IN_CAP, number_time_slot); 
+       
+       atomic{
+               
+               //verification of the next time slot
+               if(PANCoordinator == 1 && number_time_slot < 15)
+               {
+               //COORDINATOR verification of the next time slot
+                       if(GTS_db[14-number_time_slot].gts_id != 0x00 && GTS_db[14-number_time_slot].DevAddressType != 0x0000)
+                       {       
+                               if(GTS_db[14-number_time_slot].direction == 1 ) // device wants to receive
+                               {
+                                       next_on_s_GTS =1; //PAN coord mode
+                               }
+                               else
+                               {
+                                       next_on_r_GTS=1; //PAN coord mode
+                               }
+                       }       
+               }
+               else
+               {
+               //device verification of the next time slot
+                       if( (number_time_slot +1) == s_GTSss || (number_time_slot +1) == r_GTSss )
+                       {
+                               ////printfUART("s_GTSss: %i r_GTSss: %i\n", s_GTSss,r_GTSss);
+                               if((number_time_slot + 1) == s_GTSss)
+                               {       
+                                       ////printfUART("MY SEND SLOT \n", "");
+                                       next_on_s_GTS =1;
+                                       s_GTS_length --;
+                                       if (s_GTS_length != 0 )
+                                       {
+                                               s_GTSss++;
+                                       }
+                               }
+                               else                    
+                               {
+                                       //////////////printfUART("MY RECEIVE SLOT \n", "");
+                                       next_on_r_GTS =1;
+                                       r_GTS_length --;
+                                       if (r_GTS_length != 0 )
+                                       {
+                                               r_GTSss++;
+                                       }
+                               }                               
+                       }
+                       else
+                       {
+                               //idle
+                               next_on_s_GTS=0;
+                               next_on_r_GTS=0;
+                       }
+               }
+       }
+       }
+       
+return SUCCESS;
+}
+async event error_t TimerAsync.sfd_fired()
+{
+
+return SUCCESS;
+}
+
+/*******************Timer BACKOFF PERIOD******************/
+async event error_t TimerAsync.backoff_fired()
+{
+       //slotted CSMA/CA function
+       atomic{
+       
+               if( csma_locate_backoff_boundary == 1 )
+               {
+                       csma_locate_backoff_boundary=0;
+                       
+                       //post start_csma_ca_slotted();
+                       
+                       //DEFERENCE CHANGE
+                       if (backoff_deference == 0)
+                       {
+                               //normal situation
+                               delay_backoff_period = (call Random.rand16() & ((uint8_t)(powf(2,BE)) - 1));
+                               
+                               if (check_csma_ca_backoff_send_conditions((uint32_t) delay_backoff_period) == 1)
+                               {
+                                       backoff_deference = 1;
+                               }
+                               
+                       }
+                       else
+                       {
+                               backoff_deference = 0;
+                       }
+                       
+                       csma_delay=1;
+               }
+               if( csma_cca_backoff_boundary == 1 )
+                       post perform_csma_ca_slotted();
+       }
+       //CSMA/CA
+       atomic{
+               if(csma_delay == 1 )
+               {
+                       if (delay_backoff_period == 0)
+                       {
+                               if(csma_slotted == 0)
+                               {
+                                       post perform_csma_ca_unslotted();
+                               }
+                               else
+                               {
+                                       //CSMA/CA SLOTTED
+                                       csma_delay=0;
+                                       csma_cca_backoff_boundary=1;
+                               }
+                       }
+                       delay_backoff_period--;
+               }
+       }
+       number_backoff++;
+return SUCCESS;
+}
+
+/*******************T_ackwait**************************/
+  event void T_ackwait.fired() {
+  
+  //////////printfUART("Tfd \n", "");
+       
+       //call Leds.redToggle();
+
+       if (send_ack_check == 1)
+       {
+               retransmit_count++;
+               
+               if (retransmit_count == aMaxFrameRetries || send_indirect_transmission > 0)
+               {
+                               //check the type of data being send
+                               /*
+                               if (associating == 1)
+                               {
+                                       //printfUART("af ack\n", "");
+                                       associating=0;
+                                       signal MLME_ASSOCIATE.confirm(0x0000,MAC_NO_ACK);
+                               }
+                               */
+                               
+                       atomic{ 
+                               ////////////printfUART("TRANSMISSION FAIL\n",""); 
+                               //stardard procedure, if fail discard the packet
+                               atomic send_buffer_count --;
+                               send_buffer_msg_out++;
+                       
+                                       //failsafe
+                                       if(send_buffer_count > SEND_BUFFER_SIZE)
+                                       {
+                                               
+                                               atomic send_buffer_count =0;
+                                               send_buffer_msg_out=0;
+                                               send_buffer_msg_in=0;
+                                               
+                                       }
+                                       
+                                       
+                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                               send_buffer_msg_out=0;
+                                       
+                                       if (send_buffer_count > 0)
+                                               post send_frame_csma();
+                                               
+                                       send_ack_check=0;
+                                       retransmit_count=0;
+                                       ack_sequence_number_check=0;
+                               
+                               }
+               }
+               
+               ////////////printfUART("RETRY\n",""); 
+               //retransmissions
+               post send_frame_csma();
+       }
+    
+  }
+
+/*******************T_ResponseWaitTime**************************/
+  event void T_ResponseWaitTime.fired() {
+       //command response wait time
+       ////////////printfUART("T_ResponseWaitTime.fired\n", "");
+
+       if (associating == 1)
+       {
+               //printfUART("af rwt\n", "");
+               associating=0;
+               signal MLME_ASSOCIATE.confirm(0x0000,MAC_NO_DATA);
+               
+       }
+  
+  }
+
+/*****************************************************
+****************PD_DATA EVENTS***********************
+******************************************************/
+  async event error_t PD_DATA.confirm(uint8_t status) {
+
+
+    return SUCCESS;     
+  }
+/*****************************************************
+****************       PD_DATA     ********************
+******************************************************/ 
+
+async event error_t PD_DATA.indication(uint8_t psduLenght,uint8_t* psdu, int8_t ppduLinkQuality){
+               //if(I_AM_IN_CAP == 1 || I_AM_IN_CFP == 1 || mac_PIB.macShortAddress==0xffff || scanning_channels ==1 || findabeacon == 1)
+               //{
+                       if (buffer_count > RECEIVE_BUFFER_SIZE)
+                       {
+                               //call Leds.redToggle();
+                               //printfUART("full\n","");
+                       }
+                       else
+                       {
+               
+                               memcpy(&buffer_msg[current_msg_in],psdu,sizeof(MPDU));
+
+                               atomic{
+                                       current_msg_in++;
+                               
+                                       if ( current_msg_in == RECEIVE_BUFFER_SIZE ) 
+                                               current_msg_in = 0;
+               
+                                       buffer_count ++;
+                               }
+                               
+                               link_quality = ppduLinkQuality;
+                               
+                               if (scanning_channels ==1)
+                               {
+                                       //channel scan operation, accepts beacons only
+                                       post data_channel_scan_indication();
+                               
+                               }
+                               else
+                               {
+                               //normal operation
+                                       post data_indication();
+                               }
+                       }
+               //}
+               //else
+               //{
+               //      //printfUART("drop\n","");
+               //}
+
+return SUCCESS;
+}
+
+
+
+task void data_indication()
+{
+       //check all the conditions for a receiver packet
+    //pag 155
+       uint8_t link_qual;
+       
+       atomic link_qual = link_quality;
+
+       ////printfUART("data_indication\n","");
+       //////////printfUART("buf  %i %i\n",buffer_count,indirect_trans_count);
+
+       //Although the receiver of the device is enabled during the channel assessment portion of this algorithm, the
+       //device shall discard any frames received during this time.
+       //////////////printfUART("performing_csma_ca: %i\n",performing_csma_ca);
+       if (performing_csma_ca == 1)
+       {       
+               //////////////printfUART("REJ CSMA\n","");
+               atomic{ 
+                       buffer_count--;
+               
+                       current_msg_out++;
+               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
+                       current_msg_out = 0;
+                       }
+               
+               return;
+    }
+       
+       //while performing channel scan disable the packet reception
+       if ( scanning_channels == 1)
+       {       
+               atomic{ 
+                       buffer_count--;
+       
+                       current_msg_out++;
+               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
+                       current_msg_out = 0;
+                       }
+               return;
+       }       
+atomic{
+
+    //////printfUART("data ind %x %x %i\n",buffer_msg[current_msg_out].frame_control1,buffer_msg[current_msg_out].frame_control2,(buffer_msg[current_msg_out].frame_control2 & 0x7));
+       
+       //check the frame type of the received packet
+       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
+       {
+               
+                       case TYPE_DATA: ////printfUART("rd %i\n",buffer_msg[current_msg_out].seq_num);
+                                                       indication_data(&buffer_msg[current_msg_out],link_qual);
+                                                       break;
+                                                       
+                       case TYPE_ACK: ////printfUART("ra\n","");
+                                                       //ack_received = 1;
+                                                       indication_ack(&buffer_msg[current_msg_out],link_qual);
+                                                       
+                                                       break;
+                                                       
+                       case TYPE_CMD:  ////printfUART("rc\n","");
+                                                       indication_cmd(&buffer_msg[current_msg_out],link_qual);
+                                                       break;
+                       
+                       case TYPE_BEACON:
+                                                       
+                                                       ////printfUART("rb %i\n",buffer_msg[current_msg_out].seq_num);
+                                                       if (mac_PIB.macShortAddress == 0x0000) 
+                                                       {
+                                                               buffer_count--;
+                                                       }
+                                                       else
+                                                       {
+                                                               process_beacon(&buffer_msg[current_msg_out],link_qual);
+                                                               
+                                                       }
+
+                                                       break;
+                       default: 
+                                               atomic buffer_count--;
+                                               //////printfUART("Invalid frame type\n","");
+
+                                               break;
+       }
+       atomic{
+                       current_msg_out++;
+               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
+                       current_msg_out = 0;
+               }
+       }
+       return;
+}
+
+
+
+/*****************************************************
+****************PLME_ED EVENTS***********************
+******************************************************/ 
+event error_t PLME_CCA.confirm(uint8_t status){
+return SUCCESS;
+}
+   
+   
+event error_t PLME_SET.confirm(uint8_t status, uint8_t PIBAttribute){   
+return SUCCESS;
+}
+async event error_t PLME_SET_TRX_STATE.confirm(uint8_t status){
+
+return SUCCESS;
+}    
+   
+event error_t PLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue){
+   
+return SUCCESS;
+}    
+
+event error_t PLME_ED.confirm(uint8_t status,int8_t EnergyLevel){
+
+return SUCCESS;
+}
+
+/*******************************************************************************************************/
+/*******************************************************************************************************/
+/*******************************************************************************************************/
+/****************************************PACKET PROCESSING FUNCTIONS************************************/
+/*******************************************************************************************************/
+/*******************************************************************************************************/
+/*******************************************************************************************************/
+
+void process_beacon(MPDU *packet,uint8_t ppduLinkQuality)
+{
+
+       /*
+       ORGANIZE THE PROCESS BEACON FUNCION AS FOLLOWS.
+       1- GET THE BEACON ORDER
+       2- GET THE SUPERFRAME ORDER
+       3- GET THE FINAL CAP SLOT
+       4 - COMPUTE SD, BI, TS, BACKOFF PERIOD IN MILLISECONDS
+       
+       4- SYNCHRONIZE THE NODE BY DOING THE FOLLOWING
+               - SET A TIMER IN MS FOR THE FINAL TIME SLOT (SUPERFRAME DURATION) : IT EXPRIES AFTER SD - TX TIME - PROCESS TIME
+               - SET A TIMER IN MS FOR THE GTS IF ANY EXIST IT EXPRIES AFTER GTS_NBR * TIME_SLOT - TX TIME - PROCESS TIME 
+       */
+       uint32_t SO_EXPONENT;
+       uint32_t BO_EXPONENT;
+       int i=0;
+       uint16_t gts_descriptor_addr;
+       uint8_t data_count;
+       
+       uint8_t gts_directions;
+       uint8_t gts_des_count;
+       
+       uint8_t gts_ss;
+       uint8_t gts_l;
+       uint8_t dir;
+       uint8_t dir_mask;
+
+       //end gts variables
+
+       //function that processes the received beacon
+       beacon_addr_short *beacon_ptr;
+       
+       PANDescriptor pan_descriptor;
+
+       // beacon_trans_delay = (((packet->length(bytes) * 8.0) / 250.00(bits/s) ) / 0.34(s) (timer_granularity) ) (symbols)
+
+       //pending frames
+       uint8_t short_addr_pending=0;
+       uint8_t long_addr_pending=0;
+
+       //used in the synchronization
+       //uint32_t process_tick_counter; //symbols
+       
+       //uint32_t becon_trans_delay; //symbols
+       //uint32_t start_reset_ct; //number of clock ticks since the start of the beacon interval
+       
+       //used in the track beacon
+       beacon_processed = 1;
+       missed_beacons=0;
+       
+       //initializing pointer to data structure
+       beacon_ptr = (beacon_addr_short*) (packet->data);
+       
+       
+               //decrement buffer count
+       atomic buffer_count --;
+       
+       ////printfUART("Received Beacon\n","");
+       ////printfUART("rb panid: %x %x \n",beacon_ptr->source_address,mac_PIB.macCoordShortAddress);
+       ////////printfUART("My macPANID: %x\n",mac_PIB.macPANId);
+       
+       if( beacon_ptr->source_address != mac_PIB.macCoordShortAddress)
+       {
+               //
+               return;
+       }
+       ////printfUART("bea %i\n",call TimerAsync.get_current_ticks());
+       
+       /**********************************************************************************/
+       /*                                      PROCESSING THE SUPERFRAME STRUCTURE                                                       */
+       /**********************************************************************************/
+       
+       if (PANCoordinator == 0)
+       {
+               mac_PIB.macBeaconOrder = get_beacon_order(beacon_ptr->superframe_specification);
+               mac_PIB.macSuperframeOrder = get_superframe_order(beacon_ptr->superframe_specification);
+               
+               //mac_PIB.macCoordShortAddress = beacon_ptr->source_address;
+               
+               ////printfUART("BO,SO:%i %i\n",mac_PIB.macBeaconOrder,mac_PIB.macSuperframeOrder);
+               
+               //mac_PIB.macPANId = beacon_ptr->source_PAN_identifier;
+               
+               //beacon order check if it changed
+               if (mac_PIB.macSuperframeOrder == 0)
+               {
+                       SO_EXPONENT = 1;
+               }
+               else
+               {
+                       SO_EXPONENT = powf(2,mac_PIB.macSuperframeOrder);
+               }
+               
+               if ( mac_PIB.macBeaconOrder ==0)
+               {
+                       BO_EXPONENT =1;
+               }
+               else
+               {
+                               BO_EXPONENT = powf(2,mac_PIB.macBeaconOrder);
+               }
+               BI = aBaseSuperframeDuration * BO_EXPONENT; 
+               SD = aBaseSuperframeDuration * SO_EXPONENT; 
+               
+               //backoff_period
+               backoff = aUnitBackoffPeriod;
+               time_slot = SD / NUMBER_TIME_SLOTS;
+               
+               call TimerAsync.set_bi_sd(BI,SD);
+       }       
+               
+       /**********************************************************************************/
+       /*                                                      PROCESS GTS CHARACTERISTICS                                                       */
+       /**********************************************************************************/
+               allow_gts =1;
+       
+               //initializing the gts variables
+               s_GTSss=0;
+               s_GTS_length=0;
+               
+               r_GTSss=0;
+               r_GTS_length=0;
+               
+               /*
+               send_s_GTSss=0;  
+               send_r_GTSss=0; 
+               send_s_GTS_len=0;
+               send_r_GTS_len=0;
+               */
+               final_CAP_slot = 15;
+
+
+               gts_des_count = (packet->data[8] & 0x0f);
+               
+               data_count = 9;
+               
+               final_CAP_slot = 15 - gts_des_count;
+               
+               if (gts_des_count > 0 )
+               {
+               data_count = 10; //position of the current data count
+               //process descriptors
+               
+                       gts_directions = packet->data[9];
+                       
+                       ////printfUART("gts_directions:%x\n",gts_directions);
+                       
+                       for(i=0; i< gts_des_count; i++)
+                       {       
+                               gts_descriptor_addr = (uint16_t) packet->data[data_count];
+                                       
+                               ////printfUART("gts_des_addr:%x mac short:%x\n",gts_descriptor_addr,mac_PIB.macShortAddress);
+                               
+                               data_count = data_count+2;
+                               //check if it concerns me
+                               if (gts_descriptor_addr == mac_PIB.macShortAddress)
+                               {
+                                       //confirm the gts request
+                                       //////////////printfUART("packet->data[data_count]: %x\n",packet->data[data_count]);
+                                       //gts_ss = 15 - get_gts_descriptor_ss(packet->data[data_count]);
+                                       gts_ss = get_gts_descriptor_ss(packet->data[data_count]);
+                                       gts_l = get_gts_descriptor_len(packet->data[data_count]);
+
+                                       if ( i == 0 )
+                                       {
+                                               dir_mask=1;
+                                       }
+                                       else
+                                       {
+                                       
+                                                       dir_mask = powf(2,i);
+                                       }
+                                       //////////////printfUART("dir_mask: %x i: %x gts_directions: %x \n",dir_mask,i,gts_directions);
+                                       dir = ( gts_directions & dir_mask);
+                                       if (dir == 0)
+                                       {
+                                               s_GTSss=gts_ss;
+                                               s_GTS_length=gts_l;
+                                       }
+                                       else
+                                       {
+
+                                               r_GTSss=gts_ss;
+                                               r_GTS_length=gts_l;
+                                       }
+                                       
+                                       ////printfUART("PB gts_ss: %i gts_l: %i dir: %i \n",gts_ss,gts_l,dir);
+                                       //////////////printfUART("PB send_s_GTSss: %i send_s_GTS_len: %i\n",send_s_GTSss,send_s_GTS_len);
+                                       
+                                       if ( gts_l == 0 )
+                                       {
+                                               allow_gts=0;
+                                       }
+
+                                       if (gts_confirm == 1 && gts_l != 0)
+                                       {
+                                               //signal ok
+                                               ////printfUART("gts confirm \n","");
+                                               gts_confirm =0;
+                                               signal MLME_GTS.confirm(GTS_specification,MAC_SUCCESS);
+                                       }
+                                       else
+                                       {
+                                               //signal not ok
+                                               //////////////printfUART("gts not confirm \n","");
+                                               gts_confirm =0;
+                                               signal MLME_GTS.confirm(GTS_specification,MAC_DENIED);
+                                       }
+                                       
+                               }
+                               data_count++;   
+                       }
+               }
+       
+       /**********************************************************************************/
+       /*                                                      PROCESS PENDING ADDRESSES INFORMATION                             */
+       /**********************************************************************************/    
+               //this should pass to the network layer
+               
+               
+               short_addr_pending=get_number_short(packet->data[data_count]);
+               long_addr_pending=get_number_extended(packet->data[data_count]);
+               
+               ////////////printfUART("ADD COUNT %i %i\n",short_addr_pending,long_addr_pending);
+               
+               data_count++;
+               
+               if(short_addr_pending > 0)
+               {
+                       for(i=0;i < short_addr_pending;i++)
+                       {
+                               ////////////printfUART("PB %i %i\n",(uint16_t)packet->data[data_count],short_addr_pending);
+                               
+                               //if(packet->data[data_count] == (uint8_t)mac_PIB.macShortAddress && packet->data[data_count+1] == (uint8_t)(mac_PIB.macShortAddress >> 8) )
+                               if((uint16_t)packet->data[data_count] == mac_PIB.macShortAddress)
+                               {
+                                       
+                                       create_data_request_cmd();
+                               }
+                               data_count = data_count + 2;
+                       }
+               }
+               if(long_addr_pending > 0)
+               {
+                       for(i=0; i < long_addr_pending;i++)
+                       {
+                               if((uint32_t)packet->data[data_count] == aExtendedAddress0 && (uint32_t)packet->data[data_count + 4] == aExtendedAddress1)
+                               {
+                                       
+                                       data_count = data_count + 8;
+
+                               }
+                       
+                       }
+               }
+
+       /**********************************************************************************/
+       /*                              BUILD the PAN descriptor of the COORDINATOR                                               */
+       /**********************************************************************************/
+               
+               
+          //Beacon NOTIFICATION
+          //BUILD the PAN descriptor of the COORDINATOR
+               //assuming that the adress is short
+               pan_descriptor.CoordAddrMode = SHORT_ADDRESS;
+               pan_descriptor.CoordPANId = 0x0000;//beacon_ptr->source_PAN_identifier;
+               pan_descriptor.CoordAddress0=0x00000000;
+               pan_descriptor.CoordAddress1=mac_PIB.macCoordShortAddress;
+               pan_descriptor.LogicalChannel=current_channel;
+               //superframe specification field
+               pan_descriptor.SuperframeSpec = beacon_ptr->superframe_specification;
+               
+               pan_descriptor.GTSPermit=mac_PIB.macGTSPermit;
+               pan_descriptor.LinkQuality=0x00;
+               pan_descriptor.TimeStamp=0x000000;
+               pan_descriptor.SecurityUse=0;
+               pan_descriptor.ACLEntry=0x00;
+               pan_descriptor.SecurityFailure=0x00;
+          
+               //I_AM_IN_CAP = 1;
+          
+       /**********************************************************************************/
+       /*                                                              SYNCHRONIZING                                                                     */
+       /**********************************************************************************/
+
+       //processing time + beacon transmission delay
+       
+       //removed not used
+       //process_tick_counter = call TimerAsync.get_process_frame_tick_counter();
+       //removed not used      
+       //start_reset_ct = ((1000 * (packet->length * 8.0) / 250)) / 69.54;  //(process_tick_counter - receive_tick_counter);
+
+       if(PANCoordinator == 0)
+       {
+                       I_AM_IN_CAP = 1;
+                       I_AM_IN_IP = 0;
+                       
+                       //call Leds.yellowOn();
+                       call Leds.led2On();
+                       
+                       call Leds.led1On();
+                       
+                       if(findabeacon == 1)
+                       {
+                               ////printfUART("findabeacon\n", "");
+                               call TimerAsync.set_timers_enable(1);
+                               findabeacon =0;
+                       }
+                       
+                       //#ifdef PLATFORM_MICAZ
+                       //number_time_slot = call TimerAsync.reset_start(start_reset_ct+process_tick_counter+52);// //SOBI=3 52 //SOBI=0 15
+                       //#else
+                       
+                       //call TimerAsync.reset();
+                       
+                       number_time_slot = call TimerAsync.reset_start(75);   //95 old val sem print
+                                       
+                       // +process_tick_counter+52 //SOBI=3 52 //SOBI=0 
+                       //#endif
+                       on_sync=1;
+                       
+                       ////printfUART("sED\n", "");
+       }
+       signal MLME_BEACON_NOTIFY.indication((uint8_t)packet->seq_num,pan_descriptor,0, 0, mac_PIB.macBeaconPayloadLenght, packet->data);
+               
+return;
+}
+
+
+void process_gts_request(MPDU *pdu)
+{
+               error_t status;
+               cmd_gts_request *mac_gts_request;
+               
+               mac_gts_request= (cmd_gts_request*) &pdu->data;
+               
+atomic{                
+               if ( get_characteristic_type(mac_gts_request->gts_characteristics) == 1)
+               {
+               //allocation
+       
+       //process the gts request
+               status = add_gts_entry(get_gts_length(mac_gts_request->gts_characteristics),get_gts_direction(mac_gts_request->gts_characteristics),mac_gts_request->source_address);
+               
+               }
+               else
+               {
+               //dealocation
+       
+               status = remove_gts_entry(mac_gts_request->source_address);
+               }
+               
+               signal MLME_GTS.indication(mac_gts_request->source_address, mac_gts_request->gts_characteristics, 0, 0);
+               
+               }
+
+return;
+}
+/****************DATA indication functions******************/
+
+void indication_data(MPDU *pdu, int8_t ppduLinkQuality)
+{
+       uint8_t data_len;
+       
+       uint8_t payload[80];
+       uint8_t msdu_length=0;
+       
+       //int i;
+       
+       uint32_t SrcAddr[2];
+       uint32_t DstAddr[2];
+       
+       
+       //frame control variables
+       uint8_t source_address=0;
+       uint8_t destination_address=0;
+
+
+       dest_short *dest_short_ptr;
+       dest_long *dest_long_ptr;
+       
+       source_short *source_short_ptr;
+       source_long *source_long_ptr;
+
+       //implement the intra PAN data messages
+       //intra_pan_source_short *intra_pan_source_short_ptr;
+       //intra_pan_source_long *intra_pan_source_long_ptr;
+       
+       
+       source_address=get_fc2_source_addr(pdu->frame_control2);
+       destination_address=get_fc2_dest_addr(pdu->frame_control2);
+       
+       //decrement buffer count
+       atomic buffer_count --;
+       
+       SrcAddr[0]=0x00000000;
+       SrcAddr[1]=0x00000000;
+       DstAddr[0]=0x00000000;
+       DstAddr[1]=0x00000000;
+
+
+       ////printfUART("id %i %i \n",source_address,destination_address);
+
+
+       if ( get_fc1_intra_pan(pdu->frame_control1)== 0 )
+       {
+       //INTRA PAN
+               if (destination_address > 1 && source_address > 1)
+               {
+                       // Destination LONG - Source LONG       
+                       if (destination_address == LONG_ADDRESS && source_address == LONG_ADDRESS)
+                       {
+                               dest_long_ptr = (dest_long *) &pdu->data[0];
+                               source_long_ptr = (source_long *) &pdu->data[DEST_LONG_LEN];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
+                               {
+                                       ////////////printfUART("data rejected, ext destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               data_len = 20;
+                               
+                               
+                               DstAddr[1] = dest_long_ptr->destination_address0;
+                               DstAddr[0] =dest_long_ptr->destination_address1;
+                               
+                               SrcAddr[1] =source_long_ptr->source_address0;
+                               SrcAddr[0] =source_long_ptr->source_address1;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+                               
+                       }
+                       
+                       // Destination SHORT - Source LONG
+                       if ( destination_address == SHORT_ADDRESS && source_address == LONG_ADDRESS )
+                       {
+                               dest_short_ptr = (dest_short *) &pdu->data[0];
+                               source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
+                               {
+                                       ////////////printfUART("data rejected, short destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 14;
+                               
+                               DstAddr[0] =dest_short_ptr->destination_address;
+                               
+                               SrcAddr[1] =source_long_ptr->source_address0;
+                               SrcAddr[0] =source_long_ptr->source_address1;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+                       // Destination LONG - Source SHORT
+                       if ( destination_address == LONG_ADDRESS && source_address == SHORT_ADDRESS )
+                       {
+                               dest_long_ptr = (dest_long *) &pdu->data[0];
+                               source_short_ptr = (source_short *) &pdu->data[DEST_LONG_LEN];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
+                               {
+                                       ////////////printfUART("data rejected, ext destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 14;
+                               
+                               DstAddr[1] = dest_long_ptr->destination_address0;
+                               DstAddr[0] =dest_long_ptr->destination_address1;
+                               
+                               
+                               SrcAddr[0] =source_short_ptr->source_address;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+                       
+                       
+                       //Destination SHORT - Source SHORT
+                       if ( destination_address == SHORT_ADDRESS && source_address == SHORT_ADDRESS )  
+                       {
+                               dest_short_ptr = (dest_short *) &pdu->data[0];
+                               source_short_ptr = (source_short *) &pdu->data[DEST_SHORT_LEN];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
+                               {
+                                       ////printfUART("data rejected, short destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       ////printfUART("SH SH data rejected, wrong destination PAN %x\n",mac_PIB.macPANId ); 
+                                       return;
+                               }
+                               
+                               data_len = 8;
+                               
+                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                               {
+                                       build_ack(pdu->seq_num,0);
+                               }
+                               
+                               DstAddr[0] =dest_short_ptr->destination_address;
+                               
+                               SrcAddr[0] =source_short_ptr->source_address;
+                               
+                               msdu_length = (pdu->length - 5) - data_len;
+                               
+                               
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                       
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length,payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+               }
+               
+               /*********NO DESTINATION ADDRESS PRESENT ****************/
+               
+               if ( destination_address == 0 && source_address > 1 )
+               {
+                               
+                       if (source_address == LONG_ADDRESS)
+                       {//Source LONG
+                               source_long_ptr = (source_long *) &pdu->data[0];
+                               
+                               //If only source addressing fields are included in a data or MAC command frame, the frame shall be
+                               //accepted only if the device is a PAN coordinator and the source PAN identifier matches macPANId.
+                               if ( PANCoordinator==0 || source_long_ptr->source_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       ////////////printfUART("data rejected, im not pan\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 10;
+                               
+                               SrcAddr[1] =source_long_ptr->source_address0;
+                               SrcAddr[0] =source_long_ptr->source_address1;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address,(uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, 0x0000, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+                       else
+                       {//Source SHORT
+
+                               source_short_ptr = (source_short *) &pdu->data[0];
+                               //If only source addressing fields are included in a data or MAC command frame, the frame shall be
+                               //accepted only if the device is a PAN coordinator and the source PAN identifier matches macPANId.
+                               if ( PANCoordinator==0 || source_short_ptr->source_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       ////////////printfUART("data rejected, im not pan\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 4;
+
+                               
+                               SrcAddr[0] =source_short_ptr->source_address;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, 0x0000, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+               }
+               /*********NO SOURCE ADDRESS PRESENT ****************/
+               
+               if ( destination_address > 1 && source_address == 0 )
+               {
+                       if (destination_address == LONG_ADDRESS)
+                       {//Destination LONG
+                               dest_long_ptr = (dest_long *) &pdu->data[0];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
+                               {
+                                       ////////////printfUART("data rejected, ext destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 10;
+                               
+                               DstAddr[1] = dest_long_ptr->destination_address0;
+                               DstAddr[0] =dest_long_ptr->destination_address1;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                       
+                               signal MCPS_DATA.indication((uint16_t)source_address,0x0000, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+                       else
+                       {//Destination SHORT
+                               dest_short_ptr = (dest_short *) &pdu->data[0];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
+                               {
+                                       ////////////printfUART("data rejected, short destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       ////////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 4;
+                               
+                               DstAddr[0] =dest_short_ptr->destination_address;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address,0x0000, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                               data_len = 4;
+                       }
+               }
+               
+       }
+       else
+       {
+       //intra_pan == 1
+       
+       
+       
+       }
+       
+       
+return;
+}
+
+void indication_cmd(MPDU *pdu, int8_t ppduLinkQuality)
+{
+               uint8_t cmd_type;
+               //uint8_t pk_ptr;
+               uint8_t addressing_fields_length=0;
+               
+               uint32_t SrcAddr[2];
+               //uint32_t DstAddr[2];//NOT USED SO FAR
+               
+               //frame control variables
+               uint8_t source_address=0;
+               uint8_t destination_address=0;
+       
+               //NOT USED SO FAR
+               //dest_short *dest_short_ptr;
+               //dest_long *dest_long_ptr;
+               //NOT USED SO FAR
+               //source_short *source_short_ptr;
+               source_long *source_long_ptr;
+               
+               dest_short *dest_short_ptr;
+               dest_long *dest_long_ptr;
+               
+               //CHECK IMPLEMENT
+               //intra_pan_source_short *intra_pan_source_short_ptr; 
+               //intra_pan_source_long *intra_pan_source_long_ptr;
+               
+               destination_address=get_fc2_dest_addr(pdu->frame_control2);
+               source_address=get_fc2_source_addr(pdu->frame_control2);
+               
+               //decrement buffer count
+               atomic buffer_count --;
+               
+               switch(destination_address)
+               {
+                       case LONG_ADDRESS: addressing_fields_length = DEST_LONG_LEN;
+                                                               dest_long_ptr = (dest_long *) &pdu->data[0];
+                                                               if(dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1)
+                                                               {
+                                                                       //printfUART("NOT FOR ME","");
+                                                                       return;
+                                                               }
+                                                               
+                                                               break;
+                       case SHORT_ADDRESS: addressing_fields_length = DEST_SHORT_LEN;
+                                                               dest_short_ptr= (dest_short *) &pdu->data[0];
+                                                               //destination command not for me
+                                                               if (dest_short_ptr->destination_address != mac_PIB.macShortAddress && dest_short_ptr->destination_address !=0xffff)
+                                                               {
+                                                                       //printfUART("NOT FOR ME","");
+                                                                       ////////////printfUART("NOT FOR ME %x me %e\n", dest_short_ptr->destination_address,mac_PIB.macShortAddress); 
+                                                                       return;
+                                                               }
+                                                               break;
+               }
+               switch(source_address)
+               {
+                       case LONG_ADDRESS: addressing_fields_length = addressing_fields_length + SOURCE_LONG_LEN;
+                                                               break;
+                       case SHORT_ADDRESS: addressing_fields_length = addressing_fields_length + SOURCE_SHORT_LEN;
+                                                               break;
+               }
+
+               cmd_type = pdu->data[addressing_fields_length];
+               
+                               
+               switch(cmd_type)
+               {
+               
+               case CMD_ASSOCIATION_REQUEST:   
+                                                                       //check if association is allowed, if not discard the frame             
+                                                                       
+                                                                       ////////printfUART("CMD_ASSOCIATION_REQUEST \n", "");
+                                                                       
+                                                                               
+                                                                                       if (mac_PIB.macAssociationPermit == 0 )
+                                                                                       {
+                                                                                               ////////////printfUART("Association not alowed\n", "");
+                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                                               {
+                                                                                                       build_ack(pdu->seq_num,0);
+                                                                                               }
+                                                                                               return;
+                                                                                       }
+                                                                                       
+                                                                                       if ( PANCoordinator==0 )
+                                                                                       {
+                                                                                               ////////////printfUART("i�m not a pan\n", ""); 
+                                                                                               return;
+                                                                                       }
+                                                                       atomic{
+                                                                                       source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
+                                                                                       
+                                                                                       SrcAddr[1] =source_long_ptr->source_address0;
+                                                                                       SrcAddr[0] =source_long_ptr->source_address1;
+                                                                                       
+                                                                                       
+                                                                                       signal MLME_ASSOCIATE.indication(SrcAddr, pdu->data[addressing_fields_length+1] , 0, 0);
+
+                                                                                       }
+                                                                                       
+                                                                                       if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                                       {
+                                                                                               build_ack(pdu->seq_num,1);
+                                                                                       }       
+
+                                                                                       
+                                                                       break;
+               
+               case CMD_ASSOCIATION_RESPONSE: atomic{
+                                                                                               //printfUART("CMD_ASSOCIATION_RESPONSE\n", ""); 
+                                                                                               
+                                                                                               associating =0;
+                                                                                               call T_ResponseWaitTime.stop();
+                                                                                               
+                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                                               {
+                                                                                                       build_ack(pdu->seq_num,0);
+                                                                                               }
+                                                                                       
+                                                                                               signal MLME_ASSOCIATE.confirm((uint16_t)(pdu->data[addressing_fields_length+1] + (pdu->data[addressing_fields_length+2] << 8)), pdu->data[addressing_fields_length+3]);
+                                                                                               }
+                                                                               break;
+
+               case CMD_DISASSOCIATION_NOTIFICATION:   ////////////printfUART("Received CMD_DISASSOCIATION_NOTIFICATION\n", ""); 
+                                                                                               
+                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                                               {
+                                                                                                       build_ack(pdu->seq_num,0);
+                                                                                               }
+                                                                                               
+                                                                                               process_dissassociation_notification(pdu);
+                                                                                               break;
+               case CMD_DATA_REQUEST: 
+                                                               ////printfUART("CMD_DATA_REQUEST\n", ""); 
+                                                                       ////////printfUART("DR\n", "");
+                                                                       if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                       {
+                                                                               //TODO
+                                                                               //Problems with consecutive reception of messages
+                                                                               
+                                                                               //build_ack(pdu->seq_num,0);
+                                                                       }
+                                                                       
+                                                                       //cmd_data_request_0_3_reception = (cmd_data_request_0_3 *) pdu->data;
+                                                                       
+                                                                       source_long_ptr = (source_long *) &pdu->data[0];
+                                                                                       
+                                                                       SrcAddr[1] =source_long_ptr->source_address0;
+                                                                       SrcAddr[0] =source_long_ptr->source_address1;
+                                                                       
+                                                                       send_ind_trans_addr(SrcAddr);
+
+                                                               break;
+               case CMD_PANID_CONFLICT:
+                                                               break;
+                                                               
+               case CMD_ORPHAN_NOTIFICATION:
+                                                                       ////printfUART("CMD_ORPHAN_NOTIFICATION\n", ""); 
+                                                                       
+                                                                       source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
+                                                                                       
+                                                                       SrcAddr[1] =source_long_ptr->source_address0;
+                                                                       SrcAddr[0] =source_long_ptr->source_address1;
+                                                                       
+                                                                       signal MLME_ORPHAN.indication(SrcAddr, 0x00,0x00);
+                                                               
+               
+                                                               break;
+               case CMD_BEACON_REQUEST:
+                                                               break;
+               case CMD_COORDINATOR_REALIGNMENT:
+                                                                       //printfUART("CMD_COORDINATOR_REALIGNMENT\n", ""); 
+                                                                       
+                                                                       process_coordinator_realignment(pdu);
+                                                                       
+                                                               break;
+               case CMD_GTS_REQUEST:   
+                                                               //////////////printfUART("Received CMD_GTS_REQUEST\n", ""); 
+                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                               {
+                                                                       build_ack(pdu->seq_num,0);
+                                                               }
+                                                               process_gts_request(pdu);
+                                                               break;
+               default: break;
+
+               }
+
+return;
+}
+
+void indication_ack(MPDU *pdu, int8_t ppduLinkQuality)
+{
+       //decrement buffer count
+
+       atomic buffer_count --;
+
+       //////////////printfUART("ACK Received\n",""); 
+       
+       atomic{
+                       if (send_ack_check == 1 && ack_sequence_number_check == pdu->seq_num)
+                       {
+                               //transmission SUCCESS
+                               call T_ackwait.stop();
+                               
+                               send_buffer_count --;
+                               send_buffer_msg_out++;
+                               
+                               //failsafe
+                               if(send_buffer_count > SEND_BUFFER_SIZE)
+                               {
+                                       send_buffer_count =0;
+                                       send_buffer_msg_out=0;
+                                       send_buffer_msg_in=0;
+                               }
+                               
+                               if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                       send_buffer_msg_out=0;
+                               
+                               //received an ack for the association request
+                               if( associating == 1 && association_cmd_seq_num == pdu->seq_num )
+                               {
+                                       ////////////printfUART("ASSOC ACK\n",""); 
+                                       call T_ResponseWaitTime.startOneShot(response_wait_time);
+                                       //call T_ResponseWaitTime.start(TIMER_ONE_SHOT, response_wait_time);
+                               }
+                               
+                               if (gts_request == 1 && gts_request_seq_num == pdu->seq_num)
+                               {
+                               
+                                       call T_ResponseWaitTime.startOneShot(response_wait_time);
+                                       //call T_ResponseWaitTime.start(TIMER_ONE_SHOT, response_wait_time);
+                               }
+                               
+                               ////////////printfUART("TRANSMISSION SUCCESS\n",""); 
+
+                               if (send_indirect_transmission > 0 )
+                               {       //the message send was indirect
+                                       //remove the message from the indirect transmission queue
+                                       indirect_trans_queue[send_indirect_transmission-1].handler=0x00;
+                                       indirect_trans_count--;
+                                       ////////////printfUART("SU id:%i ct:%i\n", send_indirect_transmission,indirect_trans_count);
+                               }
+                               
+                               send_ack_check=0;
+                               retransmit_count=0;
+                               ack_sequence_number_check=0;
+                               
+                               
+                               if (send_buffer_count > 0)
+                                       post send_frame_csma();
+                               
+                               
+                       }
+               }
+       
+                       //CHECK
+               if (get_fc1_frame_pending(pdu->frame_control1) == 1 && pending_request_data ==1)// && associating == 1
+               {               
+                               ////////////printfUART("Frame_pending\n",""); 
+                               pending_request_data=0;
+                               create_data_request_cmd();
+               }
+               
+               //GTS mechanism, after the confirmation of the GTS request, must check if the beacon has the gts
+               /*
+               if (gts_ack == 1)
+               {
+                       gts_ack=0;
+                       gts_confirm=1;
+                       call T_ResponseWaitTime.stop();
+               
+               }
+       */
+               if(gts_send_pending_data==1)
+                       post start_gts_send();
+               
+               if(coordinator_gts_send_pending_data==1 && coordinator_gts_send_time_slot == number_time_slot)
+                       post start_coordinator_gts_send();
+       
+return;
+}
+
+
+void process_dissassociation_notification(MPDU *pdu)
+{
+atomic{
+               cmd_disassociation_notification *mac_disassociation_notification;
+               
+               //creation of a pointer to the disassociation notification structure
+               mac_disassociation_notification = (cmd_disassociation_notification*) pdu->data;                                                                 
+
+               signal MLME_DISASSOCIATE.indication(&mac_disassociation_notification->source_address0, mac_disassociation_notification->disassociation_reason, 0, 0);
+               }
+
+return;
+}
+
+
+
+
+void process_coordinator_realignment(MPDU *pdu)
+{
+
+atomic{
+       cmd_coord_realignment *cmd_realignment = 0;
+       
+       dest_long *dest_long_ptr=0;
+       source_short *source_short_ptr=0;
+
+       cmd_realignment = (cmd_coord_realignment*) &pdu->data[DEST_LONG_LEN + SOURCE_SHORT_LEN];
+       
+       //creation of a pointer the addressing structures
+       dest_long_ptr = (dest_long *) &pdu->data[0];
+       source_short_ptr = (source_short *) &pdu->data[DEST_LONG_LEN];
+               
+       mac_PIB.macCoordShortAddress = ((cmd_realignment->coordinator_short_address0 << 8) | cmd_realignment->coordinator_short_address0 );
+       mac_PIB.macShortAddress = cmd_realignment->short_address;
+       
+       
+       //printfUART("PCR %i %i\n",mac_PIB.macCoordShortAddress,mac_PIB.macShortAddress); 
+       
+       }
+return;
+}
+
+
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/************************              BUILD FRAMES FUNCTIONS                          **********************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+
+
+task void create_beacon()
+{
+       int i=0;
+       uint8_t packet_length = 25;
+       int data_count=0;
+       int pending_data_index=0;
+       MPDU* pkt_ptr=0;
+       //pending frames
+       uint8_t short_addr_pending=0;
+       uint8_t long_addr_pending=0;
+               
+       uint8_t gts_directions=0x00;
+       
+       uint16_t frame_control;
+
+       
+       atomic{
+               
+               beacon_addr_short *mac_beacon_addr_short_ptr;
+               //mac_beacon_addr_short_ptr = (beacon_addr_short*) &mac_txmpdu.data[0];
+               mac_beacon_addr_short_ptr = (beacon_addr_short*) &mac_beacon_txmpdu.data[0];
+               //call PLME_SET_TRX_STATE.request(PHY_TX_ON);
+               
+               mac_beacon_txmpdu_ptr->length = 15;
+               
+               frame_control = set_frame_control(TYPE_BEACON,0,0,0,1,SHORT_ADDRESS,SHORT_ADDRESS);
+               
+               mac_beacon_txmpdu_ptr->frame_control1 = (uint8_t)( frame_control);
+               
+               mac_beacon_txmpdu_ptr->frame_control2 = (uint8_t)( frame_control >> 8);
+               
+               //mac_beacon_txmpdu_ptr->frame_control = set_frame_control(TYPE_BEACON,0,0,0,1,SHORT_ADDRESS,SHORT_ADDRESS);
+               mac_beacon_txmpdu_ptr->seq_num = mac_PIB.macBSN;
+               mac_PIB.macBSN++;
+               
+               
+               //relocation error
+               mac_beacon_addr_short_ptr->destination_PAN_identifier= mac_PIB.macPANId;
+               //relocation error
+               mac_beacon_addr_short_ptr->destination_address = 0xffff;
+               //relocation error
+               mac_beacon_addr_short_ptr->source_address = mac_PIB.macShortAddress;
+               if (mac_PIB.macShortAddress == 0x0000)
+               {       //the device is the PAN Coordinator
+                       mac_beacon_addr_short_ptr->superframe_specification = set_superframe_specification(mac_PIB.macBeaconOrder,(uint8_t)mac_PIB.macSuperframeOrder,final_CAP_slot,0,1,mac_PIB.macAssociationPermit);
+               }
+               else
+               {
+                       mac_beacon_addr_short_ptr->superframe_specification = set_superframe_specification(mac_PIB.macBeaconOrder,(uint8_t)mac_PIB.macSuperframeOrder,final_CAP_slot,0,1,mac_PIB.macAssociationPermit);
+               }
+               
+               mac_beacon_txmpdu_ptr->data[8] = set_gts_specification(GTS_descriptor_count,mac_PIB.macGTSPermit);
+               
+               mac_beacon_txmpdu_ptr->data[9] = set_pending_address_specification(short_addr_pending,long_addr_pending);
+               
+               data_count = 9;
+               packet_length = 15;
+               
+               
+               //BUILDING the GTS DESCRIPTORS
+               if( (GTS_descriptor_count + GTS_null_descriptor_count) > 0 )
+               {
+                       data_count++;
+                                       
+                       for(i=0; i< 7 ; i++)
+                       {
+                               if( GTS_db[i].gts_id != 0x00 && GTS_db[i].DevAddressType != 0x0000) 
+                               {
+                                       
+                                       mac_beacon_txmpdu_ptr->data[data_count] = GTS_db[i].DevAddressType;
+                                       //////////////printfUART("B gts %i\n", (GTS_db[i].DevAddressType >> 8 ) ); 
+                                       
+                                       data_count++;
+                                       mac_beacon_txmpdu_ptr->data[data_count] = (GTS_db[i].DevAddressType >> 8 );
+                                       //////////////printfUART("B gts %i\n",  GTS_db[i].DevAddressType ); 
+                                       
+                                       data_count++;
+                                       
+                                       mac_beacon_txmpdu_ptr->data[data_count] = set_gts_descriptor(15-i,GTS_db[i].length);
+                                       data_count++;
+                                       //////printfUART("B gts %i\n", set_gts_descriptor(GTS_db[i].starting_slot,GTS_db[i].length) ); 
+                                       
+                                       packet_length = packet_length + 3;
+                                       
+                                       if ( GTS_db[i].direction == 1 )
+                                       {
+                                               gts_directions = gts_directions | (1 << i); 
+                                       }
+                                       else
+                                       {
+                                               gts_directions = gts_directions | (0 << i); 
+                                       }
+                                       //////printfUART("dir %i\n", gts_directions); 
+                               }
+                       }
+                       mac_beacon_txmpdu_ptr->data[9] = gts_directions;
+                       //CHECK
+                       packet_length++;
+                       //BUILDING the NULL GTS DESCRIPTORS
+                       if ( GTS_null_descriptor_count > 0 )
+                       {
+                               for(i=0; i< 7 ; i++)
+                               {
+                                       if( GTS_null_db[i].DevAddressType != 0x0000) 
+                                       {
+                                               mac_beacon_txmpdu_ptr->data[data_count] = GTS_null_db[i].DevAddressType;
+                                               //////////////printfUART("B gts %i\n", (GTS_db[i].DevAddressType >> 8 ) ); 
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count] = (GTS_null_db[i].DevAddressType >> 8 );
+                                               //////////////printfUART("B gts %i\n",  GTS_db[i].DevAddressType ); 
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count] = 0x00;
+                                               data_count++;
+                                               //////////////printfUART("B gts %i\n", set_gts_descriptor(GTS_db[i].starting_slot,GTS_db[i].length) ); 
+                                               packet_length = packet_length +3;
+                                       }
+                               }
+                       }
+                       //resetting the GTS specification field
+                       mac_beacon_txmpdu_ptr->data[8] = set_gts_specification(GTS_descriptor_count + GTS_null_descriptor_count,mac_PIB.macGTSPermit);
+                       
+
+               }
+
+                       pending_data_index = data_count;
+                       data_count++;
+               //IMPLEMENT PENDING ADDRESSES
+               //temporary
+               //indirect_trans_count =0;
+               
+               if (indirect_trans_count > 0 )
+               {
+                               //IMPLEMENT THE PENDING ADDRESSES CONSTRUCTION
+
+                       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+                       {
+                               if (indirect_trans_queue[i].handler > 0x00)
+                               {
+                                       pkt_ptr = (MPDU *)&indirect_trans_queue[i].frame;
+                                       //ADD INDIRECT TRANSMISSION DESCRIPTOR
+                                       if(get_fc2_dest_addr(pkt_ptr->frame_control2) == SHORT_ADDRESS)
+                                       {
+                                               short_addr_pending++;
+                                               packet_length = packet_length + 2;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[2];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[3];
+                                               data_count++;
+                                       }
+                               }
+                       }
+                       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+                       {
+                               if (indirect_trans_queue[i].handler > 0x00)
+                               {
+                                       if(get_fc2_dest_addr(pkt_ptr->frame_control2) == LONG_ADDRESS)
+                                       {
+                                               long_addr_pending++;
+                                               packet_length = packet_length + 8;
+
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[0];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[1];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[2];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[3];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[4];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[5];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[6];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[7];
+                                               data_count++;
+                                               
+                                       }
+                               }
+                       }
+                               
+               }
+               mac_beacon_txmpdu_ptr->data[pending_data_index] = set_pending_address_specification(short_addr_pending,long_addr_pending);
+               
+               
+               //adding the beacon payload
+               if (mac_PIB.macBeaconPayloadLenght > 0 )
+               {
+                       for (i=0;i < mac_PIB.macBeaconPayloadLenght;i++)
+                       {
+                               mac_beacon_txmpdu_ptr->data[data_count] = mac_PIB.macBeaconPayload[i];
+                               data_count++;
+                               packet_length++;
+                       }
+               
+               
+               }
+               
+               //short_addr_pending=0;
+               //long_addr_pending=0;
+               
+               mac_beacon_txmpdu_ptr->length = packet_length;
+               
+               send_beacon_length = packet_length;
+               
+               send_beacon_frame_ptr = (uint8_t*)mac_beacon_txmpdu_ptr;
+               }
+}
+
+
+void create_data_frame(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions,uint8_t on_gts_slot,uint8_t pan)
+{
+       
+       int i_indirect_trans=0;
+
+       dest_short *dest_short_ptr;
+       dest_long *dest_long_ptr;
+       
+       source_short *source_short_ptr;
+       source_long *source_long_ptr;
+
+       //intra_pan_source_short *intra_pan_source_short_ptr;
+       //intra_pan_source_long *intra_pan_source_long_ptr;
+       
+       //CHECK
+       uint8_t intra_pan=0;
+       uint8_t data_len=0;
+       
+       uint8_t current_gts_element_count=0;
+       
+       MPDU *frame_pkt=0;
+       
+       uint16_t frame_control;
+       
+       ////printfUART("create df\n","");
+       
+       //decision of the buffer where to store de packet creation
+       if (on_gts_slot > 0 )
+       {
+       
+               if (PANCoordinator == 1)
+               {
+               //setting the coordinator gts frame pointer
+                       
+                       //get the number of frames in the gts_slot_list
+                       atomic current_gts_element_count = gts_slot_list[15-on_gts_slot].element_count;
+                       
+                       ////////////printfUART("element count %i\n",gts_slot_list[15-on_gts_slot].element_count);
+                       
+                       if (current_gts_element_count  == GTS_SEND_BUFFER_SIZE || available_gts_index_count == 0)
+                       {
+                               ////////////printfUART("FULL\n","");
+                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
+                               return;
+                       }
+                       else
+                       {
+                               frame_pkt = (MPDU *) &gts_send_buffer[available_gts_index[available_gts_index_count]];
+                       }
+                       
+               }
+               else
+               {
+               //setting the device gts frame pointer
+                       //////////////printfUART("start creation %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
+               
+                       if(gts_send_buffer_count == GTS_SEND_BUFFER_SIZE)
+                       {
+                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
+                               return;
+                       }
+                       if (gts_send_buffer_msg_in == GTS_SEND_BUFFER_SIZE)
+                               gts_send_buffer_msg_in=0;
+                       
+                               frame_pkt = (MPDU *) &gts_send_buffer[gts_send_buffer_msg_in];
+               
+               }
+       }
+       else
+       {
+       
+               if ( get_txoptions_indirect_transmission(TxOptions) == 1)
+               {
+                       
+                       //CREATE THE INDIRECT TRANSMISSION PACKET POINTER
+                       //check if the is enough space to store the indirect transaction
+                       if (indirect_trans_count == INDIRECT_BUFFER_SIZE)
+                       {
+                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
+                               ////////////printfUART("buffer full %i\n", indirect_trans_count);
+                               return;
+                       }
+                       
+                       for(i_indirect_trans=0;i_indirect_trans<INDIRECT_BUFFER_SIZE;i_indirect_trans++)
+                       {
+                               if (indirect_trans_queue[i_indirect_trans].handler == 0x00)
+                               {
+                                       frame_pkt = (MPDU *) &indirect_trans_queue[i_indirect_trans].frame;
+                                       break;
+                               }
+                       }
+                       
+                       
+               }
+               else
+               {
+                       //CREATE NORMAL TRANSMISSION PACKET POINTER
+                               //////printfUART("sb  %i\n", send_buffer_count);
+                       atomic{
+                               if ((send_buffer_count +1) > SEND_BUFFER_SIZE)  
+                                       return;
+                       
+                               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                                       send_buffer_msg_in=0;
+               
+                               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+                               }
+               }
+       }
+       
+atomic{
+
+       if (intra_pan == 0 )
+       {
+       
+               if ( DstAddrMode > 1 && SrcAddrMode > 1 )
+               {
+                       // Destination LONG - Source LONG       
+                       if (DstAddrMode == LONG_ADDRESS && SrcAddrMode == LONG_ADDRESS)
+                       {
+                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+                               source_long_ptr = (source_long *) &frame_pkt->data[DEST_LONG_LEN];
+                               
+                               dest_long_ptr->destination_PAN_identifier=DestPANId;
+                               dest_long_ptr->destination_address0=DstAddr[1];
+                               dest_long_ptr->destination_address1=DstAddr[0];
+                               
+                               source_long_ptr->source_PAN_identifier=SrcPANId;
+                               source_long_ptr->source_address0=SrcAddr[1];
+                               source_long_ptr->source_address1=SrcAddr[0];
+                               
+                               data_len = 20;
+                       }
+                       
+                       // Destination SHORT - Source LONG
+                       if ( DstAddrMode == SHORT_ADDRESS && SrcAddrMode == LONG_ADDRESS )
+                       {
+                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+                               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
+                               
+                               dest_short_ptr->destination_PAN_identifier=DestPANId;
+                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
+                               
+                               source_long_ptr->source_PAN_identifier=SrcPANId;
+                               source_long_ptr->source_address0=SrcAddr[1];
+                               source_long_ptr->source_address1=SrcAddr[0];
+                               
+                               data_len = 14;
+                       }
+                       // Destination LONG - Source SHORT
+                       if ( DstAddrMode == LONG_ADDRESS && SrcAddrMode == SHORT_ADDRESS )
+                       {
+                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+                               source_short_ptr = (source_short *) &frame_pkt->data[DEST_LONG_LEN];
+                               
+                               dest_long_ptr->destination_PAN_identifier=DestPANId;
+                               dest_long_ptr->destination_address0=DstAddr[1];
+                               dest_long_ptr->destination_address1=DstAddr[0];
+                               
+                               source_short_ptr->source_PAN_identifier=SrcPANId;
+                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
+                               
+                               data_len = 14;
+                       }
+                       
+                       
+                       //Destination SHORT - Source SHORT
+                       if ( DstAddrMode == SHORT_ADDRESS && SrcAddrMode == SHORT_ADDRESS )     
+                       {
+                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+                               source_short_ptr = (source_short *) &frame_pkt->data[DEST_SHORT_LEN];
+                               
+                               dest_short_ptr->destination_PAN_identifier=DestPANId;
+                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
+                               
+                               source_short_ptr->source_PAN_identifier=SrcPANId;
+                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
+                               
+                               data_len = 8;
+                       }
+               }
+               
+               if ( DstAddrMode == 0 && SrcAddrMode > 1 )
+               {
+                               
+                       if (SrcAddrMode == LONG_ADDRESS)
+                       {//Source LONG
+                               source_long_ptr = (source_long *) &frame_pkt->data[0];
+                               
+                               source_long_ptr->source_PAN_identifier=SrcPANId;
+                               source_long_ptr->source_address0=SrcAddr[1];
+                               source_long_ptr->source_address1=SrcAddr[0];
+                               
+                               data_len = 10;
+                       }
+                       else
+                       {//Source SHORT
+
+                               source_short_ptr = (source_short *) &frame_pkt->data[0];
+                               
+                               source_short_ptr->source_PAN_identifier=SrcPANId;
+                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
+                               
+                               data_len = 4;
+                       }
+               }
+               
+               if ( DstAddrMode > 1 && SrcAddrMode == 0 )
+               {
+                       if (DstAddrMode == LONG_ADDRESS)
+                       {//Destination LONG
+                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+               
+                               dest_long_ptr->destination_PAN_identifier=DestPANId;
+                               dest_long_ptr->destination_address0=DstAddr[1];
+                               dest_long_ptr->destination_address1=DstAddr[0];
+
+                               data_len = 10;
+                       }
+                       else
+                       {//Destination SHORT
+                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+
+                               dest_short_ptr->destination_PAN_identifier=DestPANId;
+                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
+                               
+                               data_len = 4;
+                       }
+               }
+       }
+       else
+       {
+       //intra_pan == 1
+
+       }
+               
+               memcpy(&frame_pkt->data[data_len],&msdu[0],msduLength*sizeof(uint8_t));
+               
+               if(on_gts_slot > 0)
+               {
+                       //preparing a GTS transmission
+                       
+                       //////////////printfUART("GTS send slt: %i count %i %u\n",on_gts_slot,gts_slot_list[15-on_gts_slot].element_count,mac_PIB.macDSN);
+                       frame_pkt->length = data_len + msduLength + MPDU_HEADER_LEN;
+                       
+                       frame_control = set_frame_control(TYPE_DATA,0,0,1,intra_pan,DstAddrMode,SrcAddrMode);
+                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+                       
+                       frame_pkt->seq_num = mac_PIB.macDSN;
+                       mac_PIB.macDSN++;
+                                               
+                       //ADDING DATA TO THE GTS BUFFER
+                       atomic{
+                                       if (PANCoordinator == 1)
+                                       {
+                                               gts_slot_list[15-on_gts_slot].element_count ++;
+                                               gts_slot_list[15-on_gts_slot].gts_send_frame_index[gts_slot_list[15-on_gts_slot].element_in] = available_gts_index[available_gts_index_count];
+                                               //gts_slot_list[15-on_gts_slot].length = frame_pkt->length;
+                                               
+                                               gts_slot_list[15-on_gts_slot].element_in ++;
+                                               
+                                               if (gts_slot_list[15-on_gts_slot].element_in == GTS_SEND_BUFFER_SIZE)
+                                                       gts_slot_list[15-on_gts_slot].element_in=0;
+                                               
+                                               available_gts_index_count --;
+                                               
+                                               //current_gts_pending_frame++;
+                                       }
+                                       else
+                                       {
+                                               gts_send_buffer_count++;
+                                               gts_send_buffer_msg_in++;
+                                               //////////////printfUART("end c %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
+                                       }
+                       }
+               }
+               else
+               {
+                       ////////////printfUART("CSMA send %i\n", get_txoptions_ack(TxOptions));
+                       frame_pkt->length = data_len + msduLength + MPDU_HEADER_LEN;
+                       //frame_pkt->frame_control = set_frame_control(TYPE_DATA,0,0,get_txoptions_ack(TxOptions),intra_pan,DstAddrMode,SrcAddrMode);
+                       
+                       frame_control = set_frame_control(TYPE_DATA,0,0,get_txoptions_ack(TxOptions),intra_pan,DstAddrMode,SrcAddrMode);
+                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+                       
+                       frame_pkt->seq_num = mac_PIB.macDSN;
+                       
+                       ////////printfUART("sqn %i\n", mac_PIB.macDSN);
+                       
+                       mac_PIB.macDSN++;
+                       
+                       if ( get_txoptions_indirect_transmission(TxOptions) == 1)
+                       {
+                                       indirect_trans_queue[i_indirect_trans].handler = indirect_trans_count + 1;
+                                       indirect_trans_queue[i_indirect_trans].transaction_persistent_time = 0x0000;
+       
+                                       indirect_trans_count++;
+       
+                                       ////////////printfUART("ADDED HDL: %i ADDR: %i\n",indirect_trans_count,DstAddr[1]); 
+                       }
+                       else
+                       {
+                                       //enable retransmissions
+                                       send_buffer[send_buffer_msg_in].retransmission = 1;
+                                       send_buffer[send_buffer_msg_in].indirect = 0;
+                                       
+                                       send_buffer_count++;
+                                       
+                                       send_buffer_msg_in++;
+                                       
+                                       post send_frame_csma();
+                       }
+                       
+               }
+               
+       }
+return;
+}
+
+
+error_t create_association_response_cmd(uint32_t DeviceAddress[],uint16_t shortaddress, uint8_t status)
+{
+
+       cmd_association_response *mac_association_response;
+       dest_long *dest_long_ptr;
+       source_long *source_long_ptr;
+       
+       int i=0;
+       
+       MPDU *frame_pkt=0;
+       
+       uint16_t frame_control;
+       
+       //atomic{
+       /*
+                       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+       */
+       
+       //check if the is enough space to store the indirect transaction
+       if (indirect_trans_count == INDIRECT_BUFFER_SIZE)
+       {
+               //printfUART("i full","");
+               return MAC_TRANSACTION_OVERFLOW;
+       }
+       
+       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+       {
+               if (indirect_trans_queue[i].handler == 0x00)
+               {
+                       //memcpy(&indirect_trans_queue[i].frame,frame_ptr,sizeof(MPDU));
+                       frame_pkt = (MPDU *) &indirect_trans_queue[i].frame;
+                       //printfUART("found slot","");
+                       break;
+               }
+       }
+       
+       //creation of a pointer to the association response structure
+       dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+       source_long_ptr = (source_long *) &frame_pkt->data[DEST_LONG_LEN];
+       
+       mac_association_response = (cmd_association_response *) &frame_pkt->data[DEST_LONG_LEN + SOURCE_LONG_LEN];                                                                      
+       
+       frame_pkt->length = 29;
+       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
+       
+       frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
+       
+       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+       
+       frame_pkt->seq_num = mac_PIB.macDSN;
+       mac_PIB.macDSN++;
+       
+       dest_long_ptr->destination_PAN_identifier = mac_PIB.macPANId;
+
+       dest_long_ptr->destination_address0 = DeviceAddress[1];
+       dest_long_ptr->destination_address1 = DeviceAddress[0];
+       
+       source_long_ptr->source_PAN_identifier = mac_PIB.macPANId;
+       
+       source_long_ptr->source_address0 = aExtendedAddress0;
+       source_long_ptr->source_address1 = aExtendedAddress1;
+
+       mac_association_response->command_frame_identifier = CMD_ASSOCIATION_RESPONSE;
+       
+       //mac_association_response->short_address = shortaddress;
+       mac_association_response->short_address1 = (uint8_t)(shortaddress);
+       mac_association_response->short_address2 = (uint8_t)(shortaddress >> 8);
+
+
+       mac_association_response->association_status = status;
+/*
+
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+                       }       
+               post send_frame_csma();
+*/
+       //printfUART("ASS RESP S: %i\n",shortaddress); 
+
+       indirect_trans_queue[i].handler = indirect_trans_count+1;
+
+       indirect_trans_queue[i].transaction_persistent_time = 0x0000;
+       
+       indirect_trans_count++;
+       
+       //printfUART("IAD\n", "");
+
+return MAC_SUCCESS;
+}
+
+
+void create_association_request_cmd(uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation)
+{
+atomic{
+
+               cmd_association_request *cmd_association_request_ptr;
+               dest_short *dest_short_ptr;
+               source_long *source_long_ptr;
+       
+               MPDU *frame_pkt=0;
+               
+               uint16_t frame_control;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+               
+               //creation of a pointer to the association response structure
+               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
+               
+               cmd_association_request_ptr = (cmd_association_request *) &send_buffer[send_buffer_msg_in].data[DEST_SHORT_LEN + SOURCE_LONG_LEN];
+               
+               frame_pkt->length = 21;
+               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,SHORT_ADDRESS,LONG_ADDRESS);
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,1,0,SHORT_ADDRESS,LONG_ADDRESS);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               association_cmd_seq_num =  mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               dest_short_ptr->destination_PAN_identifier = CoordPANId; //mac_PIB.macPANId;
+               
+               if (CoordAddrMode == SHORT_ADDRESS )
+               {
+                       dest_short_ptr->destination_address = (uint16_t)(CoordAddress[1] & 0x000000ff) ;  //mac_PIB.macPANId;
+               }
+               else
+               {
+               //CHECK
+               
+               //implement the long address version
+               
+               }
+               
+               source_long_ptr->source_PAN_identifier = 0xffff;
+               
+               source_long_ptr->source_address0 = aExtendedAddress0;
+               source_long_ptr->source_address1 = aExtendedAddress1;
+               
+               cmd_association_request_ptr->command_frame_identifier = CMD_ASSOCIATION_REQUEST;
+               
+               cmd_association_request_ptr->capability_information = CapabilityInformation;
+
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               pending_request_data=1;
+               
+               //////printfUART("Association request %i %i \n", send_buffer_count,send_buffer_msg_in);
+               
+               
+               post send_frame_csma();
+
+       }
+return;
+}
+
+void create_data_request_cmd()
+{
+       ////////////printfUART("create_data_request_cmd\n", ""); 
+
+atomic{
+               //dest_short *dest_short_ptr;
+               source_long *source_long_ptr;
+
+               
+               MPDU *frame_pkt;
+               
+               uint16_t frame_control;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+       
+       
+               source_long_ptr= (source_long *) &send_buffer[send_buffer_msg_in].data[0];
+       
+               //creation of a pointer to the association response structure
+               //dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+               source_long_ptr = (source_long *) &frame_pkt->data[0];
+       
+       
+               frame_pkt->length = 16;                                                 
+               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,LONG_ADDRESS);   //dest | source
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,LONG_ADDRESS);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               
+               source_long_ptr->source_PAN_identifier = mac_PIB.macPANId;
+               
+               source_long_ptr->source_address0 = aExtendedAddress0;//aExtendedAddress0;
+               source_long_ptr->source_address1 = aExtendedAddress1;
+               
+               //command_frame_identifier = CMD_DATA_REQUEST;
+               frame_pkt->data[SOURCE_LONG_LEN]=CMD_DATA_REQUEST;
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+                               
+               post send_frame_csma();
+               
+               
+               }
+return;
+}
+
+void create_beacon_request_cmd()
+{
+
+atomic{
+               cmd_beacon_request *mac_beacon_request;
+       
+               MPDU *frame_pkt;
+               
+               uint16_t frame_control;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+       
+               mac_beacon_request= (cmd_beacon_request*) &send_buffer[send_buffer_msg_in].data;
+       
+               frame_pkt->length = 10;                                                 
+               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);   //dest | source
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               mac_beacon_request->destination_PAN_identifier = 0xffff;
+               
+               mac_beacon_request->destination_address = 0xffff;
+       
+               mac_beacon_request->command_frame_identifier = CMD_BEACON_REQUEST;
+               
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               post send_frame_csma();
+
+               }
+
+return;
+}
+
+void create_orphan_notification()
+{
+
+       atomic{
+       
+               cmd_default *cmd_orphan_notification=0;
+               
+               dest_short *dest_short_ptr=0;
+               source_long *source_long_ptr=0;
+
+               MPDU *frame_pkt=0;
+                       
+               uint16_t frame_control=0;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+               
+               frame_pkt->length = 20;                                                 
+                               
+               cmd_orphan_notification = (cmd_default*) &send_buffer[send_buffer_msg_in].data[DEST_SHORT_LEN + SOURCE_LONG_LEN];
+               
+               //creation of a pointer the addressing structures
+               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
+               
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,LONG_ADDRESS);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               
+               dest_short_ptr->destination_PAN_identifier = 0xffff; //mac_PIB.macPANId;
+               
+               dest_short_ptr->destination_address = 0xffff ;  //mac_PIB.macPANId;
+               
+               source_long_ptr->source_PAN_identifier = 0xffff;
+               
+               source_long_ptr->source_address0 = aExtendedAddress0;
+               source_long_ptr->source_address1 = aExtendedAddress1;
+                               
+               
+               cmd_orphan_notification->command_frame_identifier = CMD_ORPHAN_NOTIFICATION;
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               post send_frame_csma();
+       }
+
+return;
+}
+
+
+void create_coordinator_realignment_cmd(uint32_t device_extended0, uint32_t device_extended1, uint16_t device_short_address)
+{
+
+atomic{
+
+       cmd_coord_realignment *cmd_realignment =0;
+       
+       dest_long *dest_long_ptr=0;
+       source_short *source_short_ptr=0;
+       
+       MPDU *frame_pkt=0;
+       
+       uint16_t frame_control=0;
+       
+       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+               send_buffer_msg_in=0;
+
+       frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+       
+       frame_pkt->length = 27;                                                 
+       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);   //dest | source
+       
+       cmd_realignment = (cmd_coord_realignment*) &send_buffer[send_buffer_msg_in].data[DEST_LONG_LEN + SOURCE_SHORT_LEN];
+       
+       //creation of a pointer the addressing structures
+       dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+       source_short_ptr = (source_short *) &frame_pkt->data[DEST_LONG_LEN];
+
+       
+       frame_control = set_frame_control(TYPE_CMD,0,0,0,0,LONG_ADDRESS,SHORT_ADDRESS);
+       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+       frame_pkt->seq_num = mac_PIB.macDSN;
+       
+       mac_PIB.macDSN++;
+       
+       dest_long_ptr->destination_PAN_identifier = 0xffff;
+       dest_long_ptr->destination_address0 = device_extended0;
+       dest_long_ptr->destination_address1 = device_extended1;
+       
+       source_short_ptr->source_PAN_identifier = mac_PIB.macPANId;
+       source_short_ptr->source_address = mac_PIB.macCoordShortAddress;
+       
+       
+       cmd_realignment->command_frame_identifier = CMD_COORDINATOR_REALIGNMENT;
+       
+       mac_PIB.macPANId = 0x1234;
+       
+       mac_PIB.macCoordShortAddress =0x0000;
+       
+       cmd_realignment->PAN_identifier0 = (mac_PIB.macPANId);
+       cmd_realignment->PAN_identifier1 = (mac_PIB.macPANId >> 8);
+
+       cmd_realignment->coordinator_short_address0 = (mac_PIB.macCoordShortAddress);
+       cmd_realignment->coordinator_short_address1 = (mac_PIB.macCoordShortAddress >> 8);
+       
+       cmd_realignment->logical_channel = LOGICAL_CHANNEL;
+       cmd_realignment->short_address = device_short_address;
+
+       
+       //increment the send buffer variables
+       send_buffer_count++;
+       send_buffer_msg_in++;
+       
+       post send_frame_csma();
+
+       }
+
+return;
+}
+
+
+void create_gts_request_cmd(uint8_t gts_characteristics)
+{
+atomic{
+               cmd_gts_request *mac_gts_request;
+               
+               MPDU *frame_pkt;
+               
+               uint16_t frame_control;
+               //////printfUART("create_gts_request_cmd\n", "");
+               
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+               
+               mac_gts_request= (cmd_gts_request*) &send_buffer[send_buffer_msg_in].data;
+
+               frame_pkt->length = 11;
+       
+               if ( get_characteristic_type(gts_characteristics) != 0 )
+               {   
+                       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);   //dest | source
+               
+                       frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS); 
+                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               }
+               else
+               {       
+                       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);
+                       
+                       frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);
+                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               }
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               gts_request_seq_num = frame_pkt->seq_num;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               //mac_gts_request->source_PAN_identifier = 0x0001;
+               mac_gts_request->source_PAN_identifier = mac_PIB.macPANId;
+               
+               mac_gts_request->source_address = mac_PIB.macShortAddress;
+       
+               mac_gts_request->command_frame_identifier = CMD_GTS_REQUEST;
+               
+               //mac_gts_request->gts_characteristics = set_gts_characteristics(2,1,1);
+               mac_gts_request->gts_characteristics =gts_characteristics;
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               post send_frame_csma();
+               
+               }
+
+return;
+}
+
+void create_disassociation_notification_cmd(uint32_t DeviceAddress[],uint8_t disassociation_reason)
+{
+
+       atomic{
+               cmd_disassociation_notification *mac_disassociation_notification;
+               MPDU *frame_pkt;
+               
+               uint16_t frame_control;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+               
+               //creation of a pointer to the disassociation notification structure
+               mac_disassociation_notification = (cmd_disassociation_notification*) &send_buffer[send_buffer_msg_in].data;                                                             
+               
+               
+               frame_pkt->length = 27;
+               
+               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               mac_disassociation_notification->destination_PAN_identifier = mac_PIB.macPANId;
+
+               mac_disassociation_notification->destination_address0 = DeviceAddress[0];
+               mac_disassociation_notification->destination_address1 = DeviceAddress[1];
+       
+               mac_disassociation_notification->source_PAN_identifier = mac_PIB.macPANId;
+       
+               mac_disassociation_notification->source_address0 = aExtendedAddress0;
+               mac_disassociation_notification->source_address1 = aExtendedAddress1;
+       
+               mac_disassociation_notification->command_frame_identifier = CMD_DISASSOCIATION_NOTIFICATION;
+               
+               mac_disassociation_notification->disassociation_reason = disassociation_reason;
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               post send_frame_csma();
+
+       }
+return;
+}
+
+
+
+void build_ack(uint8_t sequence,uint8_t frame_pending)
+{
+       uint16_t frame_control;
+       atomic{
+                       mac_ack_ptr->length = ACK_LENGTH;
+                       //mac_ack_ptr->frame_control = set_frame_control(TYPE_ACK,0,frame_pending,0,0,0,0);
+                       
+                       frame_control = set_frame_control(TYPE_ACK,0,frame_pending,0,0,0,0);
+                       mac_ack_ptr->frame_control1 =(uint8_t)( frame_control);
+                       mac_ack_ptr->frame_control2 =(uint8_t)( frame_control >> 8);
+                       
+                       mac_ack_ptr->seq_num = sequence;
+                       
+                       call PD_DATA.request(mac_ack_ptr->length,(uint8_t*)mac_ack_ptr);
+       }
+}
+
+
+
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/************************              INTERFACES PROVIDED                     **********************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+
+/*********************************************************/
+/**************MLME_SCAN********************************/
+/*********************************************************/
+
+task void data_channel_scan_indication()
+{
+       uint8_t link_qual;
+       
+       beacon_addr_short *beacon_ptr;
+       
+       ////printfUART("data_channel_scan_indication\n","");
+
+       atomic link_qual = link_quality;
+
+       atomic buffer_count--;
+
+       switch(scan_type)
+       {
+               case ED_SCAN: 
+                                               if (scanned_values[current_scanning-1] < link_qual)
+                                                               scanned_values[current_scanning-1] = link_qual;
+                                               break;
+               
+               case ACTIVE_SCAN:break;
+                                       
+               case PASSIVE_SCAN: 
+                                                       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
+                                                       {
+                                                               case TYPE_BEACON:
+                                                               printfUART("3 ps rb\n","");
+                                                               beacon_ptr = (beacon_addr_short*) (&buffer_msg[current_msg_out].data);
+
+                                                               //Beacon NOTIFICATION
+                                                               //BUILD the PAN descriptor of the COORDINATOR
+                                                               //assuming that the adress is short
+                                                               scan_pans[current_scanning-1].CoordPANId = beacon_ptr->destination_PAN_identifier;
+                                                               scan_pans[current_scanning-1].CoordAddress=beacon_ptr->source_address;
+                                                               scan_pans[current_scanning-1].LogicalChannel=current_channel;
+                                                               //superframe specification field
+                                                               scan_pans[current_scanning-1].SuperframeSpec = beacon_ptr->superframe_specification;
+                                                               
+                                                               if (scan_pans[current_scanning-1].lqi < link_qual)
+                                                               scan_pans[current_scanning-1].lqi = link_qual;
+                                                       
+                                                               break;
+                                                               
+                                                               default: break;
+                                                       //atomic buffer_count--;
+                                                       //////////////printfUART("Invalid frame type\n","");
+
+                                                       }
+                                                       break;
+               case ORPHAN_SCAN: 
+                                                       ////printfUART("osrm\n","");
+                                                       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
+                                                       {
+                                                               case TYPE_CMD:
+                                                                               ////printfUART("received cmd\n","");
+                                                                               if (buffer_msg[current_msg_out].data[SOURCE_SHORT_LEN+ DEST_LONG_LEN] == CMD_COORDINATOR_REALIGNMENT)
+                                                                               {       
+                                                                                       //printfUART("pf\n","");
+                                                                                       atomic scanning_channels = 0;
+                                                                                       call T_ScanDuration.stop();
+                                                                                       process_coordinator_realignment(&buffer_msg[current_msg_out]);
+                                                                                       
+                                                                               }
+                                                                               
+                                                                               break;
+                                                       default: break;
+                                                       }
+                                                       break;
+               
+       }
+       
+       atomic{
+                       current_msg_out++;
+               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
+                       current_msg_out = 0;
+               }
+return;
+}
+/*******************T_ScanDuration**************************/
+event void T_ScanDuration.fired() {
+
+       current_scanning++;
+       
+       printfUART("cs%i c%i\n",current_scanning,(0x0A + current_scanning));
+                                               
+       call PLME_SET.request(PHYCURRENTCHANNEL, (0x0A + current_scanning));
+
+       current_channel = (0x0A + current_scanning);
+       
+
+       if (current_scanning == 16 )
+       {
+               ////printfUART("scan end\n","");
+               
+               atomic scanning_channels = 0;
+               
+               switch(scan_type)
+               {
+                       case ED_SCAN: 
+                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , scanned_values,0x00);
+                                                       break;
+                       
+                       case ACTIVE_SCAN:break;
+
+                       case PASSIVE_SCAN: 
+                                                       //event result_t confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[]);
+                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , 0x00, scan_pans);
+                                                       break;
+                       
+                       case ORPHAN_SCAN: 
+                                                       //orphan scan
+                                                       //send opphan command on every channel directed to the current PAN coordinator
+                                                       //printfUART("oph s end not found\n","");
+                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , 0x00, scan_pans);
+                                                       
+                                                       break;
+               }
+       }
+       else
+       {
+               switch(scan_type)
+               {
+                       case ORPHAN_SCAN:       //printfUART("con\n","");
+                                                               create_orphan_notification();
+                                                               break;
+               }
+               
+               call T_ScanDuration.startOneShot(scan_duration);
+       }
+  
+}
+
+
+
+command error_t MLME_SCAN.request(uint8_t ScanType, uint32_t ScanChannels, uint8_t ScanDuration)
+{
+//pag 93
+       //printfUART("MLME_SCAN.request\n", ""); 
+               
+       atomic scanning_channels = 1;
+       scan_type = ScanType;
+       channels_to_scan = ScanChannels;
+       
+       atomic current_scanning=0;
+       
+       
+       switch(ScanType)
+       {
+               //ED SCAN only FFD                      
+               case ED_SCAN:   
+                                       call TimerAsync.set_timers_enable(0x00);
+                                       /*
+                               
+                                       scanning_channels = 1;
+                                       scan_type = ScanType;
+                                       current_scanning=0;
+                                       scan_count=0;
+                                       channels_to_scan = ScanChannels;
+                                       scan_duration = ((aBaseSuperframeDuration * pow(2,ScanDuration)) * 4.0) / 250.0;
+                                       
+                                       ////////////printfUART("channels_to_scan %y scan_duration %y\n", channels_to_scan,scan_duration); 
+                                       
+                                       call T_ed_scan.start(TIMER_REPEAT,1);
+                                       
+                                       call T_scan_duration.start(TIMER_ONE_SHOT,scan_duration);       
+                                       */
+                                       
+                                       
+                                       //calculate the scan_duration in miliseconds
+                                       //#ifdef PLATFORM_MICAZ
+                                               scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
+                                       //#else
+                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
+                                       //#endif
+                       //scan_duration = 2000;
+                                       
+                                       call T_ScanDuration.startOneShot(scan_duration);
+                                       
+                                       ////printfUART("channels_to_scan %y scan_duration %y\n", channels_to_scan,scan_duration); 
+                                       break;
+               //active scan only FFD
+               case ACTIVE_SCAN:
+                                       call TimerAsync.set_timers_enable(0x00);
+                                       break;
+               //passive scan
+               case PASSIVE_SCAN:      
+                                       call TimerAsync.set_timers_enable(0x00);
+                                                       
+                                       //calculate the scan_duration in miliseconds
+                                       //#ifdef PLATFORM_MICAZ
+                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
+                                       //#else
+                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
+                                       //#endif
+                                       
+                                       
+                                       //defines the time (miliseconds) that the device listen in each channel
+                                       scan_duration = 2000;
+                                       
+                                       //printfUART("channels_to_scan %y scan_duration %i\n", channels_to_scan,scan_duration); 
+                                       
+                                       call T_ScanDuration.startOneShot(scan_duration);
+                                       
+                                       ////printfUART("channels_to_scan %y scan_duration %i\n", channels_to_scan,scan_duration); 
+                                       
+                                       //atomic trx_status = PHY_RX_ON;
+                                       //call PLME_SET_TRX_STATE.request(PHY_RX_ON); 
+               
+               
+               
+                                       break;
+               //orphan scan
+               case ORPHAN_SCAN:
+               
+                                       call TimerAsync.set_timers_enable(0x01);
+                                       
+                                   scan_duration = 4000;
+                                       
+                                       //printfUART("orphan cts %y sdur %i\n", channels_to_scan,scan_duration); 
+                                       
+                                       call T_ScanDuration.startOneShot(scan_duration);
+
+                                       break;
+       
+               default:
+                                       break;
+       }
+
+return SUCCESS;
+}
+
+
+
+/*********************************************************/
+/**************MLME_ORPHAN********************************/
+/*********************************************************/
+
+command error_t MLME_ORPHAN.response(uint32_t OrphanAddress[1],uint16_t ShortAddress,uint8_t AssociatedMember, uint8_t security_enabled)
+{
+
+       if (AssociatedMember==0x01)
+       {
+               create_coordinator_realignment_cmd(OrphanAddress[0], OrphanAddress[1], ShortAddress);
+       }
+       
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_SYNC********************************/
+/*********************************************************/
+
+
+command error_t MLME_SYNC.request(uint8_t logical_channel,uint8_t track_beacon)
+{
+
+call PLME_SET.request(PHYCURRENTCHANNEL,LOGICAL_CHANNEL);      
+       //call PLME_SET.request(PHYCURRENTCHANNEL,logical_channel);     
+       
+       call TimerAsync.set_timers_enable(0x01);
+       
+       //printfUART("sync req\n", ""); 
+       
+       atomic findabeacon = 1;
+
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_RESET********************************/
+/*********************************************************/
+
+
+command error_t MLME_RESET.request(uint8_t set_default_PIB)
+{
+
+
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_GTS***********************************/
+/*********************************************************/
+
+command error_t MLME_GTS.request(uint8_t GTSCharacteristics, bool security_enable)
+{
+
+       //uint32_t wait_time;
+       //if there is no short address asigned the node cannot send a GTS request
+       if (mac_PIB.macShortAddress == 0xffff)
+                       signal MLME_GTS.confirm(GTSCharacteristics,MAC_NO_SHORT_ADDRESS);
+       
+       //gts_ack=1;
+       
+       gts_request =1;
+       
+       create_gts_request_cmd(GTSCharacteristics);
+
+return SUCCESS;
+}
+
+
+/*********************************************************/
+/**************MLME_START*********************************/
+/*********************************************************/
+
+command error_t MLME_START.request(uint32_t PANId, uint8_t LogicalChannel, uint8_t beacon_order, uint8_t superframe_order,bool pan_coodinator,bool BatteryLifeExtension,bool CoordRealignment,bool securityenable,uint32_t StartTime)
+{
+
+       uint32_t BO_EXPONENT;
+       uint32_t SO_EXPONENT;
+
+       //////////printfUART("MLME_START.request\n", "");
+       //pag 102
+       atomic {
+       PANCoordinator=1;
+       Beacon_enabled_PAN=1;
+       //TEST
+       //atomic mac_PIB.macShortAddress = 0x0000;
+
+
+               if ( mac_PIB.macShortAddress == 0xffff)
+               {
+               
+                       signal MLME_START.confirm(MAC_NO_SHORT_ADDRESS);
+                       return SUCCESS;
+               }
+               else
+               {
+                       atomic mac_PIB.macBeaconOrder = beacon_order;
+                       
+                       if (beacon_order == 15) 
+                               atomic mac_PIB.macSuperframeOrder = 15;
+                       else
+                               atomic mac_PIB.macSuperframeOrder = superframe_order;
+               
+               
+                       //PANCoordinator is set to TRUE
+                       if (pan_coodinator == 1)
+                       {
+                               atomic mac_PIB.macPANId = PANId;
+                               call PLME_SET.request(PHYCURRENTCHANNEL,LogicalChannel);
+                       }
+                       if (CoordRealignment == 1)
+                       {
+                               //generates and broadcasts a coordinator realignment command containing the new PANId and LogicalChannels
+                       }
+                       if (securityenable == 1)
+                       {
+                       //security parameters
+                       }
+               }
+       
+               if (mac_PIB.macSuperframeOrder == 0)
+                       SO_EXPONENT = 1;
+               else
+               {
+                       SO_EXPONENT = powf(2,mac_PIB.macSuperframeOrder);
+               
+               }
+               if ( mac_PIB.macBeaconOrder == 0)
+                       BO_EXPONENT = 1;
+               else
+               {
+                       BO_EXPONENT = powf(2,mac_PIB.macBeaconOrder);
+               
+               }       
+       }
+       
+       BI = aBaseSuperframeDuration * BO_EXPONENT; 
+               
+       SD = aBaseSuperframeDuration * SO_EXPONENT; 
+       //backoff_period
+       backoff = aUnitBackoffPeriod;
+
+       
+       atomic time_slot = SD / NUMBER_TIME_SLOTS;
+
+       call TimerAsync.set_backoff_symbols(backoff);
+
+       call TimerAsync.set_bi_sd(BI,SD);
+       
+       atomic{
+       
+               call TimerAsync.set_timers_enable(0x01);
+               
+               call TimerAsync.reset();
+               
+       }
+               
+       signal MLME_START.confirm(MAC_SUCCESS);
+
+       return SUCCESS;
+}
+
+/*************************************************************/
+/**************MLME_ASSOCIATE*********************************/
+/*************************************************************/
+
+command error_t MLME_ASSOCIATE.request(uint8_t LogicalChannel,uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation,bool securityenable)
+{
+       //update current channel
+       //call PLME_SET.request(PHYCURRENTCHANNEL,LogicalChannel);
+       
+       
+       printfUART("MLME_ASSOCIATE.request %x %x\n", mac_PIB.macPANId,mac_PIB.macCoordShortAddress);
+       //updates the PAN ID
+       atomic{ 
+               mac_PIB.macPANId = CoordPANId;
+               mac_PIB.macCoordShortAddress = (uint16_t)(CoordAddress[1] & 0x000000ff);
+               }
+               
+               
+       associating=1; //boolean variable stating that the device is trying to associate
+       
+       call TimerAsync.set_timers_enable(1);
+       
+       //the channel selection is made during the SynC procedure
+       //call PLME_SET.request(PHYCURRENTCHANNEL, LogicalChannel);
+
+       current_channel = LogicalChannel;
+       
+       ////printfUART("SELECTED cord id %i\n", mac_PIB.macPANId);
+       ////printfUART("CoordAddress %i\n", mac_PIB.macCoordShortAddress);
+       ////printfUART("LogicalChannel %i\n", LogicalChannel);
+       ////printfUART("Cordaddr %i\n",CoordAddress[0]);
+       ////printfUART("Cordaddr %i\n",CoordAddress[1]);
+       /*
+
+       a_CoordAddrMode = CoordAddrMode;
+       a_CoordPANId=CoordPANId;
+       a_CoordAddress[0]=CoordAddress[0];
+       a_CoordAddress[1]=CoordAddress[1];
+       a_CapabilityInformation=CapabilityInformation;
+       a_securityenable=securityenable;
+       */
+       create_association_request_cmd(CoordAddrMode,CoordPANId,CoordAddress,CapabilityInformation);
+       
+       return SUCCESS;
+}
+
+command error_t MLME_ASSOCIATE.response(uint32_t DeviceAddress[], uint16_t AssocShortAddress, uint8_t status, bool securityenable)
+{
+       
+       error_t status_response;
+       
+       ////////printfUART("MAR\n", "");
+       
+       status_response = create_association_response_cmd(DeviceAddress,AssocShortAddress,status);
+       //////////////printfUART("MLME_ASSOCIATE.response\n", "");
+
+
+return SUCCESS;
+}
+
+/*************************************************************/
+/**************MLME_DISASSOCIATE*********************************/
+/*************************************************************/
+
+command error_t MLME_DISASSOCIATE.request(uint32_t DeviceAddress[], uint8_t disassociate_reason, bool securityenable)
+{
+       create_disassociation_notification_cmd(DeviceAddress,disassociate_reason);
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_GET***********************************/
+/*********************************************************/
+command error_t MLME_GET.request(uint8_t PIBAttribute)
+{
+
+       switch(PIBAttribute)
+       {
+               case MACACKWAITDURATION :               signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAckWaitDuration);
+                                                                               break;
+               case MACASSOCIATIONPERMIT:      signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAssociationPermit);
+                                                                               break;
+               case MACAUTOREQUEST :                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAutoRequest);
+                                                                               break;
+               case MACBATTLIFEEXT:                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBattLifeExt);
+                                                                               break;
+               case MACBATTLIFEEXTPERIODS:             signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBattLifeExtPeriods);
+                                                                               break;
+               case MACBEACONPAYLOAD:                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute, mac_PIB.macBeaconPayload);
+                                                                               break;
+               case MACMAXBEACONPAYLOADLENGTH: signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBeaconPayloadLenght);
+                                                                               break;
+               case MACBEACONORDER:                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBeaconOrder);
+                                                                               break;
+               case MACBEACONTXTIME:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *)&mac_PIB.macBeaconTxTime);
+                                                                               break;
+               case MACBSN:                                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBSN);
+                                                                               break;
+               case MACCOORDEXTENDEDADDRESS:   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macCoordExtendedAddress0);
+                                                                               break;
+               case MACCOORDSHORTADDRESS:              signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macCoordShortAddress);
+                                                                               break;
+               case MACDSN:                                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macDSN);
+                                                                               break;
+               case MACGTSPERMIT:                              signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macGTSPermit);
+                                                                               break;
+               case MACMAXCSMABACKOFFS:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macMaxCSMABackoffs);
+                                                                               break;
+               case MACMINBE:                                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macMinBE);
+                                                                               break;
+               case MACPANID:                                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macPANId);
+                                                                               break;
+               case MACPROMISCUOUSMODE:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macPromiscuousMode);
+                                                                               break;
+               case MACRXONWHENIDLE:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macRxOnWhenIdle);
+                                                                               break;
+               case MACSHORTADDRESS:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macShortAddress);
+                                                                               break;
+               case MACSUPERFRAMEORDER:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macSuperframeOrder);
+                                                                               break;
+               case MACTRANSACTIONPERSISTENCETIME:     signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macTransactionPersistenceTime);
+                                                                                       break;
+                                                                                       
+               default:                                                signal MLME_GET.confirm(MAC_UNSUPPORTED_ATTRIBUTE,PIBAttribute,0x00);
+                                                                               break;
+       }
+
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_SET***********************************/
+/*********************************************************/
+command error_t MLME_SET.request(uint8_t PIBAttribute,uint8_t PIBAttributeValue[])
+{
+
+//int i;
+
+////printfUART("set %i\n",PIBAttribute);
+
+atomic{
+
+       switch(PIBAttribute)
+       {
+       
+       
+               case MACACKWAITDURATION :               mac_PIB.macAckWaitDuration = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macAckWaitDuration: %x\n",mac_PIB.macAckWaitDuration);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                       
+               case MACASSOCIATIONPERMIT:      if ((uint8_t)PIBAttributeValue[1] == 0x00)
+                                                                               {
+                                                                                       mac_PIB.macAssociationPermit = 0x00;
+                                                                               }
+                                                                               else
+                                                                               {
+                                                                                       mac_PIB.macAssociationPermit = 0x01;
+                                                                               }
+                                                                               //////////printfUART("mac_PIB.macAssociationPermit: %i %y\n",mac_PIB.macAssociationPermit,PIBAttributeValue[1]);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACAUTOREQUEST :                   mac_PIB.macAutoRequest = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macAutoRequest: %i\n",mac_PIB.macAutoRequest);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACBATTLIFEEXT:                    mac_PIB.macBattLifeExt = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macBattLifeExt %i\n",mac_PIB.macBattLifeExt);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACBATTLIFEEXTPERIODS:             mac_PIB.macBattLifeExtPeriods = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macBattLifeExtPeriods %i\n",mac_PIB.macBattLifeExtPeriods);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACBEACONPAYLOAD:                  /*for(i=0;i < mac_PIB.macBeaconPayloadLenght;i++) 
+                                                                               {
+                                                                                       mac_PIB.macBeaconPayload[i] = PIBAttributeValue[i];
+                                                                               }*/
+                                                                       
+                                                                               memcpy(&PIBAttributeValue[0],&mac_PIB.macBeaconPayload[0],mac_PIB.macBeaconPayloadLenght * sizeof(uint8_t));
+                                                                               
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                               
+               case MACMAXBEACONPAYLOADLENGTH: mac_PIB.macBeaconPayloadLenght = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macBeaconPayloadLenght %i\n",mac_PIB.macBeaconPayloadLenght);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACBEACONORDER:                    mac_PIB.macBeaconOrder = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macBeaconOrder %i\n",mac_PIB.macBeaconOrder);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACBEACONTXTIME:                   mac_PIB.macBeaconTxTime =PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macBeaconTxTime %i\n",mac_PIB.macBeaconTxTime);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACBSN:                                    mac_PIB.macBSN = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macBSN %i\n",mac_PIB.macBSN);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+
+               case MACCOORDEXTENDEDADDRESS:   //mac_PIB.macCoordExtendedAddress0 = ((PIBAttributeValue[0] >> 24) | (PIBAttributeValue[1] >> 16) | (PIBAttributeValue[2] >> 8) | (PIBAttributeValue[3])) ;
+                                                                               //mac_PIB.macCoordExtendedAddress1 = ((PIBAttributeValue[4] >> 24) | (PIBAttributeValue[5] >> 16) | (PIBAttributeValue[6] >> 8) | (PIBAttributeValue[7]));
+
+                                                                               ////////////printfUART("mac_PIB.macCoordExtendedAddress0 %y\n",mac_PIB.macCoordExtendedAddress0);
+                                                                               ////////////printfUART("mac_PIB.macCoordExtendedAddress1 %y\n",mac_PIB.macCoordExtendedAddress1);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+                                                                       
+               case MACCOORDSHORTADDRESS:              mac_PIB.macCoordShortAddress= ((PIBAttributeValue[0] << 8) |PIBAttributeValue[1]);
+                                                                               ////printfUART("mac_PIB.macCoordShortAddress: %x\n",mac_PIB.macCoordShortAddress);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               
+               case MACDSN:                                    mac_PIB.macDSN = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macDSN: %x\n",mac_PIB.macDSN);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACGTSPERMIT:                              mac_PIB.macGTSPermit = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macGTSPermit: %x\n",mac_PIB.macGTSPermit);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACMAXCSMABACKOFFS:                mac_PIB.macMaxCSMABackoffs = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macMaxCSMABackoffs: %x\n",mac_PIB.macMaxCSMABackoffs);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACMINBE:                                  mac_PIB.macMinBE = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macMinBE: %x\n",mac_PIB.macMinBE);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               
+               case MACPANID:                                  mac_PIB.macPANId = ((PIBAttributeValue[0] << 8)| PIBAttributeValue[1]);
+                                                                               ////printfUART("mac_PIB.macPANId: %x\n",mac_PIB.macPANId);
+                                                                               
+                                                                               
+                                                                               call AddressFilter.set_coord_address(mac_PIB.macCoordShortAddress, mac_PIB.macPANId);
+                                                                               
+                                                                               
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               
+               case MACPROMISCUOUSMODE:                mac_PIB.macPromiscuousMode = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macPromiscuousMode: %x\n",mac_PIB.macPromiscuousMode);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACRXONWHENIDLE:                   mac_PIB.macRxOnWhenIdle = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macRxOnWhenIdle: %x\n",mac_PIB.macRxOnWhenIdle);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+                                                                               
+               case MACSHORTADDRESS:                   mac_PIB.macShortAddress = ((PIBAttributeValue[0] << 8) |PIBAttributeValue[1]);
+                                                                               ////printfUART("mac_PIB.macShortAddress: %y\n",mac_PIB.macShortAddress);
+                                                                               
+                                                                               call AddressFilter.set_address(mac_PIB.macShortAddress, aExtendedAddress0, aExtendedAddress0);
+                                                                               
+                                                                               
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACSUPERFRAMEORDER:                mac_PIB.macSuperframeOrder = PIBAttributeValue[0];
+                                                                               ////////////printfUART("mac_PIB.macSuperframeOrder: %x\n",mac_PIB.macSuperframeOrder);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACTRANSACTIONPERSISTENCETIME:      mac_PIB.macTransactionPersistenceTime = PIBAttributeValue[0];
+                                                                                        ////////////printfUART("mac_PIB.macTransactionPersistenceTime: %y\n",mac_PIB.macTransactionPersistenceTime);
+                                                                                        signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                                        break;
+                                                                                       
+               default:                                                signal MLME_SET.confirm(MAC_UNSUPPORTED_ATTRIBUTE,PIBAttribute);
+                                                                               break;
+                                                                               
+               
+       }
+
+}
+
+return SUCCESS;
+}
+/*************************************************************/
+/**************        MCPS - DATA         *******************/
+/*************************************************************/
+
+command error_t MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions)
+{
+       int i;
+       //uint8_t valid_gts=0;
+       uint32_t total_ticks;
+       
+       ////////printfUART("MCPS_DATA.request\n", ""); 
+       //check conditions on page 58
+       
+       //atomic mac_PIB.macShortAddress = TOS_LOCAL_ADDRESS;
+       
+       /*
+       ////printfUART("SrcAddrMode %x\n", SrcAddrMode);
+       ////printfUART("SrcPANId %x\n", SrcPANId);
+       ////printfUART("SrcAddr %x\n", SrcAddr[0]);
+       ////printfUART("SrcAddr %x\n", SrcAddr[1]);
+       ////printfUART("DstAddrMode %x\n", DstAddrMode);
+       ////printfUART("DestPANId %x\n", DestPANId);
+       ////printfUART("DstAddr %x\n", DstAddr[0]);
+       ////printfUART("DstAddr %x\n", DstAddr[1]);
+       ////printfUART("msduLength %x\n", msduLength);
+       ////printfUART("msduHandle %x\n", msduHandle);
+       ////printfUART("TxOptions %x\n", TxOptions);
+               */
+       
+       atomic{
+       
+       if (mac_PIB.macShortAddress == 0xffff)
+               return FAIL;
+       }
+       
+       if(PANCoordinator == 1)
+       {
+       //PAN COORDINATOR OPERATION
+               //////////////printfUART("GTS TRANS: %i TxOptions: %u dest:%u\n", get_txoptions_gts(TxOptions),TxOptions,DstAddr[1]); 
+               
+               if (get_txoptions_gts(TxOptions) == 1)
+               {
+               //GTS TRANSMISSION
+                       for (i=0 ; i < 7 ; i++)
+                       {
+                               //SEARCH FOR A VALID GTS
+                               if ( GTS_db[i].DevAddressType == (uint16_t)DstAddr[1] && GTS_db[i].direction == 1 && GTS_db[i].gts_id != 0)
+                               {
+                                       
+                               //atomic{
+                                               //////////////printfUART("BUFFER UNTIL GTS SLOT n: %i ss: %i\n",number_time_slot,GTS_db[valid_gts].starting_slot);
+                                               create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,GTS_db[i].starting_slot,1);
+                                       //}
+                                       return SUCCESS;
+                                       break;
+                               }
+                       }
+                       signal MCPS_DATA.confirm(msduHandle, MAC_INVALID_GTS);
+                       return FAIL;
+               }
+               else
+               {
+               //NORMAL/INDIRECT TRANSMISSION
+               
+                       //////////////printfUART("IND TRANS: %i TxOptions: %u\n", get_txoptions_indirect_transmission(TxOptions),TxOptions);
+                       //check if its an indirect transmission
+                       //if ( get_txoptions_indirect_transmission(TxOptions) == 1)
+                       //{
+                               //INDIRECT TRANSMISSION
+                               
+                               //////////////printfUART("CREATE INDIRECT TRANSMISSION\n","");
+                               
+                               
+                               
+                               
+                       //}
+                       //else
+                       //{
+                               //NORMAL TRANSMISSION
+                               ////printfUART("SEND NO GTS NO IND\n","");
+                               create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,0,0);
+                       //}
+               }
+       }
+       else
+       {
+       //NON PAN COORDINATOR OPERATION
+               atomic{
+                               
+                               //////////////printfUART("sslot: %i ini %i\n",s_GTSss,init_s_GTSss);
+                               //check if it a gts transmission
+                               if (get_txoptions_gts(TxOptions) == 1)
+                               {
+                               //GTS TRANSMISSION
+                                       if (s_GTSss == 0x00)
+                                       {
+                                               //////////////printfUART("NO VALID GTS \n","");
+                                               signal MCPS_DATA.confirm(msduHandle, MAC_INVALID_GTS);
+                                       }
+                                       else
+                                       {
+                                                       total_ticks = call TimerAsync.get_total_tick_counter();
+                                                       msdu[0] =(uint8_t)(total_ticks >> 0 );
+                                                       msdu[1] =(uint8_t)(total_ticks >> 8);
+                                                       msdu[2] =(uint8_t)(total_ticks >> 16);
+                                                       msdu[3] =(uint8_t)(total_ticks >> 24);
+                                                       
+                                                       if (on_sync == 1 && s_GTSss > 0)
+                                                       create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,s_GTSss,0);
+                                       }
+                               }
+                               else
+                               {
+                               //NORMAL TRANSMISSION
+                                       //printfUART("TRnsm\n","");
+                                       create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,0,0);
+                               }
+                       }
+       }
+       return SUCCESS;
+}
+
+
+
+
+/*************************************************************/
+/**************        MCPS - PURGE         *******************/
+/*************************************************************/
+
+command error_t MCPS_PURGE.request(uint8_t msduHandle)
+{
+
+
+
+return SUCCESS;
+}
+
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/************************              OTHER FUNCTIONS                         **********************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+
+task void signal_loss()
+{
+       //TODO
+       atomic signal MLME_SYNC_LOSS.indication(beacon_loss_reason); //MAC_BEACON_LOSS
+       return;
+}
+
+//inicialization of the mac constants
+void init_MacCon()
+{
+/*****************************************************/
+/*                             Boolean Variables                                        */
+/*****************************************************/  
+PANCoordinator = 0;
+//(0 NO beacon transmission; 1 beacon transmission);
+Beacon_enabled_PAN = 0;
+//(SYNC)the device will try to track the beacon ie enable its receiver just before the espected time of each beacon
+TrackBeacon=0;
+//(SYNC)the device will try to locate one beacon
+findabeacon=0;
+//(RESET) when the reset command arrives it checks whether or not to reset the PIB
+SetDefaultPIB=0;
+/*****************************************************/
+/*                             Integer Variables                                        */
+/*****************************************************/  
+/*
+//Beacon Interval
+uint32_t BI;
+//Superframe duration
+uint32_t SD;
+*/
+//(SYNC)number of beacons lost before sending a Beacon-Lost indication comparing to aMaxLostBeacons
+missed_beacons=0;
+//current_channel
+current_channel=0;
+
+
+/*****************************************************/
+/*                             Other Variables                                  */
+/*****************************************************/ 
+pending_reset=0;
+
+}
+
+//inicialization of the mac PIB
+void init_MacPIB()
+{
+
+atomic{
+       //mac PIB default values
+       
+       //mac_PIB.macAckWaitDuration = 54; OLD VALUE//Number os symbols to wait for an acknowledgment
+       mac_PIB.macAckWaitDuration = 65;
+       
+       mac_PIB.macAssociationPermit = 1; //1 - PAN allowing associations
+       mac_PIB.macAutoRequest = 1; //indication if a device automatically sends a data request command if address is listed in the beacon frame
+       
+       mac_PIB.macBattLifeExt= 0; //batery life extension CSMA-CA
+       
+       mac_PIB.macBattLifeExtPeriods=6;
+       //mac_PIB.macBeaconPayload; //payload of the beacon
+       mac_PIB.macBeaconPayloadLenght=0; //beacon payload lenght
+       
+       mac_PIB.macBeaconTxTime=(0xffffff << 24); //*****
+       
+       
+       mac_PIB.macBSN=call Random.rand16(); //sequence number of the beacon frame
+       
+       
+       mac_PIB.macCoordExtendedAddress0 = 0x00000000; //64bits address of the coordinator with witch the device is associated
+       mac_PIB.macCoordExtendedAddress1 = 0x00000000;
+       
+       mac_PIB.macCoordShortAddress = 0x0000; //16bits address of the coordinator with witch the device is associated
+       
+       /*
+       if (DEVICE_DEPTH == 0x01)
+               mac_PIB.macCoordShortAddress =D1_PAN_SHORT;
+       if (DEVICE_DEPTH == 0x02)
+               mac_PIB.macCoordShortAddress =D2_PAN_SHORT;
+       if (DEVICE_DEPTH == 0x03)
+               mac_PIB.macCoordShortAddress =D3_PAN_SHORT;
+       if (DEVICE_DEPTH == 0x04)
+               mac_PIB.macCoordShortAddress =D4_PAN_SHORT;
+       */
+       
+       mac_PIB.macDSN=call Random.rand16(); //sequence number of the transmited data or MAC command frame
+       
+       //alowing gts requests (used in beacon)
+       mac_PIB.macGTSPermit=1; //
+       
+       //Number of maximum CSMA backoffs
+       mac_PIB.macMaxCSMABackoffs=4;
+       mac_PIB.macMinBE=0;
+       
+       //mac_PIB.macPANId=0xffff; //16bits identifier of the PAN on witch this device is operating
+       mac_PIB.macPANId = MAC_PANID;
+       
+       mac_PIB.macPromiscuousMode=0;
+       mac_PIB.macRxOnWhenIdle=0;
+       //mac_PIB.macShortAddress=TOS_LOCAL_ADDRESS; //16bits short address
+       mac_PIB.macShortAddress=0xffff;
+
+
+       mac_PIB.macBeaconOrder=7;  //specification of how often the coordinator transmits a beacon
+       mac_PIB.macSuperframeOrder=3;
+       
+       //default mac_PIB.macTransactionPersistenceTime=0x01f4;
+       mac_PIB.macTransactionPersistenceTime=0x0010;
+       
+       //*******************************************
+
+       }
+}
+
+//////////////////////////////////////////////////////////////
+////////////////////////CSMA-CA functions////////////////////
+/////////////////////////////////////////////////////////////
+
+/*****************************************************/
+/*                             SEND FRAME FUNCTION                      */
+/*****************************************************/ 
+
+task void send_frame_csma()
+{
+       atomic{
+       
+               //
+               /////printfUART("I_AM_IN_IP %i %i\n",I_AM_IN_IP,send_buffer_count);
+       
+               if ((send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE && performing_csma_ca == 0) || I_AM_IN_IP != 0)
+               {
+                       //////printfUART("sf %i\n",send_buffer_count);
+                       ////////printfUART("peform\n","");
+                       
+                       performing_csma_ca = 1;
+
+                       perform_csma_ca();
+               }
+               else
+               {
+                       ////printfUART("NOT SEND\n","");
+               }
+
+               
+       }
+       
+}
+
+
+task void perform_csma_ca_slotted()
+{
+       uint8_t random_interval;
+       
+               
+               
+               //DEFERENCE CHANGE
+               if (check_csma_ca_send_conditions(send_buffer[send_buffer_msg_out].length,send_buffer[send_buffer_msg_out].frame_control1) == 1 )
+               {
+                       cca_deference = 0;
+               }
+               else
+               {
+                       //nao e necessario
+                       cca_deference = 1;
+                       return;
+               }
+               
+       atomic{
+               ////printfUART("CCA: %i\n", call CCA.get()) ;
+       
+               if(call CCA.get() == CCA_BUSY )
+               {
+                       //////////////printfUART("CCA: 1\n", "") ;
+                       //STEP 5
+                       CW--;
+                       if (CW == 0 )
+                       {
+                               //send functions
+                               csma_cca_backoff_boundary =0;
+                                       
+                                       ////////printfUART("rts %i\n",get_ack_request(send_buffer[send_buffer_msg_out].frame_control));
+
+                                               //verify if the message must be ack
+                                               if ( get_fc1_ack_request(send_buffer[send_buffer_msg_out].frame_control1) == 1 )
+                                               {
+                                                       send_ack_check=1;
+                                                       ack_sequence_number_check=send_buffer[send_buffer_msg_out].seq_num;     
+                                                       //verify retransmission
+                                                       send_retransmission = send_buffer[send_buffer_msg_out].retransmission;
+                                                       //verify if its an indirect transmission
+                                                       send_indirect_transmission = send_buffer[send_buffer_msg_out].indirect;
+                                                       //SEND WITH ACK_REQUEST
+                                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
+                                                       
+                                                       ////////printfUART("out ck\n","");
+                                                       
+                                                       
+                                                       call T_ackwait.startOneShot(ackwait_period);
+                                               }
+                                               else
+                                               {
+                                               
+                                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
+                                                       
+                                                       send_buffer_count --;
+                                                       send_buffer_msg_out++;
+                                               
+                                                       //failsafe
+                                                       if(send_buffer_count > SEND_BUFFER_SIZE)
+                                                       {
+                                                               send_buffer_count =0;
+                                                               send_buffer_msg_out=0;
+                                                               send_buffer_msg_in=0;
+                                                       }
+                                                       
+                                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                                               send_buffer_msg_out=0;
+                                                       
+                                                       if (send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE)
+                                                               post send_frame_csma();
+                                                       
+                                                       ////printfUART("sk %i\n",send_buffer_count);
+                                                       
+                                                       //////////printfUART("%i %i %i\n",send_buffer_count,send_buffer_msg_in,send_buffer_msg_out);
+                                               }
+                                       
+                               performing_csma_ca = 0;
+                       }
+               }
+               else
+               {
+                       //CHECK NOT USED
+                       //csma_backoff_counter++;
+                       //csma_backoff_counter_inst++;
+
+                       if (NB < mac_PIB.macMaxCSMABackoffs)
+                       {
+                               ////////////printfUART("NB:%i BE:%i L CW: %i\n",NB,BE,CW);
+                               //STEP 4
+                               CW = 2;
+                               NB++;
+                               BE = min(BE+1,aMaxBE);
+                               
+                               //STEP 2
+                               //random_interval = pow(2,BE) - 1;
+                               
+                               //delay_backoff_period = (call Random.rand() & random_interval);
+                               //verification of the backoff_deference
+                               //DEFERENCE CHANGE
+                               if (backoff_deference == 0)
+                               {
+                                       random_interval = powf(2,BE) - 1;
+                                       delay_backoff_period = (call Random.rand16() & random_interval );
+                                               
+                                       if (check_csma_ca_backoff_send_conditions((uint32_t) delay_backoff_period) == 1)
+                                       {
+                                                       backoff_deference = 1;
+                                       }
+                               }
+                               else
+                               {
+                                       backoff_deference = 0;
+                               }
+                               
+                               
+                               //delay_backoff_period=0;
+                               
+                               ////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
+                               csma_delay=1;
+                       }
+                       else
+                       {
+                               //CSMA/CA FAIL
+                               csma_delay=0;
+                               csma_cca_backoff_boundary=0;
+                               
+                               send_buffer_count --;
+                               send_buffer_msg_out++;
+                       
+                               //failsafe
+                               if(send_buffer_count > SEND_BUFFER_SIZE)
+                               {
+                                       send_buffer_count =0;
+                                       send_buffer_msg_out=0;
+                                       send_buffer_msg_in=0;
+                               }
+                               
+                               if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                       send_buffer_msg_out=0;
+                               
+                               if (send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE)
+                                       post send_frame_csma();
+                                       
+                               performing_csma_ca = 0;
+                               
+                               ////printfUART("SLOTTED FAIL\n","");
+                               /*
+                               if(associating == 1)
+                               {
+                                       associating=0;
+                                       signal MLME_ASSOCIATE.confirm(0x0000,MAC_CHANNEL_ACCESS_FAILURE);
+                               }*/
+                       }
+               }
+       }
+return;
+}
+
+task void perform_csma_ca_unslotted()
+{
+       uint8_t random_interval;
+       
+       atomic{
+               if (NB < mac_PIB.macMaxCSMABackoffs)
+               {
+                       //STEP 3
+                       //perform CCA
+                       ////////////printfUART("CCA: %i\n", TOSH_READ_CC_CCA_PIN()) ;
+                       
+                       //if CCA is clear send message
+                       if(call CCA.get() == CCA_BUSY)
+                       {
+                               //send functions
+                               ////////////printfUART("UNSLOTTED SUCCESS\n","");
+                               atomic{
+                               csma_delay =0;
+                               
+
+                                               
+                               if (check_csma_ca_send_conditions(send_buffer[send_buffer_msg_out].length,send_buffer[send_buffer_msg_out].frame_control1) == 1 )
+                               {
+                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
+                                       
+                                       send_buffer_count --;
+                                       send_buffer_msg_out++;
+                               
+                                       //failsafe
+                                       if(send_buffer_count > SEND_BUFFER_SIZE)
+                                       {
+                                               send_buffer_count =0;
+                                               send_buffer_msg_out=0;
+                                               send_buffer_msg_in=0;
+                                       }
+                               
+                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                               send_buffer_msg_out=0;
+                               }
+                                       
+                               
+                               performing_csma_ca =0;
+
+                               }
+                               return; //SUCCESS
+                       
+                       }
+
+                       //CCA is not clear, perform new iteration of the CSMA/CA UNSLOTTED
+                       
+                       //STEP 4
+                       NB++;
+                       BE = min(BE+1,aMaxBE);
+               
+                       ////////////printfUART("NB:%i BE:%i\n",NB,BE);
+                       
+                       //STEP 2
+                       //#ifdef PLATFORM_MICAZ
+                               random_interval = powf(2,BE) - 1;
+                       //#else
+                       //      random_interval = powf(2,BE) - 1;
+                       //#endif
+                       delay_backoff_period = (call Random.rand16() & random_interval );
+                       //delay_backoff_period=1;
+                       csma_delay=1;
+                       
+                       //////////////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
+               }
+               else
+               {
+                       atomic csma_delay=0;
+                       ////////////printfUART("UNSLOTTED FAIL\n","");
+               }
+       }
+return;
+}
+
+
+void perform_csma_ca()
+{
+       uint8_t random_interval;
+       csma_slotted=1;
+       //STEP 1
+       if (csma_slotted == 0 )
+       {
+               atomic{
+                       //UNSLOTTED version
+                       init_csma_ca(csma_slotted);
+                       //STEP 2
+                       random_interval = powf(2,BE) - 1;
+                       delay_backoff_period = (call Random.rand16() & random_interval );
+                       
+                       csma_delay=1;
+                       ////////////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
+               }
+               return;
+       }
+       else
+       {
+               //SLOTTED version
+               atomic{
+                       //DEFERENCE CHANGE
+                       if (cca_deference==0)
+                       {
+                               init_csma_ca(csma_slotted);
+                               if (mac_PIB.macBattLifeExt == 1 )
+                               {
+                                       BE = min(2,     mac_PIB.macMinBE);
+                               }
+                               else
+                               {
+                                       BE = mac_PIB.macMinBE;
+                               }
+                               csma_locate_backoff_boundary = 1;
+                       }
+                       else
+                       {
+                               cca_deference = 0;
+                               csma_delay=0;
+                               csma_locate_backoff_boundary=0;
+                               csma_cca_backoff_boundary = 1;
+                       
+                       }
+               }
+               return;
+       }
+}
+
+
+uint8_t min(uint8_t val1, uint8_t val2)
+{
+       if (val1 < val2)
+       {
+               return val1;
+       }
+       else
+       {
+               return val2;
+       }
+}
+
+void init_csma_ca(bool slotted)
+{
+
+//initialization of the CSMA/CA protocol variables
+       //////////////printfUART("init_csma_ca\n", "") ;
+       
+       csma_delay=0;
+       
+       if (slotted == 0 )
+       {
+               NB=0;
+               BE=mac_PIB.macMinBE;
+       }
+       else
+       {
+               NB=0;
+               CW=2;
+               
+               csma_cca_backoff_boundary=0;
+               csma_locate_backoff_boundary=0;
+       }
+
+return;
+}
+
+
+uint8_t calculate_ifs(uint8_t pk_length)
+{
+       if (pk_length > aMaxSIFSFrameSize)
+               return aMinLIFSPeriod; // + ( ((pk_length * 8) / 250.00) / 0.34 );
+       else
+               return aMinSIFSPeriod; // + ( ((pk_length * 8) / 250.00) / 0.34 );
+}
+
+uint32_t calculate_gts_expiration()
+{
+       uint32_t exp_res;
+       if( mac_PIB.macBeaconOrder > 9 )
+               exp_res= 1;
+       else
+       {
+               //#ifdef PLATFORM_MICAZ
+                       exp_res= powf(2,(8-mac_PIB.macBeaconOrder));
+               //#else
+               //      exp_res= powf(2,(8-mac_PIB.macBeaconOrder));
+               //#endif
+       }       
+       ////////////printfUART("alculat %i\n",exp_res ) ;
+       return exp_res;
+}
+
+uint8_t check_csma_ca_send_conditions(uint8_t frame_length,uint8_t frame_control1)
+{
+       uint8_t ifs_symbols;
+       uint32_t frame_tx_time;
+       uint32_t remaining_gts_duration;
+       
+       
+       ifs_symbols=calculate_ifs(frame_length);
+       //wait_ifs=1;
+       //call TimerAsync.set_ifs_symbols(ifs_symbols);
+       
+       //////////////printfUART("ifs_symbols %i\n",ifs_symbols ) ;
+       
+       if (get_fc1_ack_request(frame_control1) == 1 )
+               frame_tx_time =  frame_length + ACK_LENGTH + aTurnaroundTime + ifs_symbols;
+       else
+               frame_tx_time =  frame_length + ifs_symbols;
+               
+       atomic remaining_gts_duration = time_slot - ( call TimerAsync.get_current_number_backoff_on_time_slot() * aUnitBackoffPeriod);
+       
+       //////////////printfUART("frame_tx %d remaing %d\n",frame_tx_time,remaining_gts_duration ) ;
+       
+       if (frame_tx_time < remaining_gts_duration)
+               return 1;
+       else
+               return 0;
+
+}
+
+//DEFERENCE CHANGE
+uint8_t check_csma_ca_backoff_send_conditions(uint32_t delay_backoffs)
+{
+
+       uint32_t number_of_sd_ticks=0;
+       uint32_t current_ticks=0;
+       uint32_t ticks_remaining =0;
+       uint32_t number_of_backoffs_remaining =0;
+       
+       number_of_sd_ticks = call TimerAsync.get_sd_ticks();
+       
+       current_ticks = call TimerAsync.get_current_ticks();
+       
+       ticks_remaining = number_of_sd_ticks - current_ticks;
+       
+       number_of_backoffs_remaining = ticks_remaining / 5;
+       
+       if (number_of_backoffs_remaining > delay_backoffs)
+               return 0;
+       else
+               return 1;
+
+
+
+}
+
+uint8_t check_gts_send_conditions(uint8_t frame_length)
+{
+       uint8_t ifs_symbols;
+       uint32_t frame_tx_time;
+       uint32_t remaining_gts_duration;
+       
+
+       ifs_symbols=calculate_ifs(frame_length);
+       //wait_ifs=1;
+       //call TimerAsync.set_ifs_symbols(ifs_symbols);
+       
+       //////////////printfUART("ifs_symbols %i\n",ifs_symbols ) ;
+       
+       frame_tx_time =  frame_length + ACK_LENGTH + aTurnaroundTime + ifs_symbols;
+       
+       remaining_gts_duration = time_slot - ( call TimerAsync.get_current_number_backoff_on_time_slot() * aUnitBackoffPeriod);
+       
+       //////////////printfUART("frame_tx %d remaing %d\n",frame_tx_time,remaining_gts_duration ) ;
+       
+       if (frame_tx_time < remaining_gts_duration)
+               return 1;
+       else
+               return 0;
+}
+
+//////////////////////////////////////////////////////////////
+////////////////////////GTS functions////////////////////////
+/////////////////////////////////////////////////////////////
+
+void init_GTS_db()
+{
+       //initialization of the GTS database
+       int i;
+atomic{
+               for (i=0 ; i < 7 ; i++)
+               {
+                       GTS_db[i].gts_id=0x00;
+                       GTS_db[i].starting_slot=0x00;
+                       GTS_db[i].length=0x00;
+                       GTS_db[i].direction=0x00;
+                       GTS_db[i].DevAddressType=0x0000;
+               
+               }
+       }
+return;
+}
+
+error_t remove_gts_entry(uint16_t DevAddressType)
+{
+       uint8_t r_lenght=0;
+       //int r_start_slot=7;
+       int i;
+       
+       atomic{
+               for (i=0; i < 7 ; i++)
+               {
+                       if( GTS_db[i].DevAddressType == DevAddressType )
+                       {
+                               
+                               r_lenght = GTS_db[i].length;
+                               //r_start_slot = i;
+                               //delete the values
+                               GTS_db[i].gts_id=0x00;
+                               GTS_db[i].starting_slot=0x00;
+                               GTS_db[i].length=0x00;
+                               GTS_db[i].direction=0x00;
+                               GTS_db[i].DevAddressType=0x0000;
+                               GTS_db[i].expiration=0x00;
+                               
+                               //////////////printfUART("GTS Entry removed dev:%i len:%i pos %i\n", DevAddressType,r_lenght,i);
+                               GTS_startslot = GTS_startslot + r_lenght;
+                               GTS_descriptor_count--;
+                               final_CAP_slot = final_CAP_slot + r_lenght;
+                       }
+                       
+                       if ( r_lenght > 0)
+                       {
+                               if ( GTS_db[i].gts_id != 0x00 && GTS_db[i].DevAddressType !=0x0000)
+                               {                               
+                                       GTS_db[i-r_lenght].gts_id = GTS_db[i].gts_id;
+                                       GTS_db[i-r_lenght].starting_slot = i-r_lenght;
+                                       GTS_db[i-r_lenght].length = GTS_db[i].length;
+                                       GTS_db[i-r_lenght].direction = GTS_db[i].direction;
+                                       GTS_db[i-r_lenght].DevAddressType = GTS_db[i].DevAddressType;
+                                       GTS_db[i-r_lenght].expiration = GTS_db[i].expiration;
+                                       
+                                       //delete the values
+                                       GTS_db[i].gts_id=0x00;
+                                       GTS_db[i].starting_slot=0x00;
+                                       GTS_db[i].length=0x00;
+                                       GTS_db[i].direction=0x00;
+                                       GTS_db[i].DevAddressType=0x0000;
+                                       GTS_db[i].expiration=0x00;
+                                       
+                                       //////////////printfUART("UPDATED\n","" );
+                               }
+                       }
+               }
+       }
+return SUCCESS;
+}
+
+error_t add_gts_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType)
+{
+       int i;
+       //////////////printfUART("ADDING gts_length: %i\n", gts_length); 
+       //////////////printfUART("dir: %i\n", direction); 
+       //////////////printfUART("addr: %i\n", DevAddressType);
+
+       //check aMinCAPLength
+       if ( (GTS_startslot - gts_length) < 5 )
+       {
+               //////////////printfUART("ADD FAIL%i\n", ""); 
+               
+       }
+       
+       //if it has more than 7 timeslots alocated
+       if ( (GTS_startslot -gts_length) < 9 )
+       {
+               return FAIL;
+       }
+       
+       //check if the address already exists in the GTS list
+       for (i=0 ; i < 7 ; i++)
+       {
+               if ( GTS_db[i].DevAddressType == DevAddressType && GTS_db[i].direction == direction && GTS_db[i].gts_id > 0)
+               {
+                       //////////////printfUART("ALREADY ADDED\n", ""); 
+                       return FAIL;
+               }
+               if ( GTS_null_db[i].DevAddressType == DevAddressType && GTS_null_db[i].gts_id > 0)
+               {
+                       //////////////printfUART("REJECTED\n", ""); 
+                       return FAIL;
+               }
+               
+               
+       }
+       
+atomic{        
+       
+       //////////////printfUART("GTS_startslot: %i\n", GTS_startslot); 
+       GTS_startslot = GTS_startslot - gts_length;
+
+       GTS_db[15-GTS_startslot].gts_id=GTS_id;
+       GTS_db[15-GTS_startslot].starting_slot=GTS_startslot;
+       GTS_db[15-GTS_startslot].length=gts_length;
+       GTS_db[15-GTS_startslot].direction=direction;
+       GTS_db[15-GTS_startslot].DevAddressType=DevAddressType;
+       GTS_db[15-GTS_startslot].expiration=0x00;
+
+       //////////////printfUART("GTS Entry added start:%i len:%i\n", GTS_startslot,gts_length); 
+       
+       GTS_id++;
+       GTS_descriptor_count++;
+       
+       final_CAP_slot = final_CAP_slot - gts_length;
+       
+       }
+       return SUCCESS;
+}
+
+
+//GTS null functions
+void init_GTS_null_db()
+{
+       //initialization of the GTS database
+       int i;
+       atomic{
+               for (i=0 ; i < 7 ; i++)
+               {
+                       GTS_null_db[i].gts_id=0x00;
+                       GTS_null_db[i].starting_slot=0x00;
+                       GTS_null_db[i].length=0x00;
+                       //GTS_null_db[i].direction=0x00;
+                       GTS_null_db[i].DevAddressType=0x0000;
+                       GTS_null_db[i].persistencetime=0x00;
+               }
+       }
+return;
+}
+
+
+error_t add_gts_null_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType)
+{
+       int i;
+               
+       //check if the address already exists in the GTS list
+       for (i=0 ; i < 7 ; i++)
+       {
+               if ( GTS_null_db[i].DevAddressType == DevAddressType && GTS_null_db[i].gts_id > 0)
+               {
+                       //////////////printfUART("ALREADY ADDED null\n", ""); 
+                       return FAIL;
+               }
+       }
+       
+       for (i=0 ; i < 7 ; i++)
+       {
+               if ( GTS_null_db[i].DevAddressType==0x0000 && GTS_null_db[i].gts_id == 0x00)
+               {
+                       GTS_null_db[i].gts_id=GTS_id;
+                       GTS_null_db[i].starting_slot=0x00;
+                       GTS_null_db[i].length=0x00;
+                       //GTS_null_db[i].direction=0x00;
+                       GTS_null_db[i].DevAddressType=DevAddressType;
+                       GTS_null_db[i].persistencetime=0x00;
+                       
+                       
+                       //////////////printfUART("GTS null Entry added addr:%x\n", DevAddressType); 
+                       
+                       GTS_id++;
+                       GTS_null_descriptor_count++;
+                       
+               return SUCCESS;
+               }
+       }
+
+       
+return FAIL;   
+}
+
+task void increment_gts_null()
+{
+       int i;
+       
+       //////////////printfUART("init inc\n",""); 
+atomic{
+       for (i=0 ; i < 7 ; i++)
+       {
+               if ( GTS_null_db[i].DevAddressType != 0x0000 && GTS_null_db[i].gts_id != 0x00)
+               {
+                       //////////////printfUART("increm %x\n", GTS_null_db[i].DevAddressType); 
+                       GTS_null_db[i].persistencetime++;
+               
+               }
+               
+               if ( GTS_null_db[i].persistencetime > (aGTSDescPersistenceTime -1)  )
+               {
+                       GTS_null_db[i].gts_id=0x00;
+                       GTS_null_db[i].starting_slot=0x00;
+                       GTS_null_db[i].length=0x00;
+                       //GTS_null_db[i].direction=0x00;
+                       GTS_null_db[i].DevAddressType=0x0000;
+                       GTS_null_db[i].persistencetime=0x00;
+                       
+                       //////////////printfUART("GTS null removed addr:%x\n", GTS_null_db[i].DevAddressType); 
+               
+                       atomic GTS_null_descriptor_count--;
+               }
+                       
+       }
+       
+       }
+//////////////printfUART("end inc\n",""); 
+return;
+}
+
+task void check_gts_expiration()
+{
+       int i;
+//////////////printfUART("init exp\n",""); 
+atomic{        
+       atomic gts_expiration=calculate_gts_expiration();
+       //////////////printfUART("gts_expiration:%i\n", gts_expiration); 
+       atomic gts_expiration=2;
+       //////////////printfUART("gts_expiration:%i\n", gts_expiration); 
+       
+       for (i=0 ; i < 7 ; i++)
+       {
+               
+               if ( GTS_db[i].DevAddressType != 0x0000 && GTS_db[i].gts_id != 0x00)
+               {
+                       if( GTS_db[i].expiration == (gts_expiration + 1) && GTS_db[i].direction ==0x00)
+                       {
+                               //////////////printfUART("GTS expired addr:%x\n", GTS_null_db[i].DevAddressType); 
+                               //remove gts, indicate on the gts null list
+                               atomic{
+                               
+                                       add_gts_null_entry(GTS_db[i].length,GTS_db[i].direction,GTS_db[i].DevAddressType);
+                                       
+                                       remove_gts_entry(GTS_db[i].DevAddressType);
+                               }
+                       }
+                       else
+                       {
+                               atomic GTS_db[i].expiration ++;
+                       }
+               }
+       }
+       
+       
+       }
+       //////////////printfUART("end exp\n",""); 
+return;
+}
+
+void init_available_gts_index()
+       {
+               int i=0;
+               atomic{
+                       available_gts_index_count = GTS_SEND_BUFFER_SIZE;
+                       for(i=0;i < GTS_SEND_BUFFER_SIZE;i++)
+                       {
+                               available_gts_index[i]=i;
+                       }
+               }
+               return;
+       }
+/*****************************GTS BUFFER******************************/
+void init_gts_slot_list()
+{
+       int i=0;
+       for(i=0;i<7;i++)
+       {
+               gts_slot_list[i].element_count = 0x00;
+               gts_slot_list[i].element_in = 0x00;
+               gts_slot_list[i].element_out = 0x00;
+       }
+}
+
+
+task void start_coordinator_gts_send()
+{
+atomic{
+
+       coordinator_gts_send_pending_data =0;
+       
+       if(gts_slot_list[15-number_time_slot].element_count > 0)
+       {
+               if (check_gts_send_conditions(gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length) == 1 )
+               {
+                       
+                       gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length = gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length -2;
+                       
+                       call PD_DATA.request(gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length,(uint8_t *)&gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]]);
+       
+                       available_gts_index_count++;
+                       available_gts_index[available_gts_index_count] = gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out];
+                       
+                       gts_slot_list[15-number_time_slot].element_count--;
+                       gts_slot_list[15-number_time_slot].element_out++;
+                       
+                       if (gts_slot_list[15-number_time_slot].element_out == GTS_SEND_BUFFER_SIZE)
+                               gts_slot_list[15-number_time_slot].element_out=0;
+
+                       if(gts_slot_list[15-number_time_slot].element_count > 0 )
+                       {
+                               coordinator_gts_send_pending_data =1;
+                               coordinator_gts_send_time_slot = number_time_slot;
+                       }
+               }
+       }
+}
+return;
+}
+
+task void start_gts_send()
+{
+
+       atomic{
+       gts_send_pending_data = 0;
+       
+       if(gts_send_buffer_count > 0)
+       {
+               if (check_gts_send_conditions(gts_send_buffer[gts_send_buffer_msg_out].length) == 1 )
+               {
+
+                       gts_send_buffer[gts_send_buffer_msg_out].length = gts_send_buffer[gts_send_buffer_msg_out].length -2;
+
+                       call PD_DATA.request(gts_send_buffer[gts_send_buffer_msg_out].length,(uint8_t *)&gts_send_buffer[gts_send_buffer_msg_out]);
+       
+                       gts_send_buffer_count --;
+                       gts_send_buffer_msg_out++;
+
+                       if (gts_send_buffer_msg_out == GTS_SEND_BUFFER_SIZE)
+                               gts_send_buffer_msg_out=0;
+
+                       //////////////printfUART("after send %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
+                       
+                       if (gts_send_buffer_count > 0)
+                               gts_send_pending_data = 1;      
+               }
+       }
+
+}
+return;
+}
+
+//////////////////////////////////////////////////////////////
+//////////Indirect transmission functions////////////////////
+/////////////////////////////////////////////////////////////
+
+void init_indirect_trans_buffer()
+{
+       int i;
+       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+       {
+               indirect_trans_queue[i].handler = 0x00;
+               indirect_trans_count=0;
+       }
+
+return;
+}
+
+
+error_t remove_indirect_trans(uint8_t handler)
+{
+
+       int i;
+       uint8_t removed_ok=0;
+       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+       {
+               if (indirect_trans_queue[i].handler == handler)
+               {
+                       indirect_trans_queue[i].handler = 0x00;
+                       removed_ok = 1;
+                       indirect_trans_count--;
+                       break;
+               }
+       }
+
+       if (removed_ok == 0) 
+       {
+               return MAC_INVALID_HANDLE;
+       }
+       else
+       {
+               return SUCCESS;
+       }
+}
+
+
+void increment_indirect_trans()
+{
+       int i;
+       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+       {
+               if (indirect_trans_queue[i].handler != 0x00)
+               {
+                       indirect_trans_queue[i].transaction_persistent_time++;
+                       if (indirect_trans_queue[i].transaction_persistent_time == mac_PIB.macTransactionPersistenceTime )
+                               remove_indirect_trans(indirect_trans_queue[i].handler);
+               }
+       }
+
+return;
+}
+
+void send_ind_trans_addr(uint32_t DeviceAddress[])
+{
+       
+       uint8_t destination_address=0;
+       
+       dest_short *dest_short_ptr =0;
+       dest_long *dest_long_ptr=0;
+       
+       int i=0;
+       MPDU *frame_ptr=0;
+       
+       ////printfUART("send_ind_trans_addr DeviceAddress0: %y DeviceAddress1: %y \n",DeviceAddress[0],DeviceAddress[1]);
+
+    //list_indirect_trans_buffer();
+
+               for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+               {
+                       if (indirect_trans_queue[i].handler > 0x00)
+                       {
+                               frame_ptr = (MPDU *)indirect_trans_queue[i].frame;
+                               destination_address=get_fc2_dest_addr(frame_ptr->frame_control2);
+                               
+                               switch(destination_address)
+                               {
+                                       case LONG_ADDRESS: dest_long_ptr = (dest_long *) frame_ptr->data;
+                                                                               break;
+                                       case SHORT_ADDRESS: dest_short_ptr = (dest_short *) frame_ptr->data;                                                            
+                                                                               break;
+                               }
+                               
+                               //check the full address
+                               
+                               if ( (dest_long_ptr->destination_address0 == DeviceAddress[1] && dest_long_ptr->destination_address1 == DeviceAddress[0]) || ( dest_short_ptr->destination_address == (uint16_t)DeviceAddress[0] ))
+                               {
+                                       
+                                       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                                               send_buffer_msg_in=0;
+                                               
+                                       memcpy(&send_buffer[send_buffer_msg_in],(MPDU *) &indirect_trans_queue[i].frame,sizeof(MPDU));
+                                       
+                                       //enable retransmissions
+                                       send_buffer[send_buffer_msg_in].retransmission =0;
+                                       send_buffer[send_buffer_msg_in].indirect = i + 1;
+                                       
+                                       //check upon reception
+                                       indirect_trans_queue[i].handler=0x00;
+                                       //verify temporary error on the association request
+                                       
+                                       indirect_trans_count--;
+                                       if(indirect_trans_count > INDIRECT_BUFFER_SIZE )
+                                       {
+                                               indirect_trans_count=0;
+                                       }
+                                       
+                                       atomic send_buffer_count++;
+                                       atomic send_buffer_msg_in++;
+                       
+                                       post send_frame_csma();
+                                       
+                                       ////printfUART("i send\n","");
+                                       
+                                       return;
+                               }
+                       }
+               }
+               ////printfUART("i not found","");
+
+       
+return;
+} 
+
+/***************************DEBUG FUNCTIONS******************************/
+/* This function are list functions with the purpose of debug, to use then uncomment the declatarion
+on top of this file*/
+/*
+
+void list_mac_pib()
+{
+////////////printfUART("mac_PIB.macAckWaitDuration: %x\n",mac_PIB.macAckWaitDuration);
+////////////printfUART("mac_PIB.macAssociationPermit: %i\n",mac_PIB.macAssociationPermit);
+////////////printfUART("mac_PIB.macAutoRequest: %i\n",mac_PIB.macAutoRequest);
+////////////printfUART("mac_PIB.macBattLifeExt %i\n",mac_PIB.macBattLifeExt);
+////////////printfUART("mac_PIB.macBattLifeExtPeriods %i\n",mac_PIB.macBattLifeExtPeriods);
+//beacon payload
+////////////printfUART("mac_PIB.macBeaconPayloadLenght %i\n",mac_PIB.macBeaconPayloadLenght);
+////////////printfUART("mac_PIB.macBeaconOrder %i\n",mac_PIB.macBeaconOrder);
+////////////printfUART("mac_PIB.macBeaconTxTime %i\n",mac_PIB.macBeaconTxTime);
+////////////printfUART("mac_PIB.macBSN %i\n",mac_PIB.macBSN);
+////////////printfUART("mac_PIB.macCoordExtendedAddress0 %y\n",mac_PIB.macCoordExtendedAddress0);
+////////////printfUART("mac_PIB.macCoordExtendedAddress1 %y\n",mac_PIB.macCoordExtendedAddress1);
+////////////printfUART("mac_PIB.macCoordShortAddress: %x\n",mac_PIB.macCoordShortAddress);
+////////////printfUART("mac_PIB.macDSN: %x\n",mac_PIB.macDSN);
+////////////printfUART("mac_PIB.macGTSPermit: %x\n",mac_PIB.macGTSPermit);
+////////////printfUART("mac_PIB.macMaxCSMABackoffs: %x\n",mac_PIB.macMaxCSMABackoffs);
+////////////printfUART("mac_PIB.macMinBE: %x\n",mac_PIB.macMinBE);
+////////////printfUART("mac_PIB.macPANId: %x\n",mac_PIB.macPANId);
+////////////printfUART("mac_PIB.macPromiscuousMode: %x\n",mac_PIB.macPromiscuousMode);
+////////////printfUART("mac_PIB.macRxOnWhenIdle: %x\n",mac_PIB.macRxOnWhenIdle);
+////////////printfUART("mac_PIB.macShortAddress: %y\n",mac_PIB.macShortAddress);
+////////////printfUART("mac_PIB.macSuperframeOrder: %x\n",mac_PIB.macSuperframeOrder);
+////////////printfUART("mac_PIB.macTransactionPersistenceTime: %y\n",mac_PIB.macTransactionPersistenceTime);
+
+return;
+}
+
+void list_gts()
+{
+       int i;
+       ////////////printfUART("GTS list%i\n", GTS_descriptor_count); 
+       
+       for (i=0; i< 7;i++)
+       {
+               ////////////printfUART("GTSID: %i",GTS_db[i].gts_id);   
+               ////////////printfUART("start slot: %i",GTS_db[i].starting_slot);
+               ////////////printfUART("lenght: %i",GTS_db[i].length);  
+               ////////////printfUART("dir: %i",GTS_db[i].direction);  
+               ////////////printfUART("DevAddressType: %i",GTS_db[i].DevAddressType);
+               ////////////printfUART("expiration: %i \n",GTS_db[i].expiration);
+       }
+       
+}
+
+void list_my_gts()
+{
+atomic{
+               ////////////printfUART("SEND GTS s_GTSss: %i s_GTS_length: %i\n",s_GTSss,s_GTS_length);         
+               
+               ////////////printfUART("RECEIVE GTS r_GTSss: %i r_GTS_length: %i\n",r_GTSss,r_GTS_length); 
+}
+}
+*/
+
+void list_indirect_trans_buffer()
+{
+       int i;
+       //printfUART("indirect_trans_count %i\n", indirect_trans_count); 
+       
+       for (i=0; i< INDIRECT_BUFFER_SIZE;i++)
+       {
+               //printfUART("hand: %i \n",indirect_trans_queue[i].handler); 
+               
+               ////printfUART("start slot: %i",GTS_db[i].starting_slot);
+
+       }
+       
+}
+/*
+void list_gts_null()
+{
+       int i;
+       ////////////printfUART("GTS null list%i\n", GTS_null_descriptor_count); 
+       
+       for (i=0; i< GTS_null_descriptor_count;i++)
+       {
+               //////////////printfUART("GTSID: %i",GTS_null_db[i].gts_id);    
+               ////////////printfUART("start slot: %i",GTS_null_db[i].starting_slot);
+               ////////////printfUART("lenght: %i",GTS_null_db[i].length);     
+               //////////////printfUART("dir: %i",GTS_null_db[i].direction);   
+               ////////////printfUART("DevAddressType: %i \n",GTS_null_db[i].DevAddressType); 
+               ////////////printfUART("persistencetime: %i \n",GTS_null_db[i].persistencetime); 
+       }
+       
+}
+
+*/
+
+
+}
+
diff --git a/tos/lib/net/zigbee/ieee802154/macTDBS/Mac.nc b/tos/lib/net/zigbee/ieee802154/macTDBS/Mac.nc
deleted file mode 100644 (file)
index a46b6f0..0000000
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-
-#include <Timer.h>
-
-configuration Mac {
-
-
-               //MLME  
-               provides interface MLME_START;
-               provides interface MLME_SET;
-               provides interface MLME_GET;
-               
-               provides interface MLME_ASSOCIATE;
-               provides interface MLME_DISASSOCIATE;
-               
-               provides interface MLME_BEACON_NOTIFY;
-               provides interface MLME_GTS;
-               
-               provides interface MLME_ORPHAN;
-
-               provides interface MLME_SYNC;
-               provides interface MLME_SYNC_LOSS;
-               
-               provides interface MLME_RESET;
-               
-               provides interface MLME_SCAN;
-               
-               //MCPS
-               provides interface MCPS_DATA;
-               provides interface MCPS_PURGE;
-
-}
-implementation {
-
-       components MainC;
-       MainC.SoftwareInit -> MacM;
-
-       components LedsC;
-       components MacM;
-
-       components Phy;
-
-       components TimerAsyncC;
-       
-       MacM.TimerAsync ->TimerAsyncC;
-
-       MacM.Leds -> LedsC;
-       
-       
-       MacM.AMControl ->Phy.SplitControl;
-       
-       components HplCC2420PinsC as Pins;
-       MacM.CCA -> Pins.CCA;
-       
-       components RandomC;
-       MacM.Random -> RandomC;
-
-       components new TimerMilliC() as T_ackwait;
-       MacM.T_ackwait -> T_ackwait;
-       
-       components new TimerMilliC() as T_ResponseWaitTime;
-       MacM.T_ResponseWaitTime -> T_ResponseWaitTime;
-       
-       components new TimerMilliC() as T_ScanDuration;
-       MacM.T_ScanDuration -> T_ScanDuration;
-
-
-       components CC2420ReceiveC;
-       MacM.AddressFilter -> CC2420ReceiveC;
-
-       //
-       //components CC2420ControlC;
-       //MacM.CC2420Config ->CC2420ControlC;
-
-
-       /*****************************************************/
-       /*                              INTERFACES                                               */
-       /*****************************************************/  
-       MacM.PD_DATA -> Phy.PD_DATA;
-       MacM.PLME_ED ->Phy.PLME_ED;
-       MacM.PLME_CCA -> Phy.PLME_CCA;
-       MacM.PLME_SET -> Phy.PLME_SET;
-       MacM.PLME_GET -> Phy.PLME_GET;
-       MacM.PLME_SET_TRX_STATE -> Phy.PLME_SET_TRX_STATE;
-
-
-       //MLME interfaces
-       MLME_START=MacM;
-
-       MLME_SET=MacM;
-       MLME_GET=MacM;
-       
-       MLME_ASSOCIATE=MacM;
-       MLME_DISASSOCIATE=MacM;
-       
-       MLME_BEACON_NOTIFY = MacM;
-       MLME_GTS=MacM;
-       
-       MLME_ORPHAN=MacM;
-       
-       MLME_SYNC=MacM;
-       MLME_SYNC_LOSS=MacM;
-       
-       MLME_RESET=MacM;
-       
-       MLME_SCAN=MacM;
-       
-       MCPS_DATA=MacM;
-       MCPS_PURGE=MacM;
-       
-       
-       
-       
-
-}
-
diff --git a/tos/lib/net/zigbee/ieee802154/macTDBS/MacC.nc b/tos/lib/net/zigbee/ieee802154/macTDBS/MacC.nc
new file mode 100644 (file)
index 0000000..c69b3b1
--- /dev/null
@@ -0,0 +1,120 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+
+#include <Timer.h>
+
+configuration MacC {
+
+
+               //MLME  
+               provides interface MLME_START;
+               provides interface MLME_SET;
+               provides interface MLME_GET;
+               
+               provides interface MLME_ASSOCIATE;
+               provides interface MLME_DISASSOCIATE;
+               
+               provides interface MLME_BEACON_NOTIFY;
+               provides interface MLME_GTS;
+               
+               provides interface MLME_ORPHAN;
+
+               provides interface MLME_SYNC;
+               provides interface MLME_SYNC_LOSS;
+               
+               provides interface MLME_RESET;
+               
+               provides interface MLME_SCAN;
+               
+               //MCPS
+               provides interface MCPS_DATA;
+               provides interface MCPS_PURGE;
+
+}
+implementation {
+
+       components MainC;
+       MainC.SoftwareInit -> MacP;
+
+       components LedsC;
+       components MacP;
+
+       components PhyC;
+
+       components TimerAsyncC;
+       
+       MacP.TimerAsync ->TimerAsyncC;
+
+       MacP.Leds -> LedsC;
+       
+       
+       MacP.AMControl ->PhyC.SplitControl;
+       
+       components HplCC2420PinsC as Pins;
+       MacP.CCA -> Pins.CCA;
+       
+       components RandomC;
+       MacP.Random -> RandomC;
+
+       components new TimerMilliC() as T_ackwait;
+       MacP.T_ackwait -> T_ackwait;
+       
+       components new TimerMilliC() as T_ResponseWaitTime;
+       MacP.T_ResponseWaitTime -> T_ResponseWaitTime;
+       
+       components new TimerMilliC() as T_ScanDuration;
+       MacP.T_ScanDuration -> T_ScanDuration;
+
+
+       components CC2420ReceiveC;
+       MacP.AddressFilter -> CC2420ReceiveC;
+
+       //
+       //components CC2420ControlC;
+       //MacP.CC2420Config ->CC2420ControlC;
+
+
+       /*****************************************************/
+       /*                              INTERFACES                                               */
+       /*****************************************************/  
+       MacP.PD_DATA -> PhyC.PD_DATA;
+       MacP.PLME_ED ->PhyC.PLME_ED;
+       MacP.PLME_CCA -> PhyC.PLME_CCA;
+       MacP.PLME_SET -> PhyC.PLME_SET;
+       MacP.PLME_GET -> PhyC.PLME_GET;
+       MacP.PLME_SET_TRX_STATE -> PhyC.PLME_SET_TRX_STATE;
+
+
+       //MLME interfaces
+       MLME_START=MacP;
+
+       MLME_SET=MacP;
+       MLME_GET=MacP;
+       
+       MLME_ASSOCIATE=MacP;
+       MLME_DISASSOCIATE=MacP;
+       
+       MLME_BEACON_NOTIFY = MacP;
+       MLME_GTS=MacP;
+       
+       MLME_ORPHAN=MacP;
+       
+       MLME_SYNC=MacP;
+       MLME_SYNC_LOSS=MacP;
+       
+       MLME_RESET=MacP;
+       
+       MLME_SCAN=MacP;
+       
+       MCPS_DATA=MacP;
+       MCPS_PURGE=MacP;
+       
+       
+       
+       
+
+}
+
diff --git a/tos/lib/net/zigbee/ieee802154/macTDBS/MacM.nc b/tos/lib/net/zigbee/ieee802154/macTDBS/MacM.nc
deleted file mode 100644 (file)
index 2d88c16..0000000
+++ /dev/null
@@ -1,5676 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-
-#include <Timer.h>
-
-#include "printfUART.h"
-
-#include "frame_format.h"
-#include "phy_const.h"
-
-#include "mac_const.h"
-#include "mac_enumerations.h"
-
-#include "mac_func.h"
-
-module MacM {
-       provides interface Init;
-       
-       provides interface MLME_START;
-       provides interface MLME_SET;
-    provides interface MLME_GET;
-       
-       provides interface MLME_ASSOCIATE;
-       provides interface MLME_DISASSOCIATE;
-       
-       provides interface MLME_BEACON_NOTIFY;
-       provides interface MLME_GTS;
-       
-       provides interface MLME_ORPHAN;
-       
-       provides interface MLME_SYNC;
-       provides interface MLME_SYNC_LOSS;
-               
-       provides interface MLME_RESET;
-       
-       provides interface MLME_SCAN;
-       
-       //MCPS
-       provides interface MCPS_DATA;
-       provides interface MCPS_PURGE;
-               
-       
-       uses interface Timer<TMilli> as T_ackwait;      
-               
-       uses interface Timer<TMilli> as T_ResponseWaitTime;
-       
-       uses interface Timer<TMilli> as T_ScanDuration;
-       
-       uses interface Leds;
-       
-       uses interface SplitControl as AMControl;
-       
-       uses interface Random;
-       
-       uses interface GeneralIO as CCA;
-       
-       
-       //uses interface CC2420Config;
-       
-       uses interface AddressFilter;
-       
-       //uses interface Test_send;
-       
-       uses interface TimerAsync;
-       
-       uses interface PD_DATA;
-       
-       uses interface PLME_ED;
-       uses interface PLME_CCA;
-       uses interface PLME_SET;
-       uses interface PLME_GET;
-       uses interface PLME_SET_TRX_STATE;
-
-
-  
-}
-implementation {
-/*****************************************************/
-/*                             GENERAL                                  */
-/*****************************************************/  
-       /***************Variables*************************/
-       //local extended address
-       uint32_t aExtendedAddress0;
-       uint32_t aExtendedAddress1;
-
-       macPIB mac_PIB;
-
-//If the the MLME receives a start request the node becomes a pan coordinator
-       //and start transmiting beacons 
-       bool PANCoordinator = 0;
-       //(0 NO beacon transmission; 1 beacon transmission);
-       bool Beacon_enabled_PAN = 0;
-       
-       //(RESET) when the reset command arrives it checks whether or not to reset the PIB
-       bool SetDefaultPIB=0;
-       
-       //use security
-       bool SecurityEnable=0;
-       
-       //others
-       bool pending_reset=0;
-       
-       //transceiver status -every time the transceiver changes state this variable is updated
-       uint8_t trx_status;
-       
-       //defines the transmission
-       bool beacon_enabled=0;
-       
-       /***************Functions Definition***************/
-       
-       void init_MacPIB(); 
-       
-       uint8_t min(uint8_t val1, uint8_t val2);
-       
-       void init_MacCon();
-       
-       
-       task void signal_loss();
-       
-
-       void create_data_request_cmd();
-       void create_beacon_request_cmd();
-       void create_gts_request_cmd(uint8_t gts_characteristics);
-       
-       void build_ack(uint8_t sequence,uint8_t frame_pending);
-       
-       void create_data_frame(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions,uint8_t on_gts_slot,uint8_t pan);
-
-
-
-
-/*****************************************************/        
-/*                             Association                                      */
-/*****************************************************/ 
-       /***************Variables*************************/
-       uint8_t associating = 0;
-       uint8_t association_cmd_seq_num =0;
-       
-       /*association parameters*/
-       
-       uint8_t a_LogicalChannel;
-       uint8_t a_CoordAddrMode;
-       uint16_t a_CoordPANId;
-       uint32_t a_CoordAddress[2];
-       uint8_t a_CapabilityInformation;
-       bool a_securityenable;
-       
-       /***************Functions Definition***************/            
-       
-       void create_association_request_cmd(uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation);
-
-       error_t create_association_response_cmd(uint32_t DeviceAddress[],uint16_t shortaddress, uint8_t status);
-       
-       void create_disassociation_notification_cmd(uint32_t DeviceAddress[],uint8_t disassociation_reason);
-       
-       void process_dissassociation_notification(MPDU *pdu);
-
-/*****************************************************/
-/*                             Synchronization                                  */
-/*****************************************************/ 
-       /***************Variables*************************/
-       //(SYNC)the device will try to track the beacon ie enable its receiver just before the espected time of each beacon
-       bool TrackBeacon=0;
-       bool beacon_processed=0;
-       //beacon loss indication
-       uint8_t beacon_loss_reason;
-       
-       //(SYNC)the device will try to locate one beacon
-       bool findabeacon=0;
-       //(SYNC)number of beacons lost before sending a Beacon-Lost indication comparing to aMaxLostBeacons
-       uint8_t missed_beacons=0;
-       //boolean variable stating if the device is synchonized with the beacon or not
-       uint8_t on_sync=0;
-       
-       uint32_t parent_offset=0x00000000;
-
-
-/*****************************************************/
-/*                             GTS Variables                                    */
-/*****************************************************/  
-       /***************Variables*************************/
-       
-       uint8_t gts_request=0;
-       uint8_t gts_request_seq_num=0;
-       
-       bool gts_confirm;
-       
-       uint8_t GTS_specification;
-       bool GTSCapability=1;
-       
-       uint8_t final_CAP_slot=15;
-       
-       //GTS descriptor variables, coordinator usage only
-       GTSinfoEntryType GTS_db[7];
-       uint8_t GTS_descriptor_count=0;
-       uint8_t GTS_startslot=16;
-       uint8_t GTS_id=0x01;
-
-
-       //null gts descriptors
-       GTSinfoEntryType_null GTS_null_db[7];
-       
-       uint8_t GTS_null_descriptor_count=0;
-       //uint8_t GTS_null_id=0x01;
-       
-       //node GTS variables
-       // 1 GTS for transmit
-       uint8_t s_GTSss=0;           //send gts start slot
-       uint8_t s_GTS_length=0;          //send gts length
-       //1 GTS for receive
-       uint8_t r_GTSss=0;                       //receive gts start slot
-       uint8_t r_GTS_length=0;          //receive gts lenght
-       
-       //used to state that the device is on its transmit slot
-       uint8_t on_s_GTS=0;
-       //used to state that the device is on its receive slot
-       uint8_t on_r_GTS=0;
-       
-       //used to determine if the next time slot is used for transmission
-       uint8_t next_on_s_GTS=0;
-       //used to determine if the next time slot is used for reception
-       uint8_t next_on_r_GTS=0;
-       
-       //variable stating if the coordinator allow GTS allocations
-       uint8_t allow_gts=1;
-       
-       //COORDINATOR GTS BUFFER        
-       gts_slot_element gts_slot_list[7];
-       uint8_t available_gts_index[GTS_SEND_BUFFER_SIZE];
-       uint8_t available_gts_index_count;
-       
-       uint8_t coordinator_gts_send_pending_data=0;
-       uint8_t coordinator_gts_send_time_slot=0;
-       
-       //gts buffer used to store the gts messages both in COORDINATOR and NON COORDINATOR
-       norace MPDU gts_send_buffer[GTS_SEND_BUFFER_SIZE];
-       
-       //NON PAN COORDINATOR BUFFER
-       //buffering for sending
-       uint8_t gts_send_buffer_count=0;
-       uint8_t gts_send_buffer_msg_in=0;
-       uint8_t gts_send_buffer_msg_out=0;
-       uint8_t gts_send_pending_data=0;
-       
-
-       /***************Functions Definition***************/
-       
-       void process_gts_request(MPDU *pdu);    
-       void init_available_gts_index();
-       task void start_coordinator_gts_send();
-       
-       
-       //GTS FUNCTIONS
-       error_t remove_gts_entry(uint16_t DevAddressType);
-       error_t add_gts_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType);
-       error_t add_gts_null_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType);
-       
-       //increment the idle GTS for GTS deallocation purposes, not fully implemented yet
-       task void increment_gts_null();
-       
-       task void start_gts_send();
-       
-       
-       
-       //initialization functions
-       void init_gts_slot_list();
-       void init_GTS_null_db();
-       
-       void init_GTS_db();
-
-
-       uint32_t calculate_gts_expiration();
-       task void check_gts_expiration();
-
-
-/*****************************************************/
-/*                             CHANNEL SCAN Variables                           */
-/*****************************************************/ 
-       //current_channel
-       uint8_t current_channel=0;
-
-       /***************Variables*************************/
-       //ED-SCAN variables
-       
-       bool scanning_channels;
-       
-       uint32_t channels_to_scan;
-       uint8_t current_scanning=0;
-       //uint8_t scan_count=0;
-       uint8_t scanned_values[16];
-       uint8_t scan_type;
-       
-       SCAN_PANDescriptor scan_pans[16];
-       
-       uint16_t scan_duration;
-       
-       task void data_channel_scan_indication();
-       
-/*****************************************************/
-/*                             TIMER VARIABLES                                  */
-/*****************************************************/  
-       /***************Variables*************************/
-       uint32_t response_wait_time;
-       
-       //Beacon Interval
-       uint32_t BI;
-       //Superframe duration
-       uint32_t SD;
-       
-       //timer variables
-       uint32_t time_slot; //backoff boundary timer
-       uint32_t backoff;  //backoff timer
-       
-       //current number of backoffs in the active period
-       uint8_t number_backoff=1;
-       uint8_t number_time_slot=0;
-       
-       bool csma_slotted=0;
-/*****************************************************/
-/*                             CSMA VARIABLES                                   */
-/*****************************************************/        
-       /***************Variables*************************/     
-
-       //DEFERENCE CHANGE
-       uint8_t cca_deference = 0;
-       uint8_t backoff_deference = 0;
-       uint8_t check_csma_ca_backoff_send_conditions(uint32_t delay_backoffs);
-
-       //STEP 2
-       uint8_t delay_backoff_period;
-       bool csma_delay=0;
-       
-       bool csma_locate_backoff_boundary=0;
-       
-       bool csma_cca_backoff_boundary=0;
-       
-       //Although the receiver of the device is enabled during the channel assessment portion of this algorithm, the
-       //device shall discard any frames received during this time.
-       bool performing_csma_ca=0;
-       
-       //CSMA-CA variables
-       uint8_t BE; //backoff exponent
-       uint8_t CW; //contention window (number of backoffs to clear the channel)
-       uint8_t NB; //number of backoffs
-
-       /***************Functions Definition***************/    
-       
-       void init_csma_ca(bool slotted);
-       void perform_csma_ca();
-       task void perform_csma_ca_unslotted();
-       task void perform_csma_ca_slotted();
-       //task void start_csma_ca_slotted();
-       
-/*****************************************************/
-/*                             Indirect Transmission buffers            */
-/*****************************************************/
-       /***************Variables*************************/     
-       //indirect transmission buffer
-       norace indirect_transmission_element indirect_trans_queue[INDIRECT_BUFFER_SIZE];
-       //indirect transmission message counter
-       uint8_t indirect_trans_count=0;
-
-       /***************Functions Definition***************/    
-       
-       //function used to initialize the indirect transmission buffer
-       void init_indirect_trans_buffer();
-       //function used to search and send an existing indirect transmission message
-       void send_ind_trans_addr(uint32_t DeviceAddress[]);
-       //function used to remove an existing indirect transmission message
-       error_t remove_indirect_trans(uint8_t handler);
-       //function used to increment the transaction persistent time on each message
-       //if the transaction time expires the messages are discarded
-       void increment_indirect_trans();
-       
-/*****************************************************/
-/*                             RECEIVE buffers                           */
-/*****************************************************/  
-       /***************Variables*************************/
-       
-       //buffering variables
-       norace MPDU buffer_msg[RECEIVE_BUFFER_SIZE];
-       int current_msg_in=0;
-       int current_msg_out=0;
-       int buffer_count=0;
-
-       /***************Functions Definition***************/    
-       
-       task void data_indication();
-       
-       void indication_cmd(MPDU *pdu, int8_t ppduLinkQuality);
-       void indication_ack(MPDU *pdu, int8_t ppduLinkQuality);
-       void indication_data(MPDU *pdu, int8_t ppduLinkQuality);
-/*****************************************************/
-/*                             RECEPTION AND TRANSMISSION                                */
-/*****************************************************/  
-       
-       /***************Variables*************************/
-       
-       //buffering for sending
-       norace MPDUBuffer send_buffer[SEND_BUFFER_SIZE];
-       uint8_t send_buffer_count=0;
-       uint8_t send_buffer_msg_in=0;
-       uint8_t send_buffer_msg_out=0;
-       
-       //retransmission information
-       uint8_t send_ack_check;//ack requested in the transmitted frame
-       uint8_t retransmit_count;//retransmission count
-       uint8_t ack_sequence_number_check;//transmission sequence number
-       uint8_t send_retransmission;
-       uint8_t send_indirect_transmission;
-
-       uint8_t pending_request_data=0;
-       
-       uint8_t ackwait_period;
-       
-       uint8_t link_quality;
-       
-       norace ACK mac_ack;
-       ACK *mac_ack_ptr;
-       
-       uint32_t gts_expiration;
-
-       uint8_t I_AM_IN_CAP=0;
-       uint8_t I_AM_IN_CFP=0;
-       uint8_t I_AM_IN_IP=0;
-       
-       /***************Functions Definition***************/    
-       
-       task void send_frame_csma();
-       
-       uint8_t check_csma_ca_send_conditions(uint8_t frame_length,uint8_t frame_control1);
-
-       uint8_t check_gts_send_conditions(uint8_t frame_length);
-       
-       uint8_t calculate_ifs(uint8_t pk_length);
-
-
-
-/*****************************************************/
-/*                             BEACON MANAGEMENT                             */
-/*****************************************************/ 
-       /***************Variables*************************/
-       norace MPDU mac_beacon_txmpdu;
-       MPDU *mac_beacon_txmpdu_ptr;
-       
-       uint8_t *send_beacon_frame_ptr;
-       uint8_t send_beacon_length;
-
-       /***************Functions Definition***************/    
-       /*function to create the beacon*/
-       task void create_beacon();
-       /*function to process the beacon information*/
-       void process_beacon(MPDU *packet,uint8_t ppduLinkQuality);
-       
-
-/*****************************************************/
-/*      Fault tolerance functions            */
-/*****************************************************/ 
-//FAULT-TOLERANCE      
-       void create_coordinator_realignment_cmd(uint32_t device_extended0, uint32_t device_extended1, uint16_t device_short_address);
-
-       void create_orphan_notification();
-       
-       void process_coordinator_realignment(MPDU *pdu);
-
-       /*******************************************/
-       /*******BEACON SCHEDULING IMPLEMENTATION****/
-       /*******************************************/
-       
-       //bolean that checks if the device is in the parent active period
-       uint8_t I_AM_IN_PARENT_CAP = 0;
-       
-       
-       //upstream buffer
-       norace MPDUBuffer upstream_buffer[UPSTREAM_BUFFER_SIZE];
-       uint8_t upstream_buffer_count=0;
-       uint8_t upstream_buffer_msg_in=0;
-       uint8_t upstream_buffer_msg_out=0;
-
-       uint8_t sending_upstream_frame=0;
-       
-       task void send_frame_csma_upstream();
-
-/***************************DEBUG FUNCTIONS******************************/
-/* This function are list functions with the purpose of debug, to use then uncomment the declatarion
-on top of this file*/
-/*
-       void list_mac_pib();
-       
-       void list_gts();
-       
-       void list_my_gts();
-       void list_gts_null();
-       */
-       //list all the handles in the indirect transmission buffer, debug purposes
-       void list_indirect_trans_buffer();      
-                       
-/***************************END DEBUG FUNCTIONS******************************/
-
-
-/***************** Init Commands ****************/
-  command error_t Init.init() {
-  
-  call AMControl.start();
-
-
-       //initialization of the beacon structure
-       mac_beacon_txmpdu_ptr = &mac_beacon_txmpdu;
-
-
-
-   atomic{
-       //inicialize the mac PIB
-       init_MacPIB();
-       
-       init_GTS_db();
-       
-       init_GTS_null_db();
-       
-       init_gts_slot_list();
-       
-       init_available_gts_index();
-       
-       aExtendedAddress0=TOS_NODE_ID;
-       aExtendedAddress1=TOS_NODE_ID;
-       
-
-
-       call AddressFilter.set_address(mac_PIB.macShortAddress, aExtendedAddress0, aExtendedAddress1);
-
-       call AddressFilter.set_coord_address(mac_PIB.macCoordShortAddress, mac_PIB.macPANId);
-       
-
-                                                                                       
-       init_indirect_trans_buffer();
-
-
-       }
-       
-       //beacon
-       mac_beacon_txmpdu_ptr = &mac_beacon_txmpdu;
-               
-       //ack
-       mac_ack_ptr = &mac_ack;
-       
-       //Other timers, sync timers units expressed in miliseconds
-       ackwait_period = ((mac_PIB.macAckWaitDuration * 4.0 ) / 250.0) * 3;
-
-       response_wait_time = ((aResponseWaitTime * 4.0) / 250.0) * 2;
-
-       atomic{
-       
-               
-               BI = aBaseSuperframeDuration * powf(2,mac_PIB.macBeaconOrder);
-               SD = aBaseSuperframeDuration * powf(2,mac_PIB.macSuperframeOrder);
-               
-               
-               //backoff_period
-               backoff = aUnitBackoffPeriod;
-               //backoff_period_boundary
-               
-               time_slot = SD / NUMBER_TIME_SLOTS;
-                       
-               call TimerAsync.set_enable_backoffs(1); 
-               call TimerAsync.set_backoff_symbols(backoff);
-               
-               call TimerAsync.set_bi_sd(BI,SD);
-               
-               call TimerAsync.start();
-       }
-
-
-printfUART_init();
-
-    return SUCCESS;
-  }
-
-  event void AMControl.startDone(error_t err) {
-    if (err == SUCCESS) {
-       
-       call TimerAsync.start();
-               
-       }
-    else {
-      call AMControl.start();
-    }
-  }
-
-  event void AMControl.stopDone(error_t err) {
-  }
-
-
-/*****************************************************/
-/*                             TIMERS FIRED                                             */
-/*****************************************************/ 
-
-async event error_t TimerAsync.before_bi_fired()
-{
-       //printfUART("bbi %i\n",call TimerAsync.get_current_ticks());
-               
-       if (mac_PIB.macBeaconOrder != mac_PIB.macSuperframeOrder )
-       {
-               if ( Beacon_enabled_PAN == 1 )
-               {
-                       //
-                       //post set_trx();
-                       trx_status = PHY_TX_ON;
-                       call PLME_SET_TRX_STATE.request(PHY_TX_ON);
-               }
-               else
-               {
-                       //
-                       //post set_trx();
-                       trx_status = PHY_RX_ON;
-                       call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-               }
-       }
-       
-       //I_AM_IN_CAP = 1;
-       findabeacon = 1;
-               
-       return SUCCESS;
-}
-
-/*******************Timer BEACON INTERVAL******************/
-async event error_t TimerAsync.bi_fired()
-{
-       call Leds.led2On();
-       //call Test_send.send();
-       
-       I_AM_IN_CAP = 1;
-       I_AM_IN_IP = 0;
-       
-       //printfUART("bi\n","");
-       
-       
-       if ( Beacon_enabled_PAN == 1 )
-       {
-               //the beacon is send directly without CSMA/CA
-               call PD_DATA.request(send_beacon_length,send_beacon_frame_ptr);
-       }
-
-       number_backoff =0;
-       number_time_slot=0;
-       
-       
-       //CHECK there is the need to wait a small amount of time before checking if the beacon as been processed or not
-       //possible solition, if it receives a packet stand by for confirmation it its a beacon
-       //The device must always receive the beacon
-       if (TrackBeacon == 1) 
-       {
-               if (beacon_processed==1) 
-               {
-                       beacon_processed=0;
-               }
-               else
-               {
-                       //dealocate all GTS
-                       //beacon loss
-
-                       on_sync =0;
-                       beacon_loss_reason = MAC_BEACON_LOSS;
-                       
-                       //TODO
-                       //post signal_loss();
-               }
-       }
-       
-       post send_frame_csma();
-
-       return SUCCESS;
-}
-
-/*******************Timer SUPERFRAME DURATION******************/
-async event error_t TimerAsync.sd_fired()
-{
-       call Leds.led2Off();
-
-       //printfUART("sd\n","");
-
-       I_AM_IN_CFP = 0;
-       I_AM_IN_IP = 1;
-       
-       
-       number_backoff=0;
-       number_time_slot=0;
-       
-       
-       if (PANCoordinator == 0 && TYPE_DEVICE == ROUTER)
-       {
-               trx_status = PHY_RX_ON;
-       
-               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-       }
-       else
-       {
-               trx_status = PHY_RX_ON;
-               
-               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-               
-       }
-       
-       if (mac_PIB.macShortAddress==0xffff && TYPE_DEVICE == END_DEVICE)
-       {
-               trx_status = PHY_RX_ON;
-               
-               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-       }
-       
-       //trx_status = PHY_RX_ON;
-       //post set_trx();
-       /*
-               //turn the transceiver off
-       if (mac_PIB.macBeaconOrder != mac_PIB.macSuperframeOrder )
-       {
-               if ( mac_PIB.macRxOnWhenIdle == 0 && findabeacon == 0) 
-               {
-                       trx_status = PHY_TRX_OFF;
-                       post set_trx();
-               }
-               else
-               {
-                       trx_status = PHY_RX_ON;
-                       post set_trx();
-               }
-       }
-       //if the node is trying to synchronize
-               if (on_sync == 0 || mac_PIB.macPromiscuousMode == 1)
-       {
-               atomic{
-                       trx_status = PHY_RX_ON;
-                       post set_trx();
-               }
-       }
-       */
-       if (PANCoordinator == 1)
-       {
-               //increment the gts_null descriptors
-               atomic{
-                       
-                               //if (GTS_null_descriptor_count > 0) post increment_gts_null();
-                       
-                               //if (GTS_descriptor_count >0 ) post check_gts_expiration();
-                       
-                               //if (indirect_trans_count > 0) increment_indirect_trans();
-                               
-                               //creation of the beacon
-                               post create_beacon();
-               }
-               //trx_status = PHY_TRX_OFF;
-               //post set_trx();
-       }
-       else
-       {
-       //temporariamente aqui //atenção quando for para o cluster-tree Ã© preciso mudar para fora
-       //e necessario destinguir ZC de ZR (que tem que manter a sync com o respectivo pai)
-       if (on_sync == 0)
-       {
-               //sync not ok
-               
-               //findabeacon=1;
-               if (missed_beacons == aMaxLostBeacons)
-               {
-               
-                       printfUART("sync_loss %i\n",missed_beacons);
-                       //out of sync
-                       post signal_loss();
-               }
-               //printfUART("out_sync %i\n",missed_beacons);
-               missed_beacons++;
-               call Leds.led1Off();
-               
-       }
-       else
-       {
-               //sync ok
-               missed_beacons=0;
-       
-               on_sync=0;
-       }
-       
-       }
-
-       //trx_status = PHY_TRX_OFF;
-       //call PLME_SET_TRX_STATE.request(PHY_TRX_OFF);
-
-       return SUCCESS;
-}
-
-/*******************Timer BEFORE TIME SLOT FIRED******************/
-async event error_t TimerAsync.before_time_slot_fired()
-{
-       on_s_GTS=0;
-       on_r_GTS=0;
-       
-       if (next_on_s_GTS == 1)
-       {       
-               on_s_GTS=1;
-               next_on_s_GTS =0;
-               trx_status = PHY_TX_ON;
-               call PLME_SET_TRX_STATE.request(PHY_TX_ON);
-               //post set_trx();
-       }
-       
-       if(next_on_r_GTS == 1)
-       {
-               on_r_GTS=1;
-               next_on_r_GTS=0;
-               trx_status = PHY_RX_ON;
-               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
-               //post set_trx();
-       }
-
-return SUCCESS;
-}
-/*******************Timer TIME SLOT FIRED******************/
-async event error_t TimerAsync.time_slot_fired()
-{
-       //reset the backoff counter and increment the slot boundary
-       number_backoff=0;
-       number_time_slot++;
-               
-       //verify is there is data to send in the GTS, and try to send it
-       if(PANCoordinator == 1 && GTS_db[15-number_time_slot].direction == 1 && GTS_db[15-number_time_slot].gts_id != 0)
-       {
-               //COORDINATOR SEND DATA
-               //////////printfUART("bbck%i:%i:%i\n", (15-number_time_slot),GTS_db[15-number_time_slot].direction,gts_slot_list[15-number_time_slot].element_count);
-               
-               post start_coordinator_gts_send();
-                               
-       }
-       else
-       {
-               //DEVICE SEND DATA
-               if (number_time_slot == s_GTSss && gts_send_buffer_count > 0 && on_sync == 1)//(send_s_GTSss-send_s_GTS_len) 
-               {
-                               //current_time = call TimerAsync.get_total_tick_counter();
-                               post start_gts_send();
-               }               
-       }
-       
-       next_on_r_GTS =0;
-       next_on_s_GTS=0;
-       
-       
-       //printfUART("ts%i %i %i\n", number_time_slot,s_GTSss,r_GTSss);
-       
-       
-       //verification if the time slot is entering the CAP
-       //GTS FIELDS PROCESSING
-       
-       if ((number_time_slot + 1) >= final_CAP_slot && (number_time_slot + 1) < 16)
-       {
-               I_AM_IN_CAP = 0;
-               I_AM_IN_CFP = 1;
-               
-               //printfUART("bts %i\n",I_AM_IN_CAP, number_time_slot); 
-       
-       atomic{
-               
-               //verification of the next time slot
-               if(PANCoordinator == 1 && number_time_slot < 15)
-               {
-               //COORDINATOR verification of the next time slot
-                       if(GTS_db[14-number_time_slot].gts_id != 0x00 && GTS_db[14-number_time_slot].DevAddressType != 0x0000)
-                       {       
-                               if(GTS_db[14-number_time_slot].direction == 1 ) // device wants to receive
-                               {
-                                       next_on_s_GTS =1; //PAN coord mode
-                               }
-                               else
-                               {
-                                       next_on_r_GTS=1; //PAN coord mode
-                               }
-                       }       
-               }
-               else
-               {
-               //device verification of the next time slot
-                       if( (number_time_slot +1) == s_GTSss || (number_time_slot +1) == r_GTSss )
-                       {
-                               //printfUART("s_GTSss: %i r_GTSss: %i\n", s_GTSss,r_GTSss);
-                               if((number_time_slot + 1) == s_GTSss)
-                               {       
-                                       //printfUART("MY SEND SLOT \n", "");
-                                       next_on_s_GTS =1;
-                                       s_GTS_length --;
-                                       if (s_GTS_length != 0 )
-                                       {
-                                               s_GTSss++;
-                                       }
-                               }
-                               else                    
-                               {
-                                       ////////////printfUART("MY RECEIVE SLOT \n", "");
-                                       next_on_r_GTS =1;
-                                       r_GTS_length --;
-                                       if (r_GTS_length != 0 )
-                                       {
-                                               r_GTSss++;
-                                       }
-                               }                               
-                       }
-                       else
-                       {
-                               //idle
-                               next_on_s_GTS=0;
-                               next_on_r_GTS=0;
-                       }
-               }
-       }
-       }
-       
-return SUCCESS;
-}
-async event error_t TimerAsync.sfd_fired()
-{
-
-return SUCCESS;
-}
-
-/*******************Timer BACKOFF PERIOD******************/
-async event error_t TimerAsync.backoff_fired()
-{
-       //slotted CSMA/CA function
-       atomic{
-       
-               if( csma_locate_backoff_boundary == 1 )
-               {
-                       csma_locate_backoff_boundary=0;
-                       
-                       //post start_csma_ca_slotted();
-                       
-                       //DEFERENCE CHANGE
-                       if (backoff_deference == 0)
-                       {
-                               //normal situation
-                               delay_backoff_period = (call Random.rand16() & ((uint8_t)(powf(2,BE)) - 1));
-                               
-                               if (check_csma_ca_backoff_send_conditions((uint32_t) delay_backoff_period) == 1)
-                               {
-                                       backoff_deference = 1;
-                               }
-                               
-                       }
-                       else
-                       {
-                               backoff_deference = 0;
-                       }
-                       
-                       csma_delay=1;
-               }
-               
-               
-               
-               if( csma_cca_backoff_boundary == 1 )
-                       post perform_csma_ca_slotted();
-       }
-       //CSMA/CA
-       atomic{
-               if(csma_delay == 1 )
-               {
-                       if (delay_backoff_period == 0)
-                       {
-                               if(csma_slotted == 0)
-                               {
-                                       post perform_csma_ca_unslotted();
-                               }
-                               else
-                               {
-                                       //CSMA/CA SLOTTED
-                                       csma_delay=0;
-                                       csma_cca_backoff_boundary=1;
-                               }
-                       }
-                       delay_backoff_period--;
-               }
-       }
-       number_backoff++;
-return SUCCESS;
-}
-
-/*******************T_ackwait**************************/
-  event void T_ackwait.fired() {
-  
-  ////////printfUART("Tfd \n", "");
-       
-       //call Leds.redToggle();
-
-       if (send_ack_check == 1)
-       {
-               retransmit_count++;
-               
-               if (retransmit_count == aMaxFrameRetries || send_indirect_transmission > 0)
-               {
-                               //check the type of data being send
-                               /*
-                               if (associating == 1)
-                               {
-                                       printfUART("af ack\n", "");
-                                       associating=0;
-                                       signal MLME_ASSOCIATE.confirm(0x0000,MAC_NO_ACK);
-                               }
-                               */
-                               
-                       atomic{ 
-                               //////////printfUART("TRANSMISSION FAIL\n",""); 
-                               //stardard procedure, if fail discard the packet
-                               atomic send_buffer_count --;
-                               send_buffer_msg_out++;
-                       
-                                       //failsafe
-                                       if(send_buffer_count > SEND_BUFFER_SIZE)
-                                       {
-                                               
-                                               atomic send_buffer_count =0;
-                                               send_buffer_msg_out=0;
-                                               send_buffer_msg_in=0;
-                                               
-                                       }
-                                       
-                                       
-                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                               send_buffer_msg_out=0;
-                                       
-                                       if (send_buffer_count > 0)
-                                               post send_frame_csma();
-                                               
-                                       send_ack_check=0;
-                                       retransmit_count=0;
-                                       ack_sequence_number_check=0;
-                               
-                               }
-               }
-               
-               //////////printfUART("RETRY\n",""); 
-               //retransmissions
-               post send_frame_csma();
-       }
-    
-  }
-
-/*******************T_ResponseWaitTime**************************/
-  event void T_ResponseWaitTime.fired() {
-       //command response wait time
-       //////////printfUART("T_ResponseWaitTime.fired\n", "");
-
-       if (associating == 1)
-       {
-               printfUART("af rwt\n", "");
-               associating=0;
-               signal MLME_ASSOCIATE.confirm(0x0000,MAC_NO_DATA);
-               
-       }
-  
-  }
-
-/*******************TDBS Implementation Timers**************************/
-async event error_t TimerAsync.before_start_track_beacon_fired()
-{
-       I_AM_IN_PARENT_CAP = 1;
-
-return SUCCESS;
-}
-
-
-
-//track beacon events timers
-async event error_t TimerAsync.start_track_beacon_fired()
-{
-       I_AM_IN_PARENT_CAP = 1;
-
-       //printfUART("fi\n","");
-       
-       if (upstream_buffer_count > 0)
-               post send_frame_csma_upstream();
-
-
-
-return SUCCESS;
-}
-async event error_t TimerAsync.end_track_beacon_fired()
-{
-
-       I_AM_IN_PARENT_CAP = 0;
-       
-       //printfUART("unfi\n","");
-       //call Leds.greenOff();
-
-return SUCCESS;
-}
-
-
-
-
-
-/*****************************************************
-****************PD_DATA EVENTS***********************
-******************************************************/
-  async event error_t PD_DATA.confirm(uint8_t status) {
-
-
-    return SUCCESS;     
-  }
-/*****************************************************
-****************       PD_DATA     ********************
-******************************************************/ 
-
-async event error_t PD_DATA.indication(uint8_t psduLenght,uint8_t* psdu, int8_t ppduLinkQuality){
-/*
-MPDU *packet;
-
-uint8_t destination_address=0;
-
-dest_short *dest_short_ptr;
-dest_long *dest_long_ptr;
-       
-beacon_addr_short *beacon_addr_short_ptr;
-
-*/
-atomic{
-               //if(I_AM_IN_CAP == 1 || I_AM_IN_CFP == 1 || mac_PIB.macShortAddress==0xffff || scanning_channels ==1 || findabeacon == 1)
-               //{
-                       if (buffer_count > RECEIVE_BUFFER_SIZE)
-                       {
-                               //call Leds.redToggle();
-                               printfUART("full\n","");
-                       }
-                       else
-                       {
-               
-                               /*
-                               packet = (MPDU*)psdu;
-                                                       
-                               
-                               switch ((packet->frame_control1 & 0x7))
-                               {
-                                       case TYPE_BEACON:
-                                                                       beacon_addr_short_ptr = (beacon_addr_short *) &packet->data[0];
-                                                                       
-                                                                       //avoid VERIFY static assignment of coordinator parent
-                                                                       if (beacon_addr_short_ptr->source_address != mac_PIB.macCoordShortAddress)
-                                                                       {
-                                                                                       printfUART("pb %x %x\n", beacon_addr_short_ptr->source_address,mac_PIB.macCoordShortAddress);
-                                                                                       return SUCCESS;
-                                                                       }
-                                                                       
-                                                                       /*
-                                                                       
-                                                                       if ( mac_PIB.macShortAddress != 0xffff)
-                                                                       {
-                                                                               if ( beacon_addr_short_ptr->source_address != mac_PIB.macCoordShortAddress)
-                                                                               {
-                                                                                       printfUART("pb %x %x\n", beacon_addr_short_ptr->source_address,mac_PIB.macCoordShortAddress);
-                                                                                       return SUCCESS;
-                                                                               }
-                                                                       }*/
-                                       /*
-                                       break;
-                                       case TYPE_DATA:
-                                       case TYPE_CMD:
-                                                                       //VALIDATION OF DESTINATION ADDRESSES - NOT TO OVERLOAD THE PROCESSOR
-                                                                       destination_address=get_fc2_dest_addr(packet->frame_control2);
-                               
-                                                                       if (destination_address > 1)
-                                                                       {
-                                                                               switch(destination_address)
-                                                                               {
-                                                                                       case SHORT_ADDRESS: 
-                                                                                                                               dest_short_ptr = (dest_short *) &packet->data[0];
-                                                                                                                               
-                                                                                                                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
-                                                                                                                               {
-                                                                                                                                       printfUART("nsm %x %x\n", dest_short_ptr->destination_address,mac_PIB.macShortAddress); 
-                                                                                                                                       return SUCCESS;
-                                                                                                                               }
-                                                                                                                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                                                                                                                               //broadcast PAN identifier (0 x ffff).
-                                                                                                                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                                                                                                                               {
-                                                                                                                                       printfUART("wsP %x %x \n", dest_short_ptr->destination_PAN_identifier,mac_PIB.macPANId); 
-                                                                                                                                       return SUCCESS;
-                                                                                                                               }
-                                                                                                                               break;
-                                                                                       
-                                                                                       case LONG_ADDRESS: 
-                                                                                                                               dest_long_ptr = (dest_long *) &packet->data[0];
-                                                                                                                               
-                                                                                                                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
-                                                                                                                               {
-                                                                                                                                       printfUART("nlm %x %x \n",dest_long_ptr->destination_address0,dest_long_ptr->destination_address1); 
-                                                                                                                                       return SUCCESS;
-                                                                                                                               }
-                                                                                                                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                                                                                                                               //broadcast PAN identifier (0 x ffff).
-                                                                                                                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                                                                                                                               {
-                                                                                                                                       printfUART("wLP %x %x\n", dest_long_ptr->destination_PAN_identifier,mac_PIB.macPANId); 
-                                                                                                                                       return SUCCESS;
-                                                                                                                               }
-                                                                                                                               
-                                                                                                                               break;
-                                                                               }
-                                                                       }
-                                       
-
-                                       
-                                                                       break;
-                                       case TYPE_ACK:
-                               
-                                                                       break;
-                               }
-                                               
-                               */
-                               memcpy(&buffer_msg[current_msg_in],psdu,sizeof(MPDU));
-
-                               atomic{
-                                       current_msg_in++;
-                               
-                                       if ( current_msg_in == RECEIVE_BUFFER_SIZE ) 
-                                               current_msg_in = 0;
-               
-                                       buffer_count ++;
-                               }
-                               
-                               link_quality = ppduLinkQuality;
-                               
-                               if (scanning_channels ==1)
-                               {
-                                       //channel scan operation, accepts beacons only
-                                       post data_channel_scan_indication();
-                               
-                               }
-                               else
-                               {
-                               //normal operation
-                                       post data_indication();
-                               }
-                       }
-               //}
-               //else
-               //{
-               //      printfUART("drop\n","");
-               //}
-}
-return SUCCESS;
-}
-
-
-
-task void data_indication()
-{
-       //check all the conditions for a receiver packet
-    //pag 155
-       uint8_t link_qual;
-       
-       atomic link_qual = link_quality;
-
-       //printfUART("data_indication\n","");
-       ////////printfUART("buf  %i %i\n",buffer_count,indirect_trans_count);
-
-       //Although the receiver of the device is enabled during the channel assessment portion of this algorithm, the
-       //device shall discard any frames received during this time.
-       ////////////printfUART("performing_csma_ca: %i\n",performing_csma_ca);
-       if (performing_csma_ca == 1)
-       {       
-               ////////////printfUART("REJ CSMA\n","");
-               atomic{ 
-                       buffer_count--;
-               
-                       current_msg_out++;
-               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
-                       current_msg_out = 0;
-                       }
-               
-               return;
-    }
-       
-       //while performing channel scan disable the packet reception
-       if ( scanning_channels == 1)
-       {       
-               atomic{ 
-                       buffer_count--;
-       
-                       current_msg_out++;
-               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
-                       current_msg_out = 0;
-                       }
-               return;
-       }       
-atomic{
-
-    ////printfUART("data ind %x %x %i\n",buffer_msg[current_msg_out].frame_control1,buffer_msg[current_msg_out].frame_control2,(buffer_msg[current_msg_out].frame_control2 & 0x7));
-       
-       //check the frame type of the received packet
-       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
-       {
-               
-                       case TYPE_DATA: //printfUART("rd %i\n",buffer_msg[current_msg_out].seq_num);
-                                                       indication_data(&buffer_msg[current_msg_out],link_qual);
-                                                       break;
-                                                       
-                       case TYPE_ACK: //printfUART("ra\n","");
-                                                       //ack_received = 1;
-                                                       indication_ack(&buffer_msg[current_msg_out],link_qual);
-                                                       
-                                                       break;
-                                                       
-                       case TYPE_CMD:  //printfUART("rc\n","");
-                                                       indication_cmd(&buffer_msg[current_msg_out],link_qual);
-                                                       break;
-                       
-                       case TYPE_BEACON:
-                                                       
-                                                       //printfUART("rb %i\n",buffer_msg[current_msg_out].seq_num);
-                                                       if (mac_PIB.macShortAddress == 0x0000) 
-                                                       {
-                                                               buffer_count--;
-                                                       }
-                                                       else
-                                                       {
-                                                               process_beacon(&buffer_msg[current_msg_out],link_qual);
-                                                               
-                                                       }
-
-                                                       break;
-                       default: 
-                                               atomic buffer_count--;
-                                               ////printfUART("Invalid frame type\n","");
-
-                                               break;
-       }
-       atomic{
-                       current_msg_out++;
-               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
-                       current_msg_out = 0;
-               }
-       }
-       return;
-}
-
-
-
-/*****************************************************
-****************PLME_ED EVENTS***********************
-******************************************************/ 
-event error_t PLME_CCA.confirm(uint8_t status){
-return SUCCESS;
-}
-   
-   
-event error_t PLME_SET.confirm(uint8_t status, uint8_t PIBAttribute){   
-return SUCCESS;
-}
-async event error_t PLME_SET_TRX_STATE.confirm(uint8_t status){
-
-return SUCCESS;
-}    
-   
-event error_t PLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue){
-   
-return SUCCESS;
-}    
-
-event error_t PLME_ED.confirm(uint8_t status,int8_t EnergyLevel){
-
-return SUCCESS;
-}
-
-/*******************************************************************************************************/
-/*******************************************************************************************************/
-/*******************************************************************************************************/
-/****************************************PACKET PROCESSING FUNCTIONS************************************/
-/*******************************************************************************************************/
-/*******************************************************************************************************/
-/*******************************************************************************************************/
-
-void process_beacon(MPDU *packet,uint8_t ppduLinkQuality)
-{
-
-       /*
-       ORGANIZE THE PROCESS BEACON FUNCION AS FOLLOWS.
-       1- GET THE BEACON ORDER
-       2- GET THE SUPERFRAME ORDER
-       3- GET THE FINAL CAP SLOT
-       4 - COMPUTE SD, BI, TS, BACKOFF PERIOD IN MILLISECONDS
-       
-       4- SYNCHRONIZE THE NODE BY DOING THE FOLLOWING
-               - SET A TIMER IN MS FOR THE FINAL TIME SLOT (SUPERFRAME DURATION) : IT EXPRIES AFTER SD - TX TIME - PROCESS TIME
-               - SET A TIMER IN MS FOR THE GTS IF ANY EXIST IT EXPRIES AFTER GTS_NBR * TIME_SLOT - TX TIME - PROCESS TIME 
-       */
-       uint32_t SO_EXPONENT;
-       uint32_t BO_EXPONENT;
-       int i=0;
-       uint16_t gts_descriptor_addr;
-       uint8_t data_count;
-       
-       uint8_t gts_directions;
-       uint8_t gts_des_count;
-       
-       uint8_t gts_ss;
-       uint8_t gts_l;
-       uint8_t dir;
-       uint8_t dir_mask;
-
-       //end gts variables
-
-       //function that processes the received beacon
-       beacon_addr_short *beacon_ptr;
-       
-       PANDescriptor pan_descriptor;
-
-       // beacon_trans_delay = (((packet->length(bytes) * 8.0) / 250.00(bits/s) ) / 0.34(s) (timer_granularity) ) (symbols)
-
-       //pending frames
-       uint8_t short_addr_pending=0;
-       uint8_t long_addr_pending=0;
-
-       //used in the synchronization
-       //uint32_t process_tick_counter; //symbols
-       
-       //uint32_t becon_trans_delay; //symbols
-       //uint32_t start_reset_ct; //number of clock ticks since the start of the beacon interval
-       
-       //used in the track beacon
-       beacon_processed = 1;
-       missed_beacons=0;
-       
-       //initializing pointer to data structure
-       beacon_ptr = (beacon_addr_short*) (packet->data);
-       
-       
-               //decrement buffer count
-       atomic buffer_count --;
-       
-       //printfUART("Received Beacon\n","");
-       //printfUART("rb panid: %x %x \n",beacon_ptr->source_address,mac_PIB.macCoordShortAddress);
-       //////printfUART("My macPANID: %x\n",mac_PIB.macPANId);
-       printfUART("rb %x %x\n",beacon_ptr->source_address,mac_PIB.macCoordShortAddress);
-       if( beacon_ptr->source_address != mac_PIB.macCoordShortAddress)
-       {
-               printfUART("nmp \n","");
-               return;
-       }
-       //printfUART("bea %i\n",call TimerAsync.get_current_ticks());
-       
-       /**********************************************************************************/
-       /*                                      PROCESSING THE SUPERFRAME STRUCTURE                                                       */
-       /**********************************************************************************/
-       
-       if (PANCoordinator == 0)
-       {
-               mac_PIB.macBeaconOrder = get_beacon_order(beacon_ptr->superframe_specification);
-               mac_PIB.macSuperframeOrder = get_superframe_order(beacon_ptr->superframe_specification);
-               
-               //mac_PIB.macCoordShortAddress = beacon_ptr->source_address;
-               
-               //printfUART("BO,SO:%i %i\n",mac_PIB.macBeaconOrder,mac_PIB.macSuperframeOrder);
-               
-               //mac_PIB.macPANId = beacon_ptr->source_PAN_identifier;
-               
-               //beacon order check if it changed
-               if (mac_PIB.macSuperframeOrder == 0)
-               {
-                       SO_EXPONENT = 1;
-               }
-               else
-               {
-                       SO_EXPONENT = powf(2,mac_PIB.macSuperframeOrder);
-               }
-               
-               if ( mac_PIB.macBeaconOrder ==0)
-               {
-                       BO_EXPONENT =1;
-               }
-               else
-               {
-                               BO_EXPONENT = powf(2,mac_PIB.macBeaconOrder);
-               }
-               BI = aBaseSuperframeDuration * BO_EXPONENT; 
-               SD = aBaseSuperframeDuration * SO_EXPONENT; 
-               
-               //backoff_period
-               backoff = aUnitBackoffPeriod;
-               time_slot = SD / NUMBER_TIME_SLOTS;
-               
-               call TimerAsync.set_bi_sd(BI,SD);
-       }       
-               
-       /**********************************************************************************/
-       /*                                                      PROCESS GTS CHARACTERISTICS                                                       */
-       /**********************************************************************************/
-               allow_gts =1;
-       
-               //initializing the gts variables
-               s_GTSss=0;
-               s_GTS_length=0;
-               
-               r_GTSss=0;
-               r_GTS_length=0;
-               
-               /*
-               send_s_GTSss=0;  
-               send_r_GTSss=0; 
-               send_s_GTS_len=0;
-               send_r_GTS_len=0;
-               */
-               final_CAP_slot = 15;
-
-
-               gts_des_count = (packet->data[8] & 0x0f);
-               
-               data_count = 9;
-               
-               final_CAP_slot = 15 - gts_des_count;
-               
-               if (gts_des_count > 0 )
-               {
-               data_count = 10; //position of the current data count
-               //process descriptors
-               
-                       gts_directions = packet->data[9];
-                       
-                       //printfUART("gts_directions:%x\n",gts_directions);
-                       
-                       for(i=0; i< gts_des_count; i++)
-                       {       
-                               gts_descriptor_addr = (uint16_t) packet->data[data_count];
-                                       
-                               //printfUART("gts_des_addr:%x mac short:%x\n",gts_descriptor_addr,mac_PIB.macShortAddress);
-                               
-                               data_count = data_count+2;
-                               //check if it concerns me
-                               if (gts_descriptor_addr == mac_PIB.macShortAddress)
-                               {
-                                       //confirm the gts request
-                                       ////////////printfUART("packet->data[data_count]: %x\n",packet->data[data_count]);
-                                       //gts_ss = 15 - get_gts_descriptor_ss(packet->data[data_count]);
-                                       gts_ss = get_gts_descriptor_ss(packet->data[data_count]);
-                                       gts_l = get_gts_descriptor_len(packet->data[data_count]);
-
-                                       if ( i == 0 )
-                                       {
-                                               dir_mask=1;
-                                       }
-                                       else
-                                       {
-                                       
-                                                       dir_mask = powf(2,i);
-                                       }
-                                       ////////////printfUART("dir_mask: %x i: %x gts_directions: %x \n",dir_mask,i,gts_directions);
-                                       dir = ( gts_directions & dir_mask);
-                                       if (dir == 0)
-                                       {
-                                               s_GTSss=gts_ss;
-                                               s_GTS_length=gts_l;
-                                       }
-                                       else
-                                       {
-
-                                               r_GTSss=gts_ss;
-                                               r_GTS_length=gts_l;
-                                       }
-                                       
-                                       //printfUART("PB gts_ss: %i gts_l: %i dir: %i \n",gts_ss,gts_l,dir);
-                                       ////////////printfUART("PB send_s_GTSss: %i send_s_GTS_len: %i\n",send_s_GTSss,send_s_GTS_len);
-                                       
-                                       if ( gts_l == 0 )
-                                       {
-                                               allow_gts=0;
-                                       }
-
-                                       if (gts_confirm == 1 && gts_l != 0)
-                                       {
-                                               //signal ok
-                                               //printfUART("gts confirm \n","");
-                                               gts_confirm =0;
-                                               signal MLME_GTS.confirm(GTS_specification,MAC_SUCCESS);
-                                       }
-                                       else
-                                       {
-                                               //signal not ok
-                                               ////////////printfUART("gts not confirm \n","");
-                                               gts_confirm =0;
-                                               signal MLME_GTS.confirm(GTS_specification,MAC_DENIED);
-                                       }
-                                       
-                               }
-                               data_count++;   
-                       }
-               }
-       
-       /**********************************************************************************/
-       /*                                                      PROCESS PENDING ADDRESSES INFORMATION                             */
-       /**********************************************************************************/    
-               //this should pass to the network layer
-               
-               
-               short_addr_pending=get_number_short(packet->data[data_count]);
-               long_addr_pending=get_number_extended(packet->data[data_count]);
-               
-               //////////printfUART("ADD COUNT %i %i\n",short_addr_pending,long_addr_pending);
-               
-               data_count++;
-               
-               if(short_addr_pending > 0)
-               {
-                       for(i=0;i < short_addr_pending;i++)
-                       {
-                               //////////printfUART("PB %i %i\n",(uint16_t)packet->data[data_count],short_addr_pending);
-                               
-                               //if(packet->data[data_count] == (uint8_t)mac_PIB.macShortAddress && packet->data[data_count+1] == (uint8_t)(mac_PIB.macShortAddress >> 8) )
-                               if((uint16_t)packet->data[data_count] == mac_PIB.macShortAddress)
-                               {
-                                       
-                                       create_data_request_cmd();
-                               }
-                               data_count = data_count + 2;
-                       }
-               }
-               if(long_addr_pending > 0)
-               {
-                       for(i=0; i < long_addr_pending;i++)
-                       {
-                               if((uint32_t)packet->data[data_count] == aExtendedAddress0 && (uint32_t)packet->data[data_count + 4] == aExtendedAddress1)
-                               {
-                                       
-                                       data_count = data_count + 8;
-
-                               }
-                       
-                       }
-               }
-
-       /**********************************************************************************/
-       /*                              BUILD the PAN descriptor of the COORDINATOR                                               */
-       /**********************************************************************************/
-               
-               
-          //Beacon NOTIFICATION
-          //BUILD the PAN descriptor of the COORDINATOR
-               //assuming that the adress is short
-               pan_descriptor.CoordAddrMode = SHORT_ADDRESS;
-               pan_descriptor.CoordPANId = 0x0000;//beacon_ptr->source_PAN_identifier;
-               pan_descriptor.CoordAddress0=0x00000000;
-               pan_descriptor.CoordAddress1=mac_PIB.macCoordShortAddress;
-               pan_descriptor.LogicalChannel=current_channel;
-               //superframe specification field
-               pan_descriptor.SuperframeSpec = beacon_ptr->superframe_specification;
-               
-               pan_descriptor.GTSPermit=mac_PIB.macGTSPermit;
-               pan_descriptor.LinkQuality=0x00;
-               pan_descriptor.TimeStamp=0x000000;
-               pan_descriptor.SecurityUse=0;
-               pan_descriptor.ACLEntry=0x00;
-               pan_descriptor.SecurityFailure=0x00;
-          
-               //I_AM_IN_CAP = 1;
-          
-       /**********************************************************************************/
-       /*                                                              SYNCHRONIZING                                                                     */
-       /**********************************************************************************/
-
-       //processing time + beacon transmission delay
-       
-       //removed not used
-       //process_tick_counter = call TimerAsync.get_process_frame_tick_counter();
-       //removed not used      
-       //start_reset_ct = ((1000 * (packet->length * 8.0) / 250)) / 69.54;  //(process_tick_counter - receive_tick_counter);
-
-       if(PANCoordinator == 0)
-       {
-                       I_AM_IN_CAP = 1;
-                       I_AM_IN_IP = 0;
-                       
-                       //call Leds.yellowOn();
-                       call Leds.led2On();
-                       
-                       call Leds.led1On();
-                       
-                       if(findabeacon == 1)
-                       {
-                               //printfUART("findabeacon\n", "");
-                               call TimerAsync.set_timers_enable(1);
-                               findabeacon =0;
-                       }
-                       
-                       //#ifdef PLATFORM_MICAZ
-                       //number_time_slot = call TimerAsync.reset_start(start_reset_ct+process_tick_counter+52);// //SOBI=3 52 //SOBI=0 15
-                       //#else
-                       
-                       //call TimerAsync.reset();
-                       
-                       number_time_slot = call TimerAsync.reset_start(75);   //95 old val sem print
-                                       
-                       // +process_tick_counter+52 //SOBI=3 52 //SOBI=0 
-                       //#endif
-                       on_sync=1;
-                       
-                       printfUART("sE\n", "");
-       }
-       else
-       {
-               I_AM_IN_PARENT_CAP = 1;
-               
-               call TimerAsync.set_track_beacon(1);
-               
-               //#ifdef PLATFORM_MICAZ
-               //      call TimerAsync.set_track_beacon_start_ticks(parent_offset,0x00001E00,(start_reset_ct+process_tick_counter+18));
-               //#else
-                       call TimerAsync.set_track_beacon_start_ticks(parent_offset,0x00001E00,4);//(start_reset_ct)
-               //#endif
-               
-               printfUART("sP \n", "");
-       }
-       
-       call Leds.led1Toggle();
-       signal MLME_BEACON_NOTIFY.indication((uint8_t)packet->seq_num,pan_descriptor,0, 0, mac_PIB.macBeaconPayloadLenght, packet->data);
-               
-return;
-}
-
-
-void process_gts_request(MPDU *pdu)
-{
-               error_t status;
-               cmd_gts_request *mac_gts_request;
-               
-               mac_gts_request= (cmd_gts_request*) &pdu->data;
-               
-atomic{                
-               if ( get_characteristic_type(mac_gts_request->gts_characteristics) == 1)
-               {
-               //allocation
-       
-       //process the gts request
-               status = add_gts_entry(get_gts_length(mac_gts_request->gts_characteristics),get_gts_direction(mac_gts_request->gts_characteristics),mac_gts_request->source_address);
-               
-               }
-               else
-               {
-               //dealocation
-       
-               status = remove_gts_entry(mac_gts_request->source_address);
-               }
-               
-               signal MLME_GTS.indication(mac_gts_request->source_address, mac_gts_request->gts_characteristics, 0, 0);
-               
-               }
-
-return;
-}
-/****************DATA indication functions******************/
-
-void indication_data(MPDU *pdu, int8_t ppduLinkQuality)
-{
-       uint8_t data_len;
-       
-       uint8_t payload[80];
-       uint8_t msdu_length=0;
-       
-       //int i;
-       
-       uint32_t SrcAddr[2];
-       uint32_t DstAddr[2];
-       
-       
-       //frame control variables
-       uint8_t source_address=0;
-       uint8_t destination_address=0;
-
-
-       dest_short *dest_short_ptr;
-       dest_long *dest_long_ptr;
-       
-       source_short *source_short_ptr;
-       source_long *source_long_ptr;
-
-       //implement the intra PAN data messages
-       //intra_pan_source_short *intra_pan_source_short_ptr;
-       //intra_pan_source_long *intra_pan_source_long_ptr;
-       
-       
-       source_address=get_fc2_source_addr(pdu->frame_control2);
-       destination_address=get_fc2_dest_addr(pdu->frame_control2);
-       
-       //decrement buffer count
-       atomic buffer_count --;
-       
-       SrcAddr[0]=0x00000000;
-       SrcAddr[1]=0x00000000;
-       DstAddr[0]=0x00000000;
-       DstAddr[1]=0x00000000;
-
-
-       //printfUART("id %i %i \n",source_address,destination_address);
-
-
-       if ( get_fc1_intra_pan(pdu->frame_control1)== 0 )
-       {
-       //INTRA PAN
-               if (destination_address > 1 && source_address > 1)
-               {
-                       // Destination LONG - Source LONG       
-                       if (destination_address == LONG_ADDRESS && source_address == LONG_ADDRESS)
-                       {
-                               dest_long_ptr = (dest_long *) &pdu->data[0];
-                               source_long_ptr = (source_long *) &pdu->data[DEST_LONG_LEN];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
-                               {
-                                       //////////printfUART("data rejected, ext destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               data_len = 20;
-                               
-                               
-                               DstAddr[1] = dest_long_ptr->destination_address0;
-                               DstAddr[0] =dest_long_ptr->destination_address1;
-                               
-                               SrcAddr[1] =source_long_ptr->source_address0;
-                               SrcAddr[0] =source_long_ptr->source_address1;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-                               
-                       }
-                       
-                       // Destination SHORT - Source LONG
-                       if ( destination_address == SHORT_ADDRESS && source_address == LONG_ADDRESS )
-                       {
-                               dest_short_ptr = (dest_short *) &pdu->data[0];
-                               source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
-                               {
-                                       //////////printfUART("data rejected, short destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 14;
-                               
-                               DstAddr[0] =dest_short_ptr->destination_address;
-                               
-                               SrcAddr[1] =source_long_ptr->source_address0;
-                               SrcAddr[0] =source_long_ptr->source_address1;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-                       // Destination LONG - Source SHORT
-                       if ( destination_address == LONG_ADDRESS && source_address == SHORT_ADDRESS )
-                       {
-                               dest_long_ptr = (dest_long *) &pdu->data[0];
-                               source_short_ptr = (source_short *) &pdu->data[DEST_LONG_LEN];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
-                               {
-                                       //////////printfUART("data rejected, ext destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 14;
-                               
-                               DstAddr[1] = dest_long_ptr->destination_address0;
-                               DstAddr[0] =dest_long_ptr->destination_address1;
-                               
-                               
-                               SrcAddr[0] =source_short_ptr->source_address;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-                       
-                       
-                       //Destination SHORT - Source SHORT
-                       if ( destination_address == SHORT_ADDRESS && source_address == SHORT_ADDRESS )  
-                       {
-                               dest_short_ptr = (dest_short *) &pdu->data[0];
-                               source_short_ptr = (source_short *) &pdu->data[DEST_SHORT_LEN];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
-                               {
-                                       //printfUART("data rejected, short destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       //printfUART("SH SH data rejected, wrong destination PAN %x\n",mac_PIB.macPANId ); 
-                                       return;
-                               }
-                               
-                               data_len = 8;
-                               
-                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                               {
-                                       build_ack(pdu->seq_num,0);
-                               }
-                               
-                               DstAddr[0] =dest_short_ptr->destination_address;
-                               
-                               SrcAddr[0] =source_short_ptr->source_address;
-                               
-                               msdu_length = (pdu->length - 5) - data_len;
-                               
-                               
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                       
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length,payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-               }
-               
-               /*********NO DESTINATION ADDRESS PRESENT ****************/
-               
-               if ( destination_address == 0 && source_address > 1 )
-               {
-                               
-                       if (source_address == LONG_ADDRESS)
-                       {//Source LONG
-                               source_long_ptr = (source_long *) &pdu->data[0];
-                               
-                               //If only source addressing fields are included in a data or MAC command frame, the frame shall be
-                               //accepted only if the device is a PAN coordinator and the source PAN identifier matches macPANId.
-                               if ( PANCoordinator==0 || source_long_ptr->source_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       //////////printfUART("data rejected, im not pan\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 10;
-                               
-                               SrcAddr[1] =source_long_ptr->source_address0;
-                               SrcAddr[0] =source_long_ptr->source_address1;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address,(uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, 0x0000, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-                       else
-                       {//Source SHORT
-
-                               source_short_ptr = (source_short *) &pdu->data[0];
-                               //If only source addressing fields are included in a data or MAC command frame, the frame shall be
-                               //accepted only if the device is a PAN coordinator and the source PAN identifier matches macPANId.
-                               if ( PANCoordinator==0 || source_short_ptr->source_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       //////////printfUART("data rejected, im not pan\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 4;
-
-                               
-                               SrcAddr[0] =source_short_ptr->source_address;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, 0x0000, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-               }
-               /*********NO SOURCE ADDRESS PRESENT ****************/
-               
-               if ( destination_address > 1 && source_address == 0 )
-               {
-                       if (destination_address == LONG_ADDRESS)
-                       {//Destination LONG
-                               dest_long_ptr = (dest_long *) &pdu->data[0];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
-                               {
-                                       //////////printfUART("data rejected, ext destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 10;
-                               
-                               DstAddr[1] = dest_long_ptr->destination_address0;
-                               DstAddr[0] =dest_long_ptr->destination_address1;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                       
-                               signal MCPS_DATA.indication((uint16_t)source_address,0x0000, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                       }
-                       else
-                       {//Destination SHORT
-                               dest_short_ptr = (dest_short *) &pdu->data[0];
-                               
-                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
-                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
-                               //shall match aExtendedAddress.
-                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
-                               {
-                                       //////////printfUART("data rejected, short destination not for me\n", ""); 
-                                       return;
-                               }
-                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
-                               //broadcast PAN identifier (0 x ffff).
-                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
-                               {
-                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
-                                       return;
-                               }
-                               
-                               data_len = 4;
-                               
-                               DstAddr[0] =dest_short_ptr->destination_address;
-                               
-                               msdu_length = pdu->length - data_len;
-
-                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
-                               
-                               
-                               signal MCPS_DATA.indication((uint16_t)source_address,0x0000, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
-
-                               data_len = 4;
-                       }
-               }
-               
-       }
-       else
-       {
-       //intra_pan == 1
-       
-       
-       
-       }
-       
-       
-return;
-}
-
-void indication_cmd(MPDU *pdu, int8_t ppduLinkQuality)
-{
-               uint8_t cmd_type;
-               //uint8_t pk_ptr;
-               uint8_t addressing_fields_length=0;
-               
-               uint32_t SrcAddr[2];
-               //uint32_t DstAddr[2];//NOT USED SO FAR
-               
-               //frame control variables
-               uint8_t source_address=0;
-               uint8_t destination_address=0;
-       
-               //NOT USED SO FAR
-               //dest_short *dest_short_ptr;
-               //dest_long *dest_long_ptr;
-               //NOT USED SO FAR
-               //source_short *source_short_ptr;
-               source_long *source_long_ptr;
-               
-               dest_short *dest_short_ptr;
-               dest_long *dest_long_ptr;
-               
-               //CHECK IMPLEMENT
-               //intra_pan_source_short *intra_pan_source_short_ptr; 
-               //intra_pan_source_long *intra_pan_source_long_ptr;
-               
-               destination_address=get_fc2_dest_addr(pdu->frame_control2);
-               source_address=get_fc2_source_addr(pdu->frame_control2);
-               
-               //decrement buffer count
-               atomic buffer_count --;
-               
-               switch(destination_address)
-               {
-                       case LONG_ADDRESS: addressing_fields_length = DEST_LONG_LEN;
-                                                               dest_long_ptr = (dest_long *) &pdu->data[0];
-                                                               if(dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1)
-                                                               {
-                                                                       printfUART("NOT FOR ME","");
-                                                                       return;
-                                                               }
-                                                               
-                                                               break;
-                       case SHORT_ADDRESS: addressing_fields_length = DEST_SHORT_LEN;
-                                                               dest_short_ptr= (dest_short *) &pdu->data[0];
-                                                               //destination command not for me
-                                                               if (dest_short_ptr->destination_address != mac_PIB.macShortAddress && dest_short_ptr->destination_address !=0xffff)
-                                                               {
-                                                                       printfUART("NOT FOR ME","");
-                                                                       //////////printfUART("NOT FOR ME %x me %e\n", dest_short_ptr->destination_address,mac_PIB.macShortAddress); 
-                                                                       return;
-                                                               }
-                                                               break;
-               }
-               switch(source_address)
-               {
-                       case LONG_ADDRESS: addressing_fields_length = addressing_fields_length + SOURCE_LONG_LEN;
-                                                               break;
-                       case SHORT_ADDRESS: addressing_fields_length = addressing_fields_length + SOURCE_SHORT_LEN;
-                                                               break;
-               }
-
-               cmd_type = pdu->data[addressing_fields_length];
-               
-                               
-               switch(cmd_type)
-               {
-               
-               case CMD_ASSOCIATION_REQUEST:   
-                                                                       //check if association is allowed, if not discard the frame             
-                                                                       
-                                                                       //////printfUART("CMD_ASSOCIATION_REQUEST \n", "");
-                                                                       
-                                                                               
-                                                                                       if (mac_PIB.macAssociationPermit == 0 )
-                                                                                       {
-                                                                                               //////////printfUART("Association not alowed\n", "");
-                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                                               {
-                                                                                                       build_ack(pdu->seq_num,0);
-                                                                                               }
-                                                                                               return;
-                                                                                       }
-                                                                                       
-                                                                                       if ( PANCoordinator==0 )
-                                                                                       {
-                                                                                               //////////printfUART("i´m not a pan\n", ""); 
-                                                                                               return;
-                                                                                       }
-                                                                       atomic{
-                                                                                       source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
-                                                                                       
-                                                                                       SrcAddr[1] =source_long_ptr->source_address0;
-                                                                                       SrcAddr[0] =source_long_ptr->source_address1;
-                                                                                       
-                                                                                       
-                                                                                       signal MLME_ASSOCIATE.indication(SrcAddr, pdu->data[addressing_fields_length+1] , 0, 0);
-
-                                                                                       }
-                                                                                       
-                                                                                       if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                                       {
-                                                                                               build_ack(pdu->seq_num,1);
-                                                                                       }       
-
-                                                                                       
-                                                                       break;
-               
-               case CMD_ASSOCIATION_RESPONSE: atomic{
-                                                                                               printfUART("CMD_ASSOCIATION_RESPONSE\n", ""); 
-                                                                                               
-                                                                                               associating =0;
-                                                                                               call T_ResponseWaitTime.stop();
-                                                                                               
-                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                                               {
-                                                                                                       build_ack(pdu->seq_num,0);
-                                                                                               }
-                                                                                       
-                                                                                               signal MLME_ASSOCIATE.confirm((uint16_t)(pdu->data[addressing_fields_length+1] + (pdu->data[addressing_fields_length+2] << 8)), pdu->data[addressing_fields_length+3]);
-                                                                                               }
-                                                                               break;
-
-               case CMD_DISASSOCIATION_NOTIFICATION:   //////////printfUART("Received CMD_DISASSOCIATION_NOTIFICATION\n", ""); 
-                                                                                               
-                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                                               {
-                                                                                                       build_ack(pdu->seq_num,0);
-                                                                                               }
-                                                                                               
-                                                                                               process_dissassociation_notification(pdu);
-                                                                                               break;
-               case CMD_DATA_REQUEST: 
-                                                               //printfUART("CMD_DATA_REQUEST\n", ""); 
-                                                                       //////printfUART("DR\n", "");
-                                                                       if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                                       {
-                                                                               //TODO
-                                                                               //Problems with consecutive reception of messages
-                                                                               
-                                                                               build_ack(pdu->seq_num,0);
-                                                                       }
-                                                                       
-                                                                       //cmd_data_request_0_3_reception = (cmd_data_request_0_3 *) pdu->data;
-                                                                       
-                                                                       source_long_ptr = (source_long *) &pdu->data[0];
-                                                                                       
-                                                                       SrcAddr[1] =source_long_ptr->source_address0;
-                                                                       SrcAddr[0] =source_long_ptr->source_address1;
-                                                                       
-                                                                       send_ind_trans_addr(SrcAddr);
-
-                                                               break;
-               case CMD_PANID_CONFLICT:
-                                                               break;
-                                                               
-               case CMD_ORPHAN_NOTIFICATION:
-                                                                       //printfUART("CMD_ORPHAN_NOTIFICATION\n", ""); 
-                                                                       
-                                                                       source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
-                                                                                       
-                                                                       SrcAddr[1] =source_long_ptr->source_address0;
-                                                                       SrcAddr[0] =source_long_ptr->source_address1;
-                                                                       
-                                                                       signal MLME_ORPHAN.indication(SrcAddr, 0x00,0x00);
-                                                               
-               
-                                                               break;
-               case CMD_BEACON_REQUEST:
-                                                               break;
-               case CMD_COORDINATOR_REALIGNMENT:
-                                                                       printfUART("CMD_COORDINATOR_REALIGNMENT\n", ""); 
-                                                                       
-                                                                       process_coordinator_realignment(pdu);
-                                                                       
-                                                               break;
-               case CMD_GTS_REQUEST:   
-                                                               ////////////printfUART("Received CMD_GTS_REQUEST\n", ""); 
-                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
-                                                               {
-                                                                       build_ack(pdu->seq_num,0);
-                                                               }
-                                                               process_gts_request(pdu);
-                                                               break;
-               default: break;
-
-               }
-
-return;
-}
-
-void indication_ack(MPDU *pdu, int8_t ppduLinkQuality)
-{
-       //decrement buffer count
-
-       atomic buffer_count --;
-
-       ////////////printfUART("ACK Received\n",""); 
-       
-       atomic{
-                       if (send_ack_check == 1 && ack_sequence_number_check == pdu->seq_num)
-                       {
-                               //transmission SUCCESS
-                               call T_ackwait.stop();
-                               
-                               send_buffer_count --;
-                               send_buffer_msg_out++;
-                               
-                               //failsafe
-                               if(send_buffer_count > SEND_BUFFER_SIZE)
-                               {
-                                       send_buffer_count =0;
-                                       send_buffer_msg_out=0;
-                                       send_buffer_msg_in=0;
-                               }
-                               
-                               if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                       send_buffer_msg_out=0;
-                               
-                               //received an ack for the association request
-                               if( associating == 1 && association_cmd_seq_num == pdu->seq_num )
-                               {
-                                       //////////printfUART("ASSOC ACK\n",""); 
-                                       call T_ResponseWaitTime.startOneShot(response_wait_time);
-                                       //call T_ResponseWaitTime.start(TIMER_ONE_SHOT, response_wait_time);
-                               }
-                               
-                               if (gts_request == 1 && gts_request_seq_num == pdu->seq_num)
-                               {
-                               
-                                       call T_ResponseWaitTime.startOneShot(response_wait_time);
-                                       //call T_ResponseWaitTime.start(TIMER_ONE_SHOT, response_wait_time);
-                               }
-                               
-                               //////////printfUART("TRANSMISSION SUCCESS\n",""); 
-
-                               if (send_indirect_transmission > 0 )
-                               {       //the message send was indirect
-                                       //remove the message from the indirect transmission queue
-                                       indirect_trans_queue[send_indirect_transmission-1].handler=0x00;
-                                       indirect_trans_count--;
-                                       //////////printfUART("SU id:%i ct:%i\n", send_indirect_transmission,indirect_trans_count);
-                               }
-                               
-                               send_ack_check=0;
-                               retransmit_count=0;
-                               ack_sequence_number_check=0;
-                               
-                               
-                               if (send_buffer_count > 0)
-                                       post send_frame_csma();
-                               
-                               
-                       }
-               }
-       
-                       //CHECK
-               if (get_fc1_frame_pending(pdu->frame_control1) == 1 && pending_request_data ==1)// && associating == 1
-               {               
-                               //////////printfUART("Frame_pending\n",""); 
-                               pending_request_data=0;
-                               create_data_request_cmd();
-               }
-               
-               //GTS mechanism, after the confirmation of the GTS request, must check if the beacon has the gts
-               /*
-               if (gts_ack == 1)
-               {
-                       gts_ack=0;
-                       gts_confirm=1;
-                       call T_ResponseWaitTime.stop();
-               
-               }
-       */
-               if(gts_send_pending_data==1)
-                       post start_gts_send();
-               
-               if(coordinator_gts_send_pending_data==1 && coordinator_gts_send_time_slot == number_time_slot)
-                       post start_coordinator_gts_send();
-       
-return;
-}
-
-
-void process_dissassociation_notification(MPDU *pdu)
-{
-atomic{
-               cmd_disassociation_notification *mac_disassociation_notification;
-               
-               //creation of a pointer to the disassociation notification structure
-               mac_disassociation_notification = (cmd_disassociation_notification*) pdu->data;                                                                 
-
-               signal MLME_DISASSOCIATE.indication(&mac_disassociation_notification->source_address0, mac_disassociation_notification->disassociation_reason, 0, 0);
-               }
-
-return;
-}
-
-
-
-
-void process_coordinator_realignment(MPDU *pdu)
-{
-
-atomic{
-       cmd_coord_realignment *cmd_realignment = 0;
-       
-       dest_long *dest_long_ptr=0;
-       source_short *source_short_ptr=0;
-
-       cmd_realignment = (cmd_coord_realignment*) &pdu->data[DEST_LONG_LEN + SOURCE_SHORT_LEN];
-       
-       //creation of a pointer the addressing structures
-       dest_long_ptr = (dest_long *) &pdu->data[0];
-       source_short_ptr = (source_short *) &pdu->data[DEST_LONG_LEN];
-               
-       mac_PIB.macCoordShortAddress = ((cmd_realignment->coordinator_short_address0 << 8) | cmd_realignment->coordinator_short_address0 );
-       mac_PIB.macShortAddress = cmd_realignment->short_address;
-       
-       
-       printfUART("PCR %i %i\n",mac_PIB.macCoordShortAddress,mac_PIB.macShortAddress); 
-       
-       }
-return;
-}
-
-
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/************************              BUILD FRAMES FUNCTIONS                          **********************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-
-
-task void create_beacon()
-{
-       int i=0;
-       uint8_t packet_length = 25;
-       int data_count=0;
-       int pending_data_index=0;
-       MPDU* pkt_ptr=0;
-       //pending frames
-       uint8_t short_addr_pending=0;
-       uint8_t long_addr_pending=0;
-               
-       uint8_t gts_directions=0x00;
-       
-       uint16_t frame_control;
-
-       
-       atomic{
-               
-               beacon_addr_short *mac_beacon_addr_short_ptr;
-               //mac_beacon_addr_short_ptr = (beacon_addr_short*) &mac_txmpdu.data[0];
-               mac_beacon_addr_short_ptr = (beacon_addr_short*) &mac_beacon_txmpdu.data[0];
-               //call PLME_SET_TRX_STATE.request(PHY_TX_ON);
-               
-               mac_beacon_txmpdu_ptr->length = 15;
-               
-               frame_control = set_frame_control(TYPE_BEACON,0,0,0,1,SHORT_ADDRESS,SHORT_ADDRESS);
-               
-               mac_beacon_txmpdu_ptr->frame_control1 = (uint8_t)( frame_control);
-               
-               mac_beacon_txmpdu_ptr->frame_control2 = (uint8_t)( frame_control >> 8);
-               
-               //mac_beacon_txmpdu_ptr->frame_control = set_frame_control(TYPE_BEACON,0,0,0,1,SHORT_ADDRESS,SHORT_ADDRESS);
-               mac_beacon_txmpdu_ptr->seq_num = mac_PIB.macBSN;
-               mac_PIB.macBSN++;
-               
-               
-               //relocation error
-               mac_beacon_addr_short_ptr->destination_PAN_identifier= mac_PIB.macPANId;
-               //relocation error
-               mac_beacon_addr_short_ptr->destination_address = 0xffff;
-               //relocation error
-               mac_beacon_addr_short_ptr->source_address = mac_PIB.macShortAddress;
-               if (mac_PIB.macShortAddress == 0x0000)
-               {       //the device is the PAN Coordinator
-                       mac_beacon_addr_short_ptr->superframe_specification = set_superframe_specification(mac_PIB.macBeaconOrder,(uint8_t)mac_PIB.macSuperframeOrder,final_CAP_slot,0,1,mac_PIB.macAssociationPermit);
-               }
-               else
-               {
-                       mac_beacon_addr_short_ptr->superframe_specification = set_superframe_specification(mac_PIB.macBeaconOrder,(uint8_t)mac_PIB.macSuperframeOrder,final_CAP_slot,0,1,mac_PIB.macAssociationPermit);
-               }
-               
-               mac_beacon_txmpdu_ptr->data[8] = set_gts_specification(GTS_descriptor_count,mac_PIB.macGTSPermit);
-               
-               mac_beacon_txmpdu_ptr->data[9] = set_pending_address_specification(short_addr_pending,long_addr_pending);
-               
-               data_count = 9;
-               packet_length = 15;
-               
-               
-               //BUILDING the GTS DESCRIPTORS
-               if( (GTS_descriptor_count + GTS_null_descriptor_count) > 0 )
-               {
-                       data_count++;
-                                       
-                       for(i=0; i< 7 ; i++)
-                       {
-                               if( GTS_db[i].gts_id != 0x00 && GTS_db[i].DevAddressType != 0x0000) 
-                               {
-                                       
-                                       mac_beacon_txmpdu_ptr->data[data_count] = GTS_db[i].DevAddressType;
-                                       ////////////printfUART("B gts %i\n", (GTS_db[i].DevAddressType >> 8 ) ); 
-                                       
-                                       data_count++;
-                                       mac_beacon_txmpdu_ptr->data[data_count] = (GTS_db[i].DevAddressType >> 8 );
-                                       ////////////printfUART("B gts %i\n",  GTS_db[i].DevAddressType ); 
-                                       
-                                       data_count++;
-                                       
-                                       mac_beacon_txmpdu_ptr->data[data_count] = set_gts_descriptor(15-i,GTS_db[i].length);
-                                       data_count++;
-                                       ////printfUART("B gts %i\n", set_gts_descriptor(GTS_db[i].starting_slot,GTS_db[i].length) ); 
-                                       
-                                       packet_length = packet_length + 3;
-                                       
-                                       if ( GTS_db[i].direction == 1 )
-                                       {
-                                               gts_directions = gts_directions | (1 << i); 
-                                       }
-                                       else
-                                       {
-                                               gts_directions = gts_directions | (0 << i); 
-                                       }
-                                       ////printfUART("dir %i\n", gts_directions); 
-                               }
-                       }
-                       mac_beacon_txmpdu_ptr->data[9] = gts_directions;
-                       //CHECK
-                       packet_length++;
-                       //BUILDING the NULL GTS DESCRIPTORS
-                       if ( GTS_null_descriptor_count > 0 )
-                       {
-                               for(i=0; i< 7 ; i++)
-                               {
-                                       if( GTS_null_db[i].DevAddressType != 0x0000) 
-                                       {
-                                               mac_beacon_txmpdu_ptr->data[data_count] = GTS_null_db[i].DevAddressType;
-                                               ////////////printfUART("B gts %i\n", (GTS_db[i].DevAddressType >> 8 ) ); 
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count] = (GTS_null_db[i].DevAddressType >> 8 );
-                                               ////////////printfUART("B gts %i\n",  GTS_db[i].DevAddressType ); 
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count] = 0x00;
-                                               data_count++;
-                                               ////////////printfUART("B gts %i\n", set_gts_descriptor(GTS_db[i].starting_slot,GTS_db[i].length) ); 
-                                               packet_length = packet_length +3;
-                                       }
-                               }
-                       }
-                       //resetting the GTS specification field
-                       mac_beacon_txmpdu_ptr->data[8] = set_gts_specification(GTS_descriptor_count + GTS_null_descriptor_count,mac_PIB.macGTSPermit);
-                       
-
-               }
-
-                       pending_data_index = data_count;
-                       data_count++;
-               //IMPLEMENT PENDING ADDRESSES
-               //temporary
-               //indirect_trans_count =0;
-               
-               if (indirect_trans_count > 0 )
-               {
-                               //IMPLEMENT THE PENDING ADDRESSES CONSTRUCTION
-
-                       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-                       {
-                               if (indirect_trans_queue[i].handler > 0x00)
-                               {
-                                       pkt_ptr = (MPDU *)&indirect_trans_queue[i].frame;
-                                       //ADD INDIRECT TRANSMISSION DESCRIPTOR
-                                       if(get_fc2_dest_addr(pkt_ptr->frame_control2) == SHORT_ADDRESS)
-                                       {
-                                               short_addr_pending++;
-                                               packet_length = packet_length + 2;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[2];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[3];
-                                               data_count++;
-                                       }
-                               }
-                       }
-                       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-                       {
-                               if (indirect_trans_queue[i].handler > 0x00)
-                               {
-                                       if(get_fc2_dest_addr(pkt_ptr->frame_control2) == LONG_ADDRESS)
-                                       {
-                                               long_addr_pending++;
-                                               packet_length = packet_length + 8;
-
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[0];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[1];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[2];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[3];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[4];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[5];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[6];
-                                               data_count++;
-                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[7];
-                                               data_count++;
-                                               
-                                       }
-                               }
-                       }
-                               
-               }
-               mac_beacon_txmpdu_ptr->data[pending_data_index] = set_pending_address_specification(short_addr_pending,long_addr_pending);
-               
-               /*
-               //adding the beacon payload
-               if (mac_PIB.macBeaconPayloadLenght > 0 )
-               {
-                       for (i=0;i < mac_PIB.macBeaconPayloadLenght;i++)
-                       {
-                               mac_beacon_txmpdu_ptr->data[data_count] = mac_PIB.macBeaconPayload[i];
-                               data_count++;
-                               packet_length++;
-                       }
-               
-               
-               }
-               */
-               mac_beacon_txmpdu_ptr->data[data_count] = 0x12;
-               data_count++;
-               packet_length++;
-               mac_beacon_txmpdu_ptr->data[data_count] = 0x34;
-               data_count++;
-               packet_length++;
-               
-               //short_addr_pending=0;
-               //long_addr_pending=0;
-               
-               mac_beacon_txmpdu_ptr->length = packet_length;
-               
-               send_beacon_length = packet_length;
-               
-               send_beacon_frame_ptr = (uint8_t*)mac_beacon_txmpdu_ptr;
-               }
-}
-
-
-void create_data_frame(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions,uint8_t on_gts_slot,uint8_t pan)
-{
-       
-       int i_indirect_trans=0;
-
-       dest_short *dest_short_ptr;
-       dest_long *dest_long_ptr;
-       
-       source_short *source_short_ptr;
-       source_long *source_long_ptr;
-
-       //intra_pan_source_short *intra_pan_source_short_ptr;
-       //intra_pan_source_long *intra_pan_source_long_ptr;
-       
-       //CHECK
-       uint8_t intra_pan=0;
-       uint8_t data_len=0;
-       
-       uint8_t current_gts_element_count=0;
-       
-       MPDU *frame_pkt=0;
-       
-       uint16_t frame_control;
-       
-       //printfUART("create df\n","");
-       
-       //decision of the buffer where to store de packet creation
-       if (on_gts_slot > 0 )
-       {
-       
-               if (PANCoordinator == 1)
-               {
-               //setting the coordinator gts frame pointer
-                       
-                       //get the number of frames in the gts_slot_list
-                       atomic current_gts_element_count = gts_slot_list[15-on_gts_slot].element_count;
-                       
-                       //////////printfUART("element count %i\n",gts_slot_list[15-on_gts_slot].element_count);
-                       
-                       if (current_gts_element_count  == GTS_SEND_BUFFER_SIZE || available_gts_index_count == 0)
-                       {
-                               //////////printfUART("FULL\n","");
-                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
-                               return;
-                       }
-                       else
-                       {
-                               frame_pkt = (MPDU *) &gts_send_buffer[available_gts_index[available_gts_index_count]];
-                       }
-                       
-               }
-               else
-               {
-               //setting the device gts frame pointer
-                       ////////////printfUART("start creation %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
-               
-                       if(gts_send_buffer_count == GTS_SEND_BUFFER_SIZE)
-                       {
-                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
-                               return;
-                       }
-                       if (gts_send_buffer_msg_in == GTS_SEND_BUFFER_SIZE)
-                               gts_send_buffer_msg_in=0;
-                       
-                               frame_pkt = (MPDU *) &gts_send_buffer[gts_send_buffer_msg_in];
-               
-               }
-       }
-       else
-       {
-       
-               if ( get_txoptions_indirect_transmission(TxOptions) == 1)
-               {
-                       
-                       //CREATE THE INDIRECT TRANSMISSION PACKET POINTER
-                       //check if the is enough space to store the indirect transaction
-                       if (indirect_trans_count == INDIRECT_BUFFER_SIZE)
-                       {
-                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
-                               //////////printfUART("buffer full %i\n", indirect_trans_count);
-                               return;
-                       }
-                       
-                       for(i_indirect_trans=0;i_indirect_trans<INDIRECT_BUFFER_SIZE;i_indirect_trans++)
-                       {
-                               if (indirect_trans_queue[i_indirect_trans].handler == 0x00)
-                               {
-                                       frame_pkt = (MPDU *) &indirect_trans_queue[i_indirect_trans].frame;
-                                       break;
-                               }
-                       }
-                       
-                       
-               }
-               else
-               {
-                       //CREATE NORMAL TRANSMISSION PACKET POINTER
-                               ////printfUART("sb  %i\n", send_buffer_count);
-                       atomic{
-                       
-                       //TDBS Implementation
-                       if (get_txoptions_upstream_buffer(TxOptions) == 1)
-                       {
-                               ////printfUART("sel up\n", "");
-                               
-                               if (upstream_buffer_count > UPSTREAM_BUFFER_SIZE)
-                                       return;
-                               
-                               if(upstream_buffer_msg_in == UPSTREAM_BUFFER_SIZE)
-                                       upstream_buffer_msg_in=0;
-                               
-                               frame_pkt = (MPDU *) &upstream_buffer[upstream_buffer_msg_in];
-                               
-                       }
-                       else
-                       {
-
-                               ////printfUART("sb  %i\n", send_buffer_count);
-                       
-                               if ((send_buffer_count +1) > SEND_BUFFER_SIZE)  
-                                       return;
-                       
-                               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                                       send_buffer_msg_in=0;
-               
-                               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-                       }
-                       
-                       }
-                       
-
-               }
-       }
-       
-atomic{
-
-       if (intra_pan == 0 )
-       {
-       
-               if ( DstAddrMode > 1 && SrcAddrMode > 1 )
-               {
-                       // Destination LONG - Source LONG       
-                       if (DstAddrMode == LONG_ADDRESS && SrcAddrMode == LONG_ADDRESS)
-                       {
-                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-                               source_long_ptr = (source_long *) &frame_pkt->data[DEST_LONG_LEN];
-                               
-                               dest_long_ptr->destination_PAN_identifier=DestPANId;
-                               dest_long_ptr->destination_address0=DstAddr[1];
-                               dest_long_ptr->destination_address1=DstAddr[0];
-                               
-                               source_long_ptr->source_PAN_identifier=SrcPANId;
-                               source_long_ptr->source_address0=SrcAddr[1];
-                               source_long_ptr->source_address1=SrcAddr[0];
-                               
-                               data_len = 20;
-                       }
-                       
-                       // Destination SHORT - Source LONG
-                       if ( DstAddrMode == SHORT_ADDRESS && SrcAddrMode == LONG_ADDRESS )
-                       {
-                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-                               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
-                               
-                               dest_short_ptr->destination_PAN_identifier=DestPANId;
-                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
-                               
-                               source_long_ptr->source_PAN_identifier=SrcPANId;
-                               source_long_ptr->source_address0=SrcAddr[1];
-                               source_long_ptr->source_address1=SrcAddr[0];
-                               
-                               data_len = 14;
-                       }
-                       // Destination LONG - Source SHORT
-                       if ( DstAddrMode == LONG_ADDRESS && SrcAddrMode == SHORT_ADDRESS )
-                       {
-                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-                               source_short_ptr = (source_short *) &frame_pkt->data[DEST_LONG_LEN];
-                               
-                               dest_long_ptr->destination_PAN_identifier=DestPANId;
-                               dest_long_ptr->destination_address0=DstAddr[1];
-                               dest_long_ptr->destination_address1=DstAddr[0];
-                               
-                               source_short_ptr->source_PAN_identifier=SrcPANId;
-                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
-                               
-                               data_len = 14;
-                       }
-                       
-                       
-                       //Destination SHORT - Source SHORT
-                       if ( DstAddrMode == SHORT_ADDRESS && SrcAddrMode == SHORT_ADDRESS )     
-                       {
-                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-                               source_short_ptr = (source_short *) &frame_pkt->data[DEST_SHORT_LEN];
-                               
-                               dest_short_ptr->destination_PAN_identifier=DestPANId;
-                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
-                               
-                               source_short_ptr->source_PAN_identifier=SrcPANId;
-                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
-                               
-                               data_len = 8;
-                       }
-               }
-               
-               if ( DstAddrMode == 0 && SrcAddrMode > 1 )
-               {
-                               
-                       if (SrcAddrMode == LONG_ADDRESS)
-                       {//Source LONG
-                               source_long_ptr = (source_long *) &frame_pkt->data[0];
-                               
-                               source_long_ptr->source_PAN_identifier=SrcPANId;
-                               source_long_ptr->source_address0=SrcAddr[1];
-                               source_long_ptr->source_address1=SrcAddr[0];
-                               
-                               data_len = 10;
-                       }
-                       else
-                       {//Source SHORT
-
-                               source_short_ptr = (source_short *) &frame_pkt->data[0];
-                               
-                               source_short_ptr->source_PAN_identifier=SrcPANId;
-                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
-                               
-                               data_len = 4;
-                       }
-               }
-               
-               if ( DstAddrMode > 1 && SrcAddrMode == 0 )
-               {
-                       if (DstAddrMode == LONG_ADDRESS)
-                       {//Destination LONG
-                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-               
-                               dest_long_ptr->destination_PAN_identifier=DestPANId;
-                               dest_long_ptr->destination_address0=DstAddr[1];
-                               dest_long_ptr->destination_address1=DstAddr[0];
-
-                               data_len = 10;
-                       }
-                       else
-                       {//Destination SHORT
-                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-
-                               dest_short_ptr->destination_PAN_identifier=DestPANId;
-                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
-                               
-                               data_len = 4;
-                       }
-               }
-       }
-       else
-       {
-       //intra_pan == 1
-
-       }
-               
-               memcpy(&frame_pkt->data[data_len],&msdu[0],msduLength*sizeof(uint8_t));
-               
-               if(on_gts_slot > 0)
-               {
-                       //preparing a GTS transmission
-                       
-                       ////////////printfUART("GTS send slt: %i count %i %u\n",on_gts_slot,gts_slot_list[15-on_gts_slot].element_count,mac_PIB.macDSN);
-                       frame_pkt->length = data_len + msduLength + MPDU_HEADER_LEN;
-                       
-                       frame_control = set_frame_control(TYPE_DATA,0,0,1,intra_pan,DstAddrMode,SrcAddrMode);
-                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-                       
-                       frame_pkt->seq_num = mac_PIB.macDSN;
-                       mac_PIB.macDSN++;
-                                               
-                       //ADDING DATA TO THE GTS BUFFER
-                       atomic{
-                                       if (PANCoordinator == 1)
-                                       {
-                                               gts_slot_list[15-on_gts_slot].element_count ++;
-                                               gts_slot_list[15-on_gts_slot].gts_send_frame_index[gts_slot_list[15-on_gts_slot].element_in] = available_gts_index[available_gts_index_count];
-                                               //gts_slot_list[15-on_gts_slot].length = frame_pkt->length;
-                                               
-                                               gts_slot_list[15-on_gts_slot].element_in ++;
-                                               
-                                               if (gts_slot_list[15-on_gts_slot].element_in == GTS_SEND_BUFFER_SIZE)
-                                                       gts_slot_list[15-on_gts_slot].element_in=0;
-                                               
-                                               available_gts_index_count --;
-                                               
-                                               //current_gts_pending_frame++;
-                                       }
-                                       else
-                                       {
-                                               gts_send_buffer_count++;
-                                               gts_send_buffer_msg_in++;
-                                               ////////////printfUART("end c %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
-                                       }
-                       }
-               }
-               else
-               {
-                       //////////printfUART("CSMA send %i\n", get_txoptions_ack(TxOptions));
-                       frame_pkt->length = data_len + msduLength + MPDU_HEADER_LEN;
-                       //frame_pkt->frame_control = set_frame_control(TYPE_DATA,0,0,get_txoptions_ack(TxOptions),intra_pan,DstAddrMode,SrcAddrMode);
-                       
-                       frame_control = set_frame_control(TYPE_DATA,0,0,get_txoptions_ack(TxOptions),intra_pan,DstAddrMode,SrcAddrMode);
-                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-                       
-                       frame_pkt->seq_num = mac_PIB.macDSN;
-                       
-                       //////printfUART("sqn %i\n", mac_PIB.macDSN);
-                       
-                       mac_PIB.macDSN++;
-                       
-                       if ( get_txoptions_indirect_transmission(TxOptions) == 1)
-                       {
-                                       indirect_trans_queue[i_indirect_trans].handler = indirect_trans_count + 1;
-                                       indirect_trans_queue[i_indirect_trans].transaction_persistent_time = 0x0000;
-       
-                                       indirect_trans_count++;
-       
-                                       //////////printfUART("ADDED HDL: %i ADDR: %i\n",indirect_trans_count,DstAddr[1]); 
-                       }
-                       else
-                       {
-                               if (get_txoptions_upstream_buffer(TxOptions) == 1)
-                               {
-                                       upstream_buffer[upstream_buffer_msg_in].retransmission =0;
-                                       upstream_buffer[upstream_buffer_msg_in].indirect =0;
-                               
-                                       upstream_buffer_count++;
-                                       
-                                       upstream_buffer_msg_in++;
-                                       
-                                       //printfUART("up bc %i\n", upstream_buffer_count);
-                                       post send_frame_csma_upstream();
-                                       
-                               }
-                               else
-                               {
-                               
-                                       //enable retransmissions
-                                       send_buffer[send_buffer_msg_in].retransmission = 1;
-                                       send_buffer[send_buffer_msg_in].indirect = 0;
-                                       
-                                       send_buffer_count++;
-                                       
-                                       send_buffer_msg_in++;
-                                       
-                                       post send_frame_csma();
-                               }
-                                       
-                       }
-                       
-               }
-               
-       }
-return;
-}
-
-
-error_t create_association_response_cmd(uint32_t DeviceAddress[],uint16_t shortaddress, uint8_t status)
-{
-
-       cmd_association_response *mac_association_response;
-       dest_long *dest_long_ptr;
-       source_long *source_long_ptr;
-       
-       int i=0;
-       
-       MPDU *frame_pkt=0;
-       
-       uint16_t frame_control;
-       
-       //atomic{
-       /*
-                       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-       */
-       
-       //check if the is enough space to store the indirect transaction
-       if (indirect_trans_count == INDIRECT_BUFFER_SIZE)
-       {
-               printfUART("i full","");
-               return MAC_TRANSACTION_OVERFLOW;
-       }
-       
-       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-       {
-               if (indirect_trans_queue[i].handler == 0x00)
-               {
-                       //memcpy(&indirect_trans_queue[i].frame,frame_ptr,sizeof(MPDU));
-                       frame_pkt = (MPDU *) &indirect_trans_queue[i].frame;
-                       printfUART("found slot","");
-                       break;
-               }
-       }
-       
-       //creation of a pointer to the association response structure
-       dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-       source_long_ptr = (source_long *) &frame_pkt->data[DEST_LONG_LEN];
-       
-       mac_association_response = (cmd_association_response *) &frame_pkt->data[DEST_LONG_LEN + SOURCE_LONG_LEN];                                                                      
-       
-       frame_pkt->length = 29;
-       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
-       
-       frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
-       
-       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-       
-       frame_pkt->seq_num = mac_PIB.macDSN;
-       mac_PIB.macDSN++;
-       
-       dest_long_ptr->destination_PAN_identifier = mac_PIB.macPANId;
-
-       dest_long_ptr->destination_address0 = DeviceAddress[1];
-       dest_long_ptr->destination_address1 = DeviceAddress[0];
-       
-       source_long_ptr->source_PAN_identifier = mac_PIB.macPANId;
-       
-       source_long_ptr->source_address0 = aExtendedAddress0;
-       source_long_ptr->source_address1 = aExtendedAddress1;
-
-       mac_association_response->command_frame_identifier = CMD_ASSOCIATION_RESPONSE;
-       
-       //mac_association_response->short_address = shortaddress;
-       mac_association_response->short_address1 = (uint8_t)(shortaddress);
-       mac_association_response->short_address2 = (uint8_t)(shortaddress >> 8);
-
-
-       mac_association_response->association_status = status;
-/*
-
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-                       }       
-               post send_frame_csma();
-*/
-       printfUART("ASS RESP S: %i\n",shortaddress); 
-
-       indirect_trans_queue[i].handler = indirect_trans_count+1;
-
-       indirect_trans_queue[i].transaction_persistent_time = 0x0000;
-       
-       indirect_trans_count++;
-       
-       printfUART("IAD\n", "");
-
-return MAC_SUCCESS;
-}
-
-
-void create_association_request_cmd(uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation)
-{
-atomic{
-
-               cmd_association_request *cmd_association_request_ptr;
-               dest_short *dest_short_ptr;
-               source_long *source_long_ptr;
-       
-               MPDU *frame_pkt=0;
-               
-               uint16_t frame_control;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-               
-               //creation of a pointer to the association response structure
-               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
-               
-               cmd_association_request_ptr = (cmd_association_request *) &send_buffer[send_buffer_msg_in].data[DEST_SHORT_LEN + SOURCE_LONG_LEN];
-               
-               frame_pkt->length = 21;
-               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,SHORT_ADDRESS,LONG_ADDRESS);
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,1,0,SHORT_ADDRESS,LONG_ADDRESS);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               association_cmd_seq_num =  mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               dest_short_ptr->destination_PAN_identifier = CoordPANId; //mac_PIB.macPANId;
-               
-               if (CoordAddrMode == SHORT_ADDRESS )
-               {
-                       dest_short_ptr->destination_address = (uint16_t)(CoordAddress[1] & 0x000000ff) ;  //mac_PIB.macPANId;
-               }
-               else
-               {
-               //CHECK
-               
-               //implement the long address version
-               
-               }
-               
-               source_long_ptr->source_PAN_identifier = 0xffff;
-               
-               source_long_ptr->source_address0 = aExtendedAddress0;
-               source_long_ptr->source_address1 = aExtendedAddress1;
-               
-               cmd_association_request_ptr->command_frame_identifier = CMD_ASSOCIATION_REQUEST;
-               
-               cmd_association_request_ptr->capability_information = CapabilityInformation;
-
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               pending_request_data=1;
-               
-               ////printfUART("Association request %i %i \n", send_buffer_count,send_buffer_msg_in);
-               
-               
-               post send_frame_csma();
-
-       }
-return;
-}
-
-void create_data_request_cmd()
-{
-       //////////printfUART("create_data_request_cmd\n", ""); 
-
-atomic{
-               //dest_short *dest_short_ptr;
-               source_long *source_long_ptr;
-
-               
-               MPDU *frame_pkt;
-               
-               uint16_t frame_control;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-       
-       
-               source_long_ptr= (source_long *) &send_buffer[send_buffer_msg_in].data[0];
-       
-               //creation of a pointer to the association response structure
-               //dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-               source_long_ptr = (source_long *) &frame_pkt->data[0];
-       
-       
-               frame_pkt->length = 16;                                                 
-               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,LONG_ADDRESS);   //dest | source
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,LONG_ADDRESS);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               
-               source_long_ptr->source_PAN_identifier = mac_PIB.macPANId;
-               
-               source_long_ptr->source_address0 = aExtendedAddress0;//aExtendedAddress0;
-               source_long_ptr->source_address1 = aExtendedAddress1;
-               
-               //command_frame_identifier = CMD_DATA_REQUEST;
-               frame_pkt->data[SOURCE_LONG_LEN]=CMD_DATA_REQUEST;
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-                               
-               post send_frame_csma();
-               
-               
-               }
-return;
-}
-
-void create_beacon_request_cmd()
-{
-
-atomic{
-               cmd_beacon_request *mac_beacon_request;
-       
-               MPDU *frame_pkt;
-               
-               uint16_t frame_control;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-       
-               mac_beacon_request= (cmd_beacon_request*) &send_buffer[send_buffer_msg_in].data;
-       
-               frame_pkt->length = 10;                                                 
-               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);   //dest | source
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               mac_beacon_request->destination_PAN_identifier = 0xffff;
-               
-               mac_beacon_request->destination_address = 0xffff;
-       
-               mac_beacon_request->command_frame_identifier = CMD_BEACON_REQUEST;
-               
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               post send_frame_csma();
-
-               }
-
-return;
-}
-
-void create_orphan_notification()
-{
-
-       atomic{
-       
-               cmd_default *cmd_orphan_notification=0;
-               
-               dest_short *dest_short_ptr=0;
-               source_long *source_long_ptr=0;
-
-               MPDU *frame_pkt=0;
-                       
-               uint16_t frame_control=0;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-               
-               frame_pkt->length = 20;                                                 
-                               
-               cmd_orphan_notification = (cmd_default*) &send_buffer[send_buffer_msg_in].data[DEST_SHORT_LEN + SOURCE_LONG_LEN];
-               
-               //creation of a pointer the addressing structures
-               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
-               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
-               
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,LONG_ADDRESS);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               
-               dest_short_ptr->destination_PAN_identifier = 0xffff; //mac_PIB.macPANId;
-               
-               dest_short_ptr->destination_address = 0xffff ;  //mac_PIB.macPANId;
-               
-               source_long_ptr->source_PAN_identifier = 0xffff;
-               
-               source_long_ptr->source_address0 = aExtendedAddress0;
-               source_long_ptr->source_address1 = aExtendedAddress1;
-                               
-               
-               cmd_orphan_notification->command_frame_identifier = CMD_ORPHAN_NOTIFICATION;
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               post send_frame_csma();
-       }
-
-return;
-}
-
-
-void create_coordinator_realignment_cmd(uint32_t device_extended0, uint32_t device_extended1, uint16_t device_short_address)
-{
-
-atomic{
-
-       cmd_coord_realignment *cmd_realignment =0;
-       
-       dest_long *dest_long_ptr=0;
-       source_short *source_short_ptr=0;
-       
-       MPDU *frame_pkt=0;
-       
-       uint16_t frame_control=0;
-       
-       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-               send_buffer_msg_in=0;
-
-       frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-       
-       frame_pkt->length = 27;                                                 
-       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);   //dest | source
-       
-       cmd_realignment = (cmd_coord_realignment*) &send_buffer[send_buffer_msg_in].data[DEST_LONG_LEN + SOURCE_SHORT_LEN];
-       
-       //creation of a pointer the addressing structures
-       dest_long_ptr = (dest_long *) &frame_pkt->data[0];
-       source_short_ptr = (source_short *) &frame_pkt->data[DEST_LONG_LEN];
-
-       
-       frame_control = set_frame_control(TYPE_CMD,0,0,0,0,LONG_ADDRESS,SHORT_ADDRESS);
-       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-       frame_pkt->seq_num = mac_PIB.macDSN;
-       
-       mac_PIB.macDSN++;
-       
-       dest_long_ptr->destination_PAN_identifier = 0xffff;
-       dest_long_ptr->destination_address0 = device_extended0;
-       dest_long_ptr->destination_address1 = device_extended1;
-       
-       source_short_ptr->source_PAN_identifier = mac_PIB.macPANId;
-       source_short_ptr->source_address = mac_PIB.macCoordShortAddress;
-       
-       
-       cmd_realignment->command_frame_identifier = CMD_COORDINATOR_REALIGNMENT;
-       
-       mac_PIB.macPANId = 0x1234;
-       
-       mac_PIB.macCoordShortAddress =0x0000;
-       
-       cmd_realignment->PAN_identifier0 = (mac_PIB.macPANId);
-       cmd_realignment->PAN_identifier1 = (mac_PIB.macPANId >> 8);
-
-       cmd_realignment->coordinator_short_address0 = (mac_PIB.macCoordShortAddress);
-       cmd_realignment->coordinator_short_address1 = (mac_PIB.macCoordShortAddress >> 8);
-       
-       cmd_realignment->logical_channel = LOGICAL_CHANNEL;
-       cmd_realignment->short_address = device_short_address;
-
-       
-       //increment the send buffer variables
-       send_buffer_count++;
-       send_buffer_msg_in++;
-       
-       post send_frame_csma();
-
-       }
-
-return;
-}
-
-
-void create_gts_request_cmd(uint8_t gts_characteristics)
-{
-atomic{
-               cmd_gts_request *mac_gts_request;
-               
-               MPDU *frame_pkt;
-               
-               uint16_t frame_control;
-               ////printfUART("create_gts_request_cmd\n", "");
-               
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-               
-               mac_gts_request= (cmd_gts_request*) &send_buffer[send_buffer_msg_in].data;
-
-               frame_pkt->length = 11;
-       
-               if ( get_characteristic_type(gts_characteristics) != 0 )
-               {   
-                       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);   //dest | source
-               
-                       frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS); 
-                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               }
-               else
-               {       
-                       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);
-                       
-                       frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);
-                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
-                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               }
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               gts_request_seq_num = frame_pkt->seq_num;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               //mac_gts_request->source_PAN_identifier = 0x0001;
-               mac_gts_request->source_PAN_identifier = mac_PIB.macPANId;
-               
-               mac_gts_request->source_address = mac_PIB.macShortAddress;
-       
-               mac_gts_request->command_frame_identifier = CMD_GTS_REQUEST;
-               
-               //mac_gts_request->gts_characteristics = set_gts_characteristics(2,1,1);
-               mac_gts_request->gts_characteristics =gts_characteristics;
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               post send_frame_csma();
-               
-               }
-
-return;
-}
-
-void create_disassociation_notification_cmd(uint32_t DeviceAddress[],uint8_t disassociation_reason)
-{
-
-       atomic{
-               cmd_disassociation_notification *mac_disassociation_notification;
-               MPDU *frame_pkt;
-               
-               uint16_t frame_control;
-               
-               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                       send_buffer_msg_in=0;
-       
-               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
-               
-               //creation of a pointer to the disassociation notification structure
-               mac_disassociation_notification = (cmd_disassociation_notification*) &send_buffer[send_buffer_msg_in].data;                                                             
-               
-               
-               frame_pkt->length = 27;
-               
-               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
-               
-               frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
-               frame_pkt->frame_control1 =(uint8_t)( frame_control);
-               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
-               
-               frame_pkt->seq_num = mac_PIB.macDSN;
-               
-               mac_PIB.macDSN++;
-               
-               //enable retransmissions
-               send_buffer[send_buffer_msg_in].retransmission =1;
-               send_buffer[send_buffer_msg_in].indirect = 0;
-               
-               mac_disassociation_notification->destination_PAN_identifier = mac_PIB.macPANId;
-
-               mac_disassociation_notification->destination_address0 = DeviceAddress[0];
-               mac_disassociation_notification->destination_address1 = DeviceAddress[1];
-       
-               mac_disassociation_notification->source_PAN_identifier = mac_PIB.macPANId;
-       
-               mac_disassociation_notification->source_address0 = aExtendedAddress0;
-               mac_disassociation_notification->source_address1 = aExtendedAddress1;
-       
-               mac_disassociation_notification->command_frame_identifier = CMD_DISASSOCIATION_NOTIFICATION;
-               
-               mac_disassociation_notification->disassociation_reason = disassociation_reason;
-               
-               //increment the send buffer variables
-               send_buffer_count++;
-               send_buffer_msg_in++;
-               
-               post send_frame_csma();
-
-       }
-return;
-}
-
-
-
-void build_ack(uint8_t sequence,uint8_t frame_pending)
-{
-       uint16_t frame_control;
-       atomic{
-                       mac_ack_ptr->length = ACK_LENGTH;
-                       //mac_ack_ptr->frame_control = set_frame_control(TYPE_ACK,0,frame_pending,0,0,0,0);
-                       
-                       frame_control = set_frame_control(TYPE_ACK,0,frame_pending,0,0,0,0);
-                       mac_ack_ptr->frame_control1 =(uint8_t)( frame_control);
-                       mac_ack_ptr->frame_control2 =(uint8_t)( frame_control >> 8);
-                       
-                       mac_ack_ptr->seq_num = sequence;
-                       
-                       call PD_DATA.request(mac_ack_ptr->length,(uint8_t*)mac_ack_ptr);
-       }
-}
-
-
-
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/************************              INTERFACES PROVIDED                     **********************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-
-/*********************************************************/
-/**************MLME_SCAN********************************/
-/*********************************************************/
-
-task void data_channel_scan_indication()
-{
-       uint8_t link_qual;
-       
-       beacon_addr_short *beacon_ptr;
-       
-       //printfUART("data_channel_scan_indication\n","");
-
-       atomic link_qual = link_quality;
-
-       atomic buffer_count--;
-
-       switch(scan_type)
-       {
-               case ED_SCAN: 
-                                               if (scanned_values[current_scanning-1] < link_qual)
-                                                               scanned_values[current_scanning-1] = link_qual;
-                                               break;
-               
-               case ACTIVE_SCAN:break;
-                                       
-               case PASSIVE_SCAN: 
-                                                       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
-                                                       {
-                                                               case TYPE_BEACON:
-                                                               ////////////printfUART("Received Beacon\n","");
-                                                               beacon_ptr = (beacon_addr_short*) (&buffer_msg[current_msg_out].data);
-
-                                                               //Beacon NOTIFICATION
-                                                               //BUILD the PAN descriptor of the COORDINATOR
-                                                               //assuming that the adress is short
-                                                               scan_pans[current_scanning-1].CoordPANId = beacon_ptr->destination_PAN_identifier;
-                                                               scan_pans[current_scanning-1].CoordAddress=beacon_ptr->source_address;
-                                                               scan_pans[current_scanning-1].LogicalChannel=current_channel;
-                                                               //superframe specification field
-                                                               scan_pans[current_scanning-1].SuperframeSpec = beacon_ptr->superframe_specification;
-                                                               
-                                                               if (scan_pans[current_scanning-1].lqi < link_qual)
-                                                               scan_pans[current_scanning-1].lqi = link_qual;
-                                                       
-                                                               break;
-                                                               
-                                                               default: break;
-                                                       //atomic buffer_count--;
-                                                       ////////////printfUART("Invalid frame type\n","");
-
-                                                       }
-                                                       break;
-               case ORPHAN_SCAN: 
-                                                       //printfUART("osrm\n","");
-                                                       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
-                                                       {
-                                                               case TYPE_CMD:
-                                                                               //printfUART("received cmd\n","");
-                                                                               if (buffer_msg[current_msg_out].data[SOURCE_SHORT_LEN+ DEST_LONG_LEN] == CMD_COORDINATOR_REALIGNMENT)
-                                                                               {       
-                                                                                       printfUART("pf\n","");
-                                                                                       atomic scanning_channels = 0;
-                                                                                       call T_ScanDuration.stop();
-                                                                                       process_coordinator_realignment(&buffer_msg[current_msg_out]);
-                                                                                       
-                                                                               }
-                                                                               
-                                                                               break;
-                                                       default: break;
-                                                       }
-                                                       break;
-               
-       }
-       
-       atomic{
-                       current_msg_out++;
-               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
-                       current_msg_out = 0;
-               }
-return;
-}
-/*******************T_ScanDuration**************************/
-event void T_ScanDuration.fired() {
-
-       current_scanning++;
-       
-       printfUART("cs%i c%i\n",current_scanning,(0x0A + current_scanning));
-                                               
-       call PLME_SET.request(PHYCURRENTCHANNEL, (0x0A + current_scanning));
-
-       current_channel = (0x0A + current_scanning);
-       
-
-       if (current_scanning == 16 )
-       {
-               //printfUART("scan end\n","");
-               
-               atomic scanning_channels = 0;
-               
-               switch(scan_type)
-               {
-                       case ED_SCAN: 
-                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , scanned_values,0x00);
-                                                       break;
-                       
-                       case ACTIVE_SCAN:break;
-
-                       case PASSIVE_SCAN: 
-                                                       //event result_t confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[]);
-                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , 0x00, scan_pans);
-                                                       break;
-                       
-                       case ORPHAN_SCAN: 
-                                                       //orphan scan
-                                                       //send opphan command on every channel directed to the current PAN coordinator
-                                                       printfUART("oph s end not found\n","");
-                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , 0x00, scan_pans);
-                                                       
-                                                       break;
-               }
-       }
-       else
-       {
-               switch(scan_type)
-               {
-                       case ORPHAN_SCAN:       printfUART("con\n","");
-                                                               create_orphan_notification();
-                                                               break;
-               }
-               
-               call T_ScanDuration.startOneShot(scan_duration);
-       }
-  
-}
-
-
-
-command error_t MLME_SCAN.request(uint8_t ScanType, uint32_t ScanChannels, uint8_t ScanDuration)
-{
-//pag 93
-       printfUART("MLME_SCAN.request\n", ""); 
-               
-       atomic scanning_channels = 1;
-       scan_type = ScanType;
-       channels_to_scan = ScanChannels;
-       
-       atomic current_scanning=0;
-       
-       
-       switch(ScanType)
-       {
-               //ED SCAN only FFD                      
-               case ED_SCAN:   
-                                       call TimerAsync.set_timers_enable(0x00);
-                                       /*
-                               
-                                       scanning_channels = 1;
-                                       scan_type = ScanType;
-                                       current_scanning=0;
-                                       scan_count=0;
-                                       channels_to_scan = ScanChannels;
-                                       scan_duration = ((aBaseSuperframeDuration * pow(2,ScanDuration)) * 4.0) / 250.0;
-                                       
-                                       //////////printfUART("channels_to_scan %y scan_duration %y\n", channels_to_scan,scan_duration); 
-                                       
-                                       call T_ed_scan.start(TIMER_REPEAT,1);
-                                       
-                                       call T_scan_duration.start(TIMER_ONE_SHOT,scan_duration);       
-                                       */
-                                       
-                                       
-                                       //calculate the scan_duration in miliseconds
-                                       //#ifdef PLATFORM_MICAZ
-                                               scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
-                                       //#else
-                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
-                                       //#endif
-                       //scan_duration = 2000;
-                                       
-                                       call T_ScanDuration.startOneShot(scan_duration);
-                                       
-                                       //printfUART("channels_to_scan %y scan_duration %y\n", channels_to_scan,scan_duration); 
-                                       break;
-               //active scan only FFD
-               case ACTIVE_SCAN:
-                                       call TimerAsync.set_timers_enable(0x00);
-                                       break;
-               //passive scan
-               case PASSIVE_SCAN:      
-                                       call TimerAsync.set_timers_enable(0x00);
-                                                       
-                                       //calculate the scan_duration in miliseconds
-                                       //#ifdef PLATFORM_MICAZ
-                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
-                                       //#else
-                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
-                                       //#endif
-                                       
-                                       
-                                       //defines the time (miliseconds) that the device listen in each channel
-                                       scan_duration = 2000;
-                                       
-                                       printfUART("channels_to_scan %y scan_duration %i\n", channels_to_scan,scan_duration); 
-                                       
-                                       call T_ScanDuration.startOneShot(scan_duration);
-                                       
-                                       //printfUART("channels_to_scan %y scan_duration %i\n", channels_to_scan,scan_duration); 
-                                       
-                                       //atomic trx_status = PHY_RX_ON;
-                                       //call PLME_SET_TRX_STATE.request(PHY_RX_ON); 
-               
-               
-               
-                                       break;
-               //orphan scan
-               case ORPHAN_SCAN:
-               
-                                       call TimerAsync.set_timers_enable(0x01);
-                                       
-                                   scan_duration = 4000;
-                                       
-                                       printfUART("orphan cts %y sdur %i\n", channels_to_scan,scan_duration); 
-                                       
-                                       call T_ScanDuration.startOneShot(scan_duration);
-
-                                       break;
-       
-               default:
-                                       break;
-       }
-
-return SUCCESS;
-}
-
-
-
-/*********************************************************/
-/**************MLME_ORPHAN********************************/
-/*********************************************************/
-
-command error_t MLME_ORPHAN.response(uint32_t OrphanAddress[1],uint16_t ShortAddress,uint8_t AssociatedMember, uint8_t security_enabled)
-{
-
-       if (AssociatedMember==0x01)
-       {
-               create_coordinator_realignment_cmd(OrphanAddress[0], OrphanAddress[1], ShortAddress);
-       }
-       
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_SYNC********************************/
-/*********************************************************/
-
-
-command error_t MLME_SYNC.request(uint8_t logical_channel,uint8_t track_beacon)
-{
-       call PLME_SET.request(PHYCURRENTCHANNEL,logical_channel);       
-       
-       call TimerAsync.set_timers_enable(0x01);
-       
-       printfUART("sync req\n", ""); 
-       
-       atomic findabeacon = 1;
-
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_RESET********************************/
-/*********************************************************/
-
-
-command error_t MLME_RESET.request(uint8_t set_default_PIB)
-{
-
-
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_GTS***********************************/
-/*********************************************************/
-
-command error_t MLME_GTS.request(uint8_t GTSCharacteristics, bool security_enable)
-{
-
-       //uint32_t wait_time;
-       //if there is no short address asigned the node cannot send a GTS request
-       if (mac_PIB.macShortAddress == 0xffff)
-                       signal MLME_GTS.confirm(GTSCharacteristics,MAC_NO_SHORT_ADDRESS);
-       
-       //gts_ack=1;
-       
-       gts_request =1;
-       
-       create_gts_request_cmd(GTSCharacteristics);
-
-return SUCCESS;
-}
-
-
-/*********************************************************/
-/**************MLME_START*********************************/
-/*********************************************************/
-
-command error_t MLME_START.request(uint32_t PANId, uint8_t LogicalChannel, uint8_t beacon_order, uint8_t superframe_order,bool pan_coodinator,bool BatteryLifeExtension,bool CoordRealignment,bool securityenable,uint32_t StartTime)
-{
-
-       uint32_t BO_EXPONENT;
-       uint32_t SO_EXPONENT;
-
-       ////////printfUART("MLME_START.request\n", "");
-       //pag 102
-       atomic {
-       PANCoordinator=1;
-       Beacon_enabled_PAN=1;
-       //TEST
-       //atomic mac_PIB.macShortAddress = 0x0000;
-
-
-               if ( mac_PIB.macShortAddress == 0xffff)
-               {
-               
-                       signal MLME_START.confirm(MAC_NO_SHORT_ADDRESS);
-                       return SUCCESS;
-               }
-               else
-               {
-                       atomic mac_PIB.macBeaconOrder = beacon_order;
-                       
-                       if (beacon_order == 15) 
-                               atomic mac_PIB.macSuperframeOrder = 15;
-                       else
-                               atomic mac_PIB.macSuperframeOrder = superframe_order;
-               
-               
-                       //PANCoordinator is set to TRUE
-                       if (pan_coodinator == 1)
-                       {
-                               atomic mac_PIB.macPANId = PANId;
-                               call PLME_SET.request(PHYCURRENTCHANNEL,LogicalChannel);
-                       }
-                       if (CoordRealignment == 1)
-                       {
-                               //generates and broadcasts a coordinator realignment command containing the new PANId and LogicalChannels
-                       }
-                       if (securityenable == 1)
-                       {
-                       //security parameters
-                       }
-               }
-       
-               if (mac_PIB.macSuperframeOrder == 0)
-                       SO_EXPONENT = 1;
-               else
-               {
-                       SO_EXPONENT = powf(2,mac_PIB.macSuperframeOrder);
-               
-               }
-               if ( mac_PIB.macBeaconOrder == 0)
-                       BO_EXPONENT = 1;
-               else
-               {
-                       BO_EXPONENT = powf(2,mac_PIB.macBeaconOrder);
-               
-               }       
-       }
-       
-       BI = aBaseSuperframeDuration * BO_EXPONENT; 
-               
-       SD = aBaseSuperframeDuration * SO_EXPONENT; 
-       //backoff_period
-       backoff = aUnitBackoffPeriod;
-
-       
-       atomic time_slot = SD / NUMBER_TIME_SLOTS;
-
-       call TimerAsync.set_backoff_symbols(backoff);
-
-       call TimerAsync.set_bi_sd(BI,SD);
-       
-       atomic{
-       
-               call TimerAsync.set_timers_enable(0x01);
-               
-               call TimerAsync.reset();
-               
-       }
-       
-       ////////////////////////////////////////////////////
-       /////////////////TDBS IMPLEMENTATION////////////////
-       ////////////////////////////////////////////////////
-       if(TYPE_DEVICE == ROUTER)
-       {
-               atomic parent_offset = StartTime;
-       
-               call TimerAsync.set_track_beacon(1);
-               //initialization of the timer that shedules the beacon transmission offset
-               call TimerAsync.set_track_beacon_start_ticks(StartTime,0x00001E00,0x00000000);
-       }
-       else
-       {
-               atomic I_AM_IN_PARENT_CAP = 1;
-       }
-               
-       signal MLME_START.confirm(MAC_SUCCESS);
-
-       return SUCCESS;
-}
-
-/*************************************************************/
-/**************MLME_ASSOCIATE*********************************/
-/*************************************************************/
-
-command error_t MLME_ASSOCIATE.request(uint8_t LogicalChannel,uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation,bool securityenable)
-{
-       //update current channel
-       //call PLME_SET.request(PHYCURRENTCHANNEL,LogicalChannel);
-       
-       //printfUART("MLME_ASSOCIATE.request\n", "");
-       
-       //updates the PAN ID
-       atomic{ 
-               mac_PIB.macPANId = CoordPANId;
-               mac_PIB.macCoordShortAddress = (uint16_t)(CoordAddress[1] & 0x000000ff);
-               }
-               
-       associating=1; //boolean variable stating that the device is trying to associate
-       
-       call TimerAsync.set_timers_enable(1);
-       
-       //call PLME_SET.request(PHYCURRENTCHANNEL, LogicalChannel);
-
-       current_channel = LogicalChannel;
-       
-       //printfUART("SELECTED cord id %i\n", mac_PIB.macPANId);
-       //printfUART("CoordAddress %i\n", mac_PIB.macCoordShortAddress);
-       //printfUART("LogicalChannel %i\n", LogicalChannel);
-       //printfUART("Cordaddr %i\n",CoordAddress[0]);
-       //printfUART("Cordaddr %i\n",CoordAddress[1]);
-       /*
-       a_CoordAddrMode = CoordAddrMode;
-       a_CoordPANId=CoordPANId;
-       a_CoordAddress[0]=CoordAddress[0];
-       a_CoordAddress[1]=CoordAddress[1];
-       a_CapabilityInformation=CapabilityInformation;
-       a_securityenable=securityenable;
-       */
-       create_association_request_cmd(CoordAddrMode,CoordPANId,CoordAddress,CapabilityInformation);
-       
-       return SUCCESS;
-}
-
-command error_t MLME_ASSOCIATE.response(uint32_t DeviceAddress[], uint16_t AssocShortAddress, uint8_t status, bool securityenable)
-{
-       
-       error_t status_response;
-       
-       //////printfUART("MAR\n", "");
-       
-       status_response = create_association_response_cmd(DeviceAddress,AssocShortAddress,status);
-       ////////////printfUART("MLME_ASSOCIATE.response\n", "");
-
-
-return SUCCESS;
-}
-
-/*************************************************************/
-/**************MLME_DISASSOCIATE*********************************/
-/*************************************************************/
-
-command error_t MLME_DISASSOCIATE.request(uint32_t DeviceAddress[], uint8_t disassociate_reason, bool securityenable)
-{
-       create_disassociation_notification_cmd(DeviceAddress,disassociate_reason);
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_GET***********************************/
-/*********************************************************/
-command error_t MLME_GET.request(uint8_t PIBAttribute)
-{
-
-       switch(PIBAttribute)
-       {
-               case MACACKWAITDURATION :               signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAckWaitDuration);
-                                                                               break;
-               case MACASSOCIATIONPERMIT:      signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAssociationPermit);
-                                                                               break;
-               case MACAUTOREQUEST :                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAutoRequest);
-                                                                               break;
-               case MACBATTLIFEEXT:                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBattLifeExt);
-                                                                               break;
-               case MACBATTLIFEEXTPERIODS:             signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBattLifeExtPeriods);
-                                                                               break;
-               case MACBEACONPAYLOAD:                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute, mac_PIB.macBeaconPayload);
-                                                                               break;
-               case MACMAXBEACONPAYLOADLENGTH: signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBeaconPayloadLenght);
-                                                                               break;
-               case MACBEACONORDER:                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBeaconOrder);
-                                                                               break;
-               case MACBEACONTXTIME:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *)&mac_PIB.macBeaconTxTime);
-                                                                               break;
-               case MACBSN:                                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBSN);
-                                                                               break;
-               case MACCOORDEXTENDEDADDRESS:   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macCoordExtendedAddress0);
-                                                                               break;
-               case MACCOORDSHORTADDRESS:              signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macCoordShortAddress);
-                                                                               break;
-               case MACDSN:                                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macDSN);
-                                                                               break;
-               case MACGTSPERMIT:                              signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macGTSPermit);
-                                                                               break;
-               case MACMAXCSMABACKOFFS:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macMaxCSMABackoffs);
-                                                                               break;
-               case MACMINBE:                                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macMinBE);
-                                                                               break;
-               case MACPANID:                                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macPANId);
-                                                                               break;
-               case MACPROMISCUOUSMODE:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macPromiscuousMode);
-                                                                               break;
-               case MACRXONWHENIDLE:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macRxOnWhenIdle);
-                                                                               break;
-               case MACSHORTADDRESS:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macShortAddress);
-                                                                               break;
-               case MACSUPERFRAMEORDER:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macSuperframeOrder);
-                                                                               break;
-               case MACTRANSACTIONPERSISTENCETIME:     signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macTransactionPersistenceTime);
-                                                                                       break;
-                                                                                       
-               default:                                                signal MLME_GET.confirm(MAC_UNSUPPORTED_ATTRIBUTE,PIBAttribute,0x00);
-                                                                               break;
-       }
-
-return SUCCESS;
-}
-
-/*********************************************************/
-/**************MLME_SET***********************************/
-/*********************************************************/
-command error_t MLME_SET.request(uint8_t PIBAttribute,uint8_t PIBAttributeValue[])
-{
-
-//int i;
-
-//printfUART("set %i\n",PIBAttribute);
-
-atomic{
-
-       switch(PIBAttribute)
-       {
-       
-       
-               case MACACKWAITDURATION :               mac_PIB.macAckWaitDuration = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macAckWaitDuration: %x\n",mac_PIB.macAckWaitDuration);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                       
-               case MACASSOCIATIONPERMIT:      if ((uint8_t)PIBAttributeValue[1] == 0x00)
-                                                                               {
-                                                                                       mac_PIB.macAssociationPermit = 0x00;
-                                                                               }
-                                                                               else
-                                                                               {
-                                                                                       mac_PIB.macAssociationPermit = 0x01;
-                                                                               }
-                                                                               ////////printfUART("mac_PIB.macAssociationPermit: %i %y\n",mac_PIB.macAssociationPermit,PIBAttributeValue[1]);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACAUTOREQUEST :                   mac_PIB.macAutoRequest = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macAutoRequest: %i\n",mac_PIB.macAutoRequest);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACBATTLIFEEXT:                    mac_PIB.macBattLifeExt = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macBattLifeExt %i\n",mac_PIB.macBattLifeExt);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACBATTLIFEEXTPERIODS:             mac_PIB.macBattLifeExtPeriods = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macBattLifeExtPeriods %i\n",mac_PIB.macBattLifeExtPeriods);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACBEACONPAYLOAD:                  /*for(i=0;i < mac_PIB.macBeaconPayloadLenght;i++) 
-                                                                               {
-                                                                                       mac_PIB.macBeaconPayload[i] = PIBAttributeValue[i];
-                                                                               }*/
-                                                                       
-                                                                               memcpy(&PIBAttributeValue[0],&mac_PIB.macBeaconPayload[0],mac_PIB.macBeaconPayloadLenght * sizeof(uint8_t));
-                                                                               
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                               
-               case MACMAXBEACONPAYLOADLENGTH: mac_PIB.macBeaconPayloadLenght = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macBeaconPayloadLenght %i\n",mac_PIB.macBeaconPayloadLenght);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACBEACONORDER:                    mac_PIB.macBeaconOrder = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macBeaconOrder %i\n",mac_PIB.macBeaconOrder);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACBEACONTXTIME:                   mac_PIB.macBeaconTxTime =PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macBeaconTxTime %i\n",mac_PIB.macBeaconTxTime);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACBSN:                                    mac_PIB.macBSN = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macBSN %i\n",mac_PIB.macBSN);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-
-               case MACCOORDEXTENDEDADDRESS:   //mac_PIB.macCoordExtendedAddress0 = ((PIBAttributeValue[0] >> 24) | (PIBAttributeValue[1] >> 16) | (PIBAttributeValue[2] >> 8) | (PIBAttributeValue[3])) ;
-                                                                               //mac_PIB.macCoordExtendedAddress1 = ((PIBAttributeValue[4] >> 24) | (PIBAttributeValue[5] >> 16) | (PIBAttributeValue[6] >> 8) | (PIBAttributeValue[7]));
-
-                                                                               //////////printfUART("mac_PIB.macCoordExtendedAddress0 %y\n",mac_PIB.macCoordExtendedAddress0);
-                                                                               //////////printfUART("mac_PIB.macCoordExtendedAddress1 %y\n",mac_PIB.macCoordExtendedAddress1);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-                                                                       
-               case MACCOORDSHORTADDRESS:              mac_PIB.macCoordShortAddress= ((PIBAttributeValue[0] << 8) |PIBAttributeValue[1]);
-                                                                               //printfUART("mac_PIB.macCoordShortAddress: %x\n",mac_PIB.macCoordShortAddress);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               
-               case MACDSN:                                    mac_PIB.macDSN = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macDSN: %x\n",mac_PIB.macDSN);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACGTSPERMIT:                              mac_PIB.macGTSPermit = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macGTSPermit: %x\n",mac_PIB.macGTSPermit);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACMAXCSMABACKOFFS:                mac_PIB.macMaxCSMABackoffs = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macMaxCSMABackoffs: %x\n",mac_PIB.macMaxCSMABackoffs);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACMINBE:                                  mac_PIB.macMinBE = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macMinBE: %x\n",mac_PIB.macMinBE);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               
-               case MACPANID:                                  mac_PIB.macPANId = ((PIBAttributeValue[0] << 8)| PIBAttributeValue[1]);
-                                                                               printfUART("mac_PIB.macPANId: %x\n",mac_PIB.macPANId);
-                                                                               
-                                                                               //TODO ENABLE HARDWARE VERIFICATION
-                                                                               //call CC2420Config.setPanAddr(mac_PIB.macPANId);
-                                                                               //call CC2420Config.setAddressRecognition(TRUE);
-                                                                               //call CC2420Config.sync(); 
-                                                                               
-                                                                               call AddressFilter.set_coord_address(mac_PIB.macCoordShortAddress, mac_PIB.macPANId);
-                                                                               
-                                                                               
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               
-               case MACPROMISCUOUSMODE:                mac_PIB.macPromiscuousMode = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macPromiscuousMode: %x\n",mac_PIB.macPromiscuousMode);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-               case MACRXONWHENIDLE:                   mac_PIB.macRxOnWhenIdle = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macRxOnWhenIdle: %x\n",mac_PIB.macRxOnWhenIdle);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-                                                                               
-               case MACSHORTADDRESS:                   mac_PIB.macShortAddress = ((PIBAttributeValue[0] << 8) |PIBAttributeValue[1]);
-                                                                               
-                                                                               printfUART("mac_PIB.macShortAddress: %y\n",mac_PIB.macShortAddress);
-                                                                                                                                                       
-                                                                               //TODO ENABLE HARDWARE VERIFICATION
-                                                                               //call CC2420Config.setPanAddr(0x0000);
-                                                                               //call CC2420Config.setShortAddr(0x0001);
-                                                                               //call CC2420Config.setAddressRecognition(TRUE);
-                                                                               //call CC2420Config.sync(); 
-                                                                               
-                                                                               call AddressFilter.set_address(mac_PIB.macShortAddress, aExtendedAddress0, aExtendedAddress0);
-                                                                               
-                                                                               
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACSUPERFRAMEORDER:                mac_PIB.macSuperframeOrder = PIBAttributeValue[0];
-                                                                               //////////printfUART("mac_PIB.macSuperframeOrder: %x\n",mac_PIB.macSuperframeOrder);
-                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                               break;
-                                                                               
-               case MACTRANSACTIONPERSISTENCETIME:      mac_PIB.macTransactionPersistenceTime = PIBAttributeValue[0];
-                                                                                        //////////printfUART("mac_PIB.macTransactionPersistenceTime: %y\n",mac_PIB.macTransactionPersistenceTime);
-                                                                                        signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
-                                                                                        break;
-                                                                                       
-               default:                                                signal MLME_SET.confirm(MAC_UNSUPPORTED_ATTRIBUTE,PIBAttribute);
-                                                                               break;
-                                                                               
-               
-       }
-
-}
-
-return SUCCESS;
-}
-/*************************************************************/
-/**************        MCPS - DATA         *******************/
-/*************************************************************/
-
-command error_t MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions)
-{
-       int i;
-       //uint8_t valid_gts=0;
-       uint32_t total_ticks;
-       
-       //////printfUART("MCPS_DATA.request\n", ""); 
-       //check conditions on page 58
-       
-       //atomic mac_PIB.macShortAddress = TOS_LOCAL_ADDRESS;
-       
-       /*
-       //printfUART("SrcAddrMode %x\n", SrcAddrMode);
-       //printfUART("SrcPANId %x\n", SrcPANId);
-       //printfUART("SrcAddr %x\n", SrcAddr[0]);
-       //printfUART("SrcAddr %x\n", SrcAddr[1]);
-       //printfUART("DstAddrMode %x\n", DstAddrMode);
-       //printfUART("DestPANId %x\n", DestPANId);
-       //printfUART("DstAddr %x\n", DstAddr[0]);
-       //printfUART("DstAddr %x\n", DstAddr[1]);
-       //printfUART("msduLength %x\n", msduLength);
-       //printfUART("msduHandle %x\n", msduHandle);
-       //printfUART("TxOptions %x\n", TxOptions);
-               */
-       
-       atomic{
-       
-       if (mac_PIB.macShortAddress == 0xffff)
-               return FAIL;
-       }
-       
-       if(PANCoordinator == 1)
-       {
-       //PAN COORDINATOR OPERATION
-               ////////////printfUART("GTS TRANS: %i TxOptions: %u dest:%u\n", get_txoptions_gts(TxOptions),TxOptions,DstAddr[1]); 
-               
-               if (get_txoptions_gts(TxOptions) == 1)
-               {
-               //GTS TRANSMISSION
-                       for (i=0 ; i < 7 ; i++)
-                       {
-                               //SEARCH FOR A VALID GTS
-                               if ( GTS_db[i].DevAddressType == (uint16_t)DstAddr[1] && GTS_db[i].direction == 1 && GTS_db[i].gts_id != 0)
-                               {
-                                       
-                               //atomic{
-                                               ////////////printfUART("BUFFER UNTIL GTS SLOT n: %i ss: %i\n",number_time_slot,GTS_db[valid_gts].starting_slot);
-                                               create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,GTS_db[i].starting_slot,1);
-                                       //}
-                                       return SUCCESS;
-                                       break;
-                               }
-                       }
-                       signal MCPS_DATA.confirm(msduHandle, MAC_INVALID_GTS);
-                       return FAIL;
-               }
-               else
-               {
-               //NORMAL/INDIRECT TRANSMISSION
-               
-                       ////////////printfUART("IND TRANS: %i TxOptions: %u\n", get_txoptions_indirect_transmission(TxOptions),TxOptions);
-                       //check if its an indirect transmission
-                       //if ( get_txoptions_indirect_transmission(TxOptions) == 1)
-                       //{
-                               //INDIRECT TRANSMISSION
-                               
-                               ////////////printfUART("CREATE INDIRECT TRANSMISSION\n","");
-                               
-                               
-                               
-                               
-                       //}
-                       //else
-                       //{
-                               //NORMAL TRANSMISSION
-                               //printfUART("SEND NO GTS NO IND\n","");
-                               create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,0,0);
-                       //}
-               }
-       }
-       else
-       {
-       //NON PAN COORDINATOR OPERATION
-               atomic{
-                               
-                               ////////////printfUART("sslot: %i ini %i\n",s_GTSss,init_s_GTSss);
-                               //check if it a gts transmission
-                               if (get_txoptions_gts(TxOptions) == 1)
-                               {
-                               //GTS TRANSMISSION
-                                       if (s_GTSss == 0x00)
-                                       {
-                                               ////////////printfUART("NO VALID GTS \n","");
-                                               signal MCPS_DATA.confirm(msduHandle, MAC_INVALID_GTS);
-                                       }
-                                       else
-                                       {
-                                                       total_ticks = call TimerAsync.get_total_tick_counter();
-                                                       msdu[0] =(uint8_t)(total_ticks >> 0 );
-                                                       msdu[1] =(uint8_t)(total_ticks >> 8);
-                                                       msdu[2] =(uint8_t)(total_ticks >> 16);
-                                                       msdu[3] =(uint8_t)(total_ticks >> 24);
-                                                       
-                                                       if (on_sync == 1 && s_GTSss > 0)
-                                                       create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,s_GTSss,0);
-                                       }
-                               }
-                               else
-                               {
-                               //NORMAL TRANSMISSION
-                                       printfUART("TRnsm\n","");
-                                       create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,0,0);
-                               }
-                       }
-       }
-       return SUCCESS;
-}
-
-
-
-
-/*************************************************************/
-/**************        MCPS - PURGE         *******************/
-/*************************************************************/
-
-command error_t MCPS_PURGE.request(uint8_t msduHandle)
-{
-
-
-
-return SUCCESS;
-}
-
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-/************************              OTHER FUNCTIONS                         **********************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/
-/*****************************************************************************************************/
-
-task void signal_loss()
-{
-       //TODO
-       atomic signal MLME_SYNC_LOSS.indication(beacon_loss_reason); //MAC_BEACON_LOSS
-       return;
-}
-
-//inicialization of the mac constants
-void init_MacCon()
-{
-/*****************************************************/
-/*                             Boolean Variables                                        */
-/*****************************************************/  
-PANCoordinator = 0;
-//(0 NO beacon transmission; 1 beacon transmission);
-Beacon_enabled_PAN = 0;
-//(SYNC)the device will try to track the beacon ie enable its receiver just before the espected time of each beacon
-TrackBeacon=0;
-//(SYNC)the device will try to locate one beacon
-findabeacon=0;
-//(RESET) when the reset command arrives it checks whether or not to reset the PIB
-SetDefaultPIB=0;
-/*****************************************************/
-/*                             Integer Variables                                        */
-/*****************************************************/  
-/*
-//Beacon Interval
-uint32_t BI;
-//Superframe duration
-uint32_t SD;
-*/
-//(SYNC)number of beacons lost before sending a Beacon-Lost indication comparing to aMaxLostBeacons
-missed_beacons=0;
-//current_channel
-current_channel=0;
-
-
-/*****************************************************/
-/*                             Other Variables                                  */
-/*****************************************************/ 
-pending_reset=0;
-
-}
-
-//inicialization of the mac PIB
-void init_MacPIB()
-{
-
-atomic{
-       //mac PIB default values
-       
-       //mac_PIB.macAckWaitDuration = 54; OLD VALUE//Number os symbols to wait for an acknowledgment
-       mac_PIB.macAckWaitDuration = 65;
-       
-       mac_PIB.macAssociationPermit = 1; //1 - PAN allowing associations
-       mac_PIB.macAutoRequest = 1; //indication if a device automatically sends a data request command if address is listed in the beacon frame
-       
-       mac_PIB.macBattLifeExt= 0; //batery life extension CSMA-CA
-       
-       mac_PIB.macBattLifeExtPeriods=6;
-       //mac_PIB.macBeaconPayload; //payload of the beacon
-       mac_PIB.macBeaconPayloadLenght=0; //beacon payload lenght
-       
-       mac_PIB.macBeaconTxTime=(0xffffff << 24); //*****
-       
-       
-       mac_PIB.macBSN=call Random.rand16(); //sequence number of the beacon frame
-       
-       
-       mac_PIB.macCoordExtendedAddress0 = 0x00000000; //64bits address of the coordinator with witch the device is associated
-       mac_PIB.macCoordExtendedAddress1 = 0x00000000;
-       
-       mac_PIB.macCoordShortAddress = 0x0000; //16bits address of the coordinator with witch the device is associated
-       
-       
-       if (DEVICE_DEPTH == 0x01)
-               mac_PIB.macCoordShortAddress =D1_PAN_SHORT;
-       if (DEVICE_DEPTH == 0x02)
-               mac_PIB.macCoordShortAddress =D2_PAN_SHORT;
-       if (DEVICE_DEPTH == 0x03)
-               mac_PIB.macCoordShortAddress =D3_PAN_SHORT;
-       if (DEVICE_DEPTH == 0x04)
-               mac_PIB.macCoordShortAddress =D4_PAN_SHORT;
-       
-       
-       mac_PIB.macDSN=call Random.rand16(); //sequence number of the transmited data or MAC command frame
-       
-       //alowing gts requests (used in beacon)
-       mac_PIB.macGTSPermit=1; //
-       
-       //Number of maximum CSMA backoffs
-       mac_PIB.macMaxCSMABackoffs=4;
-       mac_PIB.macMinBE=0;
-       
-       //mac_PIB.macPANId=0xffff; //16bits identifier of the PAN on witch this device is operating
-       mac_PIB.macPANId = MAC_PANID;
-       
-       mac_PIB.macPromiscuousMode=0;
-       mac_PIB.macRxOnWhenIdle=0;
-       //mac_PIB.macShortAddress=TOS_LOCAL_ADDRESS; //16bits short address
-       mac_PIB.macShortAddress=0xffff;
-
-
-       mac_PIB.macBeaconOrder=7;  //specification of how often the coordinator transmits a beacon
-       mac_PIB.macSuperframeOrder=3;
-       
-       //default mac_PIB.macTransactionPersistenceTime=0x01f4;
-       mac_PIB.macTransactionPersistenceTime=0x0010;
-       
-       //*******************************************
-
-       }
-}
-
-//////////////////////////////////////////////////////////////
-////////////////////////CSMA-CA functions////////////////////
-/////////////////////////////////////////////////////////////
-
-/*****************************************************/
-/*                             SEND FRAME FUNCTION                      */
-/*****************************************************/ 
-
-task void send_frame_csma_upstream()
-{//used in TDBS
-       atomic{
-       
-               ////////printfUART("sf %i, %i \n",send_buffer_count,upstream_buffer_count);
-               ////////printfUART("I_AM_IN_IP %i \n",I_AM_IN_IP);
-               ////printfUART("send up IPCAP %i %i \n",I_AM_IN_PARENT_CAP,upstream_buffer_count);
-       
-               //beacon synchronization
-               if(upstream_buffer_count > 0 && I_AM_IN_PARENT_CAP == 1)
-               {
-               
-                       ////////printfUART("s up\n","");
-                       sending_upstream_frame =1;
-                       
-                       performing_csma_ca = 1;
-
-                       perform_csma_ca();
-               }
-               
-               
-       }
-       
-}
-
-
-task void send_frame_csma()
-{
-       atomic{
-       
-               //
-               ///printfUART("I_AM_IN_IP %i %i\n",I_AM_IN_IP,send_buffer_count);
-       
-               if ((send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE && performing_csma_ca == 0) || I_AM_IN_IP != 0)
-               {
-                       ////printfUART("sf %i\n",send_buffer_count);
-                       //////printfUART("peform\n","");
-                       
-                       performing_csma_ca = 1;
-
-                       perform_csma_ca();
-               }
-               else
-               {
-                       //printfUART("NOT SEND\n","");
-               }
-
-               
-       }
-       
-}
-
-
-task void perform_csma_ca_slotted()
-{
-       uint8_t random_interval;
-       
-               
-               
-               //DEFERENCE CHANGE
-               if (check_csma_ca_send_conditions(send_buffer[send_buffer_msg_out].length,send_buffer[send_buffer_msg_out].frame_control1) == 1 )
-               {
-                       cca_deference = 0;
-               }
-               else
-               {
-                       //nao e necessario
-                       cca_deference = 1;
-                       return;
-               }
-               
-       atomic{
-               //printfUART("CCA: %i\n", call CCA.get()) ;
-       
-               if(call CCA.get() == CCA_BUSY )
-               {
-                       ////////////printfUART("CCA: 1\n", "") ;
-                       //STEP 5
-                       CW--;
-                       if (CW == 0 )
-                       {
-                               //send functions
-                               csma_cca_backoff_boundary =0;
-                               
-                               ////////printfUART("s_up_f %i\n",sending_upstream_frame);
-                               //TDBS Implementation
-                               if(sending_upstream_frame == 0)
-                               {
-                               
-                                       //////printfUART("rts %i\n",get_ack_request(send_buffer[send_buffer_msg_out].frame_control));
-
-                                               //verify if the message must be ack
-                                               if ( get_fc1_ack_request(send_buffer[send_buffer_msg_out].frame_control1) == 1 )
-                                               {
-                                                       send_ack_check=1;
-                                                       ack_sequence_number_check=send_buffer[send_buffer_msg_out].seq_num;     
-                                                       //verify retransmission
-                                                       send_retransmission = send_buffer[send_buffer_msg_out].retransmission;
-                                                       //verify if its an indirect transmission
-                                                       send_indirect_transmission = send_buffer[send_buffer_msg_out].indirect;
-                                                       //SEND WITH ACK_REQUEST
-                                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
-                                                       
-                                                       //////printfUART("out ck\n","");
-                                                       
-                                                       
-                                                       call T_ackwait.startOneShot(ackwait_period);
-                                               }
-                                               else
-                                               {
-                                               
-                                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
-                                                       
-                                                       send_buffer_count --;
-                                                       send_buffer_msg_out++;
-                                               
-                                                       //failsafe
-                                                       if(send_buffer_count > SEND_BUFFER_SIZE)
-                                                       {
-                                                               send_buffer_count =0;
-                                                               send_buffer_msg_out=0;
-                                                               send_buffer_msg_in=0;
-                                                       }
-                                                       
-                                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                                               send_buffer_msg_out=0;
-                                                       
-                                                       if (send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE)
-                                                               post send_frame_csma();
-                                                       
-                                                       //printfUART("sk %i\n",send_buffer_count);
-                                                       
-                                                       ////////printfUART("%i %i %i\n",send_buffer_count,send_buffer_msg_in,send_buffer_msg_out);
-                                               }
-                                               
-                               }
-                               else
-                               {
-                                       //TDBS Implementation
-                                               
-                                               call PD_DATA.request(upstream_buffer[upstream_buffer_msg_out].length,(uint8_t *)&upstream_buffer[upstream_buffer_msg_out]);
-                                               
-                                               upstream_buffer_count --;
-                                               upstream_buffer_msg_out++;
-                                       
-                                               if (upstream_buffer_msg_out == UPSTREAM_BUFFER_SIZE)
-                                                       upstream_buffer_msg_out=0;
-                                                       
-                                               sending_upstream_frame=0;
-                               }               
-                               performing_csma_ca = 0;
-                       }
-               }
-               else
-               {
-                       //CHECK NOT USED
-                       //csma_backoff_counter++;
-                       //csma_backoff_counter_inst++;
-
-                       if (NB < mac_PIB.macMaxCSMABackoffs)
-                       {
-                               //////////printfUART("NB:%i BE:%i L CW: %i\n",NB,BE,CW);
-                               //STEP 4
-                               CW = 2;
-                               NB++;
-                               BE = min(BE+1,aMaxBE);
-                               
-                               //STEP 2
-                               //random_interval = pow(2,BE) - 1;
-                               
-                               //delay_backoff_period = (call Random.rand() & random_interval);
-                               //verification of the backoff_deference
-                               //DEFERENCE CHANGE
-                               if (backoff_deference == 0)
-                               {
-                                       random_interval = powf(2,BE) - 1;
-                                       delay_backoff_period = (call Random.rand16() & random_interval );
-                                               
-                                       if (check_csma_ca_backoff_send_conditions((uint32_t) delay_backoff_period) == 1)
-                                       {
-                                                       backoff_deference = 1;
-                                       }
-                               }
-                               else
-                               {
-                                       backoff_deference = 0;
-                               }
-                               
-                               
-                               //delay_backoff_period=0;
-                               
-                               //printfUART("delay_backoff_period:%i\n",delay_backoff_period);
-                               csma_delay=1;
-                       }
-                       else
-                       {
-                               //CSMA/CA FAIL
-                               csma_delay=0;
-                               csma_cca_backoff_boundary=0;
-                               
-                               send_buffer_count --;
-                               send_buffer_msg_out++;
-                       
-                               //failsafe
-                               if(send_buffer_count > SEND_BUFFER_SIZE)
-                               {
-                                       send_buffer_count =0;
-                                       send_buffer_msg_out=0;
-                                       send_buffer_msg_in=0;
-                               }
-                               
-                               if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                       send_buffer_msg_out=0;
-                               
-                               if (send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE)
-                                       post send_frame_csma();
-                                       
-                               performing_csma_ca = 0;
-                               
-                               //printfUART("SLOTTED FAIL\n","");
-                               /*
-                               if(associating == 1)
-                               {
-                                       associating=0;
-                                       signal MLME_ASSOCIATE.confirm(0x0000,MAC_CHANNEL_ACCESS_FAILURE);
-                               }*/
-                       }
-               }
-       }
-return;
-}
-
-task void perform_csma_ca_unslotted()
-{
-       uint8_t random_interval;
-       
-       atomic{
-               if (NB < mac_PIB.macMaxCSMABackoffs)
-               {
-                       //STEP 3
-                       //perform CCA
-                       //////////printfUART("CCA: %i\n", TOSH_READ_CC_CCA_PIN()) ;
-                       
-                       //if CCA is clear send message
-                       if(call CCA.get() == CCA_BUSY)
-                       {
-                               //send functions
-                               //////////printfUART("UNSLOTTED SUCCESS\n","");
-                               atomic{
-                               csma_delay =0;
-                               
-
-                                               
-                               if (check_csma_ca_send_conditions(send_buffer[send_buffer_msg_out].length,send_buffer[send_buffer_msg_out].frame_control1) == 1 )
-                               {
-                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
-                                       
-                                       send_buffer_count --;
-                                       send_buffer_msg_out++;
-                               
-                                       //failsafe
-                                       if(send_buffer_count > SEND_BUFFER_SIZE)
-                                       {
-                                               send_buffer_count =0;
-                                               send_buffer_msg_out=0;
-                                               send_buffer_msg_in=0;
-                                       }
-                               
-                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
-                                               send_buffer_msg_out=0;
-                               }
-                                       
-                               
-                               performing_csma_ca =0;
-
-                               }
-                               return; //SUCCESS
-                       
-                       }
-
-                       //CCA is not clear, perform new iteration of the CSMA/CA UNSLOTTED
-                       
-                       //STEP 4
-                       NB++;
-                       BE = min(BE+1,aMaxBE);
-               
-                       //////////printfUART("NB:%i BE:%i\n",NB,BE);
-                       
-                       //STEP 2
-                       //#ifdef PLATFORM_MICAZ
-                               random_interval = powf(2,BE) - 1;
-                       //#else
-                       //      random_interval = powf(2,BE) - 1;
-                       //#endif
-                       delay_backoff_period = (call Random.rand16() & random_interval );
-                       //delay_backoff_period=1;
-                       csma_delay=1;
-                       
-                       ////////////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
-               }
-               else
-               {
-                       atomic csma_delay=0;
-                       //////////printfUART("UNSLOTTED FAIL\n","");
-               }
-       }
-return;
-}
-
-
-void perform_csma_ca()
-{
-       uint8_t random_interval;
-       csma_slotted=1;
-       //STEP 1
-       if (csma_slotted == 0 )
-       {
-               atomic{
-                       //UNSLOTTED version
-                       init_csma_ca(csma_slotted);
-                       //STEP 2
-                       random_interval = powf(2,BE) - 1;
-                       delay_backoff_period = (call Random.rand16() & random_interval );
-                       
-                       csma_delay=1;
-                       //////////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
-               }
-               return;
-       }
-       else
-       {
-               //SLOTTED version
-               atomic{
-                       //DEFERENCE CHANGE
-                       if (cca_deference==0)
-                       {
-                               init_csma_ca(csma_slotted);
-                               if (mac_PIB.macBattLifeExt == 1 )
-                               {
-                                       BE = min(2,     mac_PIB.macMinBE);
-                               }
-                               else
-                               {
-                                       BE = mac_PIB.macMinBE;
-                               }
-                               csma_locate_backoff_boundary = 1;
-                       }
-                       else
-                       {
-                               cca_deference = 0;
-                               csma_delay=0;
-                               csma_locate_backoff_boundary=0;
-                               csma_cca_backoff_boundary = 1;
-                       
-                       }
-               }
-               return;
-       }
-}
-
-
-uint8_t min(uint8_t val1, uint8_t val2)
-{
-       if (val1 < val2)
-       {
-               return val1;
-       }
-       else
-       {
-               return val2;
-       }
-}
-
-void init_csma_ca(bool slotted)
-{
-
-//initialization of the CSMA/CA protocol variables
-       ////////////printfUART("init_csma_ca\n", "") ;
-       
-       csma_delay=0;
-       
-       if (slotted == 0 )
-       {
-               NB=0;
-               BE=mac_PIB.macMinBE;
-       }
-       else
-       {
-               NB=0;
-               CW=2;
-               
-               csma_cca_backoff_boundary=0;
-               csma_locate_backoff_boundary=0;
-       }
-
-return;
-}
-
-
-uint8_t calculate_ifs(uint8_t pk_length)
-{
-       if (pk_length > aMaxSIFSFrameSize)
-               return aMinLIFSPeriod; // + ( ((pk_length * 8) / 250.00) / 0.34 );
-       else
-               return aMinSIFSPeriod; // + ( ((pk_length * 8) / 250.00) / 0.34 );
-}
-
-uint32_t calculate_gts_expiration()
-{
-       uint32_t exp_res;
-       if( mac_PIB.macBeaconOrder > 9 )
-               exp_res= 1;
-       else
-       {
-               //#ifdef PLATFORM_MICAZ
-                       exp_res= powf(2,(8-mac_PIB.macBeaconOrder));
-               //#else
-               //      exp_res= powf(2,(8-mac_PIB.macBeaconOrder));
-               //#endif
-       }       
-       //////////printfUART("alculat %i\n",exp_res ) ;
-       return exp_res;
-}
-
-uint8_t check_csma_ca_send_conditions(uint8_t frame_length,uint8_t frame_control1)
-{
-       uint8_t ifs_symbols;
-       uint32_t frame_tx_time;
-       uint32_t remaining_gts_duration;
-       
-       
-       ifs_symbols=calculate_ifs(frame_length);
-       //wait_ifs=1;
-       //call TimerAsync.set_ifs_symbols(ifs_symbols);
-       
-       ////////////printfUART("ifs_symbols %i\n",ifs_symbols ) ;
-       
-       if (get_fc1_ack_request(frame_control1) == 1 )
-               frame_tx_time =  frame_length + ACK_LENGTH + aTurnaroundTime + ifs_symbols;
-       else
-               frame_tx_time =  frame_length + ifs_symbols;
-               
-       atomic remaining_gts_duration = time_slot - ( call TimerAsync.get_current_number_backoff_on_time_slot() * aUnitBackoffPeriod);
-       
-       ////////////printfUART("frame_tx %d remaing %d\n",frame_tx_time,remaining_gts_duration ) ;
-       
-       if (frame_tx_time < remaining_gts_duration)
-               return 1;
-       else
-               return 0;
-
-}
-
-//DEFERENCE CHANGE
-uint8_t check_csma_ca_backoff_send_conditions(uint32_t delay_backoffs)
-{
-
-       uint32_t number_of_sd_ticks=0;
-       uint32_t current_ticks=0;
-       uint32_t ticks_remaining =0;
-       uint32_t number_of_backoffs_remaining =0;
-       
-       number_of_sd_ticks = call TimerAsync.get_sd_ticks();
-       
-       current_ticks = call TimerAsync.get_current_ticks();
-       
-       ticks_remaining = number_of_sd_ticks - current_ticks;
-       
-       number_of_backoffs_remaining = ticks_remaining / 5;
-       
-       if (number_of_backoffs_remaining > delay_backoffs)
-               return 0;
-       else
-               return 1;
-
-
-
-}
-
-uint8_t check_gts_send_conditions(uint8_t frame_length)
-{
-       uint8_t ifs_symbols;
-       uint32_t frame_tx_time;
-       uint32_t remaining_gts_duration;
-       
-
-       ifs_symbols=calculate_ifs(frame_length);
-       //wait_ifs=1;
-       //call TimerAsync.set_ifs_symbols(ifs_symbols);
-       
-       ////////////printfUART("ifs_symbols %i\n",ifs_symbols ) ;
-       
-       frame_tx_time =  frame_length + ACK_LENGTH + aTurnaroundTime + ifs_symbols;
-       
-       remaining_gts_duration = time_slot - ( call TimerAsync.get_current_number_backoff_on_time_slot() * aUnitBackoffPeriod);
-       
-       ////////////printfUART("frame_tx %d remaing %d\n",frame_tx_time,remaining_gts_duration ) ;
-       
-       if (frame_tx_time < remaining_gts_duration)
-               return 1;
-       else
-               return 0;
-}
-
-//////////////////////////////////////////////////////////////
-////////////////////////GTS functions////////////////////////
-/////////////////////////////////////////////////////////////
-
-void init_GTS_db()
-{
-       //initialization of the GTS database
-       int i;
-atomic{
-               for (i=0 ; i < 7 ; i++)
-               {
-                       GTS_db[i].gts_id=0x00;
-                       GTS_db[i].starting_slot=0x00;
-                       GTS_db[i].length=0x00;
-                       GTS_db[i].direction=0x00;
-                       GTS_db[i].DevAddressType=0x0000;
-               
-               }
-       }
-return;
-}
-
-error_t remove_gts_entry(uint16_t DevAddressType)
-{
-       uint8_t r_lenght=0;
-       //int r_start_slot=7;
-       int i;
-       
-       atomic{
-               for (i=0; i < 7 ; i++)
-               {
-                       if( GTS_db[i].DevAddressType == DevAddressType )
-                       {
-                               
-                               r_lenght = GTS_db[i].length;
-                               //r_start_slot = i;
-                               //delete the values
-                               GTS_db[i].gts_id=0x00;
-                               GTS_db[i].starting_slot=0x00;
-                               GTS_db[i].length=0x00;
-                               GTS_db[i].direction=0x00;
-                               GTS_db[i].DevAddressType=0x0000;
-                               GTS_db[i].expiration=0x00;
-                               
-                               ////////////printfUART("GTS Entry removed dev:%i len:%i pos %i\n", DevAddressType,r_lenght,i);
-                               GTS_startslot = GTS_startslot + r_lenght;
-                               GTS_descriptor_count--;
-                               final_CAP_slot = final_CAP_slot + r_lenght;
-                       }
-                       
-                       if ( r_lenght > 0)
-                       {
-                               if ( GTS_db[i].gts_id != 0x00 && GTS_db[i].DevAddressType !=0x0000)
-                               {                               
-                                       GTS_db[i-r_lenght].gts_id = GTS_db[i].gts_id;
-                                       GTS_db[i-r_lenght].starting_slot = i-r_lenght;
-                                       GTS_db[i-r_lenght].length = GTS_db[i].length;
-                                       GTS_db[i-r_lenght].direction = GTS_db[i].direction;
-                                       GTS_db[i-r_lenght].DevAddressType = GTS_db[i].DevAddressType;
-                                       GTS_db[i-r_lenght].expiration = GTS_db[i].expiration;
-                                       
-                                       //delete the values
-                                       GTS_db[i].gts_id=0x00;
-                                       GTS_db[i].starting_slot=0x00;
-                                       GTS_db[i].length=0x00;
-                                       GTS_db[i].direction=0x00;
-                                       GTS_db[i].DevAddressType=0x0000;
-                                       GTS_db[i].expiration=0x00;
-                                       
-                                       ////////////printfUART("UPDATED\n","" );
-                               }
-                       }
-               }
-       }
-return SUCCESS;
-}
-
-error_t add_gts_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType)
-{
-       int i;
-       ////////////printfUART("ADDING gts_length: %i\n", gts_length); 
-       ////////////printfUART("dir: %i\n", direction); 
-       ////////////printfUART("addr: %i\n", DevAddressType);
-
-       //check aMinCAPLength
-       if ( (GTS_startslot - gts_length) < 5 )
-       {
-               ////////////printfUART("ADD FAIL%i\n", ""); 
-               
-       }
-       
-       //if it has more than 7 timeslots alocated
-       if ( (GTS_startslot -gts_length) < 9 )
-       {
-               return FAIL;
-       }
-       
-       //check if the address already exists in the GTS list
-       for (i=0 ; i < 7 ; i++)
-       {
-               if ( GTS_db[i].DevAddressType == DevAddressType && GTS_db[i].direction == direction && GTS_db[i].gts_id > 0)
-               {
-                       ////////////printfUART("ALREADY ADDED\n", ""); 
-                       return FAIL;
-               }
-               if ( GTS_null_db[i].DevAddressType == DevAddressType && GTS_null_db[i].gts_id > 0)
-               {
-                       ////////////printfUART("REJECTED\n", ""); 
-                       return FAIL;
-               }
-               
-               
-       }
-       
-atomic{        
-       
-       ////////////printfUART("GTS_startslot: %i\n", GTS_startslot); 
-       GTS_startslot = GTS_startslot - gts_length;
-
-       GTS_db[15-GTS_startslot].gts_id=GTS_id;
-       GTS_db[15-GTS_startslot].starting_slot=GTS_startslot;
-       GTS_db[15-GTS_startslot].length=gts_length;
-       GTS_db[15-GTS_startslot].direction=direction;
-       GTS_db[15-GTS_startslot].DevAddressType=DevAddressType;
-       GTS_db[15-GTS_startslot].expiration=0x00;
-
-       ////////////printfUART("GTS Entry added start:%i len:%i\n", GTS_startslot,gts_length); 
-       
-       GTS_id++;
-       GTS_descriptor_count++;
-       
-       final_CAP_slot = final_CAP_slot - gts_length;
-       
-       }
-       return SUCCESS;
-}
-
-
-//GTS null functions
-void init_GTS_null_db()
-{
-       //initialization of the GTS database
-       int i;
-       atomic{
-               for (i=0 ; i < 7 ; i++)
-               {
-                       GTS_null_db[i].gts_id=0x00;
-                       GTS_null_db[i].starting_slot=0x00;
-                       GTS_null_db[i].length=0x00;
-                       //GTS_null_db[i].direction=0x00;
-                       GTS_null_db[i].DevAddressType=0x0000;
-                       GTS_null_db[i].persistencetime=0x00;
-               }
-       }
-return;
-}
-
-
-error_t add_gts_null_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType)
-{
-       int i;
-               
-       //check if the address already exists in the GTS list
-       for (i=0 ; i < 7 ; i++)
-       {
-               if ( GTS_null_db[i].DevAddressType == DevAddressType && GTS_null_db[i].gts_id > 0)
-               {
-                       ////////////printfUART("ALREADY ADDED null\n", ""); 
-                       return FAIL;
-               }
-       }
-       
-       for (i=0 ; i < 7 ; i++)
-       {
-               if ( GTS_null_db[i].DevAddressType==0x0000 && GTS_null_db[i].gts_id == 0x00)
-               {
-                       GTS_null_db[i].gts_id=GTS_id;
-                       GTS_null_db[i].starting_slot=0x00;
-                       GTS_null_db[i].length=0x00;
-                       //GTS_null_db[i].direction=0x00;
-                       GTS_null_db[i].DevAddressType=DevAddressType;
-                       GTS_null_db[i].persistencetime=0x00;
-                       
-                       
-                       ////////////printfUART("GTS null Entry added addr:%x\n", DevAddressType); 
-                       
-                       GTS_id++;
-                       GTS_null_descriptor_count++;
-                       
-               return SUCCESS;
-               }
-       }
-
-       
-return FAIL;   
-}
-
-task void increment_gts_null()
-{
-       int i;
-       
-       ////////////printfUART("init inc\n",""); 
-atomic{
-       for (i=0 ; i < 7 ; i++)
-       {
-               if ( GTS_null_db[i].DevAddressType != 0x0000 && GTS_null_db[i].gts_id != 0x00)
-               {
-                       ////////////printfUART("increm %x\n", GTS_null_db[i].DevAddressType); 
-                       GTS_null_db[i].persistencetime++;
-               
-               }
-               
-               if ( GTS_null_db[i].persistencetime > (aGTSDescPersistenceTime -1)  )
-               {
-                       GTS_null_db[i].gts_id=0x00;
-                       GTS_null_db[i].starting_slot=0x00;
-                       GTS_null_db[i].length=0x00;
-                       //GTS_null_db[i].direction=0x00;
-                       GTS_null_db[i].DevAddressType=0x0000;
-                       GTS_null_db[i].persistencetime=0x00;
-                       
-                       ////////////printfUART("GTS null removed addr:%x\n", GTS_null_db[i].DevAddressType); 
-               
-                       atomic GTS_null_descriptor_count--;
-               }
-                       
-       }
-       
-       }
-////////////printfUART("end inc\n",""); 
-return;
-}
-
-task void check_gts_expiration()
-{
-       int i;
-////////////printfUART("init exp\n",""); 
-atomic{        
-       atomic gts_expiration=calculate_gts_expiration();
-       ////////////printfUART("gts_expiration:%i\n", gts_expiration); 
-       atomic gts_expiration=2;
-       ////////////printfUART("gts_expiration:%i\n", gts_expiration); 
-       
-       for (i=0 ; i < 7 ; i++)
-       {
-               
-               if ( GTS_db[i].DevAddressType != 0x0000 && GTS_db[i].gts_id != 0x00)
-               {
-                       if( GTS_db[i].expiration == (gts_expiration + 1) && GTS_db[i].direction ==0x00)
-                       {
-                               ////////////printfUART("GTS expired addr:%x\n", GTS_null_db[i].DevAddressType); 
-                               //remove gts, indicate on the gts null list
-                               atomic{
-                               
-                                       add_gts_null_entry(GTS_db[i].length,GTS_db[i].direction,GTS_db[i].DevAddressType);
-                                       
-                                       remove_gts_entry(GTS_db[i].DevAddressType);
-                               }
-                       }
-                       else
-                       {
-                               atomic GTS_db[i].expiration ++;
-                       }
-               }
-       }
-       
-       
-       }
-       ////////////printfUART("end exp\n",""); 
-return;
-}
-
-void init_available_gts_index()
-       {
-               int i=0;
-               atomic{
-                       available_gts_index_count = GTS_SEND_BUFFER_SIZE;
-                       for(i=0;i < GTS_SEND_BUFFER_SIZE;i++)
-                       {
-                               available_gts_index[i]=i;
-                       }
-               }
-               return;
-       }
-/*****************************GTS BUFFER******************************/
-void init_gts_slot_list()
-{
-       int i=0;
-       for(i=0;i<7;i++)
-       {
-               gts_slot_list[i].element_count = 0x00;
-               gts_slot_list[i].element_in = 0x00;
-               gts_slot_list[i].element_out = 0x00;
-       }
-}
-
-
-task void start_coordinator_gts_send()
-{
-atomic{
-
-       coordinator_gts_send_pending_data =0;
-       
-       if(gts_slot_list[15-number_time_slot].element_count > 0)
-       {
-               if (check_gts_send_conditions(gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length) == 1 )
-               {
-                       
-                       gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length = gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length -2;
-                       
-                       call PD_DATA.request(gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length,(uint8_t *)&gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]]);
-       
-                       available_gts_index_count++;
-                       available_gts_index[available_gts_index_count] = gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out];
-                       
-                       gts_slot_list[15-number_time_slot].element_count--;
-                       gts_slot_list[15-number_time_slot].element_out++;
-                       
-                       if (gts_slot_list[15-number_time_slot].element_out == GTS_SEND_BUFFER_SIZE)
-                               gts_slot_list[15-number_time_slot].element_out=0;
-
-                       if(gts_slot_list[15-number_time_slot].element_count > 0 )
-                       {
-                               coordinator_gts_send_pending_data =1;
-                               coordinator_gts_send_time_slot = number_time_slot;
-                       }
-               }
-       }
-}
-return;
-}
-
-task void start_gts_send()
-{
-
-       atomic{
-       gts_send_pending_data = 0;
-       
-       if(gts_send_buffer_count > 0)
-       {
-               if (check_gts_send_conditions(gts_send_buffer[gts_send_buffer_msg_out].length) == 1 )
-               {
-
-                       gts_send_buffer[gts_send_buffer_msg_out].length = gts_send_buffer[gts_send_buffer_msg_out].length -2;
-
-                       call PD_DATA.request(gts_send_buffer[gts_send_buffer_msg_out].length,(uint8_t *)&gts_send_buffer[gts_send_buffer_msg_out]);
-       
-                       gts_send_buffer_count --;
-                       gts_send_buffer_msg_out++;
-
-                       if (gts_send_buffer_msg_out == GTS_SEND_BUFFER_SIZE)
-                               gts_send_buffer_msg_out=0;
-
-                       ////////////printfUART("after send %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
-                       
-                       if (gts_send_buffer_count > 0)
-                               gts_send_pending_data = 1;      
-               }
-       }
-
-}
-return;
-}
-
-//////////////////////////////////////////////////////////////
-//////////Indirect transmission functions////////////////////
-/////////////////////////////////////////////////////////////
-
-void init_indirect_trans_buffer()
-{
-       int i;
-       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-       {
-               indirect_trans_queue[i].handler = 0x00;
-               indirect_trans_count=0;
-       }
-
-return;
-}
-
-
-error_t remove_indirect_trans(uint8_t handler)
-{
-
-       int i;
-       uint8_t removed_ok=0;
-       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-       {
-               if (indirect_trans_queue[i].handler == handler)
-               {
-                       indirect_trans_queue[i].handler = 0x00;
-                       removed_ok = 1;
-                       indirect_trans_count--;
-                       break;
-               }
-       }
-
-       if (removed_ok == 0) 
-       {
-               return MAC_INVALID_HANDLE;
-       }
-       else
-       {
-               return SUCCESS;
-       }
-}
-
-
-void increment_indirect_trans()
-{
-       int i;
-       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-       {
-               if (indirect_trans_queue[i].handler != 0x00)
-               {
-                       indirect_trans_queue[i].transaction_persistent_time++;
-                       if (indirect_trans_queue[i].transaction_persistent_time == mac_PIB.macTransactionPersistenceTime )
-                               remove_indirect_trans(indirect_trans_queue[i].handler);
-               }
-       }
-
-return;
-}
-
-void send_ind_trans_addr(uint32_t DeviceAddress[])
-{
-       
-       uint8_t destination_address=0;
-       
-       dest_short *dest_short_ptr =0;
-       dest_long *dest_long_ptr=0;
-       
-       int i=0;
-       MPDU *frame_ptr=0;
-       
-       //printfUART("send_ind_trans_addr DeviceAddress0: %y DeviceAddress1: %y \n",DeviceAddress[0],DeviceAddress[1]);
-
-    //list_indirect_trans_buffer();
-
-               for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
-               {
-                       if (indirect_trans_queue[i].handler > 0x00)
-                       {
-                               frame_ptr = (MPDU *)indirect_trans_queue[i].frame;
-                               destination_address=get_fc2_dest_addr(frame_ptr->frame_control2);
-                               
-                               switch(destination_address)
-                               {
-                                       case LONG_ADDRESS: dest_long_ptr = (dest_long *) frame_ptr->data;
-                                                                               break;
-                                       case SHORT_ADDRESS: dest_short_ptr = (dest_short *) frame_ptr->data;                                                            
-                                                                               break;
-                               }
-                               
-                               //check the full address
-                               if ( (dest_long_ptr->destination_address0 == DeviceAddress[1] && dest_long_ptr->destination_address1 == DeviceAddress[0]) || ( dest_short_ptr->destination_address == (uint16_t)DeviceAddress[0] ))
-                               {
-                                       
-                                       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
-                                               send_buffer_msg_in=0;
-                                               
-                                       memcpy(&send_buffer[send_buffer_msg_in],(MPDU *) &indirect_trans_queue[i].frame,sizeof(MPDU));
-                                       
-                                       //enable retransmissions
-                                       send_buffer[send_buffer_msg_in].retransmission =0;
-                                       send_buffer[send_buffer_msg_in].indirect = i + 1;
-                                       
-                                       //check upon reception
-                                       indirect_trans_queue[i].handler=0x00;
-                                       //verify temporary error on the association request
-                                       
-                                       indirect_trans_count--;
-                                       if(indirect_trans_count > INDIRECT_BUFFER_SIZE )
-                                       {
-                                               indirect_trans_count=0;
-                                       }
-                                       
-                                       atomic send_buffer_count++;
-                                       atomic send_buffer_msg_in++;
-                       
-                                       post send_frame_csma();
-                                       
-                                       //printfUART("i send\n","");
-                                       
-                                       return;
-                               }
-                       }
-               }
-               //printfUART("i not found","");
-
-       
-return;
-} 
-/*
-  event void CC2420Config.syncDone( error_t error )
-  {
-  
-       //printfUART("CC2420Config %i p %x sa %x\n",call CC2420Config.isAddressRecognitionEnabled(),call CC2420Config.getPanAddr(), call CC2420Config.getShortAddr()); 
-  
-  return;
-  }
-
-*/
-
-/***************************DEBUG FUNCTIONS******************************/
-/* This function are list functions with the purpose of debug, to use then uncomment the declatarion
-on top of this file*/
-/*
-
-void list_mac_pib()
-{
-//////////printfUART("mac_PIB.macAckWaitDuration: %x\n",mac_PIB.macAckWaitDuration);
-//////////printfUART("mac_PIB.macAssociationPermit: %i\n",mac_PIB.macAssociationPermit);
-//////////printfUART("mac_PIB.macAutoRequest: %i\n",mac_PIB.macAutoRequest);
-//////////printfUART("mac_PIB.macBattLifeExt %i\n",mac_PIB.macBattLifeExt);
-//////////printfUART("mac_PIB.macBattLifeExtPeriods %i\n",mac_PIB.macBattLifeExtPeriods);
-//beacon payload
-//////////printfUART("mac_PIB.macBeaconPayloadLenght %i\n",mac_PIB.macBeaconPayloadLenght);
-//////////printfUART("mac_PIB.macBeaconOrder %i\n",mac_PIB.macBeaconOrder);
-//////////printfUART("mac_PIB.macBeaconTxTime %i\n",mac_PIB.macBeaconTxTime);
-//////////printfUART("mac_PIB.macBSN %i\n",mac_PIB.macBSN);
-//////////printfUART("mac_PIB.macCoordExtendedAddress0 %y\n",mac_PIB.macCoordExtendedAddress0);
-//////////printfUART("mac_PIB.macCoordExtendedAddress1 %y\n",mac_PIB.macCoordExtendedAddress1);
-//////////printfUART("mac_PIB.macCoordShortAddress: %x\n",mac_PIB.macCoordShortAddress);
-//////////printfUART("mac_PIB.macDSN: %x\n",mac_PIB.macDSN);
-//////////printfUART("mac_PIB.macGTSPermit: %x\n",mac_PIB.macGTSPermit);
-//////////printfUART("mac_PIB.macMaxCSMABackoffs: %x\n",mac_PIB.macMaxCSMABackoffs);
-//////////printfUART("mac_PIB.macMinBE: %x\n",mac_PIB.macMinBE);
-//////////printfUART("mac_PIB.macPANId: %x\n",mac_PIB.macPANId);
-//////////printfUART("mac_PIB.macPromiscuousMode: %x\n",mac_PIB.macPromiscuousMode);
-//////////printfUART("mac_PIB.macRxOnWhenIdle: %x\n",mac_PIB.macRxOnWhenIdle);
-//////////printfUART("mac_PIB.macShortAddress: %y\n",mac_PIB.macShortAddress);
-//////////printfUART("mac_PIB.macSuperframeOrder: %x\n",mac_PIB.macSuperframeOrder);
-//////////printfUART("mac_PIB.macTransactionPersistenceTime: %y\n",mac_PIB.macTransactionPersistenceTime);
-
-return;
-}
-
-void list_gts()
-{
-       int i;
-       //////////printfUART("GTS list%i\n", GTS_descriptor_count); 
-       
-       for (i=0; i< 7;i++)
-       {
-               //////////printfUART("GTSID: %i",GTS_db[i].gts_id);     
-               //////////printfUART("start slot: %i",GTS_db[i].starting_slot);
-               //////////printfUART("lenght: %i",GTS_db[i].length);    
-               //////////printfUART("dir: %i",GTS_db[i].direction);    
-               //////////printfUART("DevAddressType: %i",GTS_db[i].DevAddressType);
-               //////////printfUART("expiration: %i \n",GTS_db[i].expiration);
-       }
-       
-}
-
-void list_my_gts()
-{
-atomic{
-               //////////printfUART("SEND GTS s_GTSss: %i s_GTS_length: %i\n",s_GTSss,s_GTS_length);   
-               
-               //////////printfUART("RECEIVE GTS r_GTSss: %i r_GTS_length: %i\n",r_GTSss,r_GTS_length); 
-}
-}
-*/
-
-void list_indirect_trans_buffer()
-{
-       int i;
-       printfUART("indirect_trans_count %i\n", indirect_trans_count); 
-       
-       for (i=0; i< INDIRECT_BUFFER_SIZE;i++)
-       {
-               printfUART("hand: %i \n",indirect_trans_queue[i].handler); 
-               
-               //printfUART("start slot: %i",GTS_db[i].starting_slot);
-
-       }
-       
-}
-/*
-void list_gts_null()
-{
-       int i;
-       //////////printfUART("GTS null list%i\n", GTS_null_descriptor_count); 
-       
-       for (i=0; i< GTS_null_descriptor_count;i++)
-       {
-               ////////////printfUART("GTSID: %i",GTS_null_db[i].gts_id);      
-               //////////printfUART("start slot: %i",GTS_null_db[i].starting_slot);
-               //////////printfUART("lenght: %i",GTS_null_db[i].length);       
-               ////////////printfUART("dir: %i",GTS_null_db[i].direction);     
-               //////////printfUART("DevAddressType: %i \n",GTS_null_db[i].DevAddressType); 
-               //////////printfUART("persistencetime: %i \n",GTS_null_db[i].persistencetime); 
-       }
-       
-}
-
-*/
-
-
-}
-
diff --git a/tos/lib/net/zigbee/ieee802154/macTDBS/MacP.nc b/tos/lib/net/zigbee/ieee802154/macTDBS/MacP.nc
new file mode 100644 (file)
index 0000000..75ba457
--- /dev/null
@@ -0,0 +1,5679 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+
+#include <Timer.h>
+
+#include "printfUART.h"
+
+#include "frame_format.h"
+#include "phy_const.h"
+
+#include "mac_const.h"
+#include "mac_enumerations.h"
+
+#include "mac_func.h"
+
+module MacP {
+
+#ifndef TKN154_MAC 
+       provides interface Init;
+       
+       provides interface MLME_START;
+       provides interface MLME_SET;
+    provides interface MLME_GET;
+       
+       provides interface MLME_ASSOCIATE;
+       provides interface MLME_DISASSOCIATE;
+       
+       provides interface MLME_BEACON_NOTIFY;
+       provides interface MLME_GTS;
+       
+       provides interface MLME_ORPHAN;
+       
+       provides interface MLME_SYNC;
+       provides interface MLME_SYNC_LOSS;
+               
+       provides interface MLME_RESET;
+       
+       provides interface MLME_SCAN;
+       
+       //MCPS
+       provides interface MCPS_DATA;
+       provides interface MCPS_PURGE;
+#endif
+               
+       
+       uses interface Timer<TMilli> as T_ackwait;      
+               
+       uses interface Timer<TMilli> as T_ResponseWaitTime;
+       
+       uses interface Timer<TMilli> as T_ScanDuration;
+       
+       uses interface Leds;
+       
+       uses interface SplitControl as AMControl;
+       
+       uses interface Random;
+       
+       uses interface GeneralIO as CCA;
+       
+       
+       //uses interface CC2420Config;
+       
+       uses interface AddressFilter;
+       
+       //uses interface Test_send;
+       
+       uses interface TimerAsync;
+       
+       uses interface PD_DATA;
+       
+       uses interface PLME_ED;
+       uses interface PLME_CCA;
+       uses interface PLME_SET;
+       uses interface PLME_GET;
+       uses interface PLME_SET_TRX_STATE;
+
+
+  
+}
+implementation {
+/*****************************************************/
+/*                             GENERAL                                  */
+/*****************************************************/  
+       /***************Variables*************************/
+       //local extended address
+       uint32_t aExtendedAddress0;
+       uint32_t aExtendedAddress1;
+
+       macPIB mac_PIB;
+
+//If the the MLME receives a start request the node becomes a pan coordinator
+       //and start transmiting beacons 
+       bool PANCoordinator = 0;
+       //(0 NO beacon transmission; 1 beacon transmission);
+       bool Beacon_enabled_PAN = 0;
+       
+       //(RESET) when the reset command arrives it checks whether or not to reset the PIB
+       bool SetDefaultPIB=0;
+       
+       //use security
+       bool SecurityEnable=0;
+       
+       //others
+       bool pending_reset=0;
+       
+       //transceiver status -every time the transceiver changes state this variable is updated
+       uint8_t trx_status;
+       
+       //defines the transmission
+       bool beacon_enabled=0;
+       
+       /***************Functions Definition***************/
+       
+       void init_MacPIB(); 
+       
+       uint8_t min(uint8_t val1, uint8_t val2);
+       
+       void init_MacCon();
+       
+       
+       task void signal_loss();
+       
+
+       void create_data_request_cmd();
+       void create_beacon_request_cmd();
+       void create_gts_request_cmd(uint8_t gts_characteristics);
+       
+       void build_ack(uint8_t sequence,uint8_t frame_pending);
+       
+       void create_data_frame(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions,uint8_t on_gts_slot,uint8_t pan);
+
+
+
+
+/*****************************************************/        
+/*                             Association                                      */
+/*****************************************************/ 
+       /***************Variables*************************/
+       uint8_t associating = 0;
+       uint8_t association_cmd_seq_num =0;
+       
+       /*association parameters*/
+       
+       uint8_t a_LogicalChannel;
+       uint8_t a_CoordAddrMode;
+       uint16_t a_CoordPANId;
+       uint32_t a_CoordAddress[2];
+       uint8_t a_CapabilityInformation;
+       bool a_securityenable;
+       
+       /***************Functions Definition***************/            
+       
+       void create_association_request_cmd(uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation);
+
+       error_t create_association_response_cmd(uint32_t DeviceAddress[],uint16_t shortaddress, uint8_t status);
+       
+       void create_disassociation_notification_cmd(uint32_t DeviceAddress[],uint8_t disassociation_reason);
+       
+       void process_dissassociation_notification(MPDU *pdu);
+
+/*****************************************************/
+/*                             Synchronization                                  */
+/*****************************************************/ 
+       /***************Variables*************************/
+       //(SYNC)the device will try to track the beacon ie enable its receiver just before the espected time of each beacon
+       bool TrackBeacon=0;
+       bool beacon_processed=0;
+       //beacon loss indication
+       uint8_t beacon_loss_reason;
+       
+       //(SYNC)the device will try to locate one beacon
+       bool findabeacon=0;
+       //(SYNC)number of beacons lost before sending a Beacon-Lost indication comparing to aMaxLostBeacons
+       uint8_t missed_beacons=0;
+       //boolean variable stating if the device is synchonized with the beacon or not
+       uint8_t on_sync=0;
+       
+       uint32_t parent_offset=0x00000000;
+
+
+/*****************************************************/
+/*                             GTS Variables                                    */
+/*****************************************************/  
+       /***************Variables*************************/
+       
+       uint8_t gts_request=0;
+       uint8_t gts_request_seq_num=0;
+       
+       bool gts_confirm;
+       
+       uint8_t GTS_specification;
+       bool GTSCapability=1;
+       
+       uint8_t final_CAP_slot=15;
+       
+       //GTS descriptor variables, coordinator usage only
+       GTSinfoEntryType GTS_db[7];
+       uint8_t GTS_descriptor_count=0;
+       uint8_t GTS_startslot=16;
+       uint8_t GTS_id=0x01;
+
+
+       //null gts descriptors
+       GTSinfoEntryType_null GTS_null_db[7];
+       
+       uint8_t GTS_null_descriptor_count=0;
+       //uint8_t GTS_null_id=0x01;
+       
+       //node GTS variables
+       // 1 GTS for transmit
+       uint8_t s_GTSss=0;           //send gts start slot
+       uint8_t s_GTS_length=0;          //send gts length
+       //1 GTS for receive
+       uint8_t r_GTSss=0;                       //receive gts start slot
+       uint8_t r_GTS_length=0;          //receive gts lenght
+       
+       //used to state that the device is on its transmit slot
+       uint8_t on_s_GTS=0;
+       //used to state that the device is on its receive slot
+       uint8_t on_r_GTS=0;
+       
+       //used to determine if the next time slot is used for transmission
+       uint8_t next_on_s_GTS=0;
+       //used to determine if the next time slot is used for reception
+       uint8_t next_on_r_GTS=0;
+       
+       //variable stating if the coordinator allow GTS allocations
+       uint8_t allow_gts=1;
+       
+       //COORDINATOR GTS BUFFER        
+       gts_slot_element gts_slot_list[7];
+       uint8_t available_gts_index[GTS_SEND_BUFFER_SIZE];
+       uint8_t available_gts_index_count;
+       
+       uint8_t coordinator_gts_send_pending_data=0;
+       uint8_t coordinator_gts_send_time_slot=0;
+       
+       //gts buffer used to store the gts messages both in COORDINATOR and NON COORDINATOR
+       norace MPDU gts_send_buffer[GTS_SEND_BUFFER_SIZE];
+       
+       //NON PAN COORDINATOR BUFFER
+       //buffering for sending
+       uint8_t gts_send_buffer_count=0;
+       uint8_t gts_send_buffer_msg_in=0;
+       uint8_t gts_send_buffer_msg_out=0;
+       uint8_t gts_send_pending_data=0;
+       
+
+       /***************Functions Definition***************/
+       
+       void process_gts_request(MPDU *pdu);    
+       void init_available_gts_index();
+       task void start_coordinator_gts_send();
+       
+       
+       //GTS FUNCTIONS
+       error_t remove_gts_entry(uint16_t DevAddressType);
+       error_t add_gts_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType);
+       error_t add_gts_null_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType);
+       
+       //increment the idle GTS for GTS deallocation purposes, not fully implemented yet
+       task void increment_gts_null();
+       
+       task void start_gts_send();
+       
+       
+       
+       //initialization functions
+       void init_gts_slot_list();
+       void init_GTS_null_db();
+       
+       void init_GTS_db();
+
+
+       uint32_t calculate_gts_expiration();
+       task void check_gts_expiration();
+
+
+/*****************************************************/
+/*                             CHANNEL SCAN Variables                           */
+/*****************************************************/ 
+       //current_channel
+       uint8_t current_channel=0;
+
+       /***************Variables*************************/
+       //ED-SCAN variables
+       
+       bool scanning_channels;
+       
+       uint32_t channels_to_scan;
+       uint8_t current_scanning=0;
+       //uint8_t scan_count=0;
+       uint8_t scanned_values[16];
+       uint8_t scan_type;
+       
+       SCAN_PANDescriptor scan_pans[16];
+       
+       uint16_t scan_duration;
+       
+       task void data_channel_scan_indication();
+       
+/*****************************************************/
+/*                             TIMER VARIABLES                                  */
+/*****************************************************/  
+       /***************Variables*************************/
+       uint32_t response_wait_time;
+       
+       //Beacon Interval
+       uint32_t BI;
+       //Superframe duration
+       uint32_t SD;
+       
+       //timer variables
+       uint32_t time_slot; //backoff boundary timer
+       uint32_t backoff;  //backoff timer
+       
+       //current number of backoffs in the active period
+       uint8_t number_backoff=1;
+       uint8_t number_time_slot=0;
+       
+       bool csma_slotted=0;
+/*****************************************************/
+/*                             CSMA VARIABLES                                   */
+/*****************************************************/        
+       /***************Variables*************************/     
+
+       //DEFERENCE CHANGE
+       uint8_t cca_deference = 0;
+       uint8_t backoff_deference = 0;
+       uint8_t check_csma_ca_backoff_send_conditions(uint32_t delay_backoffs);
+
+       //STEP 2
+       uint8_t delay_backoff_period;
+       bool csma_delay=0;
+       
+       bool csma_locate_backoff_boundary=0;
+       
+       bool csma_cca_backoff_boundary=0;
+       
+       //Although the receiver of the device is enabled during the channel assessment portion of this algorithm, the
+       //device shall discard any frames received during this time.
+       bool performing_csma_ca=0;
+       
+       //CSMA-CA variables
+       uint8_t BE; //backoff exponent
+       uint8_t CW; //contention window (number of backoffs to clear the channel)
+       uint8_t NB; //number of backoffs
+
+       /***************Functions Definition***************/    
+       
+       void init_csma_ca(bool slotted);
+       void perform_csma_ca();
+       task void perform_csma_ca_unslotted();
+       task void perform_csma_ca_slotted();
+       //task void start_csma_ca_slotted();
+       
+/*****************************************************/
+/*                             Indirect Transmission buffers            */
+/*****************************************************/
+       /***************Variables*************************/     
+       //indirect transmission buffer
+       norace indirect_transmission_element indirect_trans_queue[INDIRECT_BUFFER_SIZE];
+       //indirect transmission message counter
+       uint8_t indirect_trans_count=0;
+
+       /***************Functions Definition***************/    
+       
+       //function used to initialize the indirect transmission buffer
+       void init_indirect_trans_buffer();
+       //function used to search and send an existing indirect transmission message
+       void send_ind_trans_addr(uint32_t DeviceAddress[]);
+       //function used to remove an existing indirect transmission message
+       error_t remove_indirect_trans(uint8_t handler);
+       //function used to increment the transaction persistent time on each message
+       //if the transaction time expires the messages are discarded
+       void increment_indirect_trans();
+       
+/*****************************************************/
+/*                             RECEIVE buffers                           */
+/*****************************************************/  
+       /***************Variables*************************/
+       
+       //buffering variables
+       norace MPDU buffer_msg[RECEIVE_BUFFER_SIZE];
+       int current_msg_in=0;
+       int current_msg_out=0;
+       int buffer_count=0;
+
+       /***************Functions Definition***************/    
+       
+       task void data_indication();
+       
+       void indication_cmd(MPDU *pdu, int8_t ppduLinkQuality);
+       void indication_ack(MPDU *pdu, int8_t ppduLinkQuality);
+       void indication_data(MPDU *pdu, int8_t ppduLinkQuality);
+/*****************************************************/
+/*                             RECEPTION AND TRANSMISSION                                */
+/*****************************************************/  
+       
+       /***************Variables*************************/
+       
+       //buffering for sending
+       norace MPDUBuffer send_buffer[SEND_BUFFER_SIZE];
+       uint8_t send_buffer_count=0;
+       uint8_t send_buffer_msg_in=0;
+       uint8_t send_buffer_msg_out=0;
+       
+       //retransmission information
+       uint8_t send_ack_check;//ack requested in the transmitted frame
+       uint8_t retransmit_count;//retransmission count
+       uint8_t ack_sequence_number_check;//transmission sequence number
+       uint8_t send_retransmission;
+       uint8_t send_indirect_transmission;
+
+       uint8_t pending_request_data=0;
+       
+       uint8_t ackwait_period;
+       
+       uint8_t link_quality;
+       
+       norace ACK mac_ack;
+       ACK *mac_ack_ptr;
+       
+       uint32_t gts_expiration;
+
+       uint8_t I_AM_IN_CAP=0;
+       uint8_t I_AM_IN_CFP=0;
+       uint8_t I_AM_IN_IP=0;
+       
+       /***************Functions Definition***************/    
+       
+       task void send_frame_csma();
+       
+       uint8_t check_csma_ca_send_conditions(uint8_t frame_length,uint8_t frame_control1);
+
+       uint8_t check_gts_send_conditions(uint8_t frame_length);
+       
+       uint8_t calculate_ifs(uint8_t pk_length);
+
+
+
+/*****************************************************/
+/*                             BEACON MANAGEMENT                             */
+/*****************************************************/ 
+       /***************Variables*************************/
+       norace MPDU mac_beacon_txmpdu;
+       MPDU *mac_beacon_txmpdu_ptr;
+       
+       uint8_t *send_beacon_frame_ptr;
+       uint8_t send_beacon_length;
+
+       /***************Functions Definition***************/    
+       /*function to create the beacon*/
+       task void create_beacon();
+       /*function to process the beacon information*/
+       void process_beacon(MPDU *packet,uint8_t ppduLinkQuality);
+       
+
+/*****************************************************/
+/*      Fault tolerance functions            */
+/*****************************************************/ 
+//FAULT-TOLERANCE      
+       void create_coordinator_realignment_cmd(uint32_t device_extended0, uint32_t device_extended1, uint16_t device_short_address);
+
+       void create_orphan_notification();
+       
+       void process_coordinator_realignment(MPDU *pdu);
+
+       /*******************************************/
+       /*******BEACON SCHEDULING IMPLEMENTATION****/
+       /*******************************************/
+       
+       //bolean that checks if the device is in the parent active period
+       uint8_t I_AM_IN_PARENT_CAP = 0;
+       
+       
+       //upstream buffer
+       norace MPDUBuffer upstream_buffer[UPSTREAM_BUFFER_SIZE];
+       uint8_t upstream_buffer_count=0;
+       uint8_t upstream_buffer_msg_in=0;
+       uint8_t upstream_buffer_msg_out=0;
+
+       uint8_t sending_upstream_frame=0;
+       
+       task void send_frame_csma_upstream();
+
+/***************************DEBUG FUNCTIONS******************************/
+/* This function are list functions with the purpose of debug, to use then uncomment the declatarion
+on top of this file*/
+/*
+       void list_mac_pib();
+       
+       void list_gts();
+       
+       void list_my_gts();
+       void list_gts_null();
+       */
+       //list all the handles in the indirect transmission buffer, debug purposes
+       void list_indirect_trans_buffer();      
+                       
+/***************************END DEBUG FUNCTIONS******************************/
+
+
+/***************** Init Commands ****************/
+  command error_t Init.init() {
+  
+  call AMControl.start();
+
+
+       //initialization of the beacon structure
+       mac_beacon_txmpdu_ptr = &mac_beacon_txmpdu;
+
+
+
+   atomic{
+
+       //inicialize the mac PIB
+       init_MacPIB();
+       
+       init_GTS_db();
+       
+       init_GTS_null_db();
+       
+       init_gts_slot_list();
+       
+       init_available_gts_index();
+       
+       aExtendedAddress0=TOS_NODE_ID;
+       aExtendedAddress1=TOS_NODE_ID;
+       
+
+
+       call AddressFilter.set_address(mac_PIB.macShortAddress, aExtendedAddress0, aExtendedAddress1);
+
+       call AddressFilter.set_coord_address(mac_PIB.macCoordShortAddress, mac_PIB.macPANId);
+       
+
+                                                                                       
+       init_indirect_trans_buffer();
+
+
+       }
+       
+       //beacon
+       mac_beacon_txmpdu_ptr = &mac_beacon_txmpdu;
+               
+       //ack
+       mac_ack_ptr = &mac_ack;
+       
+       //Other timers, sync timers units expressed in miliseconds
+       ackwait_period = ((mac_PIB.macAckWaitDuration * 4.0 ) / 250.0) * 3;
+
+       response_wait_time = ((aResponseWaitTime * 4.0) / 250.0) * 2;
+
+       atomic{
+       
+               
+               BI = aBaseSuperframeDuration * powf(2,mac_PIB.macBeaconOrder);
+               SD = aBaseSuperframeDuration * powf(2,mac_PIB.macSuperframeOrder);
+               
+               
+               //backoff_period
+               backoff = aUnitBackoffPeriod;
+               //backoff_period_boundary
+               
+               time_slot = SD / NUMBER_TIME_SLOTS;
+                       
+               call TimerAsync.set_enable_backoffs(1); 
+               call TimerAsync.set_backoff_symbols(backoff);
+               
+               call TimerAsync.set_bi_sd(BI,SD);
+               
+               call TimerAsync.start();
+       }
+
+
+printfUART_init();
+
+    return SUCCESS;
+  }
+
+  event void AMControl.startDone(error_t err) {
+    if (err == SUCCESS) {
+       
+       call TimerAsync.start();
+               
+       }
+    else {
+      call AMControl.start();
+    }
+  }
+
+  event void AMControl.stopDone(error_t err) {
+  }
+
+
+/*****************************************************/
+/*                             TIMERS FIRED                                             */
+/*****************************************************/ 
+
+async event error_t TimerAsync.before_bi_fired()
+{
+       //printfUART("bbi %i\n",call TimerAsync.get_current_ticks());
+               
+       if (mac_PIB.macBeaconOrder != mac_PIB.macSuperframeOrder )
+       {
+               if ( Beacon_enabled_PAN == 1 )
+               {
+                       //
+                       //post set_trx();
+                       trx_status = PHY_TX_ON;
+                       call PLME_SET_TRX_STATE.request(PHY_TX_ON);
+               }
+               else
+               {
+                       //
+                       //post set_trx();
+                       trx_status = PHY_RX_ON;
+                       call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+               }
+       }
+       
+       //I_AM_IN_CAP = 1;
+       findabeacon = 1;
+               
+       return SUCCESS;
+}
+
+/*******************Timer BEACON INTERVAL******************/
+async event error_t TimerAsync.bi_fired()
+{
+       call Leds.led2On();
+       //call Test_send.send();
+       
+       I_AM_IN_CAP = 1;
+       I_AM_IN_IP = 0;
+       
+       //printfUART("bi\n","");
+       
+       
+       if ( Beacon_enabled_PAN == 1 )
+       {
+               //the beacon is send directly without CSMA/CA
+               call PD_DATA.request(send_beacon_length,send_beacon_frame_ptr);
+       }
+
+       number_backoff =0;
+       number_time_slot=0;
+       
+       
+       //CHECK there is the need to wait a small amount of time before checking if the beacon as been processed or not
+       //possible solition, if it receives a packet stand by for confirmation it its a beacon
+       //The device must always receive the beacon
+       if (TrackBeacon == 1) 
+       {
+               if (beacon_processed==1) 
+               {
+                       beacon_processed=0;
+               }
+               else
+               {
+                       //dealocate all GTS
+                       //beacon loss
+
+                       on_sync =0;
+                       beacon_loss_reason = MAC_BEACON_LOSS;
+                       
+                       //TODO
+                       //post signal_loss();
+               }
+       }
+       
+       post send_frame_csma();
+
+       return SUCCESS;
+}
+
+/*******************Timer SUPERFRAME DURATION******************/
+async event error_t TimerAsync.sd_fired()
+{
+       call Leds.led2Off();
+
+       //printfUART("sd\n","");
+
+       I_AM_IN_CFP = 0;
+       I_AM_IN_IP = 1;
+       
+       
+       number_backoff=0;
+       number_time_slot=0;
+       
+       
+       if (PANCoordinator == 0 && TYPE_DEVICE == ROUTER)
+       {
+               trx_status = PHY_RX_ON;
+       
+               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+       }
+       else
+       {
+               trx_status = PHY_RX_ON;
+               
+               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+               
+       }
+       
+       if (mac_PIB.macShortAddress==0xffff && TYPE_DEVICE == END_DEVICE)
+       {
+               trx_status = PHY_RX_ON;
+               
+               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+       }
+       
+       //trx_status = PHY_RX_ON;
+       //post set_trx();
+       /*
+               //turn the transceiver off
+       if (mac_PIB.macBeaconOrder != mac_PIB.macSuperframeOrder )
+       {
+               if ( mac_PIB.macRxOnWhenIdle == 0 && findabeacon == 0) 
+               {
+                       trx_status = PHY_TRX_OFF;
+                       post set_trx();
+               }
+               else
+               {
+                       trx_status = PHY_RX_ON;
+                       post set_trx();
+               }
+       }
+       //if the node is trying to synchronize
+               if (on_sync == 0 || mac_PIB.macPromiscuousMode == 1)
+       {
+               atomic{
+                       trx_status = PHY_RX_ON;
+                       post set_trx();
+               }
+       }
+       */
+       if (PANCoordinator == 1)
+       {
+               //increment the gts_null descriptors
+               atomic{
+                       
+                               //if (GTS_null_descriptor_count > 0) post increment_gts_null();
+                       
+                               //if (GTS_descriptor_count >0 ) post check_gts_expiration();
+                       
+                               //if (indirect_trans_count > 0) increment_indirect_trans();
+                               
+                               //creation of the beacon
+                               post create_beacon();
+               }
+               //trx_status = PHY_TRX_OFF;
+               //post set_trx();
+       }
+       else
+       {
+       //temporariamente aqui //aten��o quando for para o cluster-tree ï¿½ preciso mudar para fora
+       //e necessario destinguir ZC de ZR (que tem que manter a sync com o respectivo pai)
+       if (on_sync == 0)
+       {
+               //sync not ok
+               
+               //findabeacon=1;
+               if (missed_beacons == aMaxLostBeacons)
+               {
+               
+                       printfUART("sync_loss %i\n",missed_beacons);
+                       //out of sync
+                       post signal_loss();
+               }
+               //printfUART("out_sync %i\n",missed_beacons);
+               missed_beacons++;
+               call Leds.led1Off();
+               
+       }
+       else
+       {
+               //sync ok
+               missed_beacons=0;
+       
+               on_sync=0;
+       }
+       
+       }
+
+       //trx_status = PHY_TRX_OFF;
+       //call PLME_SET_TRX_STATE.request(PHY_TRX_OFF);
+
+       return SUCCESS;
+}
+
+/*******************Timer BEFORE TIME SLOT FIRED******************/
+async event error_t TimerAsync.before_time_slot_fired()
+{
+       on_s_GTS=0;
+       on_r_GTS=0;
+       
+       if (next_on_s_GTS == 1)
+       {       
+               on_s_GTS=1;
+               next_on_s_GTS =0;
+               trx_status = PHY_TX_ON;
+               call PLME_SET_TRX_STATE.request(PHY_TX_ON);
+               //post set_trx();
+       }
+       
+       if(next_on_r_GTS == 1)
+       {
+               on_r_GTS=1;
+               next_on_r_GTS=0;
+               trx_status = PHY_RX_ON;
+               call PLME_SET_TRX_STATE.request(PHY_RX_ON);
+               //post set_trx();
+       }
+
+return SUCCESS;
+}
+/*******************Timer TIME SLOT FIRED******************/
+async event error_t TimerAsync.time_slot_fired()
+{
+       //reset the backoff counter and increment the slot boundary
+       number_backoff=0;
+       number_time_slot++;
+               
+       //verify is there is data to send in the GTS, and try to send it
+       if(PANCoordinator == 1 && GTS_db[15-number_time_slot].direction == 1 && GTS_db[15-number_time_slot].gts_id != 0)
+       {
+               //COORDINATOR SEND DATA
+               //////////printfUART("bbck%i:%i:%i\n", (15-number_time_slot),GTS_db[15-number_time_slot].direction,gts_slot_list[15-number_time_slot].element_count);
+               
+               post start_coordinator_gts_send();
+                               
+       }
+       else
+       {
+               //DEVICE SEND DATA
+               if (number_time_slot == s_GTSss && gts_send_buffer_count > 0 && on_sync == 1)//(send_s_GTSss-send_s_GTS_len) 
+               {
+                               //current_time = call TimerAsync.get_total_tick_counter();
+                               post start_gts_send();
+               }               
+       }
+       
+       next_on_r_GTS =0;
+       next_on_s_GTS=0;
+       
+       
+       //printfUART("ts%i %i %i\n", number_time_slot,s_GTSss,r_GTSss);
+       
+       
+       //verification if the time slot is entering the CAP
+       //GTS FIELDS PROCESSING
+       
+       if ((number_time_slot + 1) >= final_CAP_slot && (number_time_slot + 1) < 16)
+       {
+               I_AM_IN_CAP = 0;
+               I_AM_IN_CFP = 1;
+               
+               //printfUART("bts %i\n",I_AM_IN_CAP, number_time_slot); 
+       
+       atomic{
+               
+               //verification of the next time slot
+               if(PANCoordinator == 1 && number_time_slot < 15)
+               {
+               //COORDINATOR verification of the next time slot
+                       if(GTS_db[14-number_time_slot].gts_id != 0x00 && GTS_db[14-number_time_slot].DevAddressType != 0x0000)
+                       {       
+                               if(GTS_db[14-number_time_slot].direction == 1 ) // device wants to receive
+                               {
+                                       next_on_s_GTS =1; //PAN coord mode
+                               }
+                               else
+                               {
+                                       next_on_r_GTS=1; //PAN coord mode
+                               }
+                       }       
+               }
+               else
+               {
+               //device verification of the next time slot
+                       if( (number_time_slot +1) == s_GTSss || (number_time_slot +1) == r_GTSss )
+                       {
+                               //printfUART("s_GTSss: %i r_GTSss: %i\n", s_GTSss,r_GTSss);
+                               if((number_time_slot + 1) == s_GTSss)
+                               {       
+                                       //printfUART("MY SEND SLOT \n", "");
+                                       next_on_s_GTS =1;
+                                       s_GTS_length --;
+                                       if (s_GTS_length != 0 )
+                                       {
+                                               s_GTSss++;
+                                       }
+                               }
+                               else                    
+                               {
+                                       ////////////printfUART("MY RECEIVE SLOT \n", "");
+                                       next_on_r_GTS =1;
+                                       r_GTS_length --;
+                                       if (r_GTS_length != 0 )
+                                       {
+                                               r_GTSss++;
+                                       }
+                               }                               
+                       }
+                       else
+                       {
+                               //idle
+                               next_on_s_GTS=0;
+                               next_on_r_GTS=0;
+                       }
+               }
+       }
+       }
+       
+return SUCCESS;
+}
+async event error_t TimerAsync.sfd_fired()
+{
+
+return SUCCESS;
+}
+
+/*******************Timer BACKOFF PERIOD******************/
+async event error_t TimerAsync.backoff_fired()
+{
+       //slotted CSMA/CA function
+       atomic{
+       
+               if( csma_locate_backoff_boundary == 1 )
+               {
+                       csma_locate_backoff_boundary=0;
+                       
+                       //post start_csma_ca_slotted();
+                       
+                       //DEFERENCE CHANGE
+                       if (backoff_deference == 0)
+                       {
+                               //normal situation
+                               delay_backoff_period = (call Random.rand16() & ((uint8_t)(powf(2,BE)) - 1));
+                               
+                               if (check_csma_ca_backoff_send_conditions((uint32_t) delay_backoff_period) == 1)
+                               {
+                                       backoff_deference = 1;
+                               }
+                               
+                       }
+                       else
+                       {
+                               backoff_deference = 0;
+                       }
+                       
+                       csma_delay=1;
+               }
+               
+               
+               
+               if( csma_cca_backoff_boundary == 1 )
+                       post perform_csma_ca_slotted();
+       }
+       //CSMA/CA
+       atomic{
+               if(csma_delay == 1 )
+               {
+                       if (delay_backoff_period == 0)
+                       {
+                               if(csma_slotted == 0)
+                               {
+                                       post perform_csma_ca_unslotted();
+                               }
+                               else
+                               {
+                                       //CSMA/CA SLOTTED
+                                       csma_delay=0;
+                                       csma_cca_backoff_boundary=1;
+                               }
+                       }
+                       delay_backoff_period--;
+               }
+       }
+       number_backoff++;
+return SUCCESS;
+}
+
+/*******************T_ackwait**************************/
+  event void T_ackwait.fired() {
+  
+  ////////printfUART("Tfd \n", "");
+       
+       //call Leds.redToggle();
+
+       if (send_ack_check == 1)
+       {
+               retransmit_count++;
+               
+               if (retransmit_count == aMaxFrameRetries || send_indirect_transmission > 0)
+               {
+                               //check the type of data being send
+                               /*
+                               if (associating == 1)
+                               {
+                                       printfUART("af ack\n", "");
+                                       associating=0;
+                                       signal MLME_ASSOCIATE.confirm(0x0000,MAC_NO_ACK);
+                               }
+                               */
+                               
+                       atomic{ 
+                               //////////printfUART("TRANSMISSION FAIL\n",""); 
+                               //stardard procedure, if fail discard the packet
+                               atomic send_buffer_count --;
+                               send_buffer_msg_out++;
+                       
+                                       //failsafe
+                                       if(send_buffer_count > SEND_BUFFER_SIZE)
+                                       {
+                                               
+                                               atomic send_buffer_count =0;
+                                               send_buffer_msg_out=0;
+                                               send_buffer_msg_in=0;
+                                               
+                                       }
+                                       
+                                       
+                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                               send_buffer_msg_out=0;
+                                       
+                                       if (send_buffer_count > 0)
+                                               post send_frame_csma();
+                                               
+                                       send_ack_check=0;
+                                       retransmit_count=0;
+                                       ack_sequence_number_check=0;
+                               
+                               }
+               }
+               
+               //////////printfUART("RETRY\n",""); 
+               //retransmissions
+               post send_frame_csma();
+       }
+    
+  }
+
+/*******************T_ResponseWaitTime**************************/
+  event void T_ResponseWaitTime.fired() {
+       //command response wait time
+       //////////printfUART("T_ResponseWaitTime.fired\n", "");
+
+       if (associating == 1)
+       {
+               printfUART("af rwt\n", "");
+               associating=0;
+               signal MLME_ASSOCIATE.confirm(0x0000,MAC_NO_DATA);
+               
+       }
+  
+  }
+
+/*******************TDBS Implementation Timers**************************/
+async event error_t TimerAsync.before_start_track_beacon_fired()
+{
+       I_AM_IN_PARENT_CAP = 1;
+
+return SUCCESS;
+}
+
+
+
+//track beacon events timers
+async event error_t TimerAsync.start_track_beacon_fired()
+{
+       I_AM_IN_PARENT_CAP = 1;
+
+       //printfUART("fi\n","");
+       
+       if (upstream_buffer_count > 0)
+               post send_frame_csma_upstream();
+
+
+
+return SUCCESS;
+}
+async event error_t TimerAsync.end_track_beacon_fired()
+{
+
+       I_AM_IN_PARENT_CAP = 0;
+       
+       //printfUART("unfi\n","");
+       //call Leds.greenOff();
+
+return SUCCESS;
+}
+
+
+
+
+
+/*****************************************************
+****************PD_DATA EVENTS***********************
+******************************************************/
+  async event error_t PD_DATA.confirm(uint8_t status) {
+
+
+    return SUCCESS;     
+  }
+/*****************************************************
+****************       PD_DATA     ********************
+******************************************************/ 
+
+async event error_t PD_DATA.indication(uint8_t psduLenght,uint8_t* psdu, int8_t ppduLinkQuality){
+/*
+MPDU *packet;
+
+uint8_t destination_address=0;
+
+dest_short *dest_short_ptr;
+dest_long *dest_long_ptr;
+       
+beacon_addr_short *beacon_addr_short_ptr;
+
+*/
+atomic{
+               //if(I_AM_IN_CAP == 1 || I_AM_IN_CFP == 1 || mac_PIB.macShortAddress==0xffff || scanning_channels ==1 || findabeacon == 1)
+               //{
+                       if (buffer_count > RECEIVE_BUFFER_SIZE)
+                       {
+                               //call Leds.redToggle();
+                               printfUART("full\n","");
+                       }
+                       else
+                       {
+               
+                               /*
+                               packet = (MPDU*)psdu;
+                                                       
+                               
+                               switch ((packet->frame_control1 & 0x7))
+                               {
+                                       case TYPE_BEACON:
+                                                                       beacon_addr_short_ptr = (beacon_addr_short *) &packet->data[0];
+                                                                       
+                                                                       //avoid VERIFY static assignment of coordinator parent
+                                                                       if (beacon_addr_short_ptr->source_address != mac_PIB.macCoordShortAddress)
+                                                                       {
+                                                                                       printfUART("pb %x %x\n", beacon_addr_short_ptr->source_address,mac_PIB.macCoordShortAddress);
+                                                                                       return SUCCESS;
+                                                                       }
+                                                                       
+                                                                       
+                                                                       
+                                                                       if ( mac_PIB.macShortAddress != 0xffff)
+                                                                       {
+                                                                               if ( beacon_addr_short_ptr->source_address != mac_PIB.macCoordShortAddress)
+                                                                               {
+                                                                                       printfUART("pb %x %x\n", beacon_addr_short_ptr->source_address,mac_PIB.macCoordShortAddress);
+                                                                                       return SUCCESS;
+                                                                               }
+                                                                       }
+                                       
+                                       break;
+                                       case TYPE_DATA:
+                                       case TYPE_CMD:
+                                                                       //VALIDATION OF DESTINATION ADDRESSES - NOT TO OVERLOAD THE PROCESSOR
+                                                                       destination_address=get_fc2_dest_addr(packet->frame_control2);
+                               
+                                                                       if (destination_address > 1)
+                                                                       {
+                                                                               switch(destination_address)
+                                                                               {
+                                                                                       case SHORT_ADDRESS: 
+                                                                                                                               dest_short_ptr = (dest_short *) &packet->data[0];
+                                                                                                                               
+                                                                                                                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
+                                                                                                                               {
+                                                                                                                                       printfUART("nsm %x %x\n", dest_short_ptr->destination_address,mac_PIB.macShortAddress); 
+                                                                                                                                       return SUCCESS;
+                                                                                                                               }
+                                                                                                                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                                                                                                                               //broadcast PAN identifier (0 x ffff).
+                                                                                                                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                                                                                                                               {
+                                                                                                                                       printfUART("wsP %x %x \n", dest_short_ptr->destination_PAN_identifier,mac_PIB.macPANId); 
+                                                                                                                                       return SUCCESS;
+                                                                                                                               }
+                                                                                                                               break;
+                                                                                       
+                                                                                       case LONG_ADDRESS: 
+                                                                                                                               dest_long_ptr = (dest_long *) &packet->data[0];
+                                                                                                                               
+                                                                                                                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
+                                                                                                                               {
+                                                                                                                                       printfUART("nlm %x %x \n",dest_long_ptr->destination_address0,dest_long_ptr->destination_address1); 
+                                                                                                                                       return SUCCESS;
+                                                                                                                               }
+                                                                                                                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                                                                                                                               //broadcast PAN identifier (0 x ffff).
+                                                                                                                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                                                                                                                               {
+                                                                                                                                       printfUART("wLP %x %x\n", dest_long_ptr->destination_PAN_identifier,mac_PIB.macPANId); 
+                                                                                                                                       return SUCCESS;
+                                                                                                                               }
+                                                                                                                               
+                                                                                                                               break;
+                                                                               }
+                                                                       }
+                                       
+
+                                       
+                                                                       break;
+                                       case TYPE_ACK:
+                               
+                                                                       break;
+                               }
+                                               
+                               */
+                               memcpy(&buffer_msg[current_msg_in],psdu,sizeof(MPDU));
+
+                               atomic{
+                                       current_msg_in++;
+                               
+                                       if ( current_msg_in == RECEIVE_BUFFER_SIZE ) 
+                                               current_msg_in = 0;
+               
+                                       buffer_count ++;
+                               }
+                               
+                               link_quality = ppduLinkQuality;
+                               
+                               if (scanning_channels ==1)
+                               {
+                                       //channel scan operation, accepts beacons only
+                                       post data_channel_scan_indication();
+                               
+                               }
+                               else
+                               {
+                               //normal operation
+                                       post data_indication();
+                               }
+                       }
+               //}
+               //else
+               //{
+               //      printfUART("drop\n","");
+               //}
+}
+return SUCCESS;
+}
+
+
+
+task void data_indication()
+{
+       //check all the conditions for a receiver packet
+    //pag 155
+       uint8_t link_qual;
+       
+       atomic link_qual = link_quality;
+
+       //printfUART("data_indication\n","");
+       ////////printfUART("buf  %i %i\n",buffer_count,indirect_trans_count);
+
+       //Although the receiver of the device is enabled during the channel assessment portion of this algorithm, the
+       //device shall discard any frames received during this time.
+       ////////////printfUART("performing_csma_ca: %i\n",performing_csma_ca);
+       if (performing_csma_ca == 1)
+       {       
+               ////////////printfUART("REJ CSMA\n","");
+               atomic{ 
+                       buffer_count--;
+               
+                       current_msg_out++;
+               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
+                       current_msg_out = 0;
+                       }
+               
+               return;
+    }
+       
+       //while performing channel scan disable the packet reception
+       if ( scanning_channels == 1)
+       {       
+               atomic{ 
+                       buffer_count--;
+       
+                       current_msg_out++;
+               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
+                       current_msg_out = 0;
+                       }
+               return;
+       }       
+atomic{
+
+    ////printfUART("data ind %x %x %i\n",buffer_msg[current_msg_out].frame_control1,buffer_msg[current_msg_out].frame_control2,(buffer_msg[current_msg_out].frame_control2 & 0x7));
+       
+       //check the frame type of the received packet
+       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
+       {
+               
+                       case TYPE_DATA: //printfUART("rd %i\n",buffer_msg[current_msg_out].seq_num);
+                                                       indication_data(&buffer_msg[current_msg_out],link_qual);
+                                                       break;
+                                                       
+                       case TYPE_ACK: //printfUART("ra\n","");
+                                                       //ack_received = 1;
+                                                       indication_ack(&buffer_msg[current_msg_out],link_qual);
+                                                       
+                                                       break;
+                                                       
+                       case TYPE_CMD:  //printfUART("rc\n","");
+                                                       indication_cmd(&buffer_msg[current_msg_out],link_qual);
+                                                       break;
+                       
+                       case TYPE_BEACON:
+                                                       
+                                                       //printfUART("rb %i\n",buffer_msg[current_msg_out].seq_num);
+                                                       if (mac_PIB.macShortAddress == 0x0000) 
+                                                       {
+                                                               buffer_count--;
+                                                       }
+                                                       else
+                                                       {
+                                                               process_beacon(&buffer_msg[current_msg_out],link_qual);
+                                                               
+                                                       }
+
+                                                       break;
+                       default: 
+                                               atomic buffer_count--;
+                                               ////printfUART("Invalid frame type\n","");
+
+                                               break;
+       }
+       atomic{
+                       current_msg_out++;
+               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
+                       current_msg_out = 0;
+               }
+       }
+       return;
+}
+
+
+
+/*****************************************************
+****************PLME_ED EVENTS***********************
+******************************************************/ 
+event error_t PLME_CCA.confirm(uint8_t status){
+return SUCCESS;
+}
+   
+   
+event error_t PLME_SET.confirm(uint8_t status, uint8_t PIBAttribute){   
+return SUCCESS;
+}
+async event error_t PLME_SET_TRX_STATE.confirm(uint8_t status){
+
+return SUCCESS;
+}    
+   
+event error_t PLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue){
+   
+return SUCCESS;
+}    
+
+event error_t PLME_ED.confirm(uint8_t status,int8_t EnergyLevel){
+
+return SUCCESS;
+}
+
+/*******************************************************************************************************/
+/*******************************************************************************************************/
+/*******************************************************************************************************/
+/****************************************PACKET PROCESSING FUNCTIONS************************************/
+/*******************************************************************************************************/
+/*******************************************************************************************************/
+/*******************************************************************************************************/
+
+void process_beacon(MPDU *packet,uint8_t ppduLinkQuality)
+{
+
+       /*
+       ORGANIZE THE PROCESS BEACON FUNCION AS FOLLOWS.
+       1- GET THE BEACON ORDER
+       2- GET THE SUPERFRAME ORDER
+       3- GET THE FINAL CAP SLOT
+       4 - COMPUTE SD, BI, TS, BACKOFF PERIOD IN MILLISECONDS
+       
+       4- SYNCHRONIZE THE NODE BY DOING THE FOLLOWING
+               - SET A TIMER IN MS FOR THE FINAL TIME SLOT (SUPERFRAME DURATION) : IT EXPRIES AFTER SD - TX TIME - PROCESS TIME
+               - SET A TIMER IN MS FOR THE GTS IF ANY EXIST IT EXPRIES AFTER GTS_NBR * TIME_SLOT - TX TIME - PROCESS TIME 
+       */
+       uint32_t SO_EXPONENT;
+       uint32_t BO_EXPONENT;
+       int i=0;
+       uint16_t gts_descriptor_addr;
+       uint8_t data_count;
+       
+       uint8_t gts_directions;
+       uint8_t gts_des_count;
+       
+       uint8_t gts_ss;
+       uint8_t gts_l;
+       uint8_t dir;
+       uint8_t dir_mask;
+
+       //end gts variables
+
+       //function that processes the received beacon
+       beacon_addr_short *beacon_ptr;
+       
+       PANDescriptor pan_descriptor;
+
+       // beacon_trans_delay = (((packet->length(bytes) * 8.0) / 250.00(bits/s) ) / 0.34(s) (timer_granularity) ) (symbols)
+
+       //pending frames
+       uint8_t short_addr_pending=0;
+       uint8_t long_addr_pending=0;
+
+       //used in the synchronization
+       //uint32_t process_tick_counter; //symbols
+       
+       //uint32_t becon_trans_delay; //symbols
+       //uint32_t start_reset_ct; //number of clock ticks since the start of the beacon interval
+       
+       //used in the track beacon
+       beacon_processed = 1;
+       missed_beacons=0;
+       
+       //initializing pointer to data structure
+       beacon_ptr = (beacon_addr_short*) (packet->data);
+       
+       
+               //decrement buffer count
+       atomic buffer_count --;
+       
+       //printfUART("Received Beacon\n","");
+       //printfUART("rb panid: %x %x \n",beacon_ptr->source_address,mac_PIB.macCoordShortAddress);
+       //////printfUART("My macPANID: %x\n",mac_PIB.macPANId);
+       printfUART("rb %x %x\n",beacon_ptr->source_address,mac_PIB.macCoordShortAddress);
+       if( beacon_ptr->source_address != mac_PIB.macCoordShortAddress)
+       {
+               printfUART("nmp \n","");
+               return;
+       }
+       //printfUART("bea %i\n",call TimerAsync.get_current_ticks());
+       
+       /**********************************************************************************/
+       /*                                      PROCESSING THE SUPERFRAME STRUCTURE                                                       */
+       /**********************************************************************************/
+       
+       if (PANCoordinator == 0)
+       {
+               mac_PIB.macBeaconOrder = get_beacon_order(beacon_ptr->superframe_specification);
+               mac_PIB.macSuperframeOrder = get_superframe_order(beacon_ptr->superframe_specification);
+               
+               //mac_PIB.macCoordShortAddress = beacon_ptr->source_address;
+               
+               //printfUART("BO,SO:%i %i\n",mac_PIB.macBeaconOrder,mac_PIB.macSuperframeOrder);
+               
+               //mac_PIB.macPANId = beacon_ptr->source_PAN_identifier;
+               
+               //beacon order check if it changed
+               if (mac_PIB.macSuperframeOrder == 0)
+               {
+                       SO_EXPONENT = 1;
+               }
+               else
+               {
+                       SO_EXPONENT = powf(2,mac_PIB.macSuperframeOrder);
+               }
+               
+               if ( mac_PIB.macBeaconOrder ==0)
+               {
+                       BO_EXPONENT =1;
+               }
+               else
+               {
+                               BO_EXPONENT = powf(2,mac_PIB.macBeaconOrder);
+               }
+               BI = aBaseSuperframeDuration * BO_EXPONENT; 
+               SD = aBaseSuperframeDuration * SO_EXPONENT; 
+               
+               //backoff_period
+               backoff = aUnitBackoffPeriod;
+               time_slot = SD / NUMBER_TIME_SLOTS;
+               
+               call TimerAsync.set_bi_sd(BI,SD);
+       }       
+               
+       /**********************************************************************************/
+       /*                                                      PROCESS GTS CHARACTERISTICS                                                       */
+       /**********************************************************************************/
+               allow_gts =1;
+       
+               //initializing the gts variables
+               s_GTSss=0;
+               s_GTS_length=0;
+               
+               r_GTSss=0;
+               r_GTS_length=0;
+               
+               /*
+               send_s_GTSss=0;  
+               send_r_GTSss=0; 
+               send_s_GTS_len=0;
+               send_r_GTS_len=0;
+               */
+               final_CAP_slot = 15;
+
+
+               gts_des_count = (packet->data[8] & 0x0f);
+               
+               data_count = 9;
+               
+               final_CAP_slot = 15 - gts_des_count;
+               
+               if (gts_des_count > 0 )
+               {
+               data_count = 10; //position of the current data count
+               //process descriptors
+               
+                       gts_directions = packet->data[9];
+                       
+                       //printfUART("gts_directions:%x\n",gts_directions);
+                       
+                       for(i=0; i< gts_des_count; i++)
+                       {       
+                               gts_descriptor_addr = (uint16_t) packet->data[data_count];
+                                       
+                               //printfUART("gts_des_addr:%x mac short:%x\n",gts_descriptor_addr,mac_PIB.macShortAddress);
+                               
+                               data_count = data_count+2;
+                               //check if it concerns me
+                               if (gts_descriptor_addr == mac_PIB.macShortAddress)
+                               {
+                                       //confirm the gts request
+                                       ////////////printfUART("packet->data[data_count]: %x\n",packet->data[data_count]);
+                                       //gts_ss = 15 - get_gts_descriptor_ss(packet->data[data_count]);
+                                       gts_ss = get_gts_descriptor_ss(packet->data[data_count]);
+                                       gts_l = get_gts_descriptor_len(packet->data[data_count]);
+
+                                       if ( i == 0 )
+                                       {
+                                               dir_mask=1;
+                                       }
+                                       else
+                                       {
+                                       
+                                                       dir_mask = powf(2,i);
+                                       }
+                                       ////////////printfUART("dir_mask: %x i: %x gts_directions: %x \n",dir_mask,i,gts_directions);
+                                       dir = ( gts_directions & dir_mask);
+                                       if (dir == 0)
+                                       {
+                                               s_GTSss=gts_ss;
+                                               s_GTS_length=gts_l;
+                                       }
+                                       else
+                                       {
+
+                                               r_GTSss=gts_ss;
+                                               r_GTS_length=gts_l;
+                                       }
+                                       
+                                       //printfUART("PB gts_ss: %i gts_l: %i dir: %i \n",gts_ss,gts_l,dir);
+                                       ////////////printfUART("PB send_s_GTSss: %i send_s_GTS_len: %i\n",send_s_GTSss,send_s_GTS_len);
+                                       
+                                       if ( gts_l == 0 )
+                                       {
+                                               allow_gts=0;
+                                       }
+
+                                       if (gts_confirm == 1 && gts_l != 0)
+                                       {
+                                               //signal ok
+                                               //printfUART("gts confirm \n","");
+                                               gts_confirm =0;
+                                               signal MLME_GTS.confirm(GTS_specification,MAC_SUCCESS);
+                                       }
+                                       else
+                                       {
+                                               //signal not ok
+                                               ////////////printfUART("gts not confirm \n","");
+                                               gts_confirm =0;
+                                               signal MLME_GTS.confirm(GTS_specification,MAC_DENIED);
+                                       }
+                                       
+                               }
+                               data_count++;   
+                       }
+               }
+       
+       /**********************************************************************************/
+       /*                                                      PROCESS PENDING ADDRESSES INFORMATION                             */
+       /**********************************************************************************/    
+               //this should pass to the network layer
+               
+               
+               short_addr_pending=get_number_short(packet->data[data_count]);
+               long_addr_pending=get_number_extended(packet->data[data_count]);
+               
+               //////////printfUART("ADD COUNT %i %i\n",short_addr_pending,long_addr_pending);
+               
+               data_count++;
+               
+               if(short_addr_pending > 0)
+               {
+                       for(i=0;i < short_addr_pending;i++)
+                       {
+                               //////////printfUART("PB %i %i\n",(uint16_t)packet->data[data_count],short_addr_pending);
+                               
+                               //if(packet->data[data_count] == (uint8_t)mac_PIB.macShortAddress && packet->data[data_count+1] == (uint8_t)(mac_PIB.macShortAddress >> 8) )
+                               if((uint16_t)packet->data[data_count] == mac_PIB.macShortAddress)
+                               {
+                                       
+                                       create_data_request_cmd();
+                               }
+                               data_count = data_count + 2;
+                       }
+               }
+               if(long_addr_pending > 0)
+               {
+                       for(i=0; i < long_addr_pending;i++)
+                       {
+                               if((uint32_t)packet->data[data_count] == aExtendedAddress0 && (uint32_t)packet->data[data_count + 4] == aExtendedAddress1)
+                               {
+                                       
+                                       data_count = data_count + 8;
+
+                               }
+                       
+                       }
+               }
+
+       /**********************************************************************************/
+       /*                              BUILD the PAN descriptor of the COORDINATOR                                               */
+       /**********************************************************************************/
+               
+               
+          //Beacon NOTIFICATION
+          //BUILD the PAN descriptor of the COORDINATOR
+               //assuming that the adress is short
+               pan_descriptor.CoordAddrMode = SHORT_ADDRESS;
+               pan_descriptor.CoordPANId = 0x0000;//beacon_ptr->source_PAN_identifier;
+               pan_descriptor.CoordAddress0=0x00000000;
+               pan_descriptor.CoordAddress1=mac_PIB.macCoordShortAddress;
+               pan_descriptor.LogicalChannel=current_channel;
+               //superframe specification field
+               pan_descriptor.SuperframeSpec = beacon_ptr->superframe_specification;
+               
+               pan_descriptor.GTSPermit=mac_PIB.macGTSPermit;
+               pan_descriptor.LinkQuality=0x00;
+               pan_descriptor.TimeStamp=0x000000;
+               pan_descriptor.SecurityUse=0;
+               pan_descriptor.ACLEntry=0x00;
+               pan_descriptor.SecurityFailure=0x00;
+          
+               //I_AM_IN_CAP = 1;
+          
+       /**********************************************************************************/
+       /*                                                              SYNCHRONIZING                                                                     */
+       /**********************************************************************************/
+
+       //processing time + beacon transmission delay
+       
+       //removed not used
+       //process_tick_counter = call TimerAsync.get_process_frame_tick_counter();
+       //removed not used      
+       //start_reset_ct = ((1000 * (packet->length * 8.0) / 250)) / 69.54;  //(process_tick_counter - receive_tick_counter);
+
+       if(PANCoordinator == 0)
+       {
+                       I_AM_IN_CAP = 1;
+                       I_AM_IN_IP = 0;
+                       
+                       //call Leds.yellowOn();
+                       call Leds.led2On();
+                       
+                       call Leds.led1On();
+                       
+                       if(findabeacon == 1)
+                       {
+                               //printfUART("findabeacon\n", "");
+                               call TimerAsync.set_timers_enable(1);
+                               findabeacon =0;
+                       }
+                       
+                       //#ifdef PLATFORM_MICAZ
+                       //number_time_slot = call TimerAsync.reset_start(start_reset_ct+process_tick_counter+52);// //SOBI=3 52 //SOBI=0 15
+                       //#else
+                       
+                       //call TimerAsync.reset();
+                       
+                       number_time_slot = call TimerAsync.reset_start(75);   //95 old val sem print
+                                       
+                       // +process_tick_counter+52 //SOBI=3 52 //SOBI=0 
+                       //#endif
+                       on_sync=1;
+                       
+                       printfUART("sE\n", "");
+       }
+       else
+       {
+               I_AM_IN_PARENT_CAP = 1;
+               
+               call TimerAsync.set_track_beacon(1);
+               
+               //#ifdef PLATFORM_MICAZ
+               //      call TimerAsync.set_track_beacon_start_ticks(parent_offset,0x00001E00,(start_reset_ct+process_tick_counter+18));
+               //#else
+                       call TimerAsync.set_track_beacon_start_ticks(parent_offset,0x00001E00,4);//(start_reset_ct)
+               //#endif
+               
+               printfUART("sP \n", "");
+       }
+       
+       call Leds.led1Toggle();
+       signal MLME_BEACON_NOTIFY.indication((uint8_t)packet->seq_num,pan_descriptor,0, 0, mac_PIB.macBeaconPayloadLenght, packet->data);
+               
+return;
+}
+
+
+void process_gts_request(MPDU *pdu)
+{
+               error_t status;
+               cmd_gts_request *mac_gts_request;
+               
+               mac_gts_request= (cmd_gts_request*) &pdu->data;
+               
+atomic{                
+               if ( get_characteristic_type(mac_gts_request->gts_characteristics) == 1)
+               {
+               //allocation
+       
+       //process the gts request
+               status = add_gts_entry(get_gts_length(mac_gts_request->gts_characteristics),get_gts_direction(mac_gts_request->gts_characteristics),mac_gts_request->source_address);
+               
+               }
+               else
+               {
+               //dealocation
+       
+               status = remove_gts_entry(mac_gts_request->source_address);
+               }
+               
+               signal MLME_GTS.indication(mac_gts_request->source_address, mac_gts_request->gts_characteristics, 0, 0);
+               
+               }
+
+return;
+}
+/****************DATA indication functions******************/
+
+void indication_data(MPDU *pdu, int8_t ppduLinkQuality)
+{
+       uint8_t data_len;
+       
+       uint8_t payload[80];
+       uint8_t msdu_length=0;
+       
+       //int i;
+       
+       uint32_t SrcAddr[2];
+       uint32_t DstAddr[2];
+       
+       
+       //frame control variables
+       uint8_t source_address=0;
+       uint8_t destination_address=0;
+
+
+       dest_short *dest_short_ptr;
+       dest_long *dest_long_ptr;
+       
+       source_short *source_short_ptr;
+       source_long *source_long_ptr;
+
+       //implement the intra PAN data messages
+       //intra_pan_source_short *intra_pan_source_short_ptr;
+       //intra_pan_source_long *intra_pan_source_long_ptr;
+       
+       
+       source_address=get_fc2_source_addr(pdu->frame_control2);
+       destination_address=get_fc2_dest_addr(pdu->frame_control2);
+       
+       //decrement buffer count
+       atomic buffer_count --;
+       
+       SrcAddr[0]=0x00000000;
+       SrcAddr[1]=0x00000000;
+       DstAddr[0]=0x00000000;
+       DstAddr[1]=0x00000000;
+
+
+       //printfUART("id %i %i \n",source_address,destination_address);
+
+
+       if ( get_fc1_intra_pan(pdu->frame_control1)== 0 )
+       {
+       //INTRA PAN
+               if (destination_address > 1 && source_address > 1)
+               {
+                       // Destination LONG - Source LONG       
+                       if (destination_address == LONG_ADDRESS && source_address == LONG_ADDRESS)
+                       {
+                               dest_long_ptr = (dest_long *) &pdu->data[0];
+                               source_long_ptr = (source_long *) &pdu->data[DEST_LONG_LEN];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
+                               {
+                                       //////////printfUART("data rejected, ext destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               data_len = 20;
+                               
+                               
+                               DstAddr[1] = dest_long_ptr->destination_address0;
+                               DstAddr[0] =dest_long_ptr->destination_address1;
+                               
+                               SrcAddr[1] =source_long_ptr->source_address0;
+                               SrcAddr[0] =source_long_ptr->source_address1;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+                               
+                       }
+                       
+                       // Destination SHORT - Source LONG
+                       if ( destination_address == SHORT_ADDRESS && source_address == LONG_ADDRESS )
+                       {
+                               dest_short_ptr = (dest_short *) &pdu->data[0];
+                               source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
+                               {
+                                       //////////printfUART("data rejected, short destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 14;
+                               
+                               DstAddr[0] =dest_short_ptr->destination_address;
+                               
+                               SrcAddr[1] =source_long_ptr->source_address0;
+                               SrcAddr[0] =source_long_ptr->source_address1;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+                       // Destination LONG - Source SHORT
+                       if ( destination_address == LONG_ADDRESS && source_address == SHORT_ADDRESS )
+                       {
+                               dest_long_ptr = (dest_long *) &pdu->data[0];
+                               source_short_ptr = (source_short *) &pdu->data[DEST_LONG_LEN];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
+                               {
+                                       //////////printfUART("data rejected, ext destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 14;
+                               
+                               DstAddr[1] = dest_long_ptr->destination_address0;
+                               DstAddr[0] =dest_long_ptr->destination_address1;
+                               
+                               
+                               SrcAddr[0] =source_short_ptr->source_address;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+                       
+                       
+                       //Destination SHORT - Source SHORT
+                       if ( destination_address == SHORT_ADDRESS && source_address == SHORT_ADDRESS )  
+                       {
+                               dest_short_ptr = (dest_short *) &pdu->data[0];
+                               source_short_ptr = (source_short *) &pdu->data[DEST_SHORT_LEN];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
+                               {
+                                       //printfUART("data rejected, short destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       //printfUART("SH SH data rejected, wrong destination PAN %x\n",mac_PIB.macPANId ); 
+                                       return;
+                               }
+                               
+                               data_len = 8;
+                               
+                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                               {
+                                       build_ack(pdu->seq_num,0);
+                               }
+                               
+                               DstAddr[0] =dest_short_ptr->destination_address;
+                               
+                               SrcAddr[0] =source_short_ptr->source_address;
+                               
+                               msdu_length = (pdu->length - 5) - data_len;
+                               
+                               
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                       
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length,payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+               }
+               
+               /*********NO DESTINATION ADDRESS PRESENT ****************/
+               
+               if ( destination_address == 0 && source_address > 1 )
+               {
+                               
+                       if (source_address == LONG_ADDRESS)
+                       {//Source LONG
+                               source_long_ptr = (source_long *) &pdu->data[0];
+                               
+                               //If only source addressing fields are included in a data or MAC command frame, the frame shall be
+                               //accepted only if the device is a PAN coordinator and the source PAN identifier matches macPANId.
+                               if ( PANCoordinator==0 || source_long_ptr->source_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       //////////printfUART("data rejected, im not pan\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 10;
+                               
+                               SrcAddr[1] =source_long_ptr->source_address0;
+                               SrcAddr[0] =source_long_ptr->source_address1;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address,(uint16_t)source_long_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, 0x0000, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+                       else
+                       {//Source SHORT
+
+                               source_short_ptr = (source_short *) &pdu->data[0];
+                               //If only source addressing fields are included in a data or MAC command frame, the frame shall be
+                               //accepted only if the device is a PAN coordinator and the source PAN identifier matches macPANId.
+                               if ( PANCoordinator==0 || source_short_ptr->source_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       //////////printfUART("data rejected, im not pan\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 4;
+
+                               
+                               SrcAddr[0] =source_short_ptr->source_address;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address, (uint16_t)source_short_ptr->source_PAN_identifier, SrcAddr,(uint16_t)destination_address, 0x0000, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+               }
+               /*********NO SOURCE ADDRESS PRESENT ****************/
+               
+               if ( destination_address > 1 && source_address == 0 )
+               {
+                       if (destination_address == LONG_ADDRESS)
+                       {//Destination LONG
+                               dest_long_ptr = (dest_long *) &pdu->data[0];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1 )
+                               {
+                                       //////////printfUART("data rejected, ext destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_long_ptr->destination_PAN_identifier != 0xffff && dest_long_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 10;
+                               
+                               DstAddr[1] = dest_long_ptr->destination_address0;
+                               DstAddr[0] =dest_long_ptr->destination_address1;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                       
+                               signal MCPS_DATA.indication((uint16_t)source_address,0x0000, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_long_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                       }
+                       else
+                       {//Destination SHORT
+                               dest_short_ptr = (dest_short *) &pdu->data[0];
+                               
+                               //If a short destination address is included in the frame, it shall match either macShortAddress or the
+                               //broadcast address (0 x ffff). Otherwise, if an extended destination address is included in the frame, it
+                               //shall match aExtendedAddress.
+                               if ( dest_short_ptr->destination_address != 0xffff && dest_short_ptr->destination_address != mac_PIB.macShortAddress)
+                               {
+                                       //////////printfUART("data rejected, short destination not for me\n", ""); 
+                                       return;
+                               }
+                               //If a destination PAN identifier is included in the frame, it shall match macPANId or shall be the
+                               //broadcast PAN identifier (0 x ffff).
+                               if(dest_short_ptr->destination_PAN_identifier != 0xffff && dest_short_ptr->destination_PAN_identifier != mac_PIB.macPANId )
+                               {
+                                       //////////printfUART("data rejected, wrong destination PAN\n", ""); 
+                                       return;
+                               }
+                               
+                               data_len = 4;
+                               
+                               DstAddr[0] =dest_short_ptr->destination_address;
+                               
+                               msdu_length = pdu->length - data_len;
+
+                               memcpy(&payload,&pdu->data[data_len],msdu_length * sizeof(uint8_t));
+                               
+                               
+                               signal MCPS_DATA.indication((uint16_t)source_address,0x0000, SrcAddr,(uint16_t)destination_address, (uint16_t)dest_short_ptr->destination_PAN_identifier, DstAddr, (uint16_t)msdu_length, payload, (uint16_t)ppduLinkQuality, 0x0000,0x0000);  
+
+                               data_len = 4;
+                       }
+               }
+               
+       }
+       else
+       {
+       //intra_pan == 1
+       
+       
+       
+       }
+       
+       
+return;
+}
+
+void indication_cmd(MPDU *pdu, int8_t ppduLinkQuality)
+{
+               uint8_t cmd_type;
+               //uint8_t pk_ptr;
+               uint8_t addressing_fields_length=0;
+               
+               uint32_t SrcAddr[2];
+               //uint32_t DstAddr[2];//NOT USED SO FAR
+               
+               //frame control variables
+               uint8_t source_address=0;
+               uint8_t destination_address=0;
+       
+               //NOT USED SO FAR
+               //dest_short *dest_short_ptr;
+               //dest_long *dest_long_ptr;
+               //NOT USED SO FAR
+               //source_short *source_short_ptr;
+               source_long *source_long_ptr;
+               
+               dest_short *dest_short_ptr;
+               dest_long *dest_long_ptr;
+               
+               //CHECK IMPLEMENT
+               //intra_pan_source_short *intra_pan_source_short_ptr; 
+               //intra_pan_source_long *intra_pan_source_long_ptr;
+               
+               destination_address=get_fc2_dest_addr(pdu->frame_control2);
+               source_address=get_fc2_source_addr(pdu->frame_control2);
+               
+               //decrement buffer count
+               atomic buffer_count --;
+               
+               switch(destination_address)
+               {
+                       case LONG_ADDRESS: addressing_fields_length = DEST_LONG_LEN;
+                                                               dest_long_ptr = (dest_long *) &pdu->data[0];
+                                                               if(dest_long_ptr->destination_address0 !=aExtendedAddress0 && dest_long_ptr->destination_address1 !=aExtendedAddress1)
+                                                               {
+                                                                       printfUART("NOT FOR ME","");
+                                                                       return;
+                                                               }
+                                                               
+                                                               break;
+                       case SHORT_ADDRESS: addressing_fields_length = DEST_SHORT_LEN;
+                                                               dest_short_ptr= (dest_short *) &pdu->data[0];
+                                                               //destination command not for me
+                                                               if (dest_short_ptr->destination_address != mac_PIB.macShortAddress && dest_short_ptr->destination_address !=0xffff)
+                                                               {
+                                                                       printfUART("NOT FOR ME","");
+                                                                       //////////printfUART("NOT FOR ME %x me %e\n", dest_short_ptr->destination_address,mac_PIB.macShortAddress); 
+                                                                       return;
+                                                               }
+                                                               break;
+               }
+               switch(source_address)
+               {
+                       case LONG_ADDRESS: addressing_fields_length = addressing_fields_length + SOURCE_LONG_LEN;
+                                                               break;
+                       case SHORT_ADDRESS: addressing_fields_length = addressing_fields_length + SOURCE_SHORT_LEN;
+                                                               break;
+               }
+
+               cmd_type = pdu->data[addressing_fields_length];
+               
+                               
+               switch(cmd_type)
+               {
+               
+               case CMD_ASSOCIATION_REQUEST:   
+                                                                       //check if association is allowed, if not discard the frame             
+                                                                       
+                                                                       //////printfUART("CMD_ASSOCIATION_REQUEST \n", "");
+                                                                       
+                                                                               
+                                                                                       if (mac_PIB.macAssociationPermit == 0 )
+                                                                                       {
+                                                                                               //////////printfUART("Association not alowed\n", "");
+                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                                               {
+                                                                                                       build_ack(pdu->seq_num,0);
+                                                                                               }
+                                                                                               return;
+                                                                                       }
+                                                                                       
+                                                                                       if ( PANCoordinator==0 )
+                                                                                       {
+                                                                                               //////////printfUART("i�m not a pan\n", ""); 
+                                                                                               return;
+                                                                                       }
+                                                                       atomic{
+                                                                                       source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
+                                                                                       
+                                                                                       SrcAddr[1] =source_long_ptr->source_address0;
+                                                                                       SrcAddr[0] =source_long_ptr->source_address1;
+                                                                                       
+                                                                                       
+                                                                                       signal MLME_ASSOCIATE.indication(SrcAddr, pdu->data[addressing_fields_length+1] , 0, 0);
+
+                                                                                       }
+                                                                                       
+                                                                                       if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                                       {
+                                                                                               build_ack(pdu->seq_num,1);
+                                                                                       }       
+
+                                                                                       
+                                                                       break;
+               
+               case CMD_ASSOCIATION_RESPONSE: atomic{
+                                                                                               printfUART("CMD_ASSOCIATION_RESPONSE\n", ""); 
+                                                                                               
+                                                                                               associating =0;
+                                                                                               call T_ResponseWaitTime.stop();
+                                                                                               
+                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                                               {
+                                                                                                       build_ack(pdu->seq_num,0);
+                                                                                               }
+                                                                                       
+                                                                                               signal MLME_ASSOCIATE.confirm((uint16_t)(pdu->data[addressing_fields_length+1] + (pdu->data[addressing_fields_length+2] << 8)), pdu->data[addressing_fields_length+3]);
+                                                                                               }
+                                                                               break;
+
+               case CMD_DISASSOCIATION_NOTIFICATION:   //////////printfUART("Received CMD_DISASSOCIATION_NOTIFICATION\n", ""); 
+                                                                                               
+                                                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                                               {
+                                                                                                       build_ack(pdu->seq_num,0);
+                                                                                               }
+                                                                                               
+                                                                                               process_dissassociation_notification(pdu);
+                                                                                               break;
+               case CMD_DATA_REQUEST: 
+                                                               //printfUART("CMD_DATA_REQUEST\n", ""); 
+                                                                       //////printfUART("DR\n", "");
+                                                                       if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                                       {
+                                                                               //TODO
+                                                                               //Problems with consecutive reception of messages
+                                                                               
+                                                                               build_ack(pdu->seq_num,0);
+                                                                       }
+                                                                       
+                                                                       //cmd_data_request_0_3_reception = (cmd_data_request_0_3 *) pdu->data;
+                                                                       
+                                                                       source_long_ptr = (source_long *) &pdu->data[0];
+                                                                                       
+                                                                       SrcAddr[1] =source_long_ptr->source_address0;
+                                                                       SrcAddr[0] =source_long_ptr->source_address1;
+                                                                       
+                                                                       send_ind_trans_addr(SrcAddr);
+
+                                                               break;
+               case CMD_PANID_CONFLICT:
+                                                               break;
+                                                               
+               case CMD_ORPHAN_NOTIFICATION:
+                                                                       //printfUART("CMD_ORPHAN_NOTIFICATION\n", ""); 
+                                                                       
+                                                                       source_long_ptr = (source_long *) &pdu->data[DEST_SHORT_LEN];
+                                                                                       
+                                                                       SrcAddr[1] =source_long_ptr->source_address0;
+                                                                       SrcAddr[0] =source_long_ptr->source_address1;
+                                                                       
+                                                                       signal MLME_ORPHAN.indication(SrcAddr, 0x00,0x00);
+                                                               
+               
+                                                               break;
+               case CMD_BEACON_REQUEST:
+                                                               break;
+               case CMD_COORDINATOR_REALIGNMENT:
+                                                                       printfUART("CMD_COORDINATOR_REALIGNMENT\n", ""); 
+                                                                       
+                                                                       process_coordinator_realignment(pdu);
+                                                                       
+                                                               break;
+               case CMD_GTS_REQUEST:   
+                                                               ////////////printfUART("Received CMD_GTS_REQUEST\n", ""); 
+                                                               if ( get_fc1_ack_request(pdu->frame_control1) == 1 ) 
+                                                               {
+                                                                       build_ack(pdu->seq_num,0);
+                                                               }
+                                                               process_gts_request(pdu);
+                                                               break;
+               default: break;
+
+               }
+
+return;
+}
+
+void indication_ack(MPDU *pdu, int8_t ppduLinkQuality)
+{
+       //decrement buffer count
+
+       atomic buffer_count --;
+
+       ////////////printfUART("ACK Received\n",""); 
+       
+       atomic{
+                       if (send_ack_check == 1 && ack_sequence_number_check == pdu->seq_num)
+                       {
+                               //transmission SUCCESS
+                               call T_ackwait.stop();
+                               
+                               send_buffer_count --;
+                               send_buffer_msg_out++;
+                               
+                               //failsafe
+                               if(send_buffer_count > SEND_BUFFER_SIZE)
+                               {
+                                       send_buffer_count =0;
+                                       send_buffer_msg_out=0;
+                                       send_buffer_msg_in=0;
+                               }
+                               
+                               if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                       send_buffer_msg_out=0;
+                               
+                               //received an ack for the association request
+                               if( associating == 1 && association_cmd_seq_num == pdu->seq_num )
+                               {
+                                       //////////printfUART("ASSOC ACK\n",""); 
+                                       call T_ResponseWaitTime.startOneShot(response_wait_time);
+                                       //call T_ResponseWaitTime.start(TIMER_ONE_SHOT, response_wait_time);
+                               }
+                               
+                               if (gts_request == 1 && gts_request_seq_num == pdu->seq_num)
+                               {
+                               
+                                       call T_ResponseWaitTime.startOneShot(response_wait_time);
+                                       //call T_ResponseWaitTime.start(TIMER_ONE_SHOT, response_wait_time);
+                               }
+                               
+                               //////////printfUART("TRANSMISSION SUCCESS\n",""); 
+
+                               if (send_indirect_transmission > 0 )
+                               {       //the message send was indirect
+                                       //remove the message from the indirect transmission queue
+                                       indirect_trans_queue[send_indirect_transmission-1].handler=0x00;
+                                       indirect_trans_count--;
+                                       //////////printfUART("SU id:%i ct:%i\n", send_indirect_transmission,indirect_trans_count);
+                               }
+                               
+                               send_ack_check=0;
+                               retransmit_count=0;
+                               ack_sequence_number_check=0;
+                               
+                               
+                               if (send_buffer_count > 0)
+                                       post send_frame_csma();
+                               
+                               
+                       }
+               }
+       
+                       //CHECK
+               if (get_fc1_frame_pending(pdu->frame_control1) == 1 && pending_request_data ==1)// && associating == 1
+               {               
+                               //////////printfUART("Frame_pending\n",""); 
+                               pending_request_data=0;
+                               create_data_request_cmd();
+               }
+               
+               //GTS mechanism, after the confirmation of the GTS request, must check if the beacon has the gts
+               /*
+               if (gts_ack == 1)
+               {
+                       gts_ack=0;
+                       gts_confirm=1;
+                       call T_ResponseWaitTime.stop();
+               
+               }
+       */
+               if(gts_send_pending_data==1)
+                       post start_gts_send();
+               
+               if(coordinator_gts_send_pending_data==1 && coordinator_gts_send_time_slot == number_time_slot)
+                       post start_coordinator_gts_send();
+       
+return;
+}
+
+
+void process_dissassociation_notification(MPDU *pdu)
+{
+atomic{
+               cmd_disassociation_notification *mac_disassociation_notification;
+               
+               //creation of a pointer to the disassociation notification structure
+               mac_disassociation_notification = (cmd_disassociation_notification*) pdu->data;                                                                 
+
+               signal MLME_DISASSOCIATE.indication(&mac_disassociation_notification->source_address0, mac_disassociation_notification->disassociation_reason, 0, 0);
+               }
+
+return;
+}
+
+
+
+
+void process_coordinator_realignment(MPDU *pdu)
+{
+
+atomic{
+       cmd_coord_realignment *cmd_realignment = 0;
+       
+       dest_long *dest_long_ptr=0;
+       source_short *source_short_ptr=0;
+
+       cmd_realignment = (cmd_coord_realignment*) &pdu->data[DEST_LONG_LEN + SOURCE_SHORT_LEN];
+       
+       //creation of a pointer the addressing structures
+       dest_long_ptr = (dest_long *) &pdu->data[0];
+       source_short_ptr = (source_short *) &pdu->data[DEST_LONG_LEN];
+               
+       mac_PIB.macCoordShortAddress = ((cmd_realignment->coordinator_short_address0 << 8) | cmd_realignment->coordinator_short_address0 );
+       mac_PIB.macShortAddress = cmd_realignment->short_address;
+       
+       
+       printfUART("PCR %i %i\n",mac_PIB.macCoordShortAddress,mac_PIB.macShortAddress); 
+       
+       }
+return;
+}
+
+
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/************************              BUILD FRAMES FUNCTIONS                          **********************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+
+
+task void create_beacon()
+{
+       int i=0;
+       uint8_t packet_length = 25;
+       int data_count=0;
+       int pending_data_index=0;
+       MPDU* pkt_ptr=0;
+       //pending frames
+       uint8_t short_addr_pending=0;
+       uint8_t long_addr_pending=0;
+               
+       uint8_t gts_directions=0x00;
+       
+       uint16_t frame_control;
+
+       
+       atomic{
+               
+               beacon_addr_short *mac_beacon_addr_short_ptr;
+               //mac_beacon_addr_short_ptr = (beacon_addr_short*) &mac_txmpdu.data[0];
+               mac_beacon_addr_short_ptr = (beacon_addr_short*) &mac_beacon_txmpdu.data[0];
+               //call PLME_SET_TRX_STATE.request(PHY_TX_ON);
+               
+               mac_beacon_txmpdu_ptr->length = 15;
+               
+               frame_control = set_frame_control(TYPE_BEACON,0,0,0,1,SHORT_ADDRESS,SHORT_ADDRESS);
+               
+               mac_beacon_txmpdu_ptr->frame_control1 = (uint8_t)( frame_control);
+               
+               mac_beacon_txmpdu_ptr->frame_control2 = (uint8_t)( frame_control >> 8);
+               
+               //mac_beacon_txmpdu_ptr->frame_control = set_frame_control(TYPE_BEACON,0,0,0,1,SHORT_ADDRESS,SHORT_ADDRESS);
+               mac_beacon_txmpdu_ptr->seq_num = mac_PIB.macBSN;
+               mac_PIB.macBSN++;
+               
+               
+               //relocation error
+               mac_beacon_addr_short_ptr->destination_PAN_identifier= mac_PIB.macPANId;
+               //relocation error
+               mac_beacon_addr_short_ptr->destination_address = 0xffff;
+               //relocation error
+               mac_beacon_addr_short_ptr->source_address = mac_PIB.macShortAddress;
+               if (mac_PIB.macShortAddress == 0x0000)
+               {       //the device is the PAN Coordinator
+                       mac_beacon_addr_short_ptr->superframe_specification = set_superframe_specification(mac_PIB.macBeaconOrder,(uint8_t)mac_PIB.macSuperframeOrder,final_CAP_slot,0,1,mac_PIB.macAssociationPermit);
+               }
+               else
+               {
+                       mac_beacon_addr_short_ptr->superframe_specification = set_superframe_specification(mac_PIB.macBeaconOrder,(uint8_t)mac_PIB.macSuperframeOrder,final_CAP_slot,0,1,mac_PIB.macAssociationPermit);
+               }
+               
+               mac_beacon_txmpdu_ptr->data[8] = set_gts_specification(GTS_descriptor_count,mac_PIB.macGTSPermit);
+               
+               mac_beacon_txmpdu_ptr->data[9] = set_pending_address_specification(short_addr_pending,long_addr_pending);
+               
+               data_count = 9;
+               packet_length = 15;
+               
+               
+               //BUILDING the GTS DESCRIPTORS
+               if( (GTS_descriptor_count + GTS_null_descriptor_count) > 0 )
+               {
+                       data_count++;
+                                       
+                       for(i=0; i< 7 ; i++)
+                       {
+                               if( GTS_db[i].gts_id != 0x00 && GTS_db[i].DevAddressType != 0x0000) 
+                               {
+                                       
+                                       mac_beacon_txmpdu_ptr->data[data_count] = GTS_db[i].DevAddressType;
+                                       ////////////printfUART("B gts %i\n", (GTS_db[i].DevAddressType >> 8 ) ); 
+                                       
+                                       data_count++;
+                                       mac_beacon_txmpdu_ptr->data[data_count] = (GTS_db[i].DevAddressType >> 8 );
+                                       ////////////printfUART("B gts %i\n",  GTS_db[i].DevAddressType ); 
+                                       
+                                       data_count++;
+                                       
+                                       mac_beacon_txmpdu_ptr->data[data_count] = set_gts_descriptor(15-i,GTS_db[i].length);
+                                       data_count++;
+                                       ////printfUART("B gts %i\n", set_gts_descriptor(GTS_db[i].starting_slot,GTS_db[i].length) ); 
+                                       
+                                       packet_length = packet_length + 3;
+                                       
+                                       if ( GTS_db[i].direction == 1 )
+                                       {
+                                               gts_directions = gts_directions | (1 << i); 
+                                       }
+                                       else
+                                       {
+                                               gts_directions = gts_directions | (0 << i); 
+                                       }
+                                       ////printfUART("dir %i\n", gts_directions); 
+                               }
+                       }
+                       mac_beacon_txmpdu_ptr->data[9] = gts_directions;
+                       //CHECK
+                       packet_length++;
+                       //BUILDING the NULL GTS DESCRIPTORS
+                       if ( GTS_null_descriptor_count > 0 )
+                       {
+                               for(i=0; i< 7 ; i++)
+                               {
+                                       if( GTS_null_db[i].DevAddressType != 0x0000) 
+                                       {
+                                               mac_beacon_txmpdu_ptr->data[data_count] = GTS_null_db[i].DevAddressType;
+                                               ////////////printfUART("B gts %i\n", (GTS_db[i].DevAddressType >> 8 ) ); 
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count] = (GTS_null_db[i].DevAddressType >> 8 );
+                                               ////////////printfUART("B gts %i\n",  GTS_db[i].DevAddressType ); 
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count] = 0x00;
+                                               data_count++;
+                                               ////////////printfUART("B gts %i\n", set_gts_descriptor(GTS_db[i].starting_slot,GTS_db[i].length) ); 
+                                               packet_length = packet_length +3;
+                                       }
+                               }
+                       }
+                       //resetting the GTS specification field
+                       mac_beacon_txmpdu_ptr->data[8] = set_gts_specification(GTS_descriptor_count + GTS_null_descriptor_count,mac_PIB.macGTSPermit);
+                       
+
+               }
+
+                       pending_data_index = data_count;
+                       data_count++;
+               //IMPLEMENT PENDING ADDRESSES
+               //temporary
+               //indirect_trans_count =0;
+               
+               if (indirect_trans_count > 0 )
+               {
+                               //IMPLEMENT THE PENDING ADDRESSES CONSTRUCTION
+
+                       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+                       {
+                               if (indirect_trans_queue[i].handler > 0x00)
+                               {
+                                       pkt_ptr = (MPDU *)&indirect_trans_queue[i].frame;
+                                       //ADD INDIRECT TRANSMISSION DESCRIPTOR
+                                       if(get_fc2_dest_addr(pkt_ptr->frame_control2) == SHORT_ADDRESS)
+                                       {
+                                               short_addr_pending++;
+                                               packet_length = packet_length + 2;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[2];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[3];
+                                               data_count++;
+                                       }
+                               }
+                       }
+                       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+                       {
+                               if (indirect_trans_queue[i].handler > 0x00)
+                               {
+                                       if(get_fc2_dest_addr(pkt_ptr->frame_control2) == LONG_ADDRESS)
+                                       {
+                                               long_addr_pending++;
+                                               packet_length = packet_length + 8;
+
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[0];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[1];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[2];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[3];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[4];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[5];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[6];
+                                               data_count++;
+                                               mac_beacon_txmpdu_ptr->data[data_count]=pkt_ptr->data[7];
+                                               data_count++;
+                                               
+                                       }
+                               }
+                       }
+                               
+               }
+               mac_beacon_txmpdu_ptr->data[pending_data_index] = set_pending_address_specification(short_addr_pending,long_addr_pending);
+               
+               /*
+               //adding the beacon payload
+               if (mac_PIB.macBeaconPayloadLenght > 0 )
+               {
+                       for (i=0;i < mac_PIB.macBeaconPayloadLenght;i++)
+                       {
+                               mac_beacon_txmpdu_ptr->data[data_count] = mac_PIB.macBeaconPayload[i];
+                               data_count++;
+                               packet_length++;
+                       }
+               
+               
+               }
+               */
+               mac_beacon_txmpdu_ptr->data[data_count] = 0x12;
+               data_count++;
+               packet_length++;
+               mac_beacon_txmpdu_ptr->data[data_count] = 0x34;
+               data_count++;
+               packet_length++;
+               
+               //short_addr_pending=0;
+               //long_addr_pending=0;
+               
+               mac_beacon_txmpdu_ptr->length = packet_length;
+               
+               send_beacon_length = packet_length;
+               
+               send_beacon_frame_ptr = (uint8_t*)mac_beacon_txmpdu_ptr;
+               }
+}
+
+
+void create_data_frame(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions,uint8_t on_gts_slot,uint8_t pan)
+{
+       
+       int i_indirect_trans=0;
+
+       dest_short *dest_short_ptr;
+       dest_long *dest_long_ptr;
+       
+       source_short *source_short_ptr;
+       source_long *source_long_ptr;
+
+       //intra_pan_source_short *intra_pan_source_short_ptr;
+       //intra_pan_source_long *intra_pan_source_long_ptr;
+       
+       //CHECK
+       uint8_t intra_pan=0;
+       uint8_t data_len=0;
+       
+       uint8_t current_gts_element_count=0;
+       
+       MPDU *frame_pkt=0;
+       
+       uint16_t frame_control;
+       
+       //printfUART("create df\n","");
+       
+       //decision of the buffer where to store de packet creation
+       if (on_gts_slot > 0 )
+       {
+       
+               if (PANCoordinator == 1)
+               {
+               //setting the coordinator gts frame pointer
+                       
+                       //get the number of frames in the gts_slot_list
+                       atomic current_gts_element_count = gts_slot_list[15-on_gts_slot].element_count;
+                       
+                       //////////printfUART("element count %i\n",gts_slot_list[15-on_gts_slot].element_count);
+                       
+                       if (current_gts_element_count  == GTS_SEND_BUFFER_SIZE || available_gts_index_count == 0)
+                       {
+                               //////////printfUART("FULL\n","");
+                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
+                               return;
+                       }
+                       else
+                       {
+                               frame_pkt = (MPDU *) &gts_send_buffer[available_gts_index[available_gts_index_count]];
+                       }
+                       
+               }
+               else
+               {
+               //setting the device gts frame pointer
+                       ////////////printfUART("start creation %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
+               
+                       if(gts_send_buffer_count == GTS_SEND_BUFFER_SIZE)
+                       {
+                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
+                               return;
+                       }
+                       if (gts_send_buffer_msg_in == GTS_SEND_BUFFER_SIZE)
+                               gts_send_buffer_msg_in=0;
+                       
+                               frame_pkt = (MPDU *) &gts_send_buffer[gts_send_buffer_msg_in];
+               
+               }
+       }
+       else
+       {
+       
+               if ( get_txoptions_indirect_transmission(TxOptions) == 1)
+               {
+                       
+                       //CREATE THE INDIRECT TRANSMISSION PACKET POINTER
+                       //check if the is enough space to store the indirect transaction
+                       if (indirect_trans_count == INDIRECT_BUFFER_SIZE)
+                       {
+                               signal MCPS_DATA.confirm(0x00, MAC_TRANSACTION_OVERFLOW);
+                               //////////printfUART("buffer full %i\n", indirect_trans_count);
+                               return;
+                       }
+                       
+                       for(i_indirect_trans=0;i_indirect_trans<INDIRECT_BUFFER_SIZE;i_indirect_trans++)
+                       {
+                               if (indirect_trans_queue[i_indirect_trans].handler == 0x00)
+                               {
+                                       frame_pkt = (MPDU *) &indirect_trans_queue[i_indirect_trans].frame;
+                                       break;
+                               }
+                       }
+                       
+                       
+               }
+               else
+               {
+                       //CREATE NORMAL TRANSMISSION PACKET POINTER
+                               ////printfUART("sb  %i\n", send_buffer_count);
+                       atomic{
+                       
+                       //TDBS Implementation
+                       if (get_txoptions_upstream_buffer(TxOptions) == 1)
+                       {
+                               ////printfUART("sel up\n", "");
+                               
+                               if (upstream_buffer_count > UPSTREAM_BUFFER_SIZE)
+                                       return;
+                               
+                               if(upstream_buffer_msg_in == UPSTREAM_BUFFER_SIZE)
+                                       upstream_buffer_msg_in=0;
+                               
+                               frame_pkt = (MPDU *) &upstream_buffer[upstream_buffer_msg_in];
+                               
+                       }
+                       else
+                       {
+
+                               ////printfUART("sb  %i\n", send_buffer_count);
+                       
+                               if ((send_buffer_count +1) > SEND_BUFFER_SIZE)  
+                                       return;
+                       
+                               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                                       send_buffer_msg_in=0;
+               
+                               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+                       }
+                       
+                       }
+                       
+
+               }
+       }
+       
+atomic{
+
+       if (intra_pan == 0 )
+       {
+       
+               if ( DstAddrMode > 1 && SrcAddrMode > 1 )
+               {
+                       // Destination LONG - Source LONG       
+                       if (DstAddrMode == LONG_ADDRESS && SrcAddrMode == LONG_ADDRESS)
+                       {
+                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+                               source_long_ptr = (source_long *) &frame_pkt->data[DEST_LONG_LEN];
+                               
+                               dest_long_ptr->destination_PAN_identifier=DestPANId;
+                               dest_long_ptr->destination_address0=DstAddr[1];
+                               dest_long_ptr->destination_address1=DstAddr[0];
+                               
+                               source_long_ptr->source_PAN_identifier=SrcPANId;
+                               source_long_ptr->source_address0=SrcAddr[1];
+                               source_long_ptr->source_address1=SrcAddr[0];
+                               
+                               data_len = 20;
+                       }
+                       
+                       // Destination SHORT - Source LONG
+                       if ( DstAddrMode == SHORT_ADDRESS && SrcAddrMode == LONG_ADDRESS )
+                       {
+                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+                               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
+                               
+                               dest_short_ptr->destination_PAN_identifier=DestPANId;
+                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
+                               
+                               source_long_ptr->source_PAN_identifier=SrcPANId;
+                               source_long_ptr->source_address0=SrcAddr[1];
+                               source_long_ptr->source_address1=SrcAddr[0];
+                               
+                               data_len = 14;
+                       }
+                       // Destination LONG - Source SHORT
+                       if ( DstAddrMode == LONG_ADDRESS && SrcAddrMode == SHORT_ADDRESS )
+                       {
+                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+                               source_short_ptr = (source_short *) &frame_pkt->data[DEST_LONG_LEN];
+                               
+                               dest_long_ptr->destination_PAN_identifier=DestPANId;
+                               dest_long_ptr->destination_address0=DstAddr[1];
+                               dest_long_ptr->destination_address1=DstAddr[0];
+                               
+                               source_short_ptr->source_PAN_identifier=SrcPANId;
+                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
+                               
+                               data_len = 14;
+                       }
+                       
+                       
+                       //Destination SHORT - Source SHORT
+                       if ( DstAddrMode == SHORT_ADDRESS && SrcAddrMode == SHORT_ADDRESS )     
+                       {
+                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+                               source_short_ptr = (source_short *) &frame_pkt->data[DEST_SHORT_LEN];
+                               
+                               dest_short_ptr->destination_PAN_identifier=DestPANId;
+                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
+                               
+                               source_short_ptr->source_PAN_identifier=SrcPANId;
+                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
+                               
+                               data_len = 8;
+                       }
+               }
+               
+               if ( DstAddrMode == 0 && SrcAddrMode > 1 )
+               {
+                               
+                       if (SrcAddrMode == LONG_ADDRESS)
+                       {//Source LONG
+                               source_long_ptr = (source_long *) &frame_pkt->data[0];
+                               
+                               source_long_ptr->source_PAN_identifier=SrcPANId;
+                               source_long_ptr->source_address0=SrcAddr[1];
+                               source_long_ptr->source_address1=SrcAddr[0];
+                               
+                               data_len = 10;
+                       }
+                       else
+                       {//Source SHORT
+
+                               source_short_ptr = (source_short *) &frame_pkt->data[0];
+                               
+                               source_short_ptr->source_PAN_identifier=SrcPANId;
+                               source_short_ptr->source_address=(uint16_t)SrcAddr[1];
+                               
+                               data_len = 4;
+                       }
+               }
+               
+               if ( DstAddrMode > 1 && SrcAddrMode == 0 )
+               {
+                       if (DstAddrMode == LONG_ADDRESS)
+                       {//Destination LONG
+                               dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+               
+                               dest_long_ptr->destination_PAN_identifier=DestPANId;
+                               dest_long_ptr->destination_address0=DstAddr[1];
+                               dest_long_ptr->destination_address1=DstAddr[0];
+
+                               data_len = 10;
+                       }
+                       else
+                       {//Destination SHORT
+                               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+
+                               dest_short_ptr->destination_PAN_identifier=DestPANId;
+                               dest_short_ptr->destination_address=(uint16_t)DstAddr[1];
+                               
+                               data_len = 4;
+                       }
+               }
+       }
+       else
+       {
+       //intra_pan == 1
+
+       }
+               
+               memcpy(&frame_pkt->data[data_len],&msdu[0],msduLength*sizeof(uint8_t));
+               
+               if(on_gts_slot > 0)
+               {
+                       //preparing a GTS transmission
+                       
+                       ////////////printfUART("GTS send slt: %i count %i %u\n",on_gts_slot,gts_slot_list[15-on_gts_slot].element_count,mac_PIB.macDSN);
+                       frame_pkt->length = data_len + msduLength + MPDU_HEADER_LEN;
+                       
+                       frame_control = set_frame_control(TYPE_DATA,0,0,1,intra_pan,DstAddrMode,SrcAddrMode);
+                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+                       
+                       frame_pkt->seq_num = mac_PIB.macDSN;
+                       mac_PIB.macDSN++;
+                                               
+                       //ADDING DATA TO THE GTS BUFFER
+                       atomic{
+                                       if (PANCoordinator == 1)
+                                       {
+                                               gts_slot_list[15-on_gts_slot].element_count ++;
+                                               gts_slot_list[15-on_gts_slot].gts_send_frame_index[gts_slot_list[15-on_gts_slot].element_in] = available_gts_index[available_gts_index_count];
+                                               //gts_slot_list[15-on_gts_slot].length = frame_pkt->length;
+                                               
+                                               gts_slot_list[15-on_gts_slot].element_in ++;
+                                               
+                                               if (gts_slot_list[15-on_gts_slot].element_in == GTS_SEND_BUFFER_SIZE)
+                                                       gts_slot_list[15-on_gts_slot].element_in=0;
+                                               
+                                               available_gts_index_count --;
+                                               
+                                               //current_gts_pending_frame++;
+                                       }
+                                       else
+                                       {
+                                               gts_send_buffer_count++;
+                                               gts_send_buffer_msg_in++;
+                                               ////////////printfUART("end c %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
+                                       }
+                       }
+               }
+               else
+               {
+                       //////////printfUART("CSMA send %i\n", get_txoptions_ack(TxOptions));
+                       frame_pkt->length = data_len + msduLength + MPDU_HEADER_LEN;
+                       //frame_pkt->frame_control = set_frame_control(TYPE_DATA,0,0,get_txoptions_ack(TxOptions),intra_pan,DstAddrMode,SrcAddrMode);
+                       
+                       frame_control = set_frame_control(TYPE_DATA,0,0,get_txoptions_ack(TxOptions),intra_pan,DstAddrMode,SrcAddrMode);
+                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+                       
+                       frame_pkt->seq_num = mac_PIB.macDSN;
+                       
+                       //////printfUART("sqn %i\n", mac_PIB.macDSN);
+                       
+                       mac_PIB.macDSN++;
+                       
+                       if ( get_txoptions_indirect_transmission(TxOptions) == 1)
+                       {
+                                       indirect_trans_queue[i_indirect_trans].handler = indirect_trans_count + 1;
+                                       indirect_trans_queue[i_indirect_trans].transaction_persistent_time = 0x0000;
+       
+                                       indirect_trans_count++;
+       
+                                       //////////printfUART("ADDED HDL: %i ADDR: %i\n",indirect_trans_count,DstAddr[1]); 
+                       }
+                       else
+                       {
+                               if (get_txoptions_upstream_buffer(TxOptions) == 1)
+                               {
+                                       upstream_buffer[upstream_buffer_msg_in].retransmission =0;
+                                       upstream_buffer[upstream_buffer_msg_in].indirect =0;
+                               
+                                       upstream_buffer_count++;
+                                       
+                                       upstream_buffer_msg_in++;
+                                       
+                                       //printfUART("up bc %i\n", upstream_buffer_count);
+                                       post send_frame_csma_upstream();
+                                       
+                               }
+                               else
+                               {
+                               
+                                       //enable retransmissions
+                                       send_buffer[send_buffer_msg_in].retransmission = 1;
+                                       send_buffer[send_buffer_msg_in].indirect = 0;
+                                       
+                                       send_buffer_count++;
+                                       
+                                       send_buffer_msg_in++;
+                                       
+                                       post send_frame_csma();
+                               }
+                                       
+                       }
+                       
+               }
+               
+       }
+return;
+}
+
+
+error_t create_association_response_cmd(uint32_t DeviceAddress[],uint16_t shortaddress, uint8_t status)
+{
+
+       cmd_association_response *mac_association_response;
+       dest_long *dest_long_ptr;
+       source_long *source_long_ptr;
+       
+       int i=0;
+       
+       MPDU *frame_pkt=0;
+       
+       uint16_t frame_control;
+       
+       //atomic{
+       /*
+                       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+       */
+       
+       //check if the is enough space to store the indirect transaction
+       if (indirect_trans_count == INDIRECT_BUFFER_SIZE)
+       {
+               printfUART("i full","");
+               return MAC_TRANSACTION_OVERFLOW;
+       }
+       
+       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+       {
+               if (indirect_trans_queue[i].handler == 0x00)
+               {
+                       //memcpy(&indirect_trans_queue[i].frame,frame_ptr,sizeof(MPDU));
+                       frame_pkt = (MPDU *) &indirect_trans_queue[i].frame;
+                       printfUART("found slot","");
+                       break;
+               }
+       }
+       
+       //creation of a pointer to the association response structure
+       dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+       source_long_ptr = (source_long *) &frame_pkt->data[DEST_LONG_LEN];
+       
+       mac_association_response = (cmd_association_response *) &frame_pkt->data[DEST_LONG_LEN + SOURCE_LONG_LEN];                                                                      
+       
+       frame_pkt->length = 29;
+       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
+       
+       frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
+       
+       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+       
+       frame_pkt->seq_num = mac_PIB.macDSN;
+       mac_PIB.macDSN++;
+       
+       dest_long_ptr->destination_PAN_identifier = mac_PIB.macPANId;
+
+       dest_long_ptr->destination_address0 = DeviceAddress[1];
+       dest_long_ptr->destination_address1 = DeviceAddress[0];
+       
+       source_long_ptr->source_PAN_identifier = mac_PIB.macPANId;
+       
+       source_long_ptr->source_address0 = aExtendedAddress0;
+       source_long_ptr->source_address1 = aExtendedAddress1;
+
+       mac_association_response->command_frame_identifier = CMD_ASSOCIATION_RESPONSE;
+       
+       //mac_association_response->short_address = shortaddress;
+       mac_association_response->short_address1 = (uint8_t)(shortaddress);
+       mac_association_response->short_address2 = (uint8_t)(shortaddress >> 8);
+
+
+       mac_association_response->association_status = status;
+/*
+
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+                       }       
+               post send_frame_csma();
+*/
+       printfUART("ASS RESP S: %i\n",shortaddress); 
+
+       indirect_trans_queue[i].handler = indirect_trans_count+1;
+
+       indirect_trans_queue[i].transaction_persistent_time = 0x0000;
+       
+       indirect_trans_count++;
+       
+       printfUART("IAD\n", "");
+
+return MAC_SUCCESS;
+}
+
+
+void create_association_request_cmd(uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation)
+{
+atomic{
+
+               cmd_association_request *cmd_association_request_ptr;
+               dest_short *dest_short_ptr;
+               source_long *source_long_ptr;
+       
+               MPDU *frame_pkt=0;
+               
+               uint16_t frame_control;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+               
+               //creation of a pointer to the association response structure
+               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
+               
+               cmd_association_request_ptr = (cmd_association_request *) &send_buffer[send_buffer_msg_in].data[DEST_SHORT_LEN + SOURCE_LONG_LEN];
+               
+               frame_pkt->length = 21;
+               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,SHORT_ADDRESS,LONG_ADDRESS);
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,1,0,SHORT_ADDRESS,LONG_ADDRESS);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               association_cmd_seq_num =  mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               dest_short_ptr->destination_PAN_identifier = CoordPANId; //mac_PIB.macPANId;
+               
+               if (CoordAddrMode == SHORT_ADDRESS )
+               {
+                       dest_short_ptr->destination_address = (uint16_t)(CoordAddress[1] & 0x000000ff) ;  //mac_PIB.macPANId;
+               }
+               else
+               {
+               //CHECK
+               
+               //implement the long address version
+               
+               }
+               
+               source_long_ptr->source_PAN_identifier = 0xffff;
+               
+               source_long_ptr->source_address0 = aExtendedAddress0;
+               source_long_ptr->source_address1 = aExtendedAddress1;
+               
+               cmd_association_request_ptr->command_frame_identifier = CMD_ASSOCIATION_REQUEST;
+               
+               cmd_association_request_ptr->capability_information = CapabilityInformation;
+
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               pending_request_data=1;
+               
+               ////printfUART("Association request %i %i \n", send_buffer_count,send_buffer_msg_in);
+               
+               
+               post send_frame_csma();
+
+       }
+return;
+}
+
+void create_data_request_cmd()
+{
+       //////////printfUART("create_data_request_cmd\n", ""); 
+
+atomic{
+               //dest_short *dest_short_ptr;
+               source_long *source_long_ptr;
+
+               
+               MPDU *frame_pkt;
+               
+               uint16_t frame_control;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+       
+       
+               source_long_ptr= (source_long *) &send_buffer[send_buffer_msg_in].data[0];
+       
+               //creation of a pointer to the association response structure
+               //dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+               source_long_ptr = (source_long *) &frame_pkt->data[0];
+       
+       
+               frame_pkt->length = 16;                                                 
+               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,LONG_ADDRESS);   //dest | source
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,LONG_ADDRESS);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               
+               source_long_ptr->source_PAN_identifier = mac_PIB.macPANId;
+               
+               source_long_ptr->source_address0 = aExtendedAddress0;//aExtendedAddress0;
+               source_long_ptr->source_address1 = aExtendedAddress1;
+               
+               //command_frame_identifier = CMD_DATA_REQUEST;
+               frame_pkt->data[SOURCE_LONG_LEN]=CMD_DATA_REQUEST;
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+                               
+               post send_frame_csma();
+               
+               
+               }
+return;
+}
+
+void create_beacon_request_cmd()
+{
+
+atomic{
+               cmd_beacon_request *mac_beacon_request;
+       
+               MPDU *frame_pkt;
+               
+               uint16_t frame_control;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+       
+               mac_beacon_request= (cmd_beacon_request*) &send_buffer[send_buffer_msg_in].data;
+       
+               frame_pkt->length = 10;                                                 
+               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);   //dest | source
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               mac_beacon_request->destination_PAN_identifier = 0xffff;
+               
+               mac_beacon_request->destination_address = 0xffff;
+       
+               mac_beacon_request->command_frame_identifier = CMD_BEACON_REQUEST;
+               
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               post send_frame_csma();
+
+               }
+
+return;
+}
+
+void create_orphan_notification()
+{
+
+       atomic{
+       
+               cmd_default *cmd_orphan_notification=0;
+               
+               dest_short *dest_short_ptr=0;
+               source_long *source_long_ptr=0;
+
+               MPDU *frame_pkt=0;
+                       
+               uint16_t frame_control=0;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+               
+               frame_pkt->length = 20;                                                 
+                               
+               cmd_orphan_notification = (cmd_default*) &send_buffer[send_buffer_msg_in].data[DEST_SHORT_LEN + SOURCE_LONG_LEN];
+               
+               //creation of a pointer the addressing structures
+               dest_short_ptr = (dest_short *) &frame_pkt->data[0];
+               source_long_ptr = (source_long *) &frame_pkt->data[DEST_SHORT_LEN];
+               
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,LONG_ADDRESS);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               
+               dest_short_ptr->destination_PAN_identifier = 0xffff; //mac_PIB.macPANId;
+               
+               dest_short_ptr->destination_address = 0xffff ;  //mac_PIB.macPANId;
+               
+               source_long_ptr->source_PAN_identifier = 0xffff;
+               
+               source_long_ptr->source_address0 = aExtendedAddress0;
+               source_long_ptr->source_address1 = aExtendedAddress1;
+                               
+               
+               cmd_orphan_notification->command_frame_identifier = CMD_ORPHAN_NOTIFICATION;
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               post send_frame_csma();
+       }
+
+return;
+}
+
+
+void create_coordinator_realignment_cmd(uint32_t device_extended0, uint32_t device_extended1, uint16_t device_short_address)
+{
+
+atomic{
+
+       cmd_coord_realignment *cmd_realignment =0;
+       
+       dest_long *dest_long_ptr=0;
+       source_short *source_short_ptr=0;
+       
+       MPDU *frame_pkt=0;
+       
+       uint16_t frame_control=0;
+       
+       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+               send_buffer_msg_in=0;
+
+       frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+       
+       frame_pkt->length = 27;                                                 
+       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,0,0,SHORT_ADDRESS,0);   //dest | source
+       
+       cmd_realignment = (cmd_coord_realignment*) &send_buffer[send_buffer_msg_in].data[DEST_LONG_LEN + SOURCE_SHORT_LEN];
+       
+       //creation of a pointer the addressing structures
+       dest_long_ptr = (dest_long *) &frame_pkt->data[0];
+       source_short_ptr = (source_short *) &frame_pkt->data[DEST_LONG_LEN];
+
+       
+       frame_control = set_frame_control(TYPE_CMD,0,0,0,0,LONG_ADDRESS,SHORT_ADDRESS);
+       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+       frame_pkt->seq_num = mac_PIB.macDSN;
+       
+       mac_PIB.macDSN++;
+       
+       dest_long_ptr->destination_PAN_identifier = 0xffff;
+       dest_long_ptr->destination_address0 = device_extended0;
+       dest_long_ptr->destination_address1 = device_extended1;
+       
+       source_short_ptr->source_PAN_identifier = mac_PIB.macPANId;
+       source_short_ptr->source_address = mac_PIB.macCoordShortAddress;
+       
+       
+       cmd_realignment->command_frame_identifier = CMD_COORDINATOR_REALIGNMENT;
+       
+       mac_PIB.macPANId = 0x1234;
+       
+       mac_PIB.macCoordShortAddress =0x0000;
+       
+       cmd_realignment->PAN_identifier0 = (mac_PIB.macPANId);
+       cmd_realignment->PAN_identifier1 = (mac_PIB.macPANId >> 8);
+
+       cmd_realignment->coordinator_short_address0 = (mac_PIB.macCoordShortAddress);
+       cmd_realignment->coordinator_short_address1 = (mac_PIB.macCoordShortAddress >> 8);
+       
+       cmd_realignment->logical_channel = LOGICAL_CHANNEL;
+       cmd_realignment->short_address = device_short_address;
+
+       
+       //increment the send buffer variables
+       send_buffer_count++;
+       send_buffer_msg_in++;
+       
+       post send_frame_csma();
+
+       }
+
+return;
+}
+
+
+void create_gts_request_cmd(uint8_t gts_characteristics)
+{
+atomic{
+               cmd_gts_request *mac_gts_request;
+               
+               MPDU *frame_pkt;
+               
+               uint16_t frame_control;
+               ////printfUART("create_gts_request_cmd\n", "");
+               
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+               
+               mac_gts_request= (cmd_gts_request*) &send_buffer[send_buffer_msg_in].data;
+
+               frame_pkt->length = 11;
+       
+               if ( get_characteristic_type(gts_characteristics) != 0 )
+               {   
+                       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);   //dest | source
+               
+                       frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS); 
+                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               }
+               else
+               {       
+                       //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);
+                       
+                       frame_control = set_frame_control(TYPE_CMD,0,0,1,1,0,SHORT_ADDRESS);
+                       frame_pkt->frame_control1 =(uint8_t)( frame_control);
+                       frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               }
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               gts_request_seq_num = frame_pkt->seq_num;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               //mac_gts_request->source_PAN_identifier = 0x0001;
+               mac_gts_request->source_PAN_identifier = mac_PIB.macPANId;
+               
+               mac_gts_request->source_address = mac_PIB.macShortAddress;
+       
+               mac_gts_request->command_frame_identifier = CMD_GTS_REQUEST;
+               
+               //mac_gts_request->gts_characteristics = set_gts_characteristics(2,1,1);
+               mac_gts_request->gts_characteristics =gts_characteristics;
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               post send_frame_csma();
+               
+               }
+
+return;
+}
+
+void create_disassociation_notification_cmd(uint32_t DeviceAddress[],uint8_t disassociation_reason)
+{
+
+       atomic{
+               cmd_disassociation_notification *mac_disassociation_notification;
+               MPDU *frame_pkt;
+               
+               uint16_t frame_control;
+               
+               if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                       send_buffer_msg_in=0;
+       
+               frame_pkt = (MPDU *) &send_buffer[send_buffer_msg_in];
+               
+               //creation of a pointer to the disassociation notification structure
+               mac_disassociation_notification = (cmd_disassociation_notification*) &send_buffer[send_buffer_msg_in].data;                                                             
+               
+               
+               frame_pkt->length = 27;
+               
+               //frame_pkt->frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
+               
+               frame_control = set_frame_control(TYPE_CMD,0,0,1,0,LONG_ADDRESS,LONG_ADDRESS);
+               frame_pkt->frame_control1 =(uint8_t)( frame_control);
+               frame_pkt->frame_control2 =(uint8_t)( frame_control >> 8);
+               
+               frame_pkt->seq_num = mac_PIB.macDSN;
+               
+               mac_PIB.macDSN++;
+               
+               //enable retransmissions
+               send_buffer[send_buffer_msg_in].retransmission =1;
+               send_buffer[send_buffer_msg_in].indirect = 0;
+               
+               mac_disassociation_notification->destination_PAN_identifier = mac_PIB.macPANId;
+
+               mac_disassociation_notification->destination_address0 = DeviceAddress[0];
+               mac_disassociation_notification->destination_address1 = DeviceAddress[1];
+       
+               mac_disassociation_notification->source_PAN_identifier = mac_PIB.macPANId;
+       
+               mac_disassociation_notification->source_address0 = aExtendedAddress0;
+               mac_disassociation_notification->source_address1 = aExtendedAddress1;
+       
+               mac_disassociation_notification->command_frame_identifier = CMD_DISASSOCIATION_NOTIFICATION;
+               
+               mac_disassociation_notification->disassociation_reason = disassociation_reason;
+               
+               //increment the send buffer variables
+               send_buffer_count++;
+               send_buffer_msg_in++;
+               
+               post send_frame_csma();
+
+       }
+return;
+}
+
+
+
+void build_ack(uint8_t sequence,uint8_t frame_pending)
+{
+       uint16_t frame_control;
+       atomic{
+                       mac_ack_ptr->length = ACK_LENGTH;
+                       //mac_ack_ptr->frame_control = set_frame_control(TYPE_ACK,0,frame_pending,0,0,0,0);
+                       
+                       frame_control = set_frame_control(TYPE_ACK,0,frame_pending,0,0,0,0);
+                       mac_ack_ptr->frame_control1 =(uint8_t)( frame_control);
+                       mac_ack_ptr->frame_control2 =(uint8_t)( frame_control >> 8);
+                       
+                       mac_ack_ptr->seq_num = sequence;
+                       
+                       call PD_DATA.request(mac_ack_ptr->length,(uint8_t*)mac_ack_ptr);
+       }
+}
+
+
+
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/************************              INTERFACES PROVIDED                     **********************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+
+/*********************************************************/
+/**************MLME_SCAN********************************/
+/*********************************************************/
+
+task void data_channel_scan_indication()
+{
+       uint8_t link_qual;
+       
+       beacon_addr_short *beacon_ptr;
+       
+       //printfUART("data_channel_scan_indication\n","");
+
+       atomic link_qual = link_quality;
+
+       atomic buffer_count--;
+
+       switch(scan_type)
+       {
+               case ED_SCAN: 
+                                               if (scanned_values[current_scanning-1] < link_qual)
+                                                               scanned_values[current_scanning-1] = link_qual;
+                                               break;
+               
+               case ACTIVE_SCAN:break;
+                                       
+               case PASSIVE_SCAN: 
+                                                       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
+                                                       {
+                                                               case TYPE_BEACON:
+                                                               ////////////printfUART("Received Beacon\n","");
+                                                               beacon_ptr = (beacon_addr_short*) (&buffer_msg[current_msg_out].data);
+
+                                                               //Beacon NOTIFICATION
+                                                               //BUILD the PAN descriptor of the COORDINATOR
+                                                               //assuming that the adress is short
+                                                               scan_pans[current_scanning-1].CoordPANId = beacon_ptr->destination_PAN_identifier;
+                                                               scan_pans[current_scanning-1].CoordAddress=beacon_ptr->source_address;
+                                                               scan_pans[current_scanning-1].LogicalChannel=current_channel;
+                                                               //superframe specification field
+                                                               scan_pans[current_scanning-1].SuperframeSpec = beacon_ptr->superframe_specification;
+                                                               
+                                                               if (scan_pans[current_scanning-1].lqi < link_qual)
+                                                               scan_pans[current_scanning-1].lqi = link_qual;
+                                                       
+                                                               break;
+                                                               
+                                                               default: break;
+                                                       //atomic buffer_count--;
+                                                       ////////////printfUART("Invalid frame type\n","");
+
+                                                       }
+                                                       break;
+               case ORPHAN_SCAN: 
+                                                       //printfUART("osrm\n","");
+                                                       switch( (buffer_msg[current_msg_out].frame_control1 & 0x7) )
+                                                       {
+                                                               case TYPE_CMD:
+                                                                               //printfUART("received cmd\n","");
+                                                                               if (buffer_msg[current_msg_out].data[SOURCE_SHORT_LEN+ DEST_LONG_LEN] == CMD_COORDINATOR_REALIGNMENT)
+                                                                               {       
+                                                                                       printfUART("pf\n","");
+                                                                                       atomic scanning_channels = 0;
+                                                                                       call T_ScanDuration.stop();
+                                                                                       process_coordinator_realignment(&buffer_msg[current_msg_out]);
+                                                                                       
+                                                                               }
+                                                                               
+                                                                               break;
+                                                       default: break;
+                                                       }
+                                                       break;
+               
+       }
+       
+       atomic{
+                       current_msg_out++;
+               if ( current_msg_out == RECEIVE_BUFFER_SIZE )   
+                       current_msg_out = 0;
+               }
+return;
+}
+/*******************T_ScanDuration**************************/
+event void T_ScanDuration.fired() {
+
+       current_scanning++;
+       
+       printfUART("cs%i c%i\n",current_scanning,(0x0A + current_scanning));
+                                               
+       call PLME_SET.request(PHYCURRENTCHANNEL, (0x0A + current_scanning));
+
+       current_channel = (0x0A + current_scanning);
+       
+
+       if (current_scanning == 16 )
+       {
+               //printfUART("scan end\n","");
+               
+               atomic scanning_channels = 0;
+               
+               switch(scan_type)
+               {
+                       case ED_SCAN: 
+                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , scanned_values,0x00);
+                                                       break;
+                       
+                       case ACTIVE_SCAN:break;
+
+                       case PASSIVE_SCAN: 
+                                                       //event result_t confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[]);
+                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , 0x00, scan_pans);
+                                                       break;
+                       
+                       case ORPHAN_SCAN: 
+                                                       //orphan scan
+                                                       //send opphan command on every channel directed to the current PAN coordinator
+                                                       printfUART("oph s end not found\n","");
+                                                       signal MLME_SCAN.confirm(MAC_SUCCESS,scan_type, 0x00, 16 , 0x00, scan_pans);
+                                                       
+                                                       break;
+               }
+       }
+       else
+       {
+               switch(scan_type)
+               {
+                       case ORPHAN_SCAN:       printfUART("con\n","");
+                                                               create_orphan_notification();
+                                                               break;
+               }
+               
+               call T_ScanDuration.startOneShot(scan_duration);
+       }
+  
+}
+
+
+
+command error_t MLME_SCAN.request(uint8_t ScanType, uint32_t ScanChannels, uint8_t ScanDuration)
+{
+//pag 93
+       printfUART("MLME_SCAN.request\n", ""); 
+               
+       atomic scanning_channels = 1;
+       scan_type = ScanType;
+       channels_to_scan = ScanChannels;
+       
+       atomic current_scanning=0;
+       
+       
+       switch(ScanType)
+       {
+               //ED SCAN only FFD                      
+               case ED_SCAN:   
+                                       call TimerAsync.set_timers_enable(0x00);
+                                       /*
+                               
+                                       scanning_channels = 1;
+                                       scan_type = ScanType;
+                                       current_scanning=0;
+                                       scan_count=0;
+                                       channels_to_scan = ScanChannels;
+                                       scan_duration = ((aBaseSuperframeDuration * pow(2,ScanDuration)) * 4.0) / 250.0;
+                                       
+                                       //////////printfUART("channels_to_scan %y scan_duration %y\n", channels_to_scan,scan_duration); 
+                                       
+                                       call T_ed_scan.start(TIMER_REPEAT,1);
+                                       
+                                       call T_scan_duration.start(TIMER_ONE_SHOT,scan_duration);       
+                                       */
+                                       
+                                       
+                                       //calculate the scan_duration in miliseconds
+                                       //#ifdef PLATFORM_MICAZ
+                                               scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
+                                       //#else
+                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
+                                       //#endif
+                       //scan_duration = 2000;
+                                       
+                                       call T_ScanDuration.startOneShot(scan_duration);
+                                       
+                                       //printfUART("channels_to_scan %y scan_duration %y\n", channels_to_scan,scan_duration); 
+                                       break;
+               //active scan only FFD
+               case ACTIVE_SCAN:
+                                       call TimerAsync.set_timers_enable(0x00);
+                                       break;
+               //passive scan
+               case PASSIVE_SCAN:      
+                                       call TimerAsync.set_timers_enable(0x00);
+                                                       
+                                       //calculate the scan_duration in miliseconds
+                                       //#ifdef PLATFORM_MICAZ
+                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
+                                       //#else
+                                       //      scan_duration = ((aBaseSuperframeDuration * (powf(2,ScanDuration)+1)) * EFFECTIVE_SYMBOL_VALUE) / 1000.0;
+                                       //#endif
+                                       
+                                       
+                                       //defines the time (miliseconds) that the device listen in each channel
+                                       scan_duration = 2000;
+                                       
+                                       printfUART("channels_to_scan %y scan_duration %i\n", channels_to_scan,scan_duration); 
+                                       
+                                       call T_ScanDuration.startOneShot(scan_duration);
+                                       
+                                       //printfUART("channels_to_scan %y scan_duration %i\n", channels_to_scan,scan_duration); 
+                                       
+                                       //atomic trx_status = PHY_RX_ON;
+                                       //call PLME_SET_TRX_STATE.request(PHY_RX_ON); 
+               
+               
+               
+                                       break;
+               //orphan scan
+               case ORPHAN_SCAN:
+               
+                                       call TimerAsync.set_timers_enable(0x01);
+                                       
+                                   scan_duration = 4000;
+                                       
+                                       printfUART("orphan cts %y sdur %i\n", channels_to_scan,scan_duration); 
+                                       
+                                       call T_ScanDuration.startOneShot(scan_duration);
+
+                                       break;
+       
+               default:
+                                       break;
+       }
+
+return SUCCESS;
+}
+
+
+
+/*********************************************************/
+/**************MLME_ORPHAN********************************/
+/*********************************************************/
+
+command error_t MLME_ORPHAN.response(uint32_t OrphanAddress[1],uint16_t ShortAddress,uint8_t AssociatedMember, uint8_t security_enabled)
+{
+
+       if (AssociatedMember==0x01)
+       {
+               create_coordinator_realignment_cmd(OrphanAddress[0], OrphanAddress[1], ShortAddress);
+       }
+       
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_SYNC********************************/
+/*********************************************************/
+
+
+command error_t MLME_SYNC.request(uint8_t logical_channel,uint8_t track_beacon)
+{
+       call PLME_SET.request(PHYCURRENTCHANNEL,logical_channel);       
+       
+       call TimerAsync.set_timers_enable(0x01);
+       
+       printfUART("sync req\n", ""); 
+       
+       atomic findabeacon = 1;
+
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_RESET********************************/
+/*********************************************************/
+
+
+command error_t MLME_RESET.request(uint8_t set_default_PIB)
+{
+printfUART("MLME_RESET.request\n", "");
+
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_GTS***********************************/
+/*********************************************************/
+
+command error_t MLME_GTS.request(uint8_t GTSCharacteristics, bool security_enable)
+{
+
+       //uint32_t wait_time;
+       //if there is no short address asigned the node cannot send a GTS request
+       if (mac_PIB.macShortAddress == 0xffff)
+                       signal MLME_GTS.confirm(GTSCharacteristics,MAC_NO_SHORT_ADDRESS);
+       
+       //gts_ack=1;
+       
+       gts_request =1;
+       
+       create_gts_request_cmd(GTSCharacteristics);
+
+return SUCCESS;
+}
+
+
+/*********************************************************/
+/**************MLME_START*********************************/
+/*********************************************************/
+
+command error_t MLME_START.request(uint32_t PANId, uint8_t LogicalChannel, uint8_t beacon_order, uint8_t superframe_order,bool pan_coodinator,bool BatteryLifeExtension,bool CoordRealignment,bool securityenable,uint32_t StartTime)
+{
+
+       uint32_t BO_EXPONENT;
+       uint32_t SO_EXPONENT;
+
+       printfUART("MLME_START.request\n", "");
+       //pag 102
+       atomic {
+       PANCoordinator=1;
+       Beacon_enabled_PAN=1;
+       //TEST
+       //atomic mac_PIB.macShortAddress = 0x0000;
+
+
+               if ( mac_PIB.macShortAddress == 0xffff)
+               {
+               
+                       signal MLME_START.confirm(MAC_NO_SHORT_ADDRESS);
+                       return SUCCESS;
+               }
+               else
+               {
+                       atomic mac_PIB.macBeaconOrder = beacon_order;
+                       
+                       if (beacon_order == 15) 
+                               atomic mac_PIB.macSuperframeOrder = 15;
+                       else
+                               atomic mac_PIB.macSuperframeOrder = superframe_order;
+               
+               
+                       //PANCoordinator is set to TRUE
+                       if (pan_coodinator == 1)
+                       {
+                               atomic mac_PIB.macPANId = PANId;
+                               call PLME_SET.request(PHYCURRENTCHANNEL,LogicalChannel);
+                       }
+                       if (CoordRealignment == 1)
+                       {
+                               //generates and broadcasts a coordinator realignment command containing the new PANId and LogicalChannels
+                       }
+                       if (securityenable == 1)
+                       {
+                       //security parameters
+                       }
+               }
+       
+               if (mac_PIB.macSuperframeOrder == 0)
+                       SO_EXPONENT = 1;
+               else
+               {
+                       SO_EXPONENT = powf(2,mac_PIB.macSuperframeOrder);
+               
+               }
+               if ( mac_PIB.macBeaconOrder == 0)
+                       BO_EXPONENT = 1;
+               else
+               {
+                       BO_EXPONENT = powf(2,mac_PIB.macBeaconOrder);
+               
+               }       
+       }
+       
+       BI = aBaseSuperframeDuration * BO_EXPONENT; 
+               
+       SD = aBaseSuperframeDuration * SO_EXPONENT; 
+       //backoff_period
+       backoff = aUnitBackoffPeriod;
+
+       
+       atomic time_slot = SD / NUMBER_TIME_SLOTS;
+
+       call TimerAsync.set_backoff_symbols(backoff);
+
+       call TimerAsync.set_bi_sd(BI,SD);
+       
+       atomic{
+       
+               call TimerAsync.set_timers_enable(0x01);
+               
+               call TimerAsync.reset();
+               
+       }
+       
+       ////////////////////////////////////////////////////
+       /////////////////TDBS IMPLEMENTATION////////////////
+       ////////////////////////////////////////////////////
+       if(TYPE_DEVICE == ROUTER)
+       {
+               atomic parent_offset = StartTime;
+       
+               call TimerAsync.set_track_beacon(1);
+               //initialization of the timer that shedules the beacon transmission offset
+               call TimerAsync.set_track_beacon_start_ticks(StartTime,0x00001E00,0x00000000);
+       }
+       else
+       {
+               atomic I_AM_IN_PARENT_CAP = 1;
+       }
+               
+       signal MLME_START.confirm(MAC_SUCCESS);
+
+       return SUCCESS;
+}
+
+/*************************************************************/
+/**************MLME_ASSOCIATE*********************************/
+/*************************************************************/
+
+command error_t MLME_ASSOCIATE.request(uint8_t LogicalChannel,uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation,bool securityenable)
+{
+       //update current channel
+       //call PLME_SET.request(PHYCURRENTCHANNEL,LogicalChannel);
+       
+       //printfUART("MLME_ASSOCIATE.request\n", "");
+       
+       //updates the PAN ID
+       atomic{ 
+               mac_PIB.macPANId = CoordPANId;
+               mac_PIB.macCoordShortAddress = (uint16_t)(CoordAddress[1] & 0x000000ff);
+               }
+               
+       associating=1; //boolean variable stating that the device is trying to associate
+       
+       call TimerAsync.set_timers_enable(1);
+       
+       //call PLME_SET.request(PHYCURRENTCHANNEL, LogicalChannel);
+
+       current_channel = LogicalChannel;
+       
+       //printfUART("SELECTED cord id %i\n", mac_PIB.macPANId);
+       //printfUART("CoordAddress %i\n", mac_PIB.macCoordShortAddress);
+       //printfUART("LogicalChannel %i\n", LogicalChannel);
+       //printfUART("Cordaddr %i\n",CoordAddress[0]);
+       //printfUART("Cordaddr %i\n",CoordAddress[1]);
+       /*
+       a_CoordAddrMode = CoordAddrMode;
+       a_CoordPANId=CoordPANId;
+       a_CoordAddress[0]=CoordAddress[0];
+       a_CoordAddress[1]=CoordAddress[1];
+       a_CapabilityInformation=CapabilityInformation;
+       a_securityenable=securityenable;
+       */
+       create_association_request_cmd(CoordAddrMode,CoordPANId,CoordAddress,CapabilityInformation);
+       
+       return SUCCESS;
+}
+
+command error_t MLME_ASSOCIATE.response(uint32_t DeviceAddress[], uint16_t AssocShortAddress, uint8_t status, bool securityenable)
+{
+       
+       error_t status_response;
+       
+       //////printfUART("MAR\n", "");
+       
+       status_response = create_association_response_cmd(DeviceAddress,AssocShortAddress,status);
+       ////////////printfUART("MLME_ASSOCIATE.response\n", "");
+
+
+return SUCCESS;
+}
+
+/*************************************************************/
+/**************MLME_DISASSOCIATE*********************************/
+/*************************************************************/
+
+command error_t MLME_DISASSOCIATE.request(uint32_t DeviceAddress[], uint8_t disassociate_reason, bool securityenable)
+{
+       create_disassociation_notification_cmd(DeviceAddress,disassociate_reason);
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_GET***********************************/
+/*********************************************************/
+command error_t MLME_GET.request(uint8_t PIBAttribute)
+{
+
+       switch(PIBAttribute)
+       {
+               case MACACKWAITDURATION :               signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAckWaitDuration);
+                                                                               break;
+               case MACASSOCIATIONPERMIT:      signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAssociationPermit);
+                                                                               break;
+               case MACAUTOREQUEST :                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macAutoRequest);
+                                                                               break;
+               case MACBATTLIFEEXT:                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBattLifeExt);
+                                                                               break;
+               case MACBATTLIFEEXTPERIODS:             signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBattLifeExtPeriods);
+                                                                               break;
+               case MACBEACONPAYLOAD:                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute, mac_PIB.macBeaconPayload);
+                                                                               break;
+               case MACMAXBEACONPAYLOADLENGTH: signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBeaconPayloadLenght);
+                                                                               break;
+               case MACBEACONORDER:                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBeaconOrder);
+                                                                               break;
+               case MACBEACONTXTIME:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *)&mac_PIB.macBeaconTxTime);
+                                                                               break;
+               case MACBSN:                                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macBSN);
+                                                                               break;
+               case MACCOORDEXTENDEDADDRESS:   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macCoordExtendedAddress0);
+                                                                               break;
+               case MACCOORDSHORTADDRESS:              signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macCoordShortAddress);
+                                                                               break;
+               case MACDSN:                                    signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macDSN);
+                                                                               break;
+               case MACGTSPERMIT:                              signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macGTSPermit);
+                                                                               break;
+               case MACMAXCSMABACKOFFS:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macMaxCSMABackoffs);
+                                                                               break;
+               case MACMINBE:                                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macMinBE);
+                                                                               break;
+               case MACPANID:                                  signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macPANId);
+                                                                               break;
+               case MACPROMISCUOUSMODE:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macPromiscuousMode);
+                                                                               break;
+               case MACRXONWHENIDLE:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macRxOnWhenIdle);
+                                                                               break;
+               case MACSHORTADDRESS:                   signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macShortAddress);
+                                                                               break;
+               case MACSUPERFRAMEORDER:                signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,&mac_PIB.macSuperframeOrder);
+                                                                               break;
+               case MACTRANSACTIONPERSISTENCETIME:     signal MLME_GET.confirm(MAC_SUCCESS,PIBAttribute,(uint8_t *) &mac_PIB.macTransactionPersistenceTime);
+                                                                                       break;
+                                                                                       
+               default:                                                signal MLME_GET.confirm(MAC_UNSUPPORTED_ATTRIBUTE,PIBAttribute,0x00);
+                                                                               break;
+       }
+
+return SUCCESS;
+}
+
+/*********************************************************/
+/**************MLME_SET***********************************/
+/*********************************************************/
+command error_t MLME_SET.request(uint8_t PIBAttribute,uint8_t PIBAttributeValue[])
+{
+
+//int i;
+
+//printfUART("set %i\n",PIBAttribute);
+
+atomic{
+
+       switch(PIBAttribute)
+       {
+       
+       
+               case MACACKWAITDURATION :               mac_PIB.macAckWaitDuration = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macAckWaitDuration: %x\n",mac_PIB.macAckWaitDuration);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                       
+               case MACASSOCIATIONPERMIT:      if ((uint8_t)PIBAttributeValue[1] == 0x00)
+                                                                               {
+                                                                                       mac_PIB.macAssociationPermit = 0x00;
+                                                                               }
+                                                                               else
+                                                                               {
+                                                                                       mac_PIB.macAssociationPermit = 0x01;
+                                                                               }
+                                                                               ////////printfUART("mac_PIB.macAssociationPermit: %i %y\n",mac_PIB.macAssociationPermit,PIBAttributeValue[1]);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACAUTOREQUEST :                   mac_PIB.macAutoRequest = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macAutoRequest: %i\n",mac_PIB.macAutoRequest);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACBATTLIFEEXT:                    mac_PIB.macBattLifeExt = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macBattLifeExt %i\n",mac_PIB.macBattLifeExt);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACBATTLIFEEXTPERIODS:             mac_PIB.macBattLifeExtPeriods = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macBattLifeExtPeriods %i\n",mac_PIB.macBattLifeExtPeriods);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACBEACONPAYLOAD:                  /*for(i=0;i < mac_PIB.macBeaconPayloadLenght;i++) 
+                                                                               {
+                                                                                       mac_PIB.macBeaconPayload[i] = PIBAttributeValue[i];
+                                                                               }*/
+                                                                       
+                                                                               memcpy(&PIBAttributeValue[0],&mac_PIB.macBeaconPayload[0],mac_PIB.macBeaconPayloadLenght * sizeof(uint8_t));
+                                                                               
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                               
+               case MACMAXBEACONPAYLOADLENGTH: mac_PIB.macBeaconPayloadLenght = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macBeaconPayloadLenght %i\n",mac_PIB.macBeaconPayloadLenght);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACBEACONORDER:                    mac_PIB.macBeaconOrder = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macBeaconOrder %i\n",mac_PIB.macBeaconOrder);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACBEACONTXTIME:                   mac_PIB.macBeaconTxTime =PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macBeaconTxTime %i\n",mac_PIB.macBeaconTxTime);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACBSN:                                    mac_PIB.macBSN = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macBSN %i\n",mac_PIB.macBSN);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+
+               case MACCOORDEXTENDEDADDRESS:   //mac_PIB.macCoordExtendedAddress0 = ((PIBAttributeValue[0] >> 24) | (PIBAttributeValue[1] >> 16) | (PIBAttributeValue[2] >> 8) | (PIBAttributeValue[3])) ;
+                                                                               //mac_PIB.macCoordExtendedAddress1 = ((PIBAttributeValue[4] >> 24) | (PIBAttributeValue[5] >> 16) | (PIBAttributeValue[6] >> 8) | (PIBAttributeValue[7]));
+
+                                                                               //////////printfUART("mac_PIB.macCoordExtendedAddress0 %y\n",mac_PIB.macCoordExtendedAddress0);
+                                                                               //////////printfUART("mac_PIB.macCoordExtendedAddress1 %y\n",mac_PIB.macCoordExtendedAddress1);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+                                                                       
+               case MACCOORDSHORTADDRESS:              mac_PIB.macCoordShortAddress= ((PIBAttributeValue[0] << 8) |PIBAttributeValue[1]);
+                                                                               //printfUART("mac_PIB.macCoordShortAddress: %x\n",mac_PIB.macCoordShortAddress);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               
+               case MACDSN:                                    mac_PIB.macDSN = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macDSN: %x\n",mac_PIB.macDSN);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACGTSPERMIT:                              mac_PIB.macGTSPermit = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macGTSPermit: %x\n",mac_PIB.macGTSPermit);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACMAXCSMABACKOFFS:                mac_PIB.macMaxCSMABackoffs = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macMaxCSMABackoffs: %x\n",mac_PIB.macMaxCSMABackoffs);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACMINBE:                                  mac_PIB.macMinBE = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macMinBE: %x\n",mac_PIB.macMinBE);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               
+               case MACPANID:                                  mac_PIB.macPANId = ((PIBAttributeValue[0] << 8)| PIBAttributeValue[1]);
+                                                                               printfUART("mac_PIB.macPANId: %x\n",mac_PIB.macPANId);
+                                                                               
+                                                                               //TODO ENABLE HARDWARE VERIFICATION
+                                                                               //call CC2420Config.setPanAddr(mac_PIB.macPANId);
+                                                                               //call CC2420Config.setAddressRecognition(TRUE);
+                                                                               //call CC2420Config.sync(); 
+                                                                               
+                                                                               call AddressFilter.set_coord_address(mac_PIB.macCoordShortAddress, mac_PIB.macPANId);
+                                                                               
+                                                                               
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               
+               case MACPROMISCUOUSMODE:                mac_PIB.macPromiscuousMode = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macPromiscuousMode: %x\n",mac_PIB.macPromiscuousMode);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+               case MACRXONWHENIDLE:                   mac_PIB.macRxOnWhenIdle = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macRxOnWhenIdle: %x\n",mac_PIB.macRxOnWhenIdle);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+                                                                               
+               case MACSHORTADDRESS:                   mac_PIB.macShortAddress = ((PIBAttributeValue[0] << 8) |PIBAttributeValue[1]);
+                                                                               
+                                                                               printfUART("mac_PIB.macShortAddress: %y\n",mac_PIB.macShortAddress);
+                                                                                                                                                       
+                                                                               //TODO ENABLE HARDWARE VERIFICATION
+                                                                               //call CC2420Config.setPanAddr(0x0000);
+                                                                               //call CC2420Config.setShortAddr(0x0001);
+                                                                               //call CC2420Config.setAddressRecognition(TRUE);
+                                                                               //call CC2420Config.sync(); 
+                                                                               
+                                                                               call AddressFilter.set_address(mac_PIB.macShortAddress, aExtendedAddress0, aExtendedAddress0);
+                                                                               
+                                                                               
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACSUPERFRAMEORDER:                mac_PIB.macSuperframeOrder = PIBAttributeValue[0];
+                                                                               //////////printfUART("mac_PIB.macSuperframeOrder: %x\n",mac_PIB.macSuperframeOrder);
+                                                                               signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                               break;
+                                                                               
+               case MACTRANSACTIONPERSISTENCETIME:      mac_PIB.macTransactionPersistenceTime = PIBAttributeValue[0];
+                                                                                        //////////printfUART("mac_PIB.macTransactionPersistenceTime: %y\n",mac_PIB.macTransactionPersistenceTime);
+                                                                                        signal MLME_SET.confirm(MAC_SUCCESS,PIBAttribute);
+                                                                                        break;
+                                                                                       
+               default:                                                signal MLME_SET.confirm(MAC_UNSUPPORTED_ATTRIBUTE,PIBAttribute);
+                                                                               break;
+                                                                               
+               
+       }
+
+}
+
+return SUCCESS;
+}
+/*************************************************************/
+/**************        MCPS - DATA         *******************/
+/*************************************************************/
+
+command error_t MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions)
+{
+       int i;
+       //uint8_t valid_gts=0;
+       uint32_t total_ticks;
+       
+       //////printfUART("MCPS_DATA.request\n", ""); 
+       //check conditions on page 58
+       
+       //atomic mac_PIB.macShortAddress = TOS_LOCAL_ADDRESS;
+       
+       /*
+       //printfUART("SrcAddrMode %x\n", SrcAddrMode);
+       //printfUART("SrcPANId %x\n", SrcPANId);
+       //printfUART("SrcAddr %x\n", SrcAddr[0]);
+       //printfUART("SrcAddr %x\n", SrcAddr[1]);
+       //printfUART("DstAddrMode %x\n", DstAddrMode);
+       //printfUART("DestPANId %x\n", DestPANId);
+       //printfUART("DstAddr %x\n", DstAddr[0]);
+       //printfUART("DstAddr %x\n", DstAddr[1]);
+       //printfUART("msduLength %x\n", msduLength);
+       //printfUART("msduHandle %x\n", msduHandle);
+       //printfUART("TxOptions %x\n", TxOptions);
+               */
+       
+       atomic{
+       
+       if (mac_PIB.macShortAddress == 0xffff)
+               return FAIL;
+       }
+       
+       if(PANCoordinator == 1)
+       {
+       //PAN COORDINATOR OPERATION
+               ////////////printfUART("GTS TRANS: %i TxOptions: %u dest:%u\n", get_txoptions_gts(TxOptions),TxOptions,DstAddr[1]); 
+               
+               if (get_txoptions_gts(TxOptions) == 1)
+               {
+               //GTS TRANSMISSION
+                       for (i=0 ; i < 7 ; i++)
+                       {
+                               //SEARCH FOR A VALID GTS
+                               if ( GTS_db[i].DevAddressType == (uint16_t)DstAddr[1] && GTS_db[i].direction == 1 && GTS_db[i].gts_id != 0)
+                               {
+                                       
+                               //atomic{
+                                               ////////////printfUART("BUFFER UNTIL GTS SLOT n: %i ss: %i\n",number_time_slot,GTS_db[valid_gts].starting_slot);
+                                               create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,GTS_db[i].starting_slot,1);
+                                       //}
+                                       return SUCCESS;
+                                       break;
+                               }
+                       }
+                       signal MCPS_DATA.confirm(msduHandle, MAC_INVALID_GTS);
+                       return FAIL;
+               }
+               else
+               {
+               //NORMAL/INDIRECT TRANSMISSION
+               
+                       ////////////printfUART("IND TRANS: %i TxOptions: %u\n", get_txoptions_indirect_transmission(TxOptions),TxOptions);
+                       //check if its an indirect transmission
+                       //if ( get_txoptions_indirect_transmission(TxOptions) == 1)
+                       //{
+                               //INDIRECT TRANSMISSION
+                               
+                               ////////////printfUART("CREATE INDIRECT TRANSMISSION\n","");
+                               
+                               
+                               
+                               
+                       //}
+                       //else
+                       //{
+                               //NORMAL TRANSMISSION
+                               //printfUART("SEND NO GTS NO IND\n","");
+                               create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,0,0);
+                       //}
+               }
+       }
+       else
+       {
+       //NON PAN COORDINATOR OPERATION
+               atomic{
+                               
+                               ////////////printfUART("sslot: %i ini %i\n",s_GTSss,init_s_GTSss);
+                               //check if it a gts transmission
+                               if (get_txoptions_gts(TxOptions) == 1)
+                               {
+                               //GTS TRANSMISSION
+                                       if (s_GTSss == 0x00)
+                                       {
+                                               ////////////printfUART("NO VALID GTS \n","");
+                                               signal MCPS_DATA.confirm(msduHandle, MAC_INVALID_GTS);
+                                       }
+                                       else
+                                       {
+                                                       total_ticks = call TimerAsync.get_total_tick_counter();
+                                                       msdu[0] =(uint8_t)(total_ticks >> 0 );
+                                                       msdu[1] =(uint8_t)(total_ticks >> 8);
+                                                       msdu[2] =(uint8_t)(total_ticks >> 16);
+                                                       msdu[3] =(uint8_t)(total_ticks >> 24);
+                                                       
+                                                       if (on_sync == 1 && s_GTSss > 0)
+                                                       create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,s_GTSss,0);
+                                       }
+                               }
+                               else
+                               {
+                               //NORMAL TRANSMISSION
+                                       printfUART("TRnsm\n","");
+                                       create_data_frame(SrcAddrMode, SrcPANId, SrcAddr, DstAddrMode, DestPANId, DstAddr, msduLength, msdu, msduHandle, TxOptions,0,0);
+                               }
+                       }
+       }
+       return SUCCESS;
+}
+
+
+
+
+/*************************************************************/
+/**************        MCPS - PURGE         *******************/
+/*************************************************************/
+
+command error_t MCPS_PURGE.request(uint8_t msduHandle)
+{
+
+
+
+return SUCCESS;
+}
+
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+/************************              OTHER FUNCTIONS                         **********************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/
+/*****************************************************************************************************/
+
+task void signal_loss()
+{
+       //TODO
+       atomic signal MLME_SYNC_LOSS.indication(beacon_loss_reason); //MAC_BEACON_LOSS
+       return;
+}
+
+//inicialization of the mac constants
+void init_MacCon()
+{
+/*****************************************************/
+/*                             Boolean Variables                                        */
+/*****************************************************/  
+PANCoordinator = 0;
+//(0 NO beacon transmission; 1 beacon transmission);
+Beacon_enabled_PAN = 0;
+//(SYNC)the device will try to track the beacon ie enable its receiver just before the espected time of each beacon
+TrackBeacon=0;
+//(SYNC)the device will try to locate one beacon
+findabeacon=0;
+//(RESET) when the reset command arrives it checks whether or not to reset the PIB
+SetDefaultPIB=0;
+/*****************************************************/
+/*                             Integer Variables                                        */
+/*****************************************************/  
+/*
+//Beacon Interval
+uint32_t BI;
+//Superframe duration
+uint32_t SD;
+*/
+//(SYNC)number of beacons lost before sending a Beacon-Lost indication comparing to aMaxLostBeacons
+missed_beacons=0;
+//current_channel
+current_channel=0;
+
+
+/*****************************************************/
+/*                             Other Variables                                  */
+/*****************************************************/ 
+pending_reset=0;
+
+}
+
+//inicialization of the mac PIB
+void init_MacPIB()
+{
+
+atomic{
+       //mac PIB default values
+       
+       //mac_PIB.macAckWaitDuration = 54; OLD VALUE//Number os symbols to wait for an acknowledgment
+       mac_PIB.macAckWaitDuration = 65;
+       
+       mac_PIB.macAssociationPermit = 1; //1 - PAN allowing associations
+       mac_PIB.macAutoRequest = 1; //indication if a device automatically sends a data request command if address is listed in the beacon frame
+       
+       mac_PIB.macBattLifeExt= 0; //batery life extension CSMA-CA
+       
+       mac_PIB.macBattLifeExtPeriods=6;
+       //mac_PIB.macBeaconPayload; //payload of the beacon
+       mac_PIB.macBeaconPayloadLenght=0; //beacon payload lenght
+       
+       mac_PIB.macBeaconTxTime=(0xffffff << 24); //*****
+       
+       
+       mac_PIB.macBSN=call Random.rand16(); //sequence number of the beacon frame
+       
+       
+       mac_PIB.macCoordExtendedAddress0 = 0x00000000; //64bits address of the coordinator with witch the device is associated
+       mac_PIB.macCoordExtendedAddress1 = 0x00000000;
+       
+       mac_PIB.macCoordShortAddress = 0x0000; //16bits address of the coordinator with witch the device is associated
+       
+       
+       if (DEVICE_DEPTH == 0x01)
+               mac_PIB.macCoordShortAddress =D1_PAN_SHORT;
+       if (DEVICE_DEPTH == 0x02)
+               mac_PIB.macCoordShortAddress =D2_PAN_SHORT;
+       if (DEVICE_DEPTH == 0x03)
+               mac_PIB.macCoordShortAddress =D3_PAN_SHORT;
+       if (DEVICE_DEPTH == 0x04)
+               mac_PIB.macCoordShortAddress =D4_PAN_SHORT;
+       
+       
+       mac_PIB.macDSN=call Random.rand16(); //sequence number of the transmited data or MAC command frame
+       
+       //alowing gts requests (used in beacon)
+       mac_PIB.macGTSPermit=1; //
+       
+       //Number of maximum CSMA backoffs
+       mac_PIB.macMaxCSMABackoffs=4;
+       mac_PIB.macMinBE=0;
+       
+       //mac_PIB.macPANId=0xffff; //16bits identifier of the PAN on witch this device is operating
+       mac_PIB.macPANId = MAC_PANID;
+       
+       mac_PIB.macPromiscuousMode=0;
+       mac_PIB.macRxOnWhenIdle=0;
+       //mac_PIB.macShortAddress=TOS_LOCAL_ADDRESS; //16bits short address
+       mac_PIB.macShortAddress=0xffff;
+
+
+       mac_PIB.macBeaconOrder=7;  //specification of how often the coordinator transmits a beacon
+       mac_PIB.macSuperframeOrder=3;
+       
+       //default mac_PIB.macTransactionPersistenceTime=0x01f4;
+       mac_PIB.macTransactionPersistenceTime=0x0010;
+       
+       //*******************************************
+
+       }
+}
+
+//////////////////////////////////////////////////////////////
+////////////////////////CSMA-CA functions////////////////////
+/////////////////////////////////////////////////////////////
+
+/*****************************************************/
+/*                             SEND FRAME FUNCTION                      */
+/*****************************************************/ 
+
+task void send_frame_csma_upstream()
+{//used in TDBS
+       atomic{
+       
+               ////////printfUART("sf %i, %i \n",send_buffer_count,upstream_buffer_count);
+               ////////printfUART("I_AM_IN_IP %i \n",I_AM_IN_IP);
+               ////printfUART("send up IPCAP %i %i \n",I_AM_IN_PARENT_CAP,upstream_buffer_count);
+       
+               //beacon synchronization
+               if(upstream_buffer_count > 0 && I_AM_IN_PARENT_CAP == 1)
+               {
+               
+                       ////////printfUART("s up\n","");
+                       sending_upstream_frame =1;
+                       
+                       performing_csma_ca = 1;
+
+                       perform_csma_ca();
+               }
+               
+               
+       }
+       
+}
+
+
+task void send_frame_csma()
+{
+       atomic{
+       
+               //
+               ///printfUART("I_AM_IN_IP %i %i\n",I_AM_IN_IP,send_buffer_count);
+       
+               if ((send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE && performing_csma_ca == 0) || I_AM_IN_IP != 0)
+               {
+                       ////printfUART("sf %i\n",send_buffer_count);
+                       //////printfUART("peform\n","");
+                       
+                       performing_csma_ca = 1;
+
+                       perform_csma_ca();
+               }
+               else
+               {
+                       //printfUART("NOT SEND\n","");
+               }
+
+               
+       }
+       
+}
+
+
+task void perform_csma_ca_slotted()
+{
+       uint8_t random_interval;
+       
+               
+               
+               //DEFERENCE CHANGE
+               if (check_csma_ca_send_conditions(send_buffer[send_buffer_msg_out].length,send_buffer[send_buffer_msg_out].frame_control1) == 1 )
+               {
+                       cca_deference = 0;
+               }
+               else
+               {
+                       //nao e necessario
+                       cca_deference = 1;
+                       return;
+               }
+               
+       atomic{
+               //printfUART("CCA: %i\n", call CCA.get()) ;
+       
+               if(call CCA.get() == CCA_BUSY )
+               {
+                       ////////////printfUART("CCA: 1\n", "") ;
+                       //STEP 5
+                       CW--;
+                       if (CW == 0 )
+                       {
+                               //send functions
+                               csma_cca_backoff_boundary =0;
+                               
+                               ////////printfUART("s_up_f %i\n",sending_upstream_frame);
+                               //TDBS Implementation
+                               if(sending_upstream_frame == 0)
+                               {
+                               
+                                       //////printfUART("rts %i\n",get_ack_request(send_buffer[send_buffer_msg_out].frame_control));
+
+                                               //verify if the message must be ack
+                                               if ( get_fc1_ack_request(send_buffer[send_buffer_msg_out].frame_control1) == 1 )
+                                               {
+                                                       send_ack_check=1;
+                                                       ack_sequence_number_check=send_buffer[send_buffer_msg_out].seq_num;     
+                                                       //verify retransmission
+                                                       send_retransmission = send_buffer[send_buffer_msg_out].retransmission;
+                                                       //verify if its an indirect transmission
+                                                       send_indirect_transmission = send_buffer[send_buffer_msg_out].indirect;
+                                                       //SEND WITH ACK_REQUEST
+                                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
+                                                       
+                                                       //////printfUART("out ck\n","");
+                                                       
+                                                       
+                                                       call T_ackwait.startOneShot(ackwait_period);
+                                               }
+                                               else
+                                               {
+                                               
+                                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
+                                                       
+                                                       send_buffer_count --;
+                                                       send_buffer_msg_out++;
+                                               
+                                                       //failsafe
+                                                       if(send_buffer_count > SEND_BUFFER_SIZE)
+                                                       {
+                                                               send_buffer_count =0;
+                                                               send_buffer_msg_out=0;
+                                                               send_buffer_msg_in=0;
+                                                       }
+                                                       
+                                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                                               send_buffer_msg_out=0;
+                                                       
+                                                       if (send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE)
+                                                               post send_frame_csma();
+                                                       
+                                                       //printfUART("sk %i\n",send_buffer_count);
+                                                       
+                                                       ////////printfUART("%i %i %i\n",send_buffer_count,send_buffer_msg_in,send_buffer_msg_out);
+                                               }
+                                               
+                               }
+                               else
+                               {
+                                       //TDBS Implementation
+                                               
+                                               call PD_DATA.request(upstream_buffer[upstream_buffer_msg_out].length,(uint8_t *)&upstream_buffer[upstream_buffer_msg_out]);
+                                               
+                                               upstream_buffer_count --;
+                                               upstream_buffer_msg_out++;
+                                       
+                                               if (upstream_buffer_msg_out == UPSTREAM_BUFFER_SIZE)
+                                                       upstream_buffer_msg_out=0;
+                                                       
+                                               sending_upstream_frame=0;
+                               }               
+                               performing_csma_ca = 0;
+                       }
+               }
+               else
+               {
+                       //CHECK NOT USED
+                       //csma_backoff_counter++;
+                       //csma_backoff_counter_inst++;
+
+                       if (NB < mac_PIB.macMaxCSMABackoffs)
+                       {
+                               //////////printfUART("NB:%i BE:%i L CW: %i\n",NB,BE,CW);
+                               //STEP 4
+                               CW = 2;
+                               NB++;
+                               BE = min(BE+1,aMaxBE);
+                               
+                               //STEP 2
+                               //random_interval = pow(2,BE) - 1;
+                               
+                               //delay_backoff_period = (call Random.rand() & random_interval);
+                               //verification of the backoff_deference
+                               //DEFERENCE CHANGE
+                               if (backoff_deference == 0)
+                               {
+                                       random_interval = powf(2,BE) - 1;
+                                       delay_backoff_period = (call Random.rand16() & random_interval );
+                                               
+                                       if (check_csma_ca_backoff_send_conditions((uint32_t) delay_backoff_period) == 1)
+                                       {
+                                                       backoff_deference = 1;
+                                       }
+                               }
+                               else
+                               {
+                                       backoff_deference = 0;
+                               }
+                               
+                               
+                               //delay_backoff_period=0;
+                               
+                               //printfUART("delay_backoff_period:%i\n",delay_backoff_period);
+                               csma_delay=1;
+                       }
+                       else
+                       {
+                               //CSMA/CA FAIL
+                               csma_delay=0;
+                               csma_cca_backoff_boundary=0;
+                               
+                               send_buffer_count --;
+                               send_buffer_msg_out++;
+                       
+                               //failsafe
+                               if(send_buffer_count > SEND_BUFFER_SIZE)
+                               {
+                                       send_buffer_count =0;
+                                       send_buffer_msg_out=0;
+                                       send_buffer_msg_in=0;
+                               }
+                               
+                               if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                       send_buffer_msg_out=0;
+                               
+                               if (send_buffer_count > 0 && send_buffer_count <= SEND_BUFFER_SIZE)
+                                       post send_frame_csma();
+                                       
+                               performing_csma_ca = 0;
+                               
+                               //printfUART("SLOTTED FAIL\n","");
+                               /*
+                               if(associating == 1)
+                               {
+                                       associating=0;
+                                       signal MLME_ASSOCIATE.confirm(0x0000,MAC_CHANNEL_ACCESS_FAILURE);
+                               }*/
+                       }
+               }
+       }
+return;
+}
+
+task void perform_csma_ca_unslotted()
+{
+       uint8_t random_interval;
+       
+       atomic{
+               if (NB < mac_PIB.macMaxCSMABackoffs)
+               {
+                       //STEP 3
+                       //perform CCA
+                       //////////printfUART("CCA: %i\n", TOSH_READ_CC_CCA_PIN()) ;
+                       
+                       //if CCA is clear send message
+                       if(call CCA.get() == CCA_BUSY)
+                       {
+                               //send functions
+                               //////////printfUART("UNSLOTTED SUCCESS\n","");
+                               atomic{
+                               csma_delay =0;
+                               
+
+                                               
+                               if (check_csma_ca_send_conditions(send_buffer[send_buffer_msg_out].length,send_buffer[send_buffer_msg_out].frame_control1) == 1 )
+                               {
+                                       call PD_DATA.request(send_buffer[send_buffer_msg_out].length,(uint8_t *)&send_buffer[send_buffer_msg_out]);
+                                       
+                                       send_buffer_count --;
+                                       send_buffer_msg_out++;
+                               
+                                       //failsafe
+                                       if(send_buffer_count > SEND_BUFFER_SIZE)
+                                       {
+                                               send_buffer_count =0;
+                                               send_buffer_msg_out=0;
+                                               send_buffer_msg_in=0;
+                                       }
+                               
+                                       if (send_buffer_msg_out == SEND_BUFFER_SIZE)
+                                               send_buffer_msg_out=0;
+                               }
+                                       
+                               
+                               performing_csma_ca =0;
+
+                               }
+                               return; //SUCCESS
+                       
+                       }
+
+                       //CCA is not clear, perform new iteration of the CSMA/CA UNSLOTTED
+                       
+                       //STEP 4
+                       NB++;
+                       BE = min(BE+1,aMaxBE);
+               
+                       //////////printfUART("NB:%i BE:%i\n",NB,BE);
+                       
+                       //STEP 2
+                       //#ifdef PLATFORM_MICAZ
+                               random_interval = powf(2,BE) - 1;
+                       //#else
+                       //      random_interval = powf(2,BE) - 1;
+                       //#endif
+                       delay_backoff_period = (call Random.rand16() & random_interval );
+                       //delay_backoff_period=1;
+                       csma_delay=1;
+                       
+                       ////////////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
+               }
+               else
+               {
+                       atomic csma_delay=0;
+                       //////////printfUART("UNSLOTTED FAIL\n","");
+               }
+       }
+return;
+}
+
+
+void perform_csma_ca()
+{
+       uint8_t random_interval;
+       csma_slotted=1;
+       //STEP 1
+       if (csma_slotted == 0 )
+       {
+               atomic{
+                       //UNSLOTTED version
+                       init_csma_ca(csma_slotted);
+                       //STEP 2
+                       random_interval = powf(2,BE) - 1;
+                       delay_backoff_period = (call Random.rand16() & random_interval );
+                       
+                       csma_delay=1;
+                       //////////printfUART("delay_backoff_period:%i\n",delay_backoff_period);
+               }
+               return;
+       }
+       else
+       {
+               //SLOTTED version
+               atomic{
+                       //DEFERENCE CHANGE
+                       if (cca_deference==0)
+                       {
+                               init_csma_ca(csma_slotted);
+                               if (mac_PIB.macBattLifeExt == 1 )
+                               {
+                                       BE = min(2,     mac_PIB.macMinBE);
+                               }
+                               else
+                               {
+                                       BE = mac_PIB.macMinBE;
+                               }
+                               csma_locate_backoff_boundary = 1;
+                       }
+                       else
+                       {
+                               cca_deference = 0;
+                               csma_delay=0;
+                               csma_locate_backoff_boundary=0;
+                               csma_cca_backoff_boundary = 1;
+                       
+                       }
+               }
+               return;
+       }
+}
+
+
+uint8_t min(uint8_t val1, uint8_t val2)
+{
+       if (val1 < val2)
+       {
+               return val1;
+       }
+       else
+       {
+               return val2;
+       }
+}
+
+void init_csma_ca(bool slotted)
+{
+
+//initialization of the CSMA/CA protocol variables
+       ////////////printfUART("init_csma_ca\n", "") ;
+       
+       csma_delay=0;
+       
+       if (slotted == 0 )
+       {
+               NB=0;
+               BE=mac_PIB.macMinBE;
+       }
+       else
+       {
+               NB=0;
+               CW=2;
+               
+               csma_cca_backoff_boundary=0;
+               csma_locate_backoff_boundary=0;
+       }
+
+return;
+}
+
+
+uint8_t calculate_ifs(uint8_t pk_length)
+{
+       if (pk_length > aMaxSIFSFrameSize)
+               return aMinLIFSPeriod; // + ( ((pk_length * 8) / 250.00) / 0.34 );
+       else
+               return aMinSIFSPeriod; // + ( ((pk_length * 8) / 250.00) / 0.34 );
+}
+
+uint32_t calculate_gts_expiration()
+{
+       uint32_t exp_res;
+       if( mac_PIB.macBeaconOrder > 9 )
+               exp_res= 1;
+       else
+       {
+               //#ifdef PLATFORM_MICAZ
+                       exp_res= powf(2,(8-mac_PIB.macBeaconOrder));
+               //#else
+               //      exp_res= powf(2,(8-mac_PIB.macBeaconOrder));
+               //#endif
+       }       
+       //////////printfUART("alculat %i\n",exp_res ) ;
+       return exp_res;
+}
+
+uint8_t check_csma_ca_send_conditions(uint8_t frame_length,uint8_t frame_control1)
+{
+       uint8_t ifs_symbols;
+       uint32_t frame_tx_time;
+       uint32_t remaining_gts_duration;
+       
+       
+       ifs_symbols=calculate_ifs(frame_length);
+       //wait_ifs=1;
+       //call TimerAsync.set_ifs_symbols(ifs_symbols);
+       
+       ////////////printfUART("ifs_symbols %i\n",ifs_symbols ) ;
+       
+       if (get_fc1_ack_request(frame_control1) == 1 )
+               frame_tx_time =  frame_length + ACK_LENGTH + aTurnaroundTime + ifs_symbols;
+       else
+               frame_tx_time =  frame_length + ifs_symbols;
+               
+       atomic remaining_gts_duration = time_slot - ( call TimerAsync.get_current_number_backoff_on_time_slot() * aUnitBackoffPeriod);
+       
+       ////////////printfUART("frame_tx %d remaing %d\n",frame_tx_time,remaining_gts_duration ) ;
+       
+       if (frame_tx_time < remaining_gts_duration)
+               return 1;
+       else
+               return 0;
+
+}
+
+//DEFERENCE CHANGE
+uint8_t check_csma_ca_backoff_send_conditions(uint32_t delay_backoffs)
+{
+
+       uint32_t number_of_sd_ticks=0;
+       uint32_t current_ticks=0;
+       uint32_t ticks_remaining =0;
+       uint32_t number_of_backoffs_remaining =0;
+       
+       number_of_sd_ticks = call TimerAsync.get_sd_ticks();
+       
+       current_ticks = call TimerAsync.get_current_ticks();
+       
+       ticks_remaining = number_of_sd_ticks - current_ticks;
+       
+       number_of_backoffs_remaining = ticks_remaining / 5;
+       
+       if (number_of_backoffs_remaining > delay_backoffs)
+               return 0;
+       else
+               return 1;
+
+
+
+}
+
+uint8_t check_gts_send_conditions(uint8_t frame_length)
+{
+       uint8_t ifs_symbols;
+       uint32_t frame_tx_time;
+       uint32_t remaining_gts_duration;
+       
+
+       ifs_symbols=calculate_ifs(frame_length);
+       //wait_ifs=1;
+       //call TimerAsync.set_ifs_symbols(ifs_symbols);
+       
+       ////////////printfUART("ifs_symbols %i\n",ifs_symbols ) ;
+       
+       frame_tx_time =  frame_length + ACK_LENGTH + aTurnaroundTime + ifs_symbols;
+       
+       remaining_gts_duration = time_slot - ( call TimerAsync.get_current_number_backoff_on_time_slot() * aUnitBackoffPeriod);
+       
+       ////////////printfUART("frame_tx %d remaing %d\n",frame_tx_time,remaining_gts_duration ) ;
+       
+       if (frame_tx_time < remaining_gts_duration)
+               return 1;
+       else
+               return 0;
+}
+
+//////////////////////////////////////////////////////////////
+////////////////////////GTS functions////////////////////////
+/////////////////////////////////////////////////////////////
+
+void init_GTS_db()
+{
+       //initialization of the GTS database
+       int i;
+atomic{
+               for (i=0 ; i < 7 ; i++)
+               {
+                       GTS_db[i].gts_id=0x00;
+                       GTS_db[i].starting_slot=0x00;
+                       GTS_db[i].length=0x00;
+                       GTS_db[i].direction=0x00;
+                       GTS_db[i].DevAddressType=0x0000;
+               
+               }
+       }
+return;
+}
+
+error_t remove_gts_entry(uint16_t DevAddressType)
+{
+       uint8_t r_lenght=0;
+       //int r_start_slot=7;
+       int i;
+       
+       atomic{
+               for (i=0; i < 7 ; i++)
+               {
+                       if( GTS_db[i].DevAddressType == DevAddressType )
+                       {
+                               
+                               r_lenght = GTS_db[i].length;
+                               //r_start_slot = i;
+                               //delete the values
+                               GTS_db[i].gts_id=0x00;
+                               GTS_db[i].starting_slot=0x00;
+                               GTS_db[i].length=0x00;
+                               GTS_db[i].direction=0x00;
+                               GTS_db[i].DevAddressType=0x0000;
+                               GTS_db[i].expiration=0x00;
+                               
+                               ////////////printfUART("GTS Entry removed dev:%i len:%i pos %i\n", DevAddressType,r_lenght,i);
+                               GTS_startslot = GTS_startslot + r_lenght;
+                               GTS_descriptor_count--;
+                               final_CAP_slot = final_CAP_slot + r_lenght;
+                       }
+                       
+                       if ( r_lenght > 0)
+                       {
+                               if ( GTS_db[i].gts_id != 0x00 && GTS_db[i].DevAddressType !=0x0000)
+                               {                               
+                                       GTS_db[i-r_lenght].gts_id = GTS_db[i].gts_id;
+                                       GTS_db[i-r_lenght].starting_slot = i-r_lenght;
+                                       GTS_db[i-r_lenght].length = GTS_db[i].length;
+                                       GTS_db[i-r_lenght].direction = GTS_db[i].direction;
+                                       GTS_db[i-r_lenght].DevAddressType = GTS_db[i].DevAddressType;
+                                       GTS_db[i-r_lenght].expiration = GTS_db[i].expiration;
+                                       
+                                       //delete the values
+                                       GTS_db[i].gts_id=0x00;
+                                       GTS_db[i].starting_slot=0x00;
+                                       GTS_db[i].length=0x00;
+                                       GTS_db[i].direction=0x00;
+                                       GTS_db[i].DevAddressType=0x0000;
+                                       GTS_db[i].expiration=0x00;
+                                       
+                                       ////////////printfUART("UPDATED\n","" );
+                               }
+                       }
+               }
+       }
+return SUCCESS;
+}
+
+error_t add_gts_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType)
+{
+       int i;
+       ////////////printfUART("ADDING gts_length: %i\n", gts_length); 
+       ////////////printfUART("dir: %i\n", direction); 
+       ////////////printfUART("addr: %i\n", DevAddressType);
+
+       //check aMinCAPLength
+       if ( (GTS_startslot - gts_length) < 5 )
+       {
+               ////////////printfUART("ADD FAIL%i\n", ""); 
+               
+       }
+       
+       //if it has more than 7 timeslots alocated
+       if ( (GTS_startslot -gts_length) < 9 )
+       {
+               return FAIL;
+       }
+       
+       //check if the address already exists in the GTS list
+       for (i=0 ; i < 7 ; i++)
+       {
+               if ( GTS_db[i].DevAddressType == DevAddressType && GTS_db[i].direction == direction && GTS_db[i].gts_id > 0)
+               {
+                       ////////////printfUART("ALREADY ADDED\n", ""); 
+                       return FAIL;
+               }
+               if ( GTS_null_db[i].DevAddressType == DevAddressType && GTS_null_db[i].gts_id > 0)
+               {
+                       ////////////printfUART("REJECTED\n", ""); 
+                       return FAIL;
+               }
+               
+               
+       }
+       
+atomic{        
+       
+       ////////////printfUART("GTS_startslot: %i\n", GTS_startslot); 
+       GTS_startslot = GTS_startslot - gts_length;
+
+       GTS_db[15-GTS_startslot].gts_id=GTS_id;
+       GTS_db[15-GTS_startslot].starting_slot=GTS_startslot;
+       GTS_db[15-GTS_startslot].length=gts_length;
+       GTS_db[15-GTS_startslot].direction=direction;
+       GTS_db[15-GTS_startslot].DevAddressType=DevAddressType;
+       GTS_db[15-GTS_startslot].expiration=0x00;
+
+       ////////////printfUART("GTS Entry added start:%i len:%i\n", GTS_startslot,gts_length); 
+       
+       GTS_id++;
+       GTS_descriptor_count++;
+       
+       final_CAP_slot = final_CAP_slot - gts_length;
+       
+       }
+       return SUCCESS;
+}
+
+
+//GTS null functions
+void init_GTS_null_db()
+{
+       //initialization of the GTS database
+       int i;
+       atomic{
+               for (i=0 ; i < 7 ; i++)
+               {
+                       GTS_null_db[i].gts_id=0x00;
+                       GTS_null_db[i].starting_slot=0x00;
+                       GTS_null_db[i].length=0x00;
+                       //GTS_null_db[i].direction=0x00;
+                       GTS_null_db[i].DevAddressType=0x0000;
+                       GTS_null_db[i].persistencetime=0x00;
+               }
+       }
+return;
+}
+
+
+error_t add_gts_null_entry(uint8_t gts_length,bool direction,uint16_t DevAddressType)
+{
+       int i;
+               
+       //check if the address already exists in the GTS list
+       for (i=0 ; i < 7 ; i++)
+       {
+               if ( GTS_null_db[i].DevAddressType == DevAddressType && GTS_null_db[i].gts_id > 0)
+               {
+                       ////////////printfUART("ALREADY ADDED null\n", ""); 
+                       return FAIL;
+               }
+       }
+       
+       for (i=0 ; i < 7 ; i++)
+       {
+               if ( GTS_null_db[i].DevAddressType==0x0000 && GTS_null_db[i].gts_id == 0x00)
+               {
+                       GTS_null_db[i].gts_id=GTS_id;
+                       GTS_null_db[i].starting_slot=0x00;
+                       GTS_null_db[i].length=0x00;
+                       //GTS_null_db[i].direction=0x00;
+                       GTS_null_db[i].DevAddressType=DevAddressType;
+                       GTS_null_db[i].persistencetime=0x00;
+                       
+                       
+                       ////////////printfUART("GTS null Entry added addr:%x\n", DevAddressType); 
+                       
+                       GTS_id++;
+                       GTS_null_descriptor_count++;
+                       
+               return SUCCESS;
+               }
+       }
+
+       
+return FAIL;   
+}
+
+task void increment_gts_null()
+{
+       int i;
+       
+       ////////////printfUART("init inc\n",""); 
+atomic{
+       for (i=0 ; i < 7 ; i++)
+       {
+               if ( GTS_null_db[i].DevAddressType != 0x0000 && GTS_null_db[i].gts_id != 0x00)
+               {
+                       ////////////printfUART("increm %x\n", GTS_null_db[i].DevAddressType); 
+                       GTS_null_db[i].persistencetime++;
+               
+               }
+               
+               if ( GTS_null_db[i].persistencetime > (aGTSDescPersistenceTime -1)  )
+               {
+                       GTS_null_db[i].gts_id=0x00;
+                       GTS_null_db[i].starting_slot=0x00;
+                       GTS_null_db[i].length=0x00;
+                       //GTS_null_db[i].direction=0x00;
+                       GTS_null_db[i].DevAddressType=0x0000;
+                       GTS_null_db[i].persistencetime=0x00;
+                       
+                       ////////////printfUART("GTS null removed addr:%x\n", GTS_null_db[i].DevAddressType); 
+               
+                       atomic GTS_null_descriptor_count--;
+               }
+                       
+       }
+       
+       }
+////////////printfUART("end inc\n",""); 
+return;
+}
+
+task void check_gts_expiration()
+{
+       int i;
+////////////printfUART("init exp\n",""); 
+atomic{        
+       atomic gts_expiration=calculate_gts_expiration();
+       ////////////printfUART("gts_expiration:%i\n", gts_expiration); 
+       atomic gts_expiration=2;
+       ////////////printfUART("gts_expiration:%i\n", gts_expiration); 
+       
+       for (i=0 ; i < 7 ; i++)
+       {
+               
+               if ( GTS_db[i].DevAddressType != 0x0000 && GTS_db[i].gts_id != 0x00)
+               {
+                       if( GTS_db[i].expiration == (gts_expiration + 1) && GTS_db[i].direction ==0x00)
+                       {
+                               ////////////printfUART("GTS expired addr:%x\n", GTS_null_db[i].DevAddressType); 
+                               //remove gts, indicate on the gts null list
+                               atomic{
+                               
+                                       add_gts_null_entry(GTS_db[i].length,GTS_db[i].direction,GTS_db[i].DevAddressType);
+                                       
+                                       remove_gts_entry(GTS_db[i].DevAddressType);
+                               }
+                       }
+                       else
+                       {
+                               atomic GTS_db[i].expiration ++;
+                       }
+               }
+       }
+       
+       
+       }
+       ////////////printfUART("end exp\n",""); 
+return;
+}
+
+void init_available_gts_index()
+       {
+               int i=0;
+               atomic{
+                       available_gts_index_count = GTS_SEND_BUFFER_SIZE;
+                       for(i=0;i < GTS_SEND_BUFFER_SIZE;i++)
+                       {
+                               available_gts_index[i]=i;
+                       }
+               }
+               return;
+       }
+/*****************************GTS BUFFER******************************/
+void init_gts_slot_list()
+{
+       int i=0;
+       for(i=0;i<7;i++)
+       {
+               gts_slot_list[i].element_count = 0x00;
+               gts_slot_list[i].element_in = 0x00;
+               gts_slot_list[i].element_out = 0x00;
+       }
+}
+
+
+task void start_coordinator_gts_send()
+{
+atomic{
+
+       coordinator_gts_send_pending_data =0;
+       
+       if(gts_slot_list[15-number_time_slot].element_count > 0)
+       {
+               if (check_gts_send_conditions(gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length) == 1 )
+               {
+                       
+                       gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length = gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length -2;
+                       
+                       call PD_DATA.request(gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]].length,(uint8_t *)&gts_send_buffer[gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out]]);
+       
+                       available_gts_index_count++;
+                       available_gts_index[available_gts_index_count] = gts_slot_list[15-number_time_slot].gts_send_frame_index[gts_slot_list[15-number_time_slot].element_out];
+                       
+                       gts_slot_list[15-number_time_slot].element_count--;
+                       gts_slot_list[15-number_time_slot].element_out++;
+                       
+                       if (gts_slot_list[15-number_time_slot].element_out == GTS_SEND_BUFFER_SIZE)
+                               gts_slot_list[15-number_time_slot].element_out=0;
+
+                       if(gts_slot_list[15-number_time_slot].element_count > 0 )
+                       {
+                               coordinator_gts_send_pending_data =1;
+                               coordinator_gts_send_time_slot = number_time_slot;
+                       }
+               }
+       }
+}
+return;
+}
+
+task void start_gts_send()
+{
+
+       atomic{
+       gts_send_pending_data = 0;
+       
+       if(gts_send_buffer_count > 0)
+       {
+               if (check_gts_send_conditions(gts_send_buffer[gts_send_buffer_msg_out].length) == 1 )
+               {
+
+                       gts_send_buffer[gts_send_buffer_msg_out].length = gts_send_buffer[gts_send_buffer_msg_out].length -2;
+
+                       call PD_DATA.request(gts_send_buffer[gts_send_buffer_msg_out].length,(uint8_t *)&gts_send_buffer[gts_send_buffer_msg_out]);
+       
+                       gts_send_buffer_count --;
+                       gts_send_buffer_msg_out++;
+
+                       if (gts_send_buffer_msg_out == GTS_SEND_BUFFER_SIZE)
+                               gts_send_buffer_msg_out=0;
+
+                       ////////////printfUART("after send %i %i %i \n",gts_send_buffer_count,gts_send_buffer_msg_in,gts_send_buffer_msg_out);
+                       
+                       if (gts_send_buffer_count > 0)
+                               gts_send_pending_data = 1;      
+               }
+       }
+
+}
+return;
+}
+
+//////////////////////////////////////////////////////////////
+//////////Indirect transmission functions////////////////////
+/////////////////////////////////////////////////////////////
+
+void init_indirect_trans_buffer()
+{
+       int i;
+       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+       {
+               indirect_trans_queue[i].handler = 0x00;
+               indirect_trans_count=0;
+       }
+
+return;
+}
+
+
+error_t remove_indirect_trans(uint8_t handler)
+{
+
+       int i;
+       uint8_t removed_ok=0;
+       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+       {
+               if (indirect_trans_queue[i].handler == handler)
+               {
+                       indirect_trans_queue[i].handler = 0x00;
+                       removed_ok = 1;
+                       indirect_trans_count--;
+                       break;
+               }
+       }
+
+       if (removed_ok == 0) 
+       {
+               return MAC_INVALID_HANDLE;
+       }
+       else
+       {
+               return SUCCESS;
+       }
+}
+
+
+void increment_indirect_trans()
+{
+       int i;
+       for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+       {
+               if (indirect_trans_queue[i].handler != 0x00)
+               {
+                       indirect_trans_queue[i].transaction_persistent_time++;
+                       if (indirect_trans_queue[i].transaction_persistent_time == mac_PIB.macTransactionPersistenceTime )
+                               remove_indirect_trans(indirect_trans_queue[i].handler);
+               }
+       }
+
+return;
+}
+
+void send_ind_trans_addr(uint32_t DeviceAddress[])
+{
+       
+       uint8_t destination_address=0;
+       
+       dest_short *dest_short_ptr =0;
+       dest_long *dest_long_ptr=0;
+       
+       int i=0;
+       MPDU *frame_ptr=0;
+       
+       //printfUART("send_ind_trans_addr DeviceAddress0: %y DeviceAddress1: %y \n",DeviceAddress[0],DeviceAddress[1]);
+
+    //list_indirect_trans_buffer();
+
+               for(i=0;i<INDIRECT_BUFFER_SIZE;i++)
+               {
+                       if (indirect_trans_queue[i].handler > 0x00)
+                       {
+                               frame_ptr = (MPDU *)indirect_trans_queue[i].frame;
+                               destination_address=get_fc2_dest_addr(frame_ptr->frame_control2);
+                               
+                               switch(destination_address)
+                               {
+                                       case LONG_ADDRESS: dest_long_ptr = (dest_long *) frame_ptr->data;
+                                                                               break;
+                                       case SHORT_ADDRESS: dest_short_ptr = (dest_short *) frame_ptr->data;                                                            
+                                                                               break;
+                               }
+                               
+                               //check the full address
+                               if ( (dest_long_ptr->destination_address0 == DeviceAddress[1] && dest_long_ptr->destination_address1 == DeviceAddress[0]) || ( dest_short_ptr->destination_address == (uint16_t)DeviceAddress[0] ))
+                               {
+                                       
+                                       if (send_buffer_msg_in == SEND_BUFFER_SIZE)
+                                               send_buffer_msg_in=0;
+                                               
+                                       memcpy(&send_buffer[send_buffer_msg_in],(MPDU *) &indirect_trans_queue[i].frame,sizeof(MPDU));
+                                       
+                                       //enable retransmissions
+                                       send_buffer[send_buffer_msg_in].retransmission =0;
+                                       send_buffer[send_buffer_msg_in].indirect = i + 1;
+                                       
+                                       //check upon reception
+                                       indirect_trans_queue[i].handler=0x00;
+                                       //verify temporary error on the association request
+                                       
+                                       indirect_trans_count--;
+                                       if(indirect_trans_count > INDIRECT_BUFFER_SIZE )
+                                       {
+                                               indirect_trans_count=0;
+                                       }
+                                       
+                                       atomic send_buffer_count++;
+                                       atomic send_buffer_msg_in++;
+                       
+                                       post send_frame_csma();
+                                       
+                                       //printfUART("i send\n","");
+                                       
+                                       return;
+                               }
+                       }
+               }
+               //printfUART("i not found","");
+
+       
+return;
+} 
+/*
+  event void CC2420Config.syncDone( error_t error )
+  {
+  
+       //printfUART("CC2420Config %i p %x sa %x\n",call CC2420Config.isAddressRecognitionEnabled(),call CC2420Config.getPanAddr(), call CC2420Config.getShortAddr()); 
+  
+  return;
+  }
+
+*/
+
+/***************************DEBUG FUNCTIONS******************************/
+/* This function are list functions with the purpose of debug, to use then uncomment the declatarion
+on top of this file*/
+/*
+
+void list_mac_pib()
+{
+//////////printfUART("mac_PIB.macAckWaitDuration: %x\n",mac_PIB.macAckWaitDuration);
+//////////printfUART("mac_PIB.macAssociationPermit: %i\n",mac_PIB.macAssociationPermit);
+//////////printfUART("mac_PIB.macAutoRequest: %i\n",mac_PIB.macAutoRequest);
+//////////printfUART("mac_PIB.macBattLifeExt %i\n",mac_PIB.macBattLifeExt);
+//////////printfUART("mac_PIB.macBattLifeExtPeriods %i\n",mac_PIB.macBattLifeExtPeriods);
+//beacon payload
+//////////printfUART("mac_PIB.macBeaconPayloadLenght %i\n",mac_PIB.macBeaconPayloadLenght);
+//////////printfUART("mac_PIB.macBeaconOrder %i\n",mac_PIB.macBeaconOrder);
+//////////printfUART("mac_PIB.macBeaconTxTime %i\n",mac_PIB.macBeaconTxTime);
+//////////printfUART("mac_PIB.macBSN %i\n",mac_PIB.macBSN);
+//////////printfUART("mac_PIB.macCoordExtendedAddress0 %y\n",mac_PIB.macCoordExtendedAddress0);
+//////////printfUART("mac_PIB.macCoordExtendedAddress1 %y\n",mac_PIB.macCoordExtendedAddress1);
+//////////printfUART("mac_PIB.macCoordShortAddress: %x\n",mac_PIB.macCoordShortAddress);
+//////////printfUART("mac_PIB.macDSN: %x\n",mac_PIB.macDSN);
+//////////printfUART("mac_PIB.macGTSPermit: %x\n",mac_PIB.macGTSPermit);
+//////////printfUART("mac_PIB.macMaxCSMABackoffs: %x\n",mac_PIB.macMaxCSMABackoffs);
+//////////printfUART("mac_PIB.macMinBE: %x\n",mac_PIB.macMinBE);
+//////////printfUART("mac_PIB.macPANId: %x\n",mac_PIB.macPANId);
+//////////printfUART("mac_PIB.macPromiscuousMode: %x\n",mac_PIB.macPromiscuousMode);
+//////////printfUART("mac_PIB.macRxOnWhenIdle: %x\n",mac_PIB.macRxOnWhenIdle);
+//////////printfUART("mac_PIB.macShortAddress: %y\n",mac_PIB.macShortAddress);
+//////////printfUART("mac_PIB.macSuperframeOrder: %x\n",mac_PIB.macSuperframeOrder);
+//////////printfUART("mac_PIB.macTransactionPersistenceTime: %y\n",mac_PIB.macTransactionPersistenceTime);
+
+return;
+}
+
+void list_gts()
+{
+       int i;
+       //////////printfUART("GTS list%i\n", GTS_descriptor_count); 
+       
+       for (i=0; i< 7;i++)
+       {
+               //////////printfUART("GTSID: %i",GTS_db[i].gts_id);     
+               //////////printfUART("start slot: %i",GTS_db[i].starting_slot);
+               //////////printfUART("lenght: %i",GTS_db[i].length);    
+               //////////printfUART("dir: %i",GTS_db[i].direction);    
+               //////////printfUART("DevAddressType: %i",GTS_db[i].DevAddressType);
+               //////////printfUART("expiration: %i \n",GTS_db[i].expiration);
+       }
+       
+}
+
+void list_my_gts()
+{
+atomic{
+               //////////printfUART("SEND GTS s_GTSss: %i s_GTS_length: %i\n",s_GTSss,s_GTS_length);   
+               
+               //////////printfUART("RECEIVE GTS r_GTSss: %i r_GTS_length: %i\n",r_GTSss,r_GTS_length); 
+}
+}
+*/
+
+void list_indirect_trans_buffer()
+{
+       int i;
+       printfUART("indirect_trans_count %i\n", indirect_trans_count); 
+       
+       for (i=0; i< INDIRECT_BUFFER_SIZE;i++)
+       {
+               printfUART("hand: %i \n",indirect_trans_queue[i].handler); 
+               
+               //printfUART("start slot: %i",GTS_db[i].starting_slot);
+
+       }
+       
+}
+/*
+void list_gts_null()
+{
+       int i;
+       //////////printfUART("GTS null list%i\n", GTS_null_descriptor_count); 
+       
+       for (i=0; i< GTS_null_descriptor_count;i++)
+       {
+               ////////////printfUART("GTSID: %i",GTS_null_db[i].gts_id);      
+               //////////printfUART("start slot: %i",GTS_null_db[i].starting_slot);
+               //////////printfUART("lenght: %i",GTS_null_db[i].length);       
+               ////////////printfUART("dir: %i",GTS_null_db[i].direction);     
+               //////////printfUART("DevAddressType: %i \n",GTS_null_db[i].DevAddressType); 
+               //////////printfUART("persistencetime: %i \n",GTS_null_db[i].persistencetime); 
+       }
+       
+}
+
+*/
+
+
+}
+
index f8004b2ce871912fc0eadbb52d9fb1732115a127..d53c9cbf1aa00a41a9183880ead2192984a535fd 100644 (file)
@@ -105,13 +105,18 @@ enum{
 };
 
 //channel scan enumerations
+#ifndef TKN154_MAC
 enum{
        ED_SCAN = 0x00,
        ACTIVE_SCAN = 0x01,
        PASSIVE_SCAN = 0x02,
        ORPHAN_SCAN = 0x03
 };
-
-
+#else
+enum{
+       ED_SCAN = 0x00
+}
+#endif
+//
 #endif
 
index 55edac20ee0ed5c45973a6071c642cec86f0aa1b..d06d4ae4d73d99d3334bf1e53c74cf39014b224a 100644 (file)
@@ -1,4 +1,4 @@
-COMPONENT=NWK
+COMPONENT=NWKC
 
 PFLAGS +=      -I$(TOSROOT)/tos/ieee802154/includes \
                        -I$(TOSROOT)/tos/ieee802154/mac \
diff --git a/tos/lib/net/zigbee/ieee802154/nwk/NWK.nc b/tos/lib/net/zigbee/ieee802154/nwk/NWK.nc
deleted file mode 100644 (file)
index a54e271..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-#include <Timer.h>
-
-#include "phy_const.h"
-#include "phy_enumerations.h"
-#include "mac_const.h"
-#include "mac_enumerations.h"
-#include "mac_func.h"
-
-#include "nwk_func.h"
-#include "nwk_enumerations.h"
-#include "nwk_const.h"
-
-
-configuration NWK {
-
-       //provides
-       
-       //NLDE NWK data service  
-       
-       provides interface NLDE_DATA;
-       
-       
-       //NLME NWK Management service
-       
-       provides interface NLME_NETWORK_FORMATION;
-       provides interface NLME_NETWORK_DISCOVERY;
-       provides interface NLME_START_ROUTER;
-       provides interface NLME_JOIN;
-       provides interface NLME_LEAVE;
-       
-       /*     
-       provides interface NLME_PERMIT_JOINING;
-       provides interface NLME_DIRECT_JOIN;            
-       provides interface NLME_RESET;
-       */
-       provides interface NLME_SYNC;
-       
-       provides interface NLME_GET;
-       provides interface NLME_SET;
-
-}
-implementation {
-
-  components MainC;
-  MainC.SoftwareInit -> NWKM;
-  
-  components LedsC;
-  components NWKM;
-       
-  components Mac;
-  
-  NWKM.Leds -> LedsC;
-   
-   
-       components RandomC;
-       NWKM.Random -> RandomC;
-   
-   
-  //MAC interfaces
-  
-  NWKM.MLME_START -> Mac.MLME_START;
-  
-  NWKM.MLME_GET ->Mac.MLME_GET;
-  NWKM.MLME_SET ->Mac.MLME_SET;
-  
-  NWKM.MLME_BEACON_NOTIFY ->Mac.MLME_BEACON_NOTIFY;
-  NWKM.MLME_GTS -> Mac.MLME_GTS;
-  
-  NWKM.MLME_ASSOCIATE->Mac.MLME_ASSOCIATE;
-  NWKM.MLME_DISASSOCIATE->Mac.MLME_DISASSOCIATE;
-  
-  NWKM.MLME_ORPHAN->Mac.MLME_ORPHAN;
-  NWKM.MLME_SYNC->Mac.MLME_SYNC;
-  NWKM.MLME_SYNC_LOSS->Mac.MLME_SYNC_LOSS;
-  NWKM.MLME_RESET->Mac.MLME_RESET;
-  
-  NWKM.MLME_SCAN->Mac.MLME_SCAN;
-  
-  
-  NWKM.MCPS_DATA->Mac.MCPS_DATA;
-       
-       
-       
-       //NLDE NWK data service  
-       NLDE_DATA=NWKM;
-       
-       //NLME NWK Management service
-       NLME_NETWORK_FORMATION=NWKM;
-       NLME_NETWORK_DISCOVERY=NWKM;
-       
-       NLME_START_ROUTER=NWKM;
-       
-       NLME_JOIN=NWKM;
-       NLME_LEAVE=NWKM;
-       
-       /*
-       NLME_PERMIT_JOINING=NWKM;
-       NLME_DIRECT_JOIN=NWKM;
-       NLME_RESET=NWKM;
-       */
-       NLME_SYNC=NWKM;
-       NLME_GET=NWKM;
-       NLME_SET=NWKM;
-         
-         
-}
diff --git a/tos/lib/net/zigbee/ieee802154/nwk/NWKC.nc b/tos/lib/net/zigbee/ieee802154/nwk/NWKC.nc
new file mode 100644 (file)
index 0000000..923d468
--- /dev/null
@@ -0,0 +1,141 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+#include <Timer.h>
+
+#ifndef TKN154_MAC
+#endif
+#include "phy_const.h"
+#include "phy_enumerations.h"
+#include "mac_const.h"
+
+
+
+#include "mac_enumerations.h"
+#include "mac_func.h"
+#include "nwk_func.h"
+#include "nwk_enumerations.h"
+#include "nwk_const.h"
+
+
+configuration NWKC {
+
+       //provides
+       
+       //NLDE NWK data service  
+       
+       provides interface NLDE_DATA;
+       
+       
+       //NLME NWK Management service
+       
+       provides interface NLME_NETWORK_FORMATION;
+       provides interface NLME_NETWORK_DISCOVERY;
+       provides interface NLME_START_ROUTER;
+       provides interface NLME_JOIN;
+       provides interface NLME_LEAVE;
+       
+       /*     
+       provides interface NLME_PERMIT_JOINING;
+       provides interface NLME_DIRECT_JOIN;    */
+       provides interface NLME_RESET;
+       
+       provides interface NLME_SYNC;
+       
+       provides interface NLME_GET;
+       provides interface NLME_SET;
+
+}
+implementation {
+
+  components MainC;
+  MainC.SoftwareInit -> NWKP;
+  
+  components LedsC;
+  components NWKP;
+       
+
+
+
+  NWKP.Leds -> LedsC;
+   
+   
+       components RandomC;
+       NWKP.Random -> RandomC;
+
+
+  //MAC interfaces
+#ifndef TKN154_MAC
+
+  components MacC;
+
+  NWKP.MLME_START -> MacC.MLME_START;
+  
+  NWKP.MLME_GET ->MacC.MLME_GET;
+  NWKP.MLME_SET ->MacC.MLME_SET;
+  
+  NWKP.MLME_BEACON_NOTIFY ->MacC.MLME_BEACON_NOTIFY;
+  NWKP.MLME_GTS -> MacC.MLME_GTS;
+  
+  NWKP.MLME_ASSOCIATE->MacC.MLME_ASSOCIATE;
+  NWKP.MLME_DISASSOCIATE->MacC.MLME_DISASSOCIATE;
+  
+  NWKP.MLME_ORPHAN->MacC.MLME_ORPHAN;
+  NWKP.MLME_SYNC->MacC.MLME_SYNC;
+  NWKP.MLME_SYNC_LOSS->MacC.MLME_SYNC_LOSS;
+  NWKP.MLME_RESET->MacC.MLME_RESET;
+  NWKP.MLME_SCAN->MacC.MLME_SCAN;
+  
+  NWKP.MCPS_DATA->MacC.MCPS_DATA;
+#else
+
+
+  components WrapperC;
+  NWKP.MLME_RESET->WrapperC.OPENZB_MLME_RESET;
+  NWKP.MLME_START -> WrapperC.OPENZB_MLME_START;
+  
+  NWKP.MLME_GET ->WrapperC.OPENZB_MLME_GET;
+  NWKP.MLME_SET ->WrapperC.OPENZB_MLME_SET;
+  
+  NWKP.MLME_BEACON_NOTIFY ->WrapperC.OPENZB_MLME_BEACON_NOTIFY;
+  NWKP.MLME_GTS -> WrapperC.OPENZB_MLME_GTS;
+  
+  NWKP.MLME_ASSOCIATE->WrapperC.OPENZB_MLME_ASSOCIATE;
+  NWKP.MLME_DISASSOCIATE->WrapperC.OPENZB_MLME_DISASSOCIATE;
+  
+  NWKP.MLME_ORPHAN->WrapperC.OPENZB_MLME_ORPHAN;
+  NWKP.MLME_SYNC->WrapperC.OPENZB_MLME_SYNC;
+  NWKP.MLME_SYNC_LOSS->WrapperC.OPENZB_MLME_SYNC_LOSS;
+  NWKP.MLME_SCAN->WrapperC.OPENZB_MLME_SCAN;
+  
+  NWKP.MCPS_DATA->WrapperC.OPENZB_MCPS_DATA;
+#endif
+
+///////////////
+       
+       //NLDE NWK data service  
+       NLDE_DATA=NWKP;
+       
+       //NLME NWK Management service
+       NLME_NETWORK_FORMATION=NWKP;
+       NLME_NETWORK_DISCOVERY=NWKP;
+       
+       NLME_START_ROUTER=NWKP;
+       
+       NLME_JOIN=NWKP;
+       NLME_LEAVE=NWKP;
+       
+       /*
+       NLME_PERMIT_JOINING=NWKP;
+       NLME_DIRECT_JOIN=NWKP;*/
+       NLME_RESET=NWKP;
+       
+       NLME_SYNC=NWKP;
+       NLME_GET=NWKP;
+       NLME_SET=NWKP;
+         
+         
+}
diff --git a/tos/lib/net/zigbee/ieee802154/nwk/NWKM.nc b/tos/lib/net/zigbee/ieee802154/nwk/NWKM.nc
deleted file mode 100644 (file)
index be24131..0000000
+++ /dev/null
@@ -1,1501 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-#include <Timer.h>
-#include "printfUART.h"
-
-module NWKM {
-       
-//uses
-       uses interface Leds;
-
-       //MAC interfaces
-       
-       uses interface MLME_START;
-       
-       uses interface MLME_GET;
-       uses interface MLME_SET;
-       
-       uses interface MLME_BEACON_NOTIFY;
-       uses interface MLME_GTS;
-       
-       uses interface MLME_ASSOCIATE;
-       uses interface MLME_DISASSOCIATE;
-       
-       uses interface MLME_ORPHAN;
-       
-       uses interface MLME_SYNC;
-       uses interface MLME_SYNC_LOSS;
-       
-       uses interface MLME_RESET;
-       
-       uses interface MLME_SCAN;
-       
-       
-       uses interface MCPS_DATA;
-
-
-       uses interface Random;
-
-//provides
-
-       provides interface Init;
-       provides interface NLDE_DATA;
-
-       //NLME NWK Management services
-    provides interface NLME_NETWORK_FORMATION;
-       provides interface NLME_NETWORK_DISCOVERY;
-       provides interface NLME_START_ROUTER;
-       provides interface NLME_JOIN;
-       provides interface NLME_LEAVE;
-       provides interface NLME_SYNC;
-       /*  
-       provides interface NLME_PERMIT_JOINING;
-       provides interface NLME_DIRECT_JOIN;
-       provides interface NLME_RESET;
-*/     
-       provides interface NLME_GET;
-       provides interface NLME_SET;
-
-  
-}
-implementation {
-
-
-       nwkIB nwk_IB;
-       
-       uint8_t device_type = END_DEVICE;
-       
-/*****************************************************/
-/*************Neighbourtable Variables****************/
-/*****************************************************/ 
-
-       //neighbour table array:
-       neighbortableentry neighbortable[NEIGHBOUR_TABLE_SIZE];
-       //number of neigbourtable entries:
-       uint8_t neighbour_count;
-       //the index of the parents neighbortable entry
-       uint8_t parent;
-       
-
-/*****************************************************/
-/****************ASSOCIATION Variables********************/
-/*****************************************************/ 
-
-       //CURRENT NETWORK ADDRESS
-       uint16_t networkaddress=0x0000;
-
-       //COORDINATOR
-       //address assignement variables
-       uint8_t depth=0;
-       uint8_t cskip=0;
-       
-       uint8_t cskip_routing=0;
-
-       //neighbour table parent index
-       uint8_t parent_index;
-
-       //NON COORDINATOR
-
-       //current pan characteristics
-       uint16_t panid;
-       uint8_t beaconorder;
-       uint8_t superframeorder;
-       
-       //next child router address
-       uint16_t next_child_router_address;
-       uint8_t number_child_router=0x01;
-       uint8_t number_child_end_devices=0x01;
-/*****************************************************/
-/****************Integer Variables********************/
-/*****************************************************/ 
-
-       uint8_t joined=0;
-       uint8_t sync_loss=0;
-       //uint8_t synchronizing=0;
-       uint8_t syncwait;
-       
-       
-       //USED AFTER DE SCAN //GIVE SOME TIME TO THE DEVICE TO SYNC WITH THE PARENT
-       uint8_t received_beacon_count=0;
-       
-       uint8_t go_associate =0;
-       
-       PANDescriptor pan_des;
-       uint32_t coordinator_addr[2];
-/******************************************************/
-/*********NEIGHBOuRTABLE  MANAGEMENT FUNCTIONS*********/
-/******************************************************/ 
-
-       void init_nwkIB();
-       
-       uint8_t check_neighbortableentry(uint8_t addrmode,uint32_t Extended_Address0,uint32_t Extended_Address1);
-       
-       void add_neighbortableentry     (uint16_t PAN_Id,uint32_t Extended_Address0,uint32_t Extended_Address1,uint32_t Network_Address,uint8_t Device_Type,uint8_t Relationship);
-       void update_neighbortableentry (uint16_t PAN_Id,uint32_t Extended_Address0,uint32_t Extended_Address1,uint32_t Network_Address,uint8_t Device_Type,uint8_t Relationship);       
-       
-       uint8_t find_suitable_parent();
-       
-       uint16_t Cskip(uint8_t d);
-       
-       uint16_t nexthopaddress(uint16_t destinationaddress,uint8_t d);
-       
-       void list_neighbourtable();
-
-
-
- command error_t Init.init() {
-       
-       printfUART_init();//make the possibility to print
-               
-       init_nwkIB();
-       
-       nwk_IB.nwkSequenceNumber=call Random.rand16();
-  
-       return SUCCESS;
- }
-
-
-/*****************************************************************************************************/  
-/**************************************MLME-SCAN*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
-{
-//FAULT-TOLERANCE
-
-//the device channel scan ends with a scan confirm containing a list of the PANs (beacons received during the scan) 
-
-       int i;
-       uint8_t max_lqi=0;
-       uint8_t best_pan_index=0;
-       
-       
-       networkdescriptor networkdescriptorlist[1];
-       
-       
-       //call Leds.redOff();
-       
-       printfUART("4 rec scan\n", "");
-       
-       //printfUART("MLME_SCAN.confirm %i\n", ScanType);
-       
-       if (ScanType == ORPHAN_SCAN)
-       {
-               printfUART("new scan \n", "");
-       
-               call MLME_SCAN.request(PASSIVE_SCAN,0xFFFFFFFF,7);
-               return SUCCESS;
-       }
-       
-       
-       
-       if(ScanType == ED_SCAN)
-       {
-               for(i=0;i<ResultListSize;i++)
-               {
-                       printfUART("ED SCAN %i %i\n", (0x0A + i),EnergyDetectList[i]);
-               }
-               return SUCCESS;
-       }
-       
-       for (i=0; i<ResultListSize;i++)
-       {               /*
-                       printfUART("cord id %i", PANDescriptorList[i].CoordPANId);
-                       printfUART("CoordAddress %i", PANDescriptorList[i].CoordAddress);
-                       printfUART("LogicalChannel %i", PANDescriptorList[i].LogicalChannel);
-                       printfUART("SuperframeSpec %i", PANDescriptorList[i].SuperframeSpec);
-                       printfUART("lqi %i\n", PANDescriptorList[i].lqi);
-                       */
-               if(max_lqi < PANDescriptorList[i].lqi)
-               {
-                       max_lqi =PANDescriptorList[i].lqi;
-                       best_pan_index = i;
-               }
-       }
-       
-       printfUART("SELECTED cord id %i", PANDescriptorList[best_pan_index].CoordPANId);
-       printfUART("CoordAddress %i", PANDescriptorList[best_pan_index].CoordAddress);
-       printfUART("LogicalChannel %i", PANDescriptorList[best_pan_index].LogicalChannel);
-       printfUART("SuperframeSpec %i", PANDescriptorList[best_pan_index].SuperframeSpec);
-       printfUART("lqi %i\n", PANDescriptorList[best_pan_index].lqi);
-       
-       
-       
-       /*
-       
-       coordinator_addr[0] = 0x00000001;
-       
-       coordinator_addr[1] = (uint32_t)PANDescriptorList[best_pan_index].CoordAddress;
-       
-       //pan_des = PANDescriptorList[best_pan_index];
-
-       
-       //BUILD the PAN descriptor of the COORDINATOR
-       //assuming that the adress is short
-       pan_des.CoordAddrMode = SHORT_ADDRESS;
-       pan_des.CoordPANId = PANDescriptorList[best_pan_index].CoordAddress;
-       pan_des.CoordAddress0=0x00000000;
-       pan_des.CoordAddress1=0x00000000;
-       pan_des.LogicalChannel=PANDescriptorList[best_pan_index].LogicalChannel;
-       //superframe specification field
-       pan_des.SuperframeSpec = PANDescriptorList[best_pan_index].SuperframeSpec;
-       
-       pan_des.GTSPermit=0x01;
-       pan_des.LinkQuality=0x00;
-       pan_des.TimeStamp=0x000000;
-       pan_des.SecurityUse=0;
-       pan_des.ACLEntry=0x00;
-       pan_des.SecurityFailure=0x00;
-       
-       */
-
-       
-       
-       printfUART("5 en sync %x \n", PANDescriptorList[best_pan_index].LogicalChannel);
-       // the sync enables the TimerAsync events, in order to enable the synchronization with the PAN coordinator
-       call MLME_SYNC.request(PANDescriptorList[best_pan_index].LogicalChannel,0);
-       
-       
-       
-       //The networkdescriptorlist must contain information about every network that was heard
-       
-       //make NetworkDescriptorList out of the PanDescriptorList
-
-
-    printfUART("6 add neigh\n", "");
-
-       networkdescriptorlist[0].PANId=PANDescriptorList[best_pan_index].CoordPANId;
-       networkdescriptorlist[0].LogicalChannel=LOGICAL_CHANNEL;
-       networkdescriptorlist[0].StackProfile=0x00;
-       networkdescriptorlist[0].ZigBeeVersion=0x01;
-       networkdescriptorlist[0].BeaconOrder=7;
-       networkdescriptorlist[0].SuperframeOrder=6;
-       networkdescriptorlist[0].PermitJoining=1;
-
-       add_neighbortableentry(networkdescriptorlist[0].PANId,0x00000000,0x00000000,PANDescriptorList[best_pan_index].CoordAddress,COORDINATOR,NEIGHBOR_IS_PARENT);
-       
-       signal NLME_NETWORK_DISCOVERY.confirm(1,networkdescriptorlist, NWK_SUCCESS);
-       
-       
-       
-       return SUCCESS;
-}
-
-/*****************************************************************************************************/  
-/**************************************MLME-ORPHAN****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
-{
-
-       
-               
-               return 0x0000;
-       }
-
-/*****************************************************************************************************/  
-/**************************************MLME-RESET*****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_RESET.confirm(uint8_t status)
-{
-
-
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-SYNC-LOSS*************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
-{
-       ////printfUART("MLME_SYNC_LOSS.indication\n", ""); 
-       sync_loss = 1;
-       syncwait=1;
-       //signal NLME_SYNC.indication();
-/*
-
-printfUART("SL\n","");
-               
-               call MLME_SCAN.request(ORPHAN_SCAN,0xFFFFFFFF,7);
-*/
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-GTS*******************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
-{
-
-
-
-       return SUCCESS;
-}
-
-event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
-{
-
-
-
-       return SUCCESS;
-}
-
-/*****************************************************************************************************/  
-/**************************************MLME-BEACON NOTIFY*********************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
-{
-       
-       uint32_t destinaddress[2];
-       printfUART("BN\n", "");
-
-       
-       if (go_associate==1)
-       {
-               received_beacon_count++;
-               
-               printfUART("bn %i\n", received_beacon_count);
-               
-               if (received_beacon_count==5)
-               {
-                               printfUART("sa \n", "");
-                               
-                               go_associate=0;
-                               //call MLME_ASSOCIATE.request(pan_des.LogicalChannel,SHORT_ADDRESS,pan_des.CoordPANId,coordinator_addr,0x00,0x00);
-               
-               destinaddress[0]=0x00000000;
-               destinaddress[1]=0x00000000;
-               
-               
-               call MLME_ASSOCIATE.request(LOGICAL_CHANNEL,SHORT_ADDRESS,0x1234,destinaddress, set_capability_information(0x00,0x00,0x00,0x00,0x00,0x01),0);
-               
-               }
-               
-       }
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-START*****************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_START.confirm(uint8_t status)
-{
-               ////printfUART("MLME_START.confirm\n", "");
-       if (device_type==COORDINATOR)
-       {
-               signal NLME_NETWORK_FORMATION.confirm(status);
-               joined=1;
-       }
-       else
-       {
-               signal NLME_START_ROUTER.confirm(status);
-       }
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**********************                                  MLME-SET                          ******************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
-{
-       
-       
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/*************************                     MLME-GET                            ******************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
-{
-       
-       
-       return SUCCESS;
-}
-       
-/*****************************************************************************************************/  
-/**************************************MLME-ASSOCIATE*************************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
-{
-       
-       //notification that an other device wants to associate
-       //THIS DEVICE IS EITHER A COORDINATOR OR A ROUTER
-               
-       uint8_t cindex=0;
-
-atomic{
-
-       //check the neighbour table
-       cindex = check_neighbortableentry(LONG_ADDRESS,DeviceAddress[0] , DeviceAddress[1]);
-       
-
-       if( cindex > 0 )
-       {
-               call MLME_ASSOCIATE.response(DeviceAddress,neighbortable[cindex - 1].Network_Address,MAC_SUCCESS,0);
-       }
-       else
-       {       
-                       if(nwk_IB.nwkAvailableAddresses > 0)
-                       {
-                       
-                               //verify if the device is associating as a router or an end device
-                               if ( get_alternate_PAN_coordinator(CapabilityInformation) == 1)
-                               {
-                                       //add device to the neighbour table
-                                       add_neighbortableentry(panid,DeviceAddress[0],DeviceAddress[1],next_child_router_address,ROUTER,NEIGHBOR_IS_CHILD);
-                                       
-                                       printfUART("An_cr %x\n",next_child_router_address);
-
-                                       //send response, this shall lead to confirm in child device
-                                       call MLME_ASSOCIATE.response(DeviceAddress,next_child_router_address,MAC_SUCCESS,0);
-                                       //calculate the next address
-                                       next_child_router_address = networkaddress + ((number_child_router-1) * cskip) +1 ;
-                                       //increment the number of associated routers
-                                       number_child_router++;
-                                       //decrese the number of available addresses //the available addresses are influenced by the network configurations
-                                       nwk_IB.nwkAvailableAddresses--;
-                                       
-                                       printfUART("Dn_cr %x\n",next_child_router_address);
-                               }
-                               else
-                               {
-                                       //verify if its possible to associate children in the address space
-                                       //the number of end devices must be greater than 1 and lesser or iqual to maximum children minus maximum routers
-                                       if (number_child_end_devices > 1 && number_child_end_devices > (MAXCHILDREN - MAXROUTERS))
-                                       {
-                                               call MLME_ASSOCIATE.response(DeviceAddress,0xffff,CMD_RESP_PAN_CAPACITY,0);
-                                               //return SUCCESS;
-                                       }
-                                       else
-                                       {
-                                               //CHECK COMMENTED ON SHORT VERSION
-                                               add_neighbortableentry(panid,DeviceAddress[0],DeviceAddress[1],nwk_IB.nwkNextAddress,END_DEVICE,NEIGHBOR_IS_CHILD);
-                                               //send response, this shall lead to confirm in child device
-                                               call MLME_ASSOCIATE.response(DeviceAddress,nwk_IB.nwkNextAddress,MAC_SUCCESS,0);
-                                               
-                                               nwk_IB.nwkNextAddress=nwk_IB.nwkNextAddress + nwk_IB.nwkAddressIncrement;
-                                               
-                                               number_child_end_devices++;
-                                               
-                                               nwk_IB.nwkAvailableAddresses--;
-                                               
-                                       }
-                               }
-                               
-                               if (nwk_IB.nwkAvailableAddresses == 0 )
-                               {
-                                       call MLME_SET.request(MACASSOCIATIONPERMIT,(uint8_t *)0x00000000);
-                               }
-                       }
-                       else
-                       {
-                               //if there are no available addresses the coordinator/router shall not respond to the association request
-                               call MLME_ASSOCIATE.response(DeviceAddress,0xffff,CMD_RESP_PAN_CAPACITY,0);
-                       }
-       }
-}
-       return SUCCESS;
-}
-
-event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
-{
-
-       uint8_t v_temp[2];
-       ////printfUART("MLME_ASSOCIATE.confirm\n","");
-
-       if (AssocShortAddress == 0xffff)
-       {
-               //association failed
-               //printfUART("nwkass fail\n","");
-               signal NLME_JOIN.confirm(panid,NWK_NOT_PERMITTED);
-       
-       }
-       else
-       {
-       
-               networkaddress = AssocShortAddress;
-               //add_neighbortableentry(panid,DeviceAddress[0],DeviceAddress[1],nwk_IB.nwkNextAddress,END_DEVICE,NEIGHBOR_IS_CHILD);
-               //set the short address
-               
-               if (status == MAC_SUCCESS)
-               {
-                       joined = 0x01;
-                       v_temp[0] = (uint8_t)(networkaddress >> 8);
-                       v_temp[1] = (uint8_t)(networkaddress );
-
-                       //call MLME_SET.request(MACSHORTADDRESS,(uint32_t*)(uint32_t)&networkaddress);
-                       call MLME_SET.request(MACSHORTADDRESS,v_temp);
-                       
-                       signal NLME_JOIN.confirm(panid, NWK_SUCCESS);
-               }
-               else
-               {
-                       signal NLME_JOIN.confirm(panid,NWK_NOT_PERMITTED);
-               }
-       }
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/**************************************MLME-DISASSOCIATE**********************************************/
-/*****************************************************************************************************/ 
-event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
-{
-       ////printfUART("MLME_DISASSOCIATE.indication:SUCCESS\n", "");
-       signal NLME_LEAVE.confirm(DeviceAddress, NWK_SUCCESS);
-
-       return SUCCESS;
-}
-  
-event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
-{
-       if (status == MAC_SUCCESS)
-       {
-               signal NLME_LEAVE.confirm(0, status);
-               ////printfUART("MLME_DISASSOCIATE.confirm:SUCCESS\n", "");
-       }
-       else
-       {
-               signal NLME_LEAVE.confirm(0, NWK_LEAVE_UNCONFIRMED);
-               ////printfUART("MLME_DISASSOCIATE.confirm:leave unconfirmed\n", "");
-       }
-
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/*****************************************************************************************************/  
-/****************                                      MCPS EVENTS                              *************************************/
-/*****************************************************************************************************/ 
-/*****************************************************************************************************/  
-
-
-/*****************************************************************************************************/  
-/*********************                                 MCPS-DATA                          ***************************************/
-/*****************************************************************************************************/ 
-event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
-{
-       ////printfUART("MCPS_DATA.confirm\n", "");
-       signal NLDE_DATA.confirm(1,status);
-       
-       return SUCCESS;
-}  
-event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
-{
-       uint8_t payload[100];
-       uint32_t route_destination_address[2];
-       uint32_t net_addr[2];
-       uint8_t next_hop_index;
-       
-       routing_fields *routing_fields_ptr;
-       routing_fields_ptr = (routing_fields *)&msdu[0];
-       
-       net_addr[1] =(uint32_t) networkaddress;
-       net_addr[0]=0x00000000;
-
-       if ( routing_fields_ptr->destination_address == networkaddress)
-       {
-               //I am the destination
-               memcpy(&payload,&msdu[8],(msduLength-8)*sizeof(uint8_t));
-               
-               //pass data on to APL layer
-               signal NLDE_DATA.indication(routing_fields_ptr->source_address,(uint16_t)(msduLength-8),payload, mpduLinkQuality);
-               
-               return SUCCESS; 
-       }
-       else
-       {
-               //I am not the destination
-               if(device_type != COORDINATOR)
-               {
-                       if( (networkaddress < routing_fields_ptr->destination_address) && (routing_fields_ptr->destination_address < (networkaddress + cskip_routing ) ) )
-                       {
-                               printfUART("route down to appropriate child\n", "");
-                               
-                               //check if destination is one of my children
-                               next_hop_index = check_neighbortableentry(SHORT_ADDRESS,(uint32_t)routing_fields_ptr->destination_address,0x00000000);
-
-                               if (next_hop_index == 0)
-                               {
-                                       //destination is not my child
-                                       route_destination_address[0]=0x00000000;
-                                       route_destination_address[1]=nexthopaddress(routing_fields_ptr->destination_address,depth);
-                               }
-                               else
-                               {
-                                       //Im routing to my child
-                                       route_destination_address[0]=0x00000000;
-                                       route_destination_address[1]=neighbortable[next_hop_index-1].Network_Address;
-                               }
-                               //send message
-                               call MCPS_DATA.request(SHORT_ADDRESS, panid, net_addr, SHORT_ADDRESS, DestPANId, route_destination_address, msduLength, msdu,1,set_txoptions(1,0,0,0));
-                       }
-                       else
-                       {
-                               
-                               //changes to meet with the BEACON SYNCHRONIZATION requirements
-                               //route up to the parent
-                               atomic{
-                                       route_destination_address[0]=0x00000000;
-                                       route_destination_address[1]=neighbortable[parent].Network_Address;
-
-                                       call MCPS_DATA.request(SHORT_ADDRESS, panid, net_addr, SHORT_ADDRESS, DestPANId, route_destination_address, msduLength, msdu,1,set_txoptions_upstream(1,0,0,0,1));
-                               }
-                       }
-               }
-               else
-               {
-                       //I AM THE PAN COORDINATOR
-                       //THE COORDINATOR ALWAYS ROUTES DOWN
-                       
-                       //route down to appropriate child
-                       //check if destination is one of my children
-                       next_hop_index = check_neighbortableentry(SHORT_ADDRESS,(uint32_t)routing_fields_ptr->destination_address,0x00000000);
-                       
-                       if (next_hop_index == 0 )
-                       {
-                               //no entry in neigbortable
-                               //calculate route address
-                               route_destination_address[0]=0x00000000;
-                               route_destination_address[1]=nexthopaddress(routing_fields_ptr->destination_address,depth);
-                                       
-                               call MCPS_DATA.request(SHORT_ADDRESS, panid, net_addr, SHORT_ADDRESS, DestPANId, route_destination_address, msduLength, msdu,1,set_txoptions(1,0,0,0));
-                       }
-                       else
-                       {
-                               //is my child
-                               route_destination_address[0]=0x00000000;
-                               route_destination_address[1]=neighbortable[next_hop_index-1].Network_Address;
-
-                               call MCPS_DATA.request(SHORT_ADDRESS, panid, net_addr, SHORT_ADDRESS, DestPANId, route_destination_address, msduLength, msdu,1,set_txoptions(1,0,0,0));
-                       }
-                       
-               }
-               
-               
-       }
-       
-return SUCCESS;
-}
-
-
-/*************************************************************/
-/*******************NLDE IMPLEMENTATION***********************/
-/*************************************************************/
-       
-/*************************************************************/
-/*************************NLDE - DATA*************************/
-/*************************************************************/
-
-//This primitive requests the transfer of a data PDU
-//page 159-161
-
-command error_t NLDE_DATA.request(uint16_t DstAddr, uint16_t NsduLength, uint8_t Nsdu[100], uint8_t NsduHandle, uint8_t Radius, uint8_t DiscoverRoute, uint8_t SecurityEnable)
-{      
-
-       uint32_t srcadd[2];
-       //prefixed size because the devices reset itself when there is an error in the length
-       uint8_t MSDU[100];
-       uint32_t route_destination_address[2];
-       routing_fields *routing_fields_ptr;
-       uint8_t next_hop_index;
-       
-       routing_fields_ptr = (routing_fields *)&MSDU[0];
-       
-       if(joined==0)
-       {       
-               signal NLDE_DATA.confirm(NsduHandle, NWK_INVALID_REQUEST);
-       }
-       else
-       {
-               routing_fields_ptr->frame_control= set_route_frame_control(0x00,0x01,DiscoverRoute,SecurityEnable);
-               routing_fields_ptr->destination_address=DstAddr;
-               routing_fields_ptr->source_address=networkaddress;
-               routing_fields_ptr->radius=Radius;
-               routing_fields_ptr->sequence_number=nwk_IB.nwkSequenceNumber;
-               nwk_IB.nwkSequenceNumber++;
-               
-               memcpy(&MSDU[8],&Nsdu[0],NsduLength*sizeof(uint8_t));
-
-               srcadd[0] = 0x00000000;
-               srcadd[1] = (uint32_t)networkaddress;
-               
-               if (device_type == END_DEVICE)
-               {
-                       //if the device is an end device always sends the message to the parent
-
-                       route_destination_address[0]=0x00000000;
-                       route_destination_address[1]=neighbortable[parent].Network_Address;
-                                                                                                                                                                                                                                                                                                               //ack
-                       call MCPS_DATA.request(SHORT_ADDRESS, panid, srcadd, SHORT_ADDRESS,panid, route_destination_address, (NsduLength + 8), MSDU,1,set_txoptions(1,0,0,0));
-                       return SUCCESS;
-               }
-               
-               //send message if the device is the COORDINATOR or a ROUTER
-               if( (networkaddress < routing_fields_ptr->destination_address) && (routing_fields_ptr->destination_address < (networkaddress + cskip_routing ) ) )
-               {
-                       //route down to appropriate child
-                       //check if destination is one of my children
-                       next_hop_index = check_neighbortableentry(SHORT_ADDRESS,(uint32_t)routing_fields_ptr->destination_address,0x00000000);
-
-                       if (next_hop_index == 0)
-                       {
-                               //destination is not my child
-                               route_destination_address[0]=0x00000000;
-                               route_destination_address[1]=nexthopaddress(routing_fields_ptr->destination_address,depth);
-                       }
-                       else
-                       {
-                               //Im routing to my child
-                               route_destination_address[0]=0x00000000;
-                               route_destination_address[1]=neighbortable[next_hop_index-1].Network_Address;
-                       }
-                       //send the data                                                                                                                                                                                                                                                                 //ack
-                       call MCPS_DATA.request(SHORT_ADDRESS, panid, srcadd, SHORT_ADDRESS, panid, route_destination_address, (NsduLength + 8), MSDU,1,set_txoptions(1,0,0,0));
-               }
-               else
-               {
-                       //route up to parent
-                       atomic{
-                               route_destination_address[0]=0x00000000;
-                               route_destination_address[1]=neighbortable[parent].Network_Address;
-                                                                                                                                                                                                                                                                                                       //ack
-                               call MCPS_DATA.request(SHORT_ADDRESS, panid, srcadd, SHORT_ADDRESS, panid, route_destination_address, (NsduLength + 8), MSDU,1,set_txoptions_upstream(1,0,0,0,1));
-                       }
-               }
-               
-       }
-       
-       return SUCCESS;
-}
-
-/*************************************************************/
-/*******************NLME IMPLEMENTATION***********************/
-/*************************************************************/
-
-/*************************************************************/
-/*******************NLME - START - ROUTER*********************/
-/*************************************************************/
-
-//This primitive allows the NHL of a ZigBee Router to initialize or change its superframe configuration.
-//p171 and 210
-command error_t NLME_START_ROUTER.request(uint8_t BeaconOrder, uint8_t SuperframeOrder, bool BatteryLifeExtension,uint32_t StartTime)
-{      
-       //printfUART("NLME_START_ROUTER.request\n", "");
-       
-       device_type = ROUTER;
-       
-       if(TYPE_DEVICE == ROUTER)
-       {
-       
-               //assign current BO and SO
-               beaconorder = BeaconOrder;
-               superframeorder = SuperframeOrder;
-       
-               call MLME_SET.request(MACBEACONORDER, (uint8_t *)&BeaconOrder);
-               
-               call MLME_SET.request(MACSUPERFRAMEORDER, (uint8_t *)&SuperframeOrder);
-               
-               //*******************************************************
-               //***********SET PAN VARIABLES***************************
-               depth=DEVICE_DEPTH;
-               
-               nwk_IB.nwkAvailableAddresses=AVAILABLEADDRESSES;
-               nwk_IB.nwkAddressIncrement= ADDRESSINCREMENT;
-               
-               nwk_IB.nwkMaxChildren=MAXCHILDREN;      //number of children a device is allowed to have on its current network
-               nwk_IB.nwkMaxDepth=MAXDEPTH;    //the depth a device can have
-               nwk_IB.nwkMaxRouters=MAXROUTERS;
-               
-               cskip = Cskip(depth);
-               
-               cskip_routing = Cskip(depth -1);
-               
-               nwk_IB.nwkNextAddress = networkaddress + (cskip * nwk_IB.nwkMaxRouters) + nwk_IB.nwkAddressIncrement;
-       
-               next_child_router_address = networkaddress +((number_child_router-1) * cskip) +1;
-       
-               
-               number_child_router++;
-               
-               
-               printfUART("cskip  %d\n", cskip);
-               printfUART("C %d D %d r %d\n", MAXCHILDREN,MAXDEPTH,MAXROUTERS);
-       
-               //  command error_t request(uint32_t PANId, uint8_t LogicalChannel, uint8_t BeaconOrder, uint8_t SuperframeOrder,bool PANCoordinator,bool BatteryLifeExtension,bool CoordRealignment,bool SecurityEnable);
-               call MLME_START.request(panid,LOGICAL_CHANNEL,BeaconOrder, SuperframeOrder, 0, 0,0,0,StartTime);
-               
-       }
-       else
-       {
-       
-               signal NLME_START_ROUTER.confirm(NWK_INVALID_REQUEST);
-               
-       }
-       return SUCCESS;
-}
-
-
-/*************************************************************/
-/******************NLME - NETWORK - FORMATION*****************/
-/*************************************************************/
-
-//This primitive allows the NHL to request to start a ZigBee network with itself as the coordinator
-//Page 167-169
-command error_t NLME_NETWORK_FORMATION.request(uint32_t ScanChannels, uint8_t ScanDuration, uint8_t BeaconOrder, uint8_t SuperframeOrder, uint16_t PANId, bool BatteryLifeExtension)
-{
-
-       uint8_t v_temp[6];
-
-       v_temp[0] = 0x06;
-       
-       device_type = COORDINATOR;
-       //device_type = ROUTER;
-       
-       call MLME_SET.request(MACMAXBEACONPAYLOADLENGTH,v_temp);
-       
-       //protocol ID
-       v_temp[0] = 0x00;
-       //uint8_t nwk_payload_profile_protocolversion(uint8_t stackprofile,uint8_t nwkcprotocolversion)
-       v_temp[1] = nwk_payload_profile_protocolversion(0x00,0x00);
-       //uint8_t nwk_payload_capacity(uint8_t routercapacity,uint8_t devicedepth,uint8_t enddevicecapacity)
-       v_temp[2] = nwk_payload_capacity(0x01,0x00,0x01);
-       
-       //TX OFFSET (3 bytes)
-       v_temp[3] = 0x56;
-       v_temp[4] = 0x34;
-       v_temp[5] = 0x12;
-       
-       
-       call MLME_SET.request(MACBEACONPAYLOAD,v_temp);
-       
-
-       ////printfUART("NLME_NETWORK_FORMATION.request\n", "");
-       //perform an energydetection scan
-       //perform an active scan
-       //and select a suitable channel
-       //panid must be less than or equal to 0x3fff
-       
-       //assign current panid
-       panid=PANId;
-       
-       //assign current BO and SO
-       beaconorder = BeaconOrder;
-       superframeorder = SuperframeOrder;
-       
-       call MLME_SET.request(MACBEACONORDER, (uint8_t *)&BeaconOrder);
-
-       call MLME_SET.request(MACSUPERFRAMEORDER, (uint8_t *)&SuperframeOrder);
-       
-       v_temp[0] = (uint8_t)(PANId >> 8);
-       v_temp[1] = (uint8_t)PANId;
-       
-       call MLME_SET.request(MACPANID, v_temp);
-
-       //static assignement of the coordinator address
-       networkaddress=0x0000;//Network address of the ZC of a network always 0x0000;
-       
-       //////printfUART("setting short addr: %i\n", networkaddress);
-       
-       v_temp[0] = (uint8_t)(networkaddress >> 8);
-       v_temp[1] = (uint8_t)(networkaddress);
-
-       
-       call MLME_SET.request(MACSHORTADDRESS,v_temp);
-       
-       
-       //*******************************************************
-       //***********SET PAN VARIABLES***************************
-       //nwk_IB.nwkNextAddress=networkaddress+0x0001;
-       depth=DEVICE_DEPTH;
-       nwk_IB.nwkAvailableAddresses=AVAILABLEADDRESSES;
-       nwk_IB.nwkAddressIncrement= ADDRESSINCREMENT;
-       
-       nwk_IB.nwkMaxChildren=MAXCHILDREN;      //number of children a device is allowed to have on its current network
-       nwk_IB.nwkMaxDepth=MAXDEPTH;    //the depth a device can have
-       nwk_IB.nwkMaxRouters=MAXROUTERS;
-       
-       cskip = Cskip(depth);
-       
-       cskip_routing = Cskip(depth -1 );
-       
-       nwk_IB.nwkNextAddress = networkaddress + (cskip * nwk_IB.nwkMaxRouters) + nwk_IB.nwkAddressIncrement;
-       
-       next_child_router_address = networkaddress +((number_child_router-1) * cskip) +1;
-       
-       number_child_router++;
-       
-       printfUART("cskip  %d\n", cskip);
-       printfUART("C %d D %d r %d\n", MAXCHILDREN,MAXDEPTH,MAXROUTERS);
-       
-       
-       call MLME_START.request(PANId, LOGICAL_CHANNEL,BeaconOrder ,SuperframeOrder,1,0,0,0,0);
-       
-       return SUCCESS;
-}
-       
-/*************************************************************/
-/***************NLME - NETWORK - DISCOVERY *******************/
-/*************************************************************/
-
-//This primitive allows the next higher layer to request that the NWK layer discover networks currently operating within the POS.
-//p164 and 210
-command error_t NLME_NETWORK_DISCOVERY.request(uint32_t ScanChannels, uint8_t Scanduration)
-{
-       
-       //ISSUE an MLME_SCAN.request to find the available networks
-       //Temporary descover of the network
-       //Channel Scan is not working properly
-       //manually assign the network descriptor
-       
-       /*
-       networkdescriptor networkdescriptorlist[1];
-*/
-       printfUART("2 lauch passive scan\n", "");
-       //The networkdescriptorlist must contain information about every network that was heard
-       
-       //make NetworkDescriptorList out of the PanDescriptorList
-
-    call MLME_SCAN.request(PASSIVE_SCAN,0xFFFFFFFF,7);
-
-/*
-
-       networkdescriptorlist[0].PANId=0x1234;
-       networkdescriptorlist[0].LogicalChannel=LOGICAL_CHANNEL;
-       networkdescriptorlist[0].StackProfile=0x00;
-       networkdescriptorlist[0].ZigBeeVersion=0x01;
-       networkdescriptorlist[0].BeaconOrder=7;
-       networkdescriptorlist[0].SuperframeOrder=6;
-       networkdescriptorlist[0].PermitJoining=1;
-       
-       //temporary assignement on the neighbout table of the suitable PAN coordinator
-       if (DEVICE_DEPTH == 0x01)
-               add_neighbortableentry(networkdescriptorlist[0].PANId,D1_PAN_EXT0,D1_PAN_EXT1,D1_PAN_SHORT,COORDINATOR,NEIGHBOR_IS_PARENT);
-       if (DEVICE_DEPTH == 0x02)
-               add_neighbortableentry(networkdescriptorlist[0].PANId,D2_PAN_EXT0,D2_PAN_EXT1,D2_PAN_SHORT,COORDINATOR,NEIGHBOR_IS_PARENT);
-       if (DEVICE_DEPTH == 0x03)
-               add_neighbortableentry(networkdescriptorlist[0].PANId,D3_PAN_EXT0,D3_PAN_EXT1,D3_PAN_SHORT,COORDINATOR,NEIGHBOR_IS_PARENT);
-       if (DEVICE_DEPTH == 0x04)
-               add_neighbortableentry(networkdescriptorlist[0].PANId,D4_PAN_EXT0,D4_PAN_EXT1,D4_PAN_SHORT,COORDINATOR,NEIGHBOR_IS_PARENT);
-       
-       
-       
-       signal NLME_NETWORK_DISCOVERY.confirm(1,networkdescriptorlist, NWK_SUCCESS);
-*/
-       return SUCCESS;
-}
-
-/*************************************************************/
-/************************NLME - JOIN**************************/
-/*************************************************************/
-//This primitive allows the NHL to request to join a network either through association.
-//p173 and 210
-command error_t NLME_JOIN.request(uint16_t PANId, bool JoinAsRouter, bool RejoinNetwork, uint32_t ScanChannels, uint8_t ScanDuration, uint8_t PowerSource, uint8_t RxOnWhenIdle, uint8_t MACSecurity)
-{      
-
-       //Assume we have selected a suitable parent and all previous conditions were true
-       uint32_t destinaddress[2];
-       
-       printfUART("9 find parent\n", "");
-       
-       //list_neighbourtable();
-       
-       parent_index = find_suitable_parent();
-       
-       panid = PANId;
-       
-       //printfUART("NLME_JOIN %i %i\n", parent_index,panid); 
-       
-       if(parent_index == 0)
-       {
-               signal NLME_JOIN.confirm(PANId,NWK_NOT_PERMITTED);
-       }
-       else
-       {
-               //assign the true value to parent index
-               parent_index = parent_index - 1;
-                               
-               //destinaddress[0]=neighbortable[parent_index].Extended_Address0;
-               //destinaddress[1]=neighbortable[parent_index].Extended_Address1;
-               //verificar o endereço do pan coordinator
-               destinaddress[0]=0x00000000;
-               
-               
-               destinaddress[1] = neighbortable[parent_index].Network_Address;
-               
-               /*
-               if (DEVICE_DEPTH == 0x01)
-                       destinaddress[1]=D1_PAN_SHORT;
-               if (DEVICE_DEPTH == 0x02)
-                       destinaddress[1]=D2_PAN_SHORT;
-               if (DEVICE_DEPTH == 0x03)
-                       destinaddress[1]=D3_PAN_SHORT;
-               if (DEVICE_DEPTH == 0x04)
-                       destinaddress[1]=D4_PAN_SHORT;
-               */      
-                       
-               printfUART("10 associate to %i\n", destinaddress[1]);   
-               //set_capability_information(uint8_t alternate_PAN_coordinator, uint8_t device_type, uint8_t power_source, uint8_t receiver_on_when_idle, uint8_t security, uint8_t allocate_address)
-               
-               if (JoinAsRouter == 0x01)
-                       call MLME_ASSOCIATE.request(LOGICAL_CHANNEL,SHORT_ADDRESS,PANId,destinaddress, set_capability_information(JoinAsRouter,0x01,PowerSource,RxOnWhenIdle,MACSecurity,0x01),0);
-               else
-               {
-               
-                       printfUART("11 go ass\n", "");  
-               
-                       coordinator_addr[0]=0x00000000;
-                       coordinator_addr[1] = neighbortable[parent_index].Network_Address;
-                       //BUILD the PAN descriptor of the COORDINATOR
-                       //assuming that the adress is short
-                       pan_des.CoordAddrMode = SHORT_ADDRESS;
-                       pan_des.CoordPANId = panid;
-                       pan_des.CoordAddress0=0x00000000;
-                       pan_des.CoordAddress1=(uint32_t)neighbortable[parent_index].Network_Address;
-                       pan_des.LogicalChannel=neighbortable[parent_index].Logical_Channel;
-                       //superframe specification field
-                       //pan_des.SuperframeSpec = neighbortable[parent_index].SuperframeSpec;
-
-                       pan_des.GTSPermit=0x01;
-                       pan_des.LinkQuality=0x00;
-                       pan_des.TimeStamp=0x000000;
-                       pan_des.SecurityUse=0;
-                       pan_des.ACLEntry=0x00;
-                       pan_des.SecurityFailure=0x00;
-       
-                       received_beacon_count=0;
-                       go_associate=1;
-                       
-                       //call MLME_ASSOCIATE.request(LOGICAL_CHANNEL,SHORT_ADDRESS,PANId,destinaddress, set_capability_information(JoinAsRouter,0x00,PowerSource,RxOnWhenIdle,MACSecurity,0x01),0);
-               }
-       }
-       
-       return SUCCESS;
-}
-
-
-/*************************************************************/
-/************************NLME - LEAVE*************************/
-/*************************************************************/
-
-//This primitive allows the NHL to request that it or another device leaves the network
-//page 181-183
-command error_t NLME_LEAVE.request(uint32_t DeviceAddress[],bool RemoveChildren, bool MACSecurityEnable)
-{      
-       uint32_t devaddr[2];
-       ////printfUART("NLME_LEAVE.request\n", ""); 
-       if (DeviceAddress == 0)//child asked to leave
-       {       
-               if(RemoveChildren == 0)//implemented like it is always 0
-               {       
-                       //send leave request command frame: RemoveChildren subfield=0 of the command option field of the command frame payload
-                       //call MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint8_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint8_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions);
-                       devaddr[0]=neighbortable[parent].Extended_Address0;
-                       devaddr[1]=neighbortable[parent].Extended_Address1;
-                       call MLME_DISASSOCIATE.request(devaddr,0x02,0);
-               }
-               else
-               {
-                       //send leave request command frame: RemoveChildren subfield=1
-                       //try to remove the children, call NLME_LEAVE.request(uint32_t DeviceAddress[]=address of child,bool RemoveChildren, bool MACSecurityEnable)
-                       //call MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint8_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint8_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions);
-               }
-       }
-       else//parent forced a child to leave
-       {
-               //if(check_neighbortableentry(DeviceAddress[0], DeviceAddress[1]) == 0)
-               //{
-               //      signal NLME_LEAVE.confirm(DeviceAddress,NWK_UNKNOWN_DEVICE);
-               //      //call MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint8_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint8_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions);
-               //}
-               
-       }
-       
-       
-       return SUCCESS;
-}
-
-/*************************************************************/
-/************************NLME - SYNC**************************/
-/*************************************************************/
-
-//This primitive allows the NHL to synchronize or extract data from its ZigBee coordinator or router
-//page 186-187
-command error_t NLME_SYNC.request(bool Track)
-{
-
-       return SUCCESS;
-}
-  
-/*************************************************************/
-/*****************        NLME-SET     ********************/
-/*************************************************************/
-       
-command error_t NLME_SET.request(uint8_t NIBAttribute, uint16_t NIBAttributeLength, uint16_t NIBAttributeValue)
-{
-
-       atomic{
-       
-               switch(NIBAttribute)
-               {
-                       case NWKSEQUENCENUMBER :                nwk_IB.nwkSequenceNumber = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkSequenceNumber: %x\n",nwk_IB.nwkSequenceNumber);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                                                                                       
-                       case NWKPASSIVEACKTIMEOUT :             nwk_IB.nwkPassiveAckTimeout = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkPassiveAckTimeout: %x\n",nwk_IB.nwkPassiveAckTimeout);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                       
-                       
-                       case NWKMAXBROADCASTRETRIES :   nwk_IB.nwkMaxBroadcastRetries = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkMaxBroadcastRetries: %x\n",nwk_IB.nwkMaxBroadcastRetries);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                                                                                       
-                       case NWKMAXCHILDREN :                   nwk_IB.nwkMaxChildren = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkMaxChildren: %x\n",nwk_IB.nwkMaxChildren);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                                                                                       
-                       case NWKMAXDEPTH :                              nwk_IB.nwkMaxDepth = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkMaxDepth: %x\n",nwk_IB.nwkMaxDepth);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-       
-                       case NWKMAXROUTERS :                    nwk_IB.nwkMaxRouters = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkMaxRouters: %x\n",nwk_IB.nwkMaxRouters);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-       
-                       case NWKMETWORKBROADCASTDELIVERYTIME :          nwk_IB.nwkNetworkBroadcastDeliveryTime = (uint8_t) NIBAttributeValue;
-                                                                                                               //////printfUART("nwk_IB.nwkNetworkBroadcastDeliveryTime: %x\n",nwk_IB.nwkNetworkBroadcastDeliveryTime);
-                                                                                                               signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                                               break;
-                       case NWKREPORTCONSTANTCOST :    nwk_IB.nwkReportConstantCost = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkReportConstantCost: %x\n",nwk_IB.nwkReportConstantCost);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                       case NWKROUTEDISCOVERYRETRIESPERMITED :         nwk_IB.nwkRouteDiscoveryRetriesPermitted = (uint8_t) NIBAttributeValue;
-                                                                                                               //////printfUART("nwk_IB.nwkRouteDiscoveryRetriesPermitted: %x\n",nwk_IB.nwkRouteDiscoveryRetriesPermitted);
-                                                                                                               signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                                               break;
-       
-                       case NWKSYMLINK :                               nwk_IB.nwkSymLink = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkSymLink: %x\n",nwk_IB.nwkSymLink);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                       
-                       case NWKCAPABILITYINFORMATION : nwk_IB.nwkCapabilityInformation = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkCapabilityInformation: %x\n",nwk_IB.nwkCapabilityInformation);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                                                                                       
-                       case NWKUSETREEADDRALLOC :              nwk_IB.nwkUseTreeAddrAlloc = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkUseTreeAddrAlloc: %x\n",nwk_IB.nwkUseTreeAddrAlloc);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                                                                                       
-                       case NWKUSETREEROUTING :                nwk_IB.nwkUseTreeRouting = (uint8_t) NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkUseTreeRouting: %x\n",nwk_IB.nwkUseTreeRouting);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                                                                                       
-                       case NWKNEXTADDRESS :                   nwk_IB.nwkNextAddress = NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkNextAddress: %x\n",nwk_IB.nwkNextAddress);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                                                                                       
-                       case NWKAVAILABLEADDRESSES :    nwk_IB.nwkAvailableAddresses = NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkAvailableAddresses: %x\n",nwk_IB.nwkAvailableAddresses);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                                                                                       
-                       case NWKADDRESSINCREMENT :              nwk_IB.nwkAddressIncrement =NIBAttributeValue;
-                                                                                       //////printfUART("nwk_IB.nwkAddressIncrement: %x\n",nwk_IB.nwkAddressIncrement);
-                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                       break;
-                                                                                       
-                       case NWKTRANSACTIONPERSISTENCETIME :    nwk_IB.nwkTransactionPersistenceTime = (uint8_t) NIBAttributeValue;
-                                                                                                       //////printfUART("nwk_IB.nwkTransactionPersistenceTime: %x\n",nwk_IB.nwkTransactionPersistenceTime);
-                                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
-                                                                                                       break;
-                                                                                       
-                       default:                                                signal NLME_SET.confirm(NWK_UNSUPPORTED_ATTRIBUTE,NIBAttribute);
-                                                                                       break;
-                       
-               }
-               
-       }
-
-
-       return SUCCESS;
-}
-
-/*************************************************************/
-/*****************        NLME-GET     ********************/
-/*************************************************************/
-       
-command error_t NLME_GET.request(uint8_t NIBAttribute)
-{
-       switch(NIBAttribute)
-       {
-               case NWKSEQUENCENUMBER :                signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkSequenceNumber);
-                                                                               break;
-                                                                       
-               case NWKPASSIVEACKTIMEOUT :             signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkPassiveAckTimeout);
-                                                                               break;
-               
-               case NWKMAXBROADCASTRETRIES :   signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkMaxBroadcastRetries);
-                                                                               break;
-
-               case NWKMAXCHILDREN :                   signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkMaxChildren);
-                                                                               break;
-
-               case NWKMAXDEPTH :                              signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkMaxDepth);
-                                                                               break;
-
-               case NWKMAXROUTERS :                    signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkMaxRouters);
-                                                                               break;
-
-               case NWKMETWORKBROADCASTDELIVERYTIME :          signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkNetworkBroadcastDeliveryTime);
-                                                                                                       break;
-
-               case NWKREPORTCONSTANTCOST :    signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkReportConstantCost);
-                                                                               break;
-
-               case NWKROUTEDISCOVERYRETRIESPERMITED :         signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkRouteDiscoveryRetriesPermitted);
-                                                                                                       break;
-
-               case NWKSYMLINK :                               signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkSymLink);
-                                                                               break;
-               
-               case NWKCAPABILITYINFORMATION : signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkCapabilityInformation);
-                                                                               break;
-                                                                               
-               case NWKUSETREEADDRALLOC :              signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkUseTreeAddrAlloc);
-                                                                               break;
-                                                                               
-               case NWKUSETREEROUTING :                signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkUseTreeRouting);
-                                                                               break;
-                                                                               
-               case NWKNEXTADDRESS :                   signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0002,(uint16_t)&nwk_IB.nwkNextAddress);
-                                                                               break;
-
-               case NWKAVAILABLEADDRESSES :    signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0002,(uint16_t)&nwk_IB.nwkAvailableAddresses);
-                                                                               break;
-                                                                               
-               case NWKADDRESSINCREMENT :              signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0002,(uint16_t)&nwk_IB.nwkAddressIncrement);
-                                                                               break;
-                                                                               
-               case NWKTRANSACTIONPERSISTENCETIME :    signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkTransactionPersistenceTime);
-                                                                                               break;
-
-               default:                                                signal NLME_GET.confirm(NWK_UNSUPPORTED_ATTRIBUTE,NIBAttribute,0x0000,0x00);
-                                                                               break;
-       }
-       
-       return SUCCESS;
-}
-
-/*************************************************************/
-/**************neighbor table management functions************/
-/*************************************************************/
-
-//check if a specific neighbourtable Entry is present
-//Return 0:Entry is not present
-//Return i:Entry is present and return the index of the entry + 1
-       uint8_t check_neighbortableentry(uint8_t addrmode,uint32_t Address0,uint32_t Address1)
-       {       
-               
-               int i=0;
-               
-               
-               //printfUART("neighbourtable check c %i\n", neighbour_count);
-       
-               if (neighbour_count == 0)
-               {
-                       //printfUART("no neib\n", "");
-                       return 0;
-               }
-               
-               if(addrmode == SHORT_ADDRESS)
-               {       
-                       for(i=0; i < neighbour_count; i++)
-                       {       
-                               ///printfUART("compare %i %i\n", neighbortable[i].Network_Address, test);
-                               
-                               if(neighbortable[i].Network_Address == (uint16_t) Address0)
-                               {
-                                       //printfUART("already present \n", "" );
-                                       return i+1;
-                               }
-                       }
-                       return 0;
-               }
-               else
-               {
-                       for(i=0; i<neighbour_count; i++)
-                       {       
-                               ////printfUART("compare %x %x\n", neighbortable[i].Extended_Address0, Address0);
-                               if( (neighbortable[i].Extended_Address0 == Address0) && (neighbortable[i].Extended_Address1 == Address1))
-                               {
-                                       //printfUART("already present \n", "" );
-                                       return i+1;
-                               }
-                       }
-                       return 0;
-               }
-               
-               return 0;
-       }
-       
-       //function user to find a parent in the neighbour table
-       //Return 0:no parent is present
-       //Return i:parent is present and return the index of the entry + 1
-       uint8_t find_suitable_parent()
-       {
-               int i =0;
-               for (i=0; i<neighbour_count; i++)
-               {
-                       if(neighbortable[i].Relationship == NEIGHBOR_IS_PARENT)
-                       {
-                               return i+1;
-                       }
-               }
-               return 0;
-       }
-
-
-       //add a neighbortable entry     
-       void add_neighbortableentry     (uint16_t PAN_Id,uint32_t Extended_Address0,uint32_t Extended_Address1,uint32_t Network_Address,uint8_t Device_Type,uint8_t Relationship)
-       {
-       
-       atomic{
-               neighbortable[neighbour_count].PAN_Id=PAN_Id;
-               neighbortable[neighbour_count].Extended_Address0=Extended_Address0;
-               neighbortable[neighbour_count].Extended_Address1=Extended_Address1;
-               neighbortable[neighbour_count].Network_Address=Network_Address;
-               neighbortable[neighbour_count].Device_Type=Device_Type;
-               neighbortable[neighbour_count].Relationship=Relationship;
-               
-               neighbour_count++;
-               }
-               
-       }
-
-
-       
-       //update a neighbourtable entry
-       void update_neighbortableentry(uint16_t PAN_Id,uint32_t Extended_Address0,uint32_t Extended_Address1,uint32_t Network_Address,uint8_t Device_Type,uint8_t Relationship)
-       {
-               //search entry with correct extended address
-               uint8_t nrofEntry=0;
-               nrofEntry = check_neighbortableentry(0x01,Extended_Address0,Extended_Address1) - 1;
-               
-               //update every attribute
-               neighbortable[nrofEntry].PAN_Id=PAN_Id;
-               neighbortable[nrofEntry].Extended_Address0=Extended_Address0;
-               neighbortable[nrofEntry].Extended_Address1=Extended_Address1;
-               neighbortable[nrofEntry].Network_Address=Network_Address;
-               neighbortable[nrofEntry].Device_Type=Device_Type;
-               neighbortable[nrofEntry].Relationship=Relationship;
-               
-               ////printfUART("updated neighbourtable entry\n", "");
-       }
-
-
-       void list_neighbourtable()
-       {
-               int i;
-               ////printfUART("N List Count: %u\n", neighbour_count);
-       
-               for(i=0;i<neighbour_count;i++)
-               {
-                       printfUART("Panid %x", neighbortable[i].PAN_Id);
-                       printfUART("Extaddr0 %x", neighbortable[i].Extended_Address0);
-                       printfUART("Extaddr1 %x", neighbortable[i].Extended_Address1);
-                       printfUART("nwkaddr %u", neighbortable[i].Network_Address);
-                       printfUART("devtype %u", neighbortable[i].Device_Type);
-                       printfUART("relation %u", neighbortable[i].Relationship);
-                       printfUART("depth %u\n", neighbortable[i].Depth);               
-               }
-       }
-/*************************************************************/
-/*****************Address Assignment functions****************/
-/*************************************************************/
-
-//calculate the size of the address sub-block for a router at depth d
-uint16_t Cskip(uint8_t d)
-{      
-       uint8_t skip;
-       uint8_t power;
-       uint8_t x=1;
-       uint8_t Cm = nwk_IB.nwkMaxChildren;
-       uint8_t Rm = nwk_IB.nwkMaxRouters;
-       uint8_t Lm = nwk_IB.nwkMaxDepth;
-       /*////printfUART("nwk_IB.nwkMaxChildren: %i\n",  nwk_IB.nwkMaxChildren);
-       ////printfUART("nwk_IB.nwkMaxRouters: %i\n", nwk_IB.nwkMaxRouters);
-       ////printfUART("nwk_IB.nwkMaxDepth: %i\n", nwk_IB.nwkMaxDepth);*/
-       if (Rm == 1)
-       {
-               skip = 1 + Cm * (Lm - d - 1);
-       }
-       else
-       {       
-               int i;
-               
-               power=(Lm - d - 1);
-               for(i=0;i<power;i++)
-               {
-                       x=x*Rm;
-               }
-               skip = (1 + Cm - Rm - (Cm * x))/(1-Rm);
-       }
-       ////printfUART("Cksip function calculated: %i\n", skip);
-       return skip;
-}
-
-//Calculate the nexthopaddress of the appropriate child if route down is required
-uint16_t nexthopaddress(uint16_t destinationaddress,uint8_t d)
-{
-       uint16_t next_hop;
-
-       next_hop=(networkaddress + 1 + ((destinationaddress-(networkaddress+1))/cskip)* cskip);
-       
-       ////printfUART("Nexthop address calculated: %i\n", next_hop);
-       return next_hop;
-}
-
-/*************************************************************/
-/*****************Initialization functions********************/
-/*************************************************************/
-       //initialization of the nwk IB
-       void init_nwkIB()
-       {       
-               //nwk IB default values p 204-206
-               nwk_IB.nwkPassiveAckTimeout=0x03;
-               nwk_IB.nwkMaxBroadcastRetries=0x03;
-               nwk_IB.nwkMaxChildren=0x07;     //number of children a device is allowed to have on its current network
-               nwk_IB.nwkMaxDepth=0x05;        //the depth a device can have
-               nwk_IB.nwkMaxRouters=0x02;      //number of routers anyone device is allowed to have on its current network
-               //neighbortableentry nwkNeighborTable[];//null set
-               nwk_IB.nwkNetworkBroadcastDeliveryTime=( nwk_IB.nwkPassiveAckTimeout * nwk_IB.nwkMaxBroadcastRetries );
-               nwk_IB.nwkReportConstantCost=0x00;
-               nwk_IB.nwkRouteDiscoveryRetriesPermitted=nwkcDiscoveryRetryLimit;
-       //set? nwkRouteTable;//Null set
-               nwk_IB.nwkSymLink=0;
-               nwk_IB.nwkCapabilityInformation=0x00;
-               nwk_IB.nwkUseTreeAddrAlloc=1;
-               nwk_IB.nwkUseTreeRouting=1;
-               nwk_IB.nwkNextAddress=0x0000;
-               nwk_IB.nwkAvailableAddresses=0x0000;
-               nwk_IB.nwkAddressIncrement=0x0001;
-               nwk_IB.nwkTransactionPersistenceTime=0x01f4;
-       }
-
-
-  
-}
-
diff --git a/tos/lib/net/zigbee/ieee802154/nwk/NWKP.nc b/tos/lib/net/zigbee/ieee802154/nwk/NWKP.nc
new file mode 100644 (file)
index 0000000..e1032cc
--- /dev/null
@@ -0,0 +1,1559 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+#include <Timer.h>
+#include "printfUART.h"
+
+
+
+
+module NWKP {
+       
+
+       uses interface Leds;
+       
+       //MAC interfaces
+#ifndef TKN154_MAC
+       uses interface MLME_START;
+       
+       uses interface MLME_GET;
+       uses interface MLME_SET;
+       
+       uses interface MLME_BEACON_NOTIFY;
+       uses interface MLME_GTS;
+       
+       uses interface MLME_ASSOCIATE;
+       uses interface MLME_DISASSOCIATE;
+       
+       uses interface MLME_ORPHAN;
+       
+       uses interface MLME_SYNC;
+       uses interface MLME_SYNC_LOSS;
+       
+       uses interface MLME_RESET;
+       
+       uses interface MLME_SCAN;
+       
+       
+       uses interface MCPS_DATA;
+
+#else
+       uses interface OPENZB_MLME_START as MLME_START;
+       
+       uses interface OPENZB_MLME_GET as MLME_GET;
+       uses interface OPENZB_MLME_SET as MLME_SET;
+       
+       uses interface OPENZB_MLME_BEACON_NOTIFY as MLME_BEACON_NOTIFY;
+       uses interface OPENZB_MLME_GTS as MLME_GTS;
+       
+       uses interface OPENZB_MLME_ASSOCIATE as MLME_ASSOCIATE;
+       uses interface OPENZB_MLME_DISASSOCIATE as MLME_DISASSOCIATE;
+       
+       uses interface OPENZB_MLME_ORPHAN as MLME_ORPHAN;
+       
+       uses interface OPENZB_MLME_SYNC as MLME_SYNC;
+       uses interface OPENZB_MLME_SYNC_LOSS as MLME_SYNC_LOSS;
+       
+       uses interface OPENZB_MLME_RESET as MLME_RESET;
+       
+       uses interface OPENZB_MLME_SCAN as MLME_SCAN;
+       
+       
+       uses interface OPENZB_MCPS_DATA as MCPS_DATA;
+
+
+#endif
+
+
+       uses interface Random;
+
+//provides
+
+       provides interface Init;
+       provides interface NLDE_DATA;
+
+       //NLME NWK Management services
+    provides interface NLME_NETWORK_FORMATION;
+       provides interface NLME_NETWORK_DISCOVERY;
+       provides interface NLME_START_ROUTER;
+       provides interface NLME_JOIN;
+       provides interface NLME_LEAVE;
+       provides interface NLME_SYNC;
+       /*  
+       provides interface NLME_PERMIT_JOINING;
+       provides interface NLME_DIRECT_JOIN;*/
+       provides interface NLME_RESET;
+       
+       provides interface NLME_GET;
+       provides interface NLME_SET;
+
+  
+}
+implementation {
+
+
+       nwkIB nwk_IB;
+       
+       uint8_t device_type = END_DEVICE;
+       
+/*****************************************************/
+/*************Neighbourtable Variables****************/
+/*****************************************************/ 
+
+       //neighbour table array:
+       neighbortableentry neighbortable[NEIGHBOUR_TABLE_SIZE];
+       //number of neigbourtable entries:
+       uint8_t neighbour_count;
+       //the index of the parents neighbortable entry
+       uint8_t parent;
+       
+
+/*****************************************************/
+/****************ASSOCIATION Variables********************/
+/*****************************************************/ 
+
+       //CURRENT NETWORK ADDRESS
+       uint16_t networkaddress=0x0000;
+
+       //COORDINATOR
+       //address assignement variables
+       uint8_t depth=0;
+       uint8_t cskip=0;
+       
+       uint8_t cskip_routing=0;
+
+       //neighbour table parent index
+       uint8_t parent_index;
+
+       //NON COORDINATOR
+
+       //current pan characteristics
+       uint16_t panid;
+       uint8_t beaconorder;
+       uint8_t superframeorder;
+       
+       //next child router address
+       uint16_t next_child_router_address;
+       uint8_t number_child_router=0x01;
+       uint8_t number_child_end_devices=0x01;
+/*****************************************************/
+/****************Integer Variables********************/
+/*****************************************************/ 
+
+       uint8_t joined=0;
+       uint8_t sync_loss=0;
+       //uint8_t synchronizing=0;
+       uint8_t syncwait;
+       
+       
+       //USED AFTER DE SCAN //GIVE SOME TIME TO THE DEVICE TO SYNC WITH THE PARENT
+       uint8_t received_beacon_count=0;
+       
+       uint8_t go_associate =0;
+       
+       PANDescriptor pan_des;
+       uint32_t coordinator_addr[2];
+/******************************************************/
+/*********NEIGHBOuRTABLE  MANAGEMENT FUNCTIONS*********/
+/******************************************************/ 
+
+       void init_nwkIB();
+       
+       uint8_t check_neighbortableentry(uint8_t addrmode,uint32_t Extended_Address0,uint32_t Extended_Address1);
+       
+       void add_neighbortableentry     (uint16_t PAN_Id,uint32_t Extended_Address0,uint32_t Extended_Address1,uint32_t Network_Address,uint8_t Device_Type,uint8_t Relationship);
+       void update_neighbortableentry (uint16_t PAN_Id,uint32_t Extended_Address0,uint32_t Extended_Address1,uint32_t Network_Address,uint8_t Device_Type,uint8_t Relationship);       
+       
+       uint8_t find_suitable_parent();
+       
+       uint16_t Cskip(uint8_t d);
+       
+       uint16_t nexthopaddress(uint16_t destinationaddress,uint8_t d);
+       
+       void list_neighbourtable();
+
+
+
+ command error_t Init.init() {
+       
+       printfUART_init();//make the possibility to print
+               
+       init_nwkIB();
+       
+       nwk_IB.nwkSequenceNumber=call Random.rand16();
+  
+       return SUCCESS;
+ }
+
+
+/*****************************************************************************************************/  
+/**************************************MLME-SCAN*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SCAN.confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[])
+{
+//FAULT-TOLERANCE
+
+//the device channel scan ends with a scan confirm containing a list of the PANs (beacons received during the scan) 
+
+       int i;
+       uint8_t max_lqi=0;
+       uint8_t best_pan_index=0;
+       
+       
+       networkdescriptor networkdescriptorlist[1];
+       
+       
+       //call Leds.redOff();
+       
+       printfUART("4 rec scan\n", "");
+       
+       //printfUART("MLME_SCAN.confirm %i\n", ScanType);
+       
+       if (ScanType == ORPHAN_SCAN)
+       {
+               printfUART("new scan \n", "");
+       
+               call MLME_SCAN.request(PASSIVE_SCAN,0xFFFFFFFF,7);
+               return SUCCESS;
+       }
+       
+       
+       
+       if(ScanType == ED_SCAN)
+       {
+               for(i=0;i<ResultListSize;i++)
+               {
+                       printfUART("ED SCAN %i %i\n", (0x0A + i),EnergyDetectList[i]);
+               }
+               return SUCCESS;
+       }
+       
+       for (i=0; i<ResultListSize;i++)
+       {               /*
+                       printfUART("cord id %i", PANDescriptorList[i].CoordPANId);
+                       printfUART("CoordAddress %i", PANDescriptorList[i].CoordAddress);
+                       printfUART("LogicalChannel %i", PANDescriptorList[i].LogicalChannel);
+                       printfUART("SuperframeSpec %i", PANDescriptorList[i].SuperframeSpec);
+                       printfUART("lqi %i\n", PANDescriptorList[i].lqi);
+                       */
+               if(max_lqi < PANDescriptorList[i].lqi)
+               {
+                       max_lqi =PANDescriptorList[i].lqi;
+                       best_pan_index = i;
+               }
+       }
+       
+       printfUART("SELECTED cord id %i", PANDescriptorList[best_pan_index].CoordPANId);
+       printfUART("CoordAddress %i", PANDescriptorList[best_pan_index].CoordAddress);
+       printfUART("LogicalChannel %i", PANDescriptorList[best_pan_index].LogicalChannel);
+       printfUART("SuperframeSpec %i", PANDescriptorList[best_pan_index].SuperframeSpec);
+       printfUART("lqi %i\n", PANDescriptorList[best_pan_index].lqi);
+       
+       
+       
+       /*
+       
+       coordinator_addr[0] = 0x00000001;
+       
+       coordinator_addr[1] = (uint32_t)PANDescriptorList[best_pan_index].CoordAddress;
+       
+       //pan_des = PANDescriptorList[best_pan_index];
+
+       
+       //BUILD the PAN descriptor of the COORDINATOR
+       //assuming that the adress is short
+       pan_des.CoordAddrMode = SHORT_ADDRESS;
+       pan_des.CoordPANId = PANDescriptorList[best_pan_index].CoordAddress;
+       pan_des.CoordAddress0=0x00000000;
+       pan_des.CoordAddress1=0x00000000;
+       pan_des.LogicalChannel=PANDescriptorList[best_pan_index].LogicalChannel;
+       //superframe specification field
+       pan_des.SuperframeSpec = PANDescriptorList[best_pan_index].SuperframeSpec;
+       
+       pan_des.GTSPermit=0x01;
+       pan_des.LinkQuality=0x00;
+       pan_des.TimeStamp=0x000000;
+       pan_des.SecurityUse=0;
+       pan_des.ACLEntry=0x00;
+       pan_des.SecurityFailure=0x00;
+       
+       */
+
+       
+       
+       printfUART("5 en sync %x \n", PANDescriptorList[best_pan_index].LogicalChannel);
+       // the sync enables the TimerAsync events, in order to enable the synchronization with the PAN coordinator
+       call MLME_SYNC.request(PANDescriptorList[best_pan_index].LogicalChannel,0);
+       
+       
+       
+       //The networkdescriptorlist must contain information about every network that was heard
+       
+       //make NetworkDescriptorList out of the PanDescriptorList
+
+
+    printfUART("6 add neigh\n", "");
+
+       networkdescriptorlist[0].PANId=PANDescriptorList[best_pan_index].CoordPANId;
+       networkdescriptorlist[0].LogicalChannel=LOGICAL_CHANNEL;
+       networkdescriptorlist[0].StackProfile=0x00;
+       networkdescriptorlist[0].ZigBeeVersion=0x01;
+       networkdescriptorlist[0].BeaconOrder=7;
+       networkdescriptorlist[0].SuperframeOrder=6;
+       networkdescriptorlist[0].PermitJoining=1;
+
+       add_neighbortableentry(networkdescriptorlist[0].PANId,0x00000000,0x00000000,PANDescriptorList[best_pan_index].CoordAddress,COORDINATOR,NEIGHBOR_IS_PARENT);
+       
+       signal NLME_NETWORK_DISCOVERY.confirm(1,networkdescriptorlist, NWK_SUCCESS);
+       
+       
+       
+       return SUCCESS;
+}
+
+/*****************************************************************************************************/  
+/**************************************MLME-ORPHAN****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_ORPHAN.indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry)
+{
+
+       
+               
+               return 0x0000;
+       }
+
+/*****************************************************************************************************/  
+/**************************************MLME-RESET*****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_RESET.confirm(uint8_t status)
+{
+
+  signal NLME_RESET.confirm(status);
+
+  return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-SYNC-LOSS*************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SYNC_LOSS.indication(uint8_t LossReason)
+{
+       ////printfUART("MLME_SYNC_LOSS.indication\n", ""); 
+       sync_loss = 1;
+       syncwait=1;
+       //signal NLME_SYNC.indication();
+/*
+
+printfUART("SL\n","");
+               
+               call MLME_SCAN.request(ORPHAN_SCAN,0xFFFFFFFF,7);
+*/
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-GTS*******************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_GTS.confirm(uint8_t GTSCharacteristics, uint8_t status)
+{
+
+
+
+       return SUCCESS;
+}
+
+event error_t MLME_GTS.indication(uint16_t DevAddress, uint8_t GTSCharacteristics, bool SecurityUse, uint8_t ACLEntry)
+{
+
+
+
+       return SUCCESS;
+}
+
+/*****************************************************************************************************/  
+/**************************************MLME-BEACON NOTIFY*********************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_BEACON_NOTIFY.indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[])
+{
+       
+       uint32_t destinaddress[2];
+       printfUART("BN\n", "");
+
+       
+       if (go_associate==1)
+       {
+               received_beacon_count++;
+               
+               printfUART("bn %i\n", received_beacon_count);
+               
+               if (received_beacon_count==5)
+               {
+                               printfUART("sa \n", "");
+                               
+                               go_associate=0;
+                               //call MLME_ASSOCIATE.request(pan_des.LogicalChannel,SHORT_ADDRESS,pan_des.CoordPANId,coordinator_addr,0x00,0x00);
+               
+               destinaddress[0]=0x00000000;
+               destinaddress[1]=0x00000000;
+               
+               
+               call MLME_ASSOCIATE.request(LOGICAL_CHANNEL,SHORT_ADDRESS,0x1234,destinaddress, set_capability_information(0x00,0x00,0x00,0x00,0x00,0x01),0);
+               
+               }
+               
+       }
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-START*****************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_START.confirm(uint8_t status)
+{
+               ////printfUART("MLME_START.confirm\n", "");
+       if (device_type==COORDINATOR)
+       {
+               signal NLME_NETWORK_FORMATION.confirm(status);
+               joined=1;
+       }
+       else
+       {
+               signal NLME_START_ROUTER.confirm(status);
+       }
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**********************                                  MLME-SET                          ******************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_SET.confirm(uint8_t status,uint8_t PIBAttribute)
+{
+       
+       
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/*************************                     MLME-GET                            ******************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_GET.confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[])
+{
+       
+       
+       return SUCCESS;
+}
+       
+/*****************************************************************************************************/  
+/**************************************MLME-ASSOCIATE*************************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_ASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry)
+{
+       
+       //notification that an other device wants to associate
+       //THIS DEVICE IS EITHER A COORDINATOR OR A ROUTER
+               
+       uint8_t cindex=0;
+
+atomic{
+
+       //check the neighbour table
+       cindex = check_neighbortableentry(LONG_ADDRESS,DeviceAddress[0] , DeviceAddress[1]);
+       
+
+       if( cindex > 0 )
+       {
+               call MLME_ASSOCIATE.response(DeviceAddress,neighbortable[cindex - 1].Network_Address,MAC_SUCCESS,0);
+       }
+       else
+       {       
+                       if(nwk_IB.nwkAvailableAddresses > 0)
+                       {
+                       
+                               //verify if the device is associating as a router or an end device
+                               if ( get_alternate_PAN_coordinator(CapabilityInformation) == 1)
+                               {
+                                       //add device to the neighbour table
+                                       add_neighbortableentry(panid,DeviceAddress[0],DeviceAddress[1],next_child_router_address,ROUTER,NEIGHBOR_IS_CHILD);
+                                       
+                                       printfUART("An_cr %x\n",next_child_router_address);
+
+                                       //send response, this shall lead to confirm in child device
+                                       call MLME_ASSOCIATE.response(DeviceAddress,next_child_router_address,MAC_SUCCESS,0);
+                                       //calculate the next address
+                                       next_child_router_address = networkaddress + ((number_child_router-1) * cskip) +1 ;
+                                       //increment the number of associated routers
+                                       number_child_router++;
+                                       //decrese the number of available addresses //the available addresses are influenced by the network configurations
+                                       nwk_IB.nwkAvailableAddresses--;
+                                       
+                                       printfUART("Dn_cr %x\n",next_child_router_address);
+                               }
+                               else
+                               {
+                                       //verify if its possible to associate children in the address space
+                                       //the number of end devices must be greater than 1 and lesser or iqual to maximum children minus maximum routers
+                                       if (number_child_end_devices > 1 && number_child_end_devices > (MAXCHILDREN - MAXROUTERS))
+                                       {
+                                               call MLME_ASSOCIATE.response(DeviceAddress,0xffff,CMD_RESP_PAN_CAPACITY,0);
+                                               //return SUCCESS;
+                                       }
+                                       else
+                                       {
+                                               //CHECK COMMENTED ON SHORT VERSION
+                                               add_neighbortableentry(panid,DeviceAddress[0],DeviceAddress[1],nwk_IB.nwkNextAddress,END_DEVICE,NEIGHBOR_IS_CHILD);
+                                               //send response, this shall lead to confirm in child device
+                                               call MLME_ASSOCIATE.response(DeviceAddress,nwk_IB.nwkNextAddress,MAC_SUCCESS,0);
+                                               
+                                               nwk_IB.nwkNextAddress=nwk_IB.nwkNextAddress + nwk_IB.nwkAddressIncrement;
+                                               
+                                               number_child_end_devices++;
+                                               
+                                               nwk_IB.nwkAvailableAddresses--;
+                                               
+                                       }
+                               }
+                               
+                               if (nwk_IB.nwkAvailableAddresses == 0 )
+                               {
+                                       call MLME_SET.request(MACASSOCIATIONPERMIT,(uint8_t *)0x00000000);
+                               }
+                       }
+                       else
+                       {
+                               //if there are no available addresses the coordinator/router shall not respond to the association request
+                               call MLME_ASSOCIATE.response(DeviceAddress,0xffff,CMD_RESP_PAN_CAPACITY,0);
+                       }
+       }
+}
+       return SUCCESS;
+}
+
+event error_t MLME_ASSOCIATE.confirm(uint16_t AssocShortAddress, uint8_t status)
+{
+
+       uint8_t v_temp[2];
+       ////printfUART("MLME_ASSOCIATE.confirm\n","");
+
+       if (AssocShortAddress == 0xffff)
+       {
+               //association failed
+               //printfUART("nwkass fail\n","");
+               signal NLME_JOIN.confirm(panid,NWK_NOT_PERMITTED);
+       
+       }
+       else
+       {
+       
+               networkaddress = AssocShortAddress;
+               //add_neighbortableentry(panid,DeviceAddress[0],DeviceAddress[1],nwk_IB.nwkNextAddress,END_DEVICE,NEIGHBOR_IS_CHILD);
+               //set the short address
+               
+               if (status == MAC_SUCCESS)
+               {
+                       joined = 0x01;
+                       v_temp[0] = (uint8_t)(networkaddress >> 8);
+                       v_temp[1] = (uint8_t)(networkaddress );
+
+                       //call MLME_SET.request(MACSHORTADDRESS,(uint32_t*)(uint32_t)&networkaddress);
+                       call MLME_SET.request(MACSHORTADDRESS,v_temp);
+                       
+                       signal NLME_JOIN.confirm(panid, NWK_SUCCESS);
+               }
+               else
+               {
+                       signal NLME_JOIN.confirm(panid,NWK_NOT_PERMITTED);
+               }
+       }
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/**************************************MLME-DISASSOCIATE**********************************************/
+/*****************************************************************************************************/ 
+event error_t MLME_DISASSOCIATE.indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, bool SecurityUse, uint8_t ACLEntry)
+{
+       ////printfUART("MLME_DISASSOCIATE.indication:SUCCESS\n", "");
+       signal NLME_LEAVE.confirm(DeviceAddress, NWK_SUCCESS);
+
+       return SUCCESS;
+}
+  
+event error_t MLME_DISASSOCIATE.confirm(uint8_t status)
+{
+       if (status == MAC_SUCCESS)
+       {
+               signal NLME_LEAVE.confirm(0, status);
+               ////printfUART("MLME_DISASSOCIATE.confirm:SUCCESS\n", "");
+       }
+       else
+       {
+               signal NLME_LEAVE.confirm(0, NWK_LEAVE_UNCONFIRMED);
+               ////printfUART("MLME_DISASSOCIATE.confirm:leave unconfirmed\n", "");
+       }
+
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/*****************************************************************************************************/  
+/****************                                      MCPS EVENTS                              *************************************/
+/*****************************************************************************************************/ 
+/*****************************************************************************************************/  
+
+
+/*****************************************************************************************************/  
+/*********************                                 MCPS-DATA                          ***************************************/
+/*****************************************************************************************************/ 
+event error_t MCPS_DATA.confirm(uint8_t msduHandle, uint8_t status)
+{
+       ////printfUART("MCPS_DATA.confirm\n", "");
+       signal NLDE_DATA.confirm(1,status);
+       
+       return SUCCESS;
+}  
+event error_t MCPS_DATA.indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry)
+{
+       uint8_t payload[100];
+       uint32_t route_destination_address[2];
+       uint32_t net_addr[2];
+       uint8_t next_hop_index;
+       
+       routing_fields *routing_fields_ptr;
+       routing_fields_ptr = (routing_fields *)&msdu[0];
+       
+       net_addr[1] =(uint32_t) networkaddress;
+       net_addr[0]=0x00000000;
+
+       if ( routing_fields_ptr->destination_address == networkaddress)
+       {
+               //I am the destination
+               memcpy(&payload,&msdu[8],(msduLength-8)*sizeof(uint8_t));
+               
+               //pass data on to APL layer
+               signal NLDE_DATA.indication(routing_fields_ptr->source_address,(uint16_t)(msduLength-8),payload, mpduLinkQuality);
+               
+               return SUCCESS; 
+       }
+       else
+       {
+               //I am not the destination
+               if(device_type != COORDINATOR)
+               {
+                       if( (networkaddress < routing_fields_ptr->destination_address) && (routing_fields_ptr->destination_address < (networkaddress + cskip_routing ) ) )
+                       {
+                               printfUART("route down to appropriate child\n", "");
+                               
+                               //check if destination is one of my children
+                               next_hop_index = check_neighbortableentry(SHORT_ADDRESS,(uint32_t)routing_fields_ptr->destination_address,0x00000000);
+
+                               if (next_hop_index == 0)
+                               {
+                                       //destination is not my child
+                                       route_destination_address[0]=0x00000000;
+                                       route_destination_address[1]=nexthopaddress(routing_fields_ptr->destination_address,depth);
+                               }
+                               else
+                               {
+                                       //Im routing to my child
+                                       route_destination_address[0]=0x00000000;
+                                       route_destination_address[1]=neighbortable[next_hop_index-1].Network_Address;
+                               }
+                               //send message
+                               call MCPS_DATA.request(SHORT_ADDRESS, panid, net_addr, SHORT_ADDRESS, DestPANId, route_destination_address, msduLength, msdu,1,set_txoptions(1,0,0,0));
+                       }
+                       else
+                       {
+                               
+                               //changes to meet with the BEACON SYNCHRONIZATION requirements
+                               //route up to the parent
+                               atomic{
+                                       route_destination_address[0]=0x00000000;
+                                       route_destination_address[1]=neighbortable[parent].Network_Address;
+
+                                       call MCPS_DATA.request(SHORT_ADDRESS, panid, net_addr, SHORT_ADDRESS, DestPANId, route_destination_address, msduLength, msdu,1,set_txoptions_upstream(1,0,0,0,1));
+                               }
+                       }
+               }
+               else
+               {
+                       //I AM THE PAN COORDINATOR
+                       //THE COORDINATOR ALWAYS ROUTES DOWN
+                       
+                       //route down to appropriate child
+                       //check if destination is one of my children
+                       next_hop_index = check_neighbortableentry(SHORT_ADDRESS,(uint32_t)routing_fields_ptr->destination_address,0x00000000);
+                       
+                       if (next_hop_index == 0 )
+                       {
+                               //no entry in neigbortable
+                               //calculate route address
+                               route_destination_address[0]=0x00000000;
+                               route_destination_address[1]=nexthopaddress(routing_fields_ptr->destination_address,depth);
+                                       
+                               call MCPS_DATA.request(SHORT_ADDRESS, panid, net_addr, SHORT_ADDRESS, DestPANId, route_destination_address, msduLength, msdu,1,set_txoptions(1,0,0,0));
+                       }
+                       else
+                       {
+                               //is my child
+                               route_destination_address[0]=0x00000000;
+                               route_destination_address[1]=neighbortable[next_hop_index-1].Network_Address;
+
+                               call MCPS_DATA.request(SHORT_ADDRESS, panid, net_addr, SHORT_ADDRESS, DestPANId, route_destination_address, msduLength, msdu,1,set_txoptions(1,0,0,0));
+                       }
+                       
+               }
+               
+               
+       }
+       
+return SUCCESS;
+}
+
+
+/*************************************************************/
+/*******************NLDE IMPLEMENTATION***********************/
+/*************************************************************/
+       
+/*************************************************************/
+/*************************NLDE - DATA*************************/
+/*************************************************************/
+
+//This primitive requests the transfer of a data PDU
+//page 159-161
+
+command error_t NLDE_DATA.request(uint16_t DstAddr, uint16_t NsduLength, uint8_t Nsdu[100], uint8_t NsduHandle, uint8_t Radius, uint8_t DiscoverRoute, uint8_t SecurityEnable)
+{      
+
+       uint32_t srcadd[2];
+       //prefixed size because the devices reset itself when there is an error in the length
+       uint8_t MSDU[100];
+       uint32_t route_destination_address[2];
+       routing_fields *routing_fields_ptr;
+       uint8_t next_hop_index;
+       
+       routing_fields_ptr = (routing_fields *)&MSDU[0];
+       
+       if(joined==0)
+       {       
+               signal NLDE_DATA.confirm(NsduHandle, NWK_INVALID_REQUEST);
+       }
+       else
+       {
+               routing_fields_ptr->frame_control= set_route_frame_control(0x00,0x01,DiscoverRoute,SecurityEnable);
+               routing_fields_ptr->destination_address=DstAddr;
+               routing_fields_ptr->source_address=networkaddress;
+               routing_fields_ptr->radius=Radius;
+               routing_fields_ptr->sequence_number=nwk_IB.nwkSequenceNumber;
+               nwk_IB.nwkSequenceNumber++;
+               
+               memcpy(&MSDU[8],&Nsdu[0],NsduLength*sizeof(uint8_t));
+
+               srcadd[0] = 0x00000000;
+               srcadd[1] = (uint32_t)networkaddress;
+               
+               if (device_type == END_DEVICE)
+               {
+                       //if the device is an end device always sends the message to the parent
+
+                       route_destination_address[0]=0x00000000;
+                       route_destination_address[1]=neighbortable[parent].Network_Address;
+                                                                                                                                                                                                                                                                                                               //ack
+                       call MCPS_DATA.request(SHORT_ADDRESS, panid, srcadd, SHORT_ADDRESS,panid, route_destination_address, (NsduLength + 8), MSDU,1,set_txoptions(1,0,0,0));
+                       return SUCCESS;
+               }
+               
+               //send message if the device is the COORDINATOR or a ROUTER
+               if( (networkaddress < routing_fields_ptr->destination_address) && (routing_fields_ptr->destination_address < (networkaddress + cskip_routing ) ) )
+               {
+                       //route down to appropriate child
+                       //check if destination is one of my children
+                       next_hop_index = check_neighbortableentry(SHORT_ADDRESS,(uint32_t)routing_fields_ptr->destination_address,0x00000000);
+
+                       if (next_hop_index == 0)
+                       {
+                               //destination is not my child
+                               route_destination_address[0]=0x00000000;
+                               route_destination_address[1]=nexthopaddress(routing_fields_ptr->destination_address,depth);
+                       }
+                       else
+                       {
+                               //Im routing to my child
+                               route_destination_address[0]=0x00000000;
+                               route_destination_address[1]=neighbortable[next_hop_index-1].Network_Address;
+                       }
+                       //send the data                                                                                                                                                                                                                                                                 //ack
+                       call MCPS_DATA.request(SHORT_ADDRESS, panid, srcadd, SHORT_ADDRESS, panid, route_destination_address, (NsduLength + 8), MSDU,1,set_txoptions(1,0,0,0));
+               }
+               else
+               {
+                       //route up to parent
+                       atomic{
+                               route_destination_address[0]=0x00000000;
+                               route_destination_address[1]=neighbortable[parent].Network_Address;
+                                                                                                                                                                                                                                                                                                       //ack
+                               call MCPS_DATA.request(SHORT_ADDRESS, panid, srcadd, SHORT_ADDRESS, panid, route_destination_address, (NsduLength + 8), MSDU,1,set_txoptions_upstream(1,0,0,0,1));
+                       }
+               }
+               
+       }
+       
+       return SUCCESS;
+}
+
+/*************************************************************/
+/*******************NLME IMPLEMENTATION***********************/
+/*************************************************************/
+
+
+/*************************************************************
+******************* NLME-RESET********************************
+**************************************************************/
+ command error_t NLME_RESET.request(){
+
+  call MLME_RESET.request(TRUE);
+return SUCCESS;
+}
+/*************************************************************/
+/*******************NLME - START - ROUTER*********************/
+/*************************************************************/
+
+//This primitive allows the NHL of a ZigBee Router to initialize or change its superframe configuration.
+//p171 and 210
+command error_t NLME_START_ROUTER.request(uint8_t BeaconOrder, uint8_t SuperframeOrder, bool BatteryLifeExtension,uint32_t StartTime)
+{      
+       //printfUART("NLME_START_ROUTER.request\n", "");
+       
+       device_type = ROUTER;
+       
+       if(TYPE_DEVICE == ROUTER)
+       {
+       
+               //assign current BO and SO
+               beaconorder = BeaconOrder;
+               superframeorder = SuperframeOrder;
+       
+               call MLME_SET.request(MACBEACONORDER, (uint8_t *)&BeaconOrder);
+               
+               call MLME_SET.request(MACSUPERFRAMEORDER, (uint8_t *)&SuperframeOrder);
+               
+               //*******************************************************
+               //***********SET PAN VARIABLES***************************
+               depth=DEVICE_DEPTH;
+               
+               nwk_IB.nwkAvailableAddresses=AVAILABLEADDRESSES;
+               nwk_IB.nwkAddressIncrement= ADDRESSINCREMENT;
+               
+               nwk_IB.nwkMaxChildren=MAXCHILDREN;      //number of children a device is allowed to have on its current network
+               nwk_IB.nwkMaxDepth=MAXDEPTH;    //the depth a device can have
+               nwk_IB.nwkMaxRouters=MAXROUTERS;
+               
+               cskip = Cskip(depth);
+               
+               cskip_routing = Cskip(depth -1);
+               
+               nwk_IB.nwkNextAddress = networkaddress + (cskip * nwk_IB.nwkMaxRouters) + nwk_IB.nwkAddressIncrement;
+       
+               next_child_router_address = networkaddress +((number_child_router-1) * cskip) +1;
+       
+               
+               number_child_router++;
+               
+               
+               printfUART("cskip  %d\n", cskip);
+               printfUART("C %d D %d r %d\n", MAXCHILDREN,MAXDEPTH,MAXROUTERS);
+       
+               //  command error_t request(uint32_t PANId, uint8_t LogicalChannel, uint8_t BeaconOrder, uint8_t SuperframeOrder,bool PANCoordinator,bool BatteryLifeExtension,bool CoordRealignment,bool SecurityEnable);
+               call MLME_START.request(panid,LOGICAL_CHANNEL,BeaconOrder, SuperframeOrder, 0, 0,0,0,StartTime);
+               
+       }
+       else
+       {
+       
+               signal NLME_START_ROUTER.confirm(NWK_INVALID_REQUEST);
+               
+       }
+       return SUCCESS;
+}
+
+
+/*************************************************************/
+/******************NLME - NETWORK - FORMATION*****************/
+/*************************************************************/
+
+//This primitive allows the NHL to request to start a ZigBee network with itself as the coordinator
+//Page 167-169
+command error_t NLME_NETWORK_FORMATION.request(uint32_t ScanChannels, uint8_t ScanDuration, uint8_t BeaconOrder, uint8_t SuperframeOrder, uint16_t PANId, bool BatteryLifeExtension)
+{
+
+       uint8_t v_temp[6];
+
+call Leds.led0On();
+call Leds.led1On();
+call Leds.led2On();
+   
+       v_temp[0] = 0x06;
+       
+       device_type = COORDINATOR;
+       //device_type = ROUTER;
+       
+       call MLME_SET.request(MACMAXBEACONPAYLOADLENGTH,v_temp);
+       
+       //protocol ID
+       v_temp[0] = 0x00;
+       //uint8_t nwk_payload_profile_protocolversion(uint8_t stackprofile,uint8_t nwkcprotocolversion)
+       v_temp[1] = nwk_payload_profile_protocolversion(0x00,0x00);
+       //uint8_t nwk_payload_capacity(uint8_t routercapacity,uint8_t devicedepth,uint8_t enddevicecapacity)
+       v_temp[2] = nwk_payload_capacity(0x01,0x00,0x01);
+       
+       //TX OFFSET (3 bytes)
+       v_temp[3] = 0x56;
+       v_temp[4] = 0x34;
+       v_temp[5] = 0x12;
+       
+       
+       call MLME_SET.request(MACBEACONPAYLOAD,v_temp);
+       
+
+       printfUART("NLME_NETWORK_FORMATION.request\n", "");
+       //perform an energydetection scan
+       //perform an active scan
+       //and select a suitable channel
+       //panid must be less than or equal to 0x3fff
+       
+       //assign current panid
+       panid=PANId;
+       
+       //assign current BO and SO
+       beaconorder = BeaconOrder;
+       superframeorder = SuperframeOrder;
+       
+       call MLME_SET.request(MACBEACONORDER, (uint8_t *)&BeaconOrder);
+
+       call MLME_SET.request(MACSUPERFRAMEORDER, (uint8_t *)&SuperframeOrder);
+       
+       v_temp[0] = (uint8_t)(PANId >> 8);
+       v_temp[1] = (uint8_t)PANId;
+       
+       call MLME_SET.request(MACPANID, v_temp);
+
+       //static assignement of the coordinator address
+       networkaddress=0x0000;//Network address of the ZC of a network always 0x0000;
+       
+       //////printfUART("setting short addr: %i\n", networkaddress);
+       
+       v_temp[0] = (uint8_t)(networkaddress >> 8);
+       v_temp[1] = (uint8_t)(networkaddress);
+
+       
+       call MLME_SET.request(MACSHORTADDRESS,v_temp);
+       
+       
+       //*******************************************************
+       //***********SET PAN VARIABLES***************************
+       //nwk_IB.nwkNextAddress=networkaddress+0x0001;
+       depth=DEVICE_DEPTH;
+       nwk_IB.nwkAvailableAddresses=AVAILABLEADDRESSES;
+       nwk_IB.nwkAddressIncrement= ADDRESSINCREMENT;
+       
+       nwk_IB.nwkMaxChildren=MAXCHILDREN;      //number of children a device is allowed to have on its current network
+       nwk_IB.nwkMaxDepth=MAXDEPTH;    //the depth a device can have
+       nwk_IB.nwkMaxRouters=MAXROUTERS;
+       
+       cskip = Cskip(depth);
+       
+       cskip_routing = Cskip(depth -1 );
+       
+       nwk_IB.nwkNextAddress = networkaddress + (cskip * nwk_IB.nwkMaxRouters) + nwk_IB.nwkAddressIncrement;
+       
+       next_child_router_address = networkaddress +((number_child_router-1) * cskip) +1;
+       
+       number_child_router++;
+       
+       printfUART("cskip  %d\n", cskip);
+       printfUART("C %d D %d r %d\n", MAXCHILDREN,MAXDEPTH,MAXROUTERS);
+       
+       
+       call MLME_START.request(PANId, LOGICAL_CHANNEL,BeaconOrder ,SuperframeOrder,1,0,0,0,0);
+       
+
+
+
+    
+
+
+
+
+       return SUCCESS;
+}
+       
+/*************************************************************/
+/***************NLME - NETWORK - DISCOVERY *******************/
+/*************************************************************/
+
+//This primitive allows the next higher layer to request that the NWK layer discover networks currently operating within the POS.
+//p164 and 210
+command error_t NLME_NETWORK_DISCOVERY.request(uint32_t ScanChannels, uint8_t Scanduration)
+{
+       
+       //ISSUE an MLME_SCAN.request to find the available networks
+       //Temporary descover of the network
+       //Channel Scan is not working properly
+       //manually assign the network descriptor
+       
+       
+       networkdescriptor networkdescriptorlist[1];
+
+       printfUART("2 lauch passive scan\n", "");
+       //The networkdescriptorlist must contain information about every network that was heard
+       
+       //make NetworkDescriptorList out of the PanDescriptorList
+#ifndef TKN154_MAC
+    call MLME_SCAN.request(PASSIVE_SCAN,0xFFFFFFFF,7);
+#else
+
+
+       networkdescriptorlist[0].PANId=0x1234;
+       networkdescriptorlist[0].LogicalChannel=LOGICAL_CHANNEL;
+       networkdescriptorlist[0].StackProfile=0x00;
+       networkdescriptorlist[0].ZigBeeVersion=0x01;
+       networkdescriptorlist[0].BeaconOrder=7;
+       networkdescriptorlist[0].SuperframeOrder=6;
+       networkdescriptorlist[0].PermitJoining=1;
+       
+       //temporary assignement on the neighbout table of the suitable PAN coordinator
+       if (DEVICE_DEPTH == 0x01)
+               add_neighbortableentry(networkdescriptorlist[0].PANId,D1_PAN_EXT0,D1_PAN_EXT1,D1_PAN_SHORT,COORDINATOR,NEIGHBOR_IS_PARENT);
+       if (DEVICE_DEPTH == 0x02)
+               add_neighbortableentry(networkdescriptorlist[0].PANId,D2_PAN_EXT0,D2_PAN_EXT1,D2_PAN_SHORT,COORDINATOR,NEIGHBOR_IS_PARENT);
+       if (DEVICE_DEPTH == 0x03)
+               add_neighbortableentry(networkdescriptorlist[0].PANId,D3_PAN_EXT0,D3_PAN_EXT1,D3_PAN_SHORT,COORDINATOR,NEIGHBOR_IS_PARENT);
+       if (DEVICE_DEPTH == 0x04)
+               add_neighbortableentry(networkdescriptorlist[0].PANId,D4_PAN_EXT0,D4_PAN_EXT1,D4_PAN_SHORT,COORDINATOR,NEIGHBOR_IS_PARENT);
+#endif 
+               
+       signal NLME_NETWORK_DISCOVERY.confirm(1,networkdescriptorlist, NWK_SUCCESS);
+
+       return SUCCESS;
+}
+
+/*************************************************************/
+/************************NLME - JOIN**************************/
+/*************************************************************/
+//This primitive allows the NHL to request to join a network either through association.
+//p173 and 210
+command error_t NLME_JOIN.request(uint16_t PANId, bool JoinAsRouter, bool RejoinNetwork, uint32_t ScanChannels, uint8_t ScanDuration, uint8_t PowerSource, uint8_t RxOnWhenIdle, uint8_t MACSecurity)
+{      
+
+       //Assume we have selected a suitable parent and all previous conditions were true
+       uint32_t destinaddress[2];
+       
+       printfUART("9 find parent\n", "");
+       
+       //list_neighbourtable();
+       
+       parent_index = find_suitable_parent();
+       
+       panid = PANId;
+       
+       //printfUART("NLME_JOIN %i %i\n", parent_index,panid); 
+       
+       if(parent_index == 0)
+       {
+               signal NLME_JOIN.confirm(PANId,NWK_NOT_PERMITTED);
+       }
+       else
+       {
+               //assign the true value to parent index
+               parent_index = parent_index - 1;
+                               
+               //destinaddress[0]=neighbortable[parent_index].Extended_Address0;
+               //destinaddress[1]=neighbortable[parent_index].Extended_Address1;
+               //verificar o endere�o do pan coordinator
+               destinaddress[0]=0x00000000;
+               
+               
+               destinaddress[1] = neighbortable[parent_index].Network_Address;
+#ifdef TKN154_MAC              
+               
+               if (DEVICE_DEPTH == 0x01)
+                       destinaddress[1]=D1_PAN_SHORT;
+               if (DEVICE_DEPTH == 0x02)
+                       destinaddress[1]=D2_PAN_SHORT;
+               if (DEVICE_DEPTH == 0x03)
+                       destinaddress[1]=D3_PAN_SHORT;
+               if (DEVICE_DEPTH == 0x04)
+                       destinaddress[1]=D4_PAN_SHORT;
+                       
+#endif                 
+               printfUART("10 associate to %i\n", destinaddress[1]);   
+               //set_capability_information(uint8_t alternate_PAN_coordinator, uint8_t device_type, uint8_t power_source, uint8_t receiver_on_when_idle, uint8_t security, uint8_t allocate_address)
+               
+               if (JoinAsRouter == 0x01)
+                       call MLME_ASSOCIATE.request(LOGICAL_CHANNEL,SHORT_ADDRESS,PANId,destinaddress, set_capability_information(JoinAsRouter,0x01,PowerSource,RxOnWhenIdle,MACSecurity,0x01),0);
+               else
+               {
+               
+                       printfUART("11 go ass\n", "");  
+               
+                       coordinator_addr[0]=0x00000000;
+                       coordinator_addr[1] = neighbortable[parent_index].Network_Address;
+                       //BUILD the PAN descriptor of the COORDINATOR
+                       //assuming that the adress is short
+                       pan_des.CoordAddrMode = SHORT_ADDRESS;
+                       pan_des.CoordPANId = panid;
+                       pan_des.CoordAddress0=0x00000000;
+                       pan_des.CoordAddress1=(uint32_t)neighbortable[parent_index].Network_Address;
+                       pan_des.LogicalChannel=neighbortable[parent_index].Logical_Channel;
+                       //superframe specification field
+                       //pan_des.SuperframeSpec = neighbortable[parent_index].SuperframeSpec;
+
+                       pan_des.GTSPermit=0x01;
+                       pan_des.LinkQuality=0x00;
+                       pan_des.TimeStamp=0x000000;
+                       pan_des.SecurityUse=0;
+                       pan_des.ACLEntry=0x00;
+                       pan_des.SecurityFailure=0x00;
+       
+                       received_beacon_count=0;
+                       go_associate=1;
+#ifdef TKN154_MAC
+
+                       
+                       //call MLME_ASSOCIATE.request(LOGICAL_CHANNEL,SHORT_ADDRESS,PANId,destinaddress, set_capability_information(JoinAsRouter,0x00,PowerSource,RxOnWhenIdle,MACSecurity,0x01),0);
+#endif
+               }
+       }
+       
+       return SUCCESS;
+}
+
+
+/*************************************************************/
+/************************NLME - LEAVE*************************/
+/*************************************************************/
+
+//This primitive allows the NHL to request that it or another device leaves the network
+//page 181-183
+command error_t NLME_LEAVE.request(uint32_t DeviceAddress[],bool RemoveChildren, bool MACSecurityEnable)
+{      
+       uint32_t devaddr[2];
+       ////printfUART("NLME_LEAVE.request\n", ""); 
+       if (DeviceAddress == 0)//child asked to leave
+       {       
+               if(RemoveChildren == 0)//implemented like it is always 0
+               {       
+                       //send leave request command frame: RemoveChildren subfield=0 of the command option field of the command frame payload
+                       //call MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint8_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint8_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions);
+                       devaddr[0]=neighbortable[parent].Extended_Address0;
+                       devaddr[1]=neighbortable[parent].Extended_Address1;
+                       call MLME_DISASSOCIATE.request(devaddr,0x02,0);
+               }
+               else
+               {
+                       //send leave request command frame: RemoveChildren subfield=1
+                       //try to remove the children, call NLME_LEAVE.request(uint32_t DeviceAddress[]=address of child,bool RemoveChildren, bool MACSecurityEnable)
+                       //call MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint8_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint8_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions);
+               }
+       }
+       else//parent forced a child to leave
+       {
+               //if(check_neighbortableentry(DeviceAddress[0], DeviceAddress[1]) == 0)
+               //{
+               //      signal NLME_LEAVE.confirm(DeviceAddress,NWK_UNKNOWN_DEVICE);
+               //      //call MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint8_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint8_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions);
+               //}
+               
+       }
+       
+       
+       return SUCCESS;
+}
+
+/*************************************************************/
+/************************NLME - SYNC**************************/
+/*************************************************************/
+
+//This primitive allows the NHL to synchronize or extract data from its ZigBee coordinator or router
+//page 186-187
+command error_t NLME_SYNC.request(bool Track)
+{
+//call MLME_SET.request(0x00,0x15);
+ // call MLME_SET.request(MACCOORDSHORTADDRESS, 0x0000);
+  //   call MLME_SET.request(0x50,0x1234);
+
+  call MLME_SYNC.request(LOGICAL_CHANNEL,1);
+       return SUCCESS;
+}
+  
+/*************************************************************/
+/*****************        NLME-SET     ********************/
+/*************************************************************/
+       
+command error_t NLME_SET.request(uint8_t NIBAttribute, uint16_t NIBAttributeLength, uint16_t NIBAttributeValue)
+{
+
+       atomic{
+       
+               switch(NIBAttribute)
+               {
+                       case NWKSEQUENCENUMBER :                nwk_IB.nwkSequenceNumber = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkSequenceNumber: %x\n",nwk_IB.nwkSequenceNumber);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                                                                                       
+                       case NWKPASSIVEACKTIMEOUT :             nwk_IB.nwkPassiveAckTimeout = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkPassiveAckTimeout: %x\n",nwk_IB.nwkPassiveAckTimeout);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                       
+                       
+                       case NWKMAXBROADCASTRETRIES :   nwk_IB.nwkMaxBroadcastRetries = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkMaxBroadcastRetries: %x\n",nwk_IB.nwkMaxBroadcastRetries);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                                                                                       
+                       case NWKMAXCHILDREN :                   nwk_IB.nwkMaxChildren = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkMaxChildren: %x\n",nwk_IB.nwkMaxChildren);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                                                                                       
+                       case NWKMAXDEPTH :                              nwk_IB.nwkMaxDepth = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkMaxDepth: %x\n",nwk_IB.nwkMaxDepth);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+       
+                       case NWKMAXROUTERS :                    nwk_IB.nwkMaxRouters = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkMaxRouters: %x\n",nwk_IB.nwkMaxRouters);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+       
+                       case NWKMETWORKBROADCASTDELIVERYTIME :          nwk_IB.nwkNetworkBroadcastDeliveryTime = (uint8_t) NIBAttributeValue;
+                                                                                                               //////printfUART("nwk_IB.nwkNetworkBroadcastDeliveryTime: %x\n",nwk_IB.nwkNetworkBroadcastDeliveryTime);
+                                                                                                               signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                                               break;
+                       case NWKREPORTCONSTANTCOST :    nwk_IB.nwkReportConstantCost = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkReportConstantCost: %x\n",nwk_IB.nwkReportConstantCost);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                       case NWKROUTEDISCOVERYRETRIESPERMITED :         nwk_IB.nwkRouteDiscoveryRetriesPermitted = (uint8_t) NIBAttributeValue;
+                                                                                                               //////printfUART("nwk_IB.nwkRouteDiscoveryRetriesPermitted: %x\n",nwk_IB.nwkRouteDiscoveryRetriesPermitted);
+                                                                                                               signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                                               break;
+       
+                       case NWKSYMLINK :                               nwk_IB.nwkSymLink = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkSymLink: %x\n",nwk_IB.nwkSymLink);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                       
+                       case NWKCAPABILITYINFORMATION : nwk_IB.nwkCapabilityInformation = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkCapabilityInformation: %x\n",nwk_IB.nwkCapabilityInformation);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                                                                                       
+                       case NWKUSETREEADDRALLOC :              nwk_IB.nwkUseTreeAddrAlloc = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkUseTreeAddrAlloc: %x\n",nwk_IB.nwkUseTreeAddrAlloc);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                                                                                       
+                       case NWKUSETREEROUTING :                nwk_IB.nwkUseTreeRouting = (uint8_t) NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkUseTreeRouting: %x\n",nwk_IB.nwkUseTreeRouting);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                                                                                       
+                       case NWKNEXTADDRESS :                   nwk_IB.nwkNextAddress = NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkNextAddress: %x\n",nwk_IB.nwkNextAddress);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                                                                                       
+                       case NWKAVAILABLEADDRESSES :    nwk_IB.nwkAvailableAddresses = NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkAvailableAddresses: %x\n",nwk_IB.nwkAvailableAddresses);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                                                                                       
+                       case NWKADDRESSINCREMENT :              nwk_IB.nwkAddressIncrement =NIBAttributeValue;
+                                                                                       //////printfUART("nwk_IB.nwkAddressIncrement: %x\n",nwk_IB.nwkAddressIncrement);
+                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                       break;
+                                                                                       
+                       case NWKTRANSACTIONPERSISTENCETIME :    nwk_IB.nwkTransactionPersistenceTime = (uint8_t) NIBAttributeValue;
+                                                                                                       //////printfUART("nwk_IB.nwkTransactionPersistenceTime: %x\n",nwk_IB.nwkTransactionPersistenceTime);
+                                                                                                       signal NLME_SET.confirm(NWK_SUCCESS,NIBAttribute);
+                                                                                                       break;
+                                                                                       
+                       default:                                                signal NLME_SET.confirm(NWK_UNSUPPORTED_ATTRIBUTE,NIBAttribute);
+                                                                                       break;
+                       
+               }
+               
+       }
+
+
+       return SUCCESS;
+}
+
+/*************************************************************/
+/*****************        NLME-GET     ********************/
+/*************************************************************/
+       
+command error_t NLME_GET.request(uint8_t NIBAttribute)
+{
+       switch(NIBAttribute)
+       {
+               case NWKSEQUENCENUMBER :                signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkSequenceNumber);
+                                                                               break;
+                                                                       
+               case NWKPASSIVEACKTIMEOUT :             signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkPassiveAckTimeout);
+                                                                               break;
+               
+               case NWKMAXBROADCASTRETRIES :   signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkMaxBroadcastRetries);
+                                                                               break;
+
+               case NWKMAXCHILDREN :                   signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkMaxChildren);
+                                                                               break;
+
+               case NWKMAXDEPTH :                              signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkMaxDepth);
+                                                                               break;
+
+               case NWKMAXROUTERS :                    signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkMaxRouters);
+                                                                               break;
+
+               case NWKMETWORKBROADCASTDELIVERYTIME :          signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkNetworkBroadcastDeliveryTime);
+                                                                                                       break;
+
+               case NWKREPORTCONSTANTCOST :    signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkReportConstantCost);
+                                                                               break;
+
+               case NWKROUTEDISCOVERYRETRIESPERMITED :         signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkRouteDiscoveryRetriesPermitted);
+                                                                                                       break;
+
+               case NWKSYMLINK :                               signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkSymLink);
+                                                                               break;
+               
+               case NWKCAPABILITYINFORMATION : signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkCapabilityInformation);
+                                                                               break;
+                                                                               
+               case NWKUSETREEADDRALLOC :              signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkUseTreeAddrAlloc);
+                                                                               break;
+                                                                               
+               case NWKUSETREEROUTING :                signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkUseTreeRouting);
+                                                                               break;
+                                                                               
+               case NWKNEXTADDRESS :                   signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0002,(uint16_t)&nwk_IB.nwkNextAddress);
+                                                                               break;
+
+               case NWKAVAILABLEADDRESSES :    signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0002,(uint16_t)&nwk_IB.nwkAvailableAddresses);
+                                                                               break;
+                                                                               
+               case NWKADDRESSINCREMENT :              signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0002,(uint16_t)&nwk_IB.nwkAddressIncrement);
+                                                                               break;
+                                                                               
+               case NWKTRANSACTIONPERSISTENCETIME :    signal NLME_GET.confirm(NWK_SUCCESS,NIBAttribute,0x0001,(uint16_t)&nwk_IB.nwkTransactionPersistenceTime);
+                                                                                               break;
+
+               default:                                                signal NLME_GET.confirm(NWK_UNSUPPORTED_ATTRIBUTE,NIBAttribute,0x0000,0x00);
+                                                                               break;
+       }
+       
+       return SUCCESS;
+}
+
+
+/*************************************************************/
+/**************neighbor table management functions************/
+/*************************************************************/
+
+//check if a specific neighbourtable Entry is present
+//Return 0:Entry is not present
+//Return i:Entry is present and return the index of the entry + 1
+       uint8_t check_neighbortableentry(uint8_t addrmode,uint32_t Address0,uint32_t Address1)
+       {       
+               
+               int i=0;
+               
+               
+               //printfUART("neighbourtable check c %i\n", neighbour_count);
+       
+               if (neighbour_count == 0)
+               {
+                       //printfUART("no neib\n", "");
+                       return 0;
+               }
+               
+               if(addrmode == SHORT_ADDRESS)
+               {       
+                       for(i=0; i < neighbour_count; i++)
+                       {       
+                               ///printfUART("compare %i %i\n", neighbortable[i].Network_Address, test);
+                               
+                               if(neighbortable[i].Network_Address == (uint16_t) Address0)
+                               {
+                                       //printfUART("already present \n", "" );
+                                       return i+1;
+                               }
+                       }
+                       return 0;
+               }
+               else
+               {
+                       for(i=0; i<neighbour_count; i++)
+                       {       
+                               ////printfUART("compare %x %x\n", neighbortable[i].Extended_Address0, Address0);
+                               if( (neighbortable[i].Extended_Address0 == Address0) && (neighbortable[i].Extended_Address1 == Address1))
+                               {
+                                       //printfUART("already present \n", "" );
+                                       return i+1;
+                               }
+                       }
+                       return 0;
+               }
+               
+               return 0;
+       }
+       
+       //function user to find a parent in the neighbour table
+       //Return 0:no parent is present
+       //Return i:parent is present and return the index of the entry + 1
+       uint8_t find_suitable_parent()
+       {
+               int i =0;
+               for (i=0; i<neighbour_count; i++)
+               {
+                       if(neighbortable[i].Relationship == NEIGHBOR_IS_PARENT)
+                       {
+                               return i+1;
+                       }
+               }
+               return 0;
+       }
+
+
+       //add a neighbortable entry     
+       void add_neighbortableentry     (uint16_t PAN_Id,uint32_t Extended_Address0,uint32_t Extended_Address1,uint32_t Network_Address,uint8_t Device_Type,uint8_t Relationship)
+       {
+       
+       atomic{
+               neighbortable[neighbour_count].PAN_Id=PAN_Id;
+               neighbortable[neighbour_count].Extended_Address0=Extended_Address0;
+               neighbortable[neighbour_count].Extended_Address1=Extended_Address1;
+               neighbortable[neighbour_count].Network_Address=Network_Address;
+               neighbortable[neighbour_count].Device_Type=Device_Type;
+               neighbortable[neighbour_count].Relationship=Relationship;
+               
+               neighbour_count++;
+               }
+               
+       }
+
+
+       
+       //update a neighbourtable entry
+       void update_neighbortableentry(uint16_t PAN_Id,uint32_t Extended_Address0,uint32_t Extended_Address1,uint32_t Network_Address,uint8_t Device_Type,uint8_t Relationship)
+       {
+               //search entry with correct extended address
+               uint8_t nrofEntry=0;
+               nrofEntry = check_neighbortableentry(0x01,Extended_Address0,Extended_Address1) - 1;
+               
+               //update every attribute
+               neighbortable[nrofEntry].PAN_Id=PAN_Id;
+               neighbortable[nrofEntry].Extended_Address0=Extended_Address0;
+               neighbortable[nrofEntry].Extended_Address1=Extended_Address1;
+               neighbortable[nrofEntry].Network_Address=Network_Address;
+               neighbortable[nrofEntry].Device_Type=Device_Type;
+               neighbortable[nrofEntry].Relationship=Relationship;
+               
+               ////printfUART("updated neighbourtable entry\n", "");
+       }
+
+
+       void list_neighbourtable()
+       {
+               int i;
+               ////printfUART("N List Count: %u\n", neighbour_count);
+       
+               for(i=0;i<neighbour_count;i++)
+               {
+                       printfUART("Panid %x", neighbortable[i].PAN_Id);
+                       printfUART("Extaddr0 %x", neighbortable[i].Extended_Address0);
+                       printfUART("Extaddr1 %x", neighbortable[i].Extended_Address1);
+                       printfUART("nwkaddr %u", neighbortable[i].Network_Address);
+                       printfUART("devtype %u", neighbortable[i].Device_Type);
+                       printfUART("relation %u", neighbortable[i].Relationship);
+                       printfUART("depth %u\n", neighbortable[i].Depth);               
+               }
+       }
+/*************************************************************/
+/*****************Address Assignment functions****************/
+/*************************************************************/
+
+//calculate the size of the address sub-block for a router at depth d
+uint16_t Cskip(uint8_t d)
+{      
+       uint8_t skip;
+       uint8_t power;
+       uint8_t x=1;
+       uint8_t Cm = nwk_IB.nwkMaxChildren;
+       uint8_t Rm = nwk_IB.nwkMaxRouters;
+       uint8_t Lm = nwk_IB.nwkMaxDepth;
+       /*////printfUART("nwk_IB.nwkMaxChildren: %i\n",  nwk_IB.nwkMaxChildren);
+       ////printfUART("nwk_IB.nwkMaxRouters: %i\n", nwk_IB.nwkMaxRouters);
+       ////printfUART("nwk_IB.nwkMaxDepth: %i\n", nwk_IB.nwkMaxDepth);*/
+       if (Rm == 1)
+       {
+               skip = 1 + Cm * (Lm - d - 1);
+       }
+       else
+       {       
+               int i;
+               
+               power=(Lm - d - 1);
+               for(i=0;i<power;i++)
+               {
+                       x=x*Rm;
+               }
+               skip = (1 + Cm - Rm - (Cm * x))/(1-Rm);
+       }
+       ////printfUART("Cksip function calculated: %i\n", skip);
+       return skip;
+}
+
+//Calculate the nexthopaddress of the appropriate child if route down is required
+uint16_t nexthopaddress(uint16_t destinationaddress,uint8_t d)
+{
+       uint16_t next_hop;
+
+       next_hop=(networkaddress + 1 + ((destinationaddress-(networkaddress+1))/cskip)* cskip);
+       
+       ////printfUART("Nexthop address calculated: %i\n", next_hop);
+       return next_hop;
+}
+
+/*************************************************************/
+/*****************Initialization functions********************/
+/*************************************************************/
+       //initialization of the nwk IB
+       void init_nwkIB()
+       {       
+               //nwk IB default values p 204-206
+               nwk_IB.nwkPassiveAckTimeout=0x03;
+               nwk_IB.nwkMaxBroadcastRetries=0x03;
+               nwk_IB.nwkMaxChildren=0x07;     //number of children a device is allowed to have on its current network
+               nwk_IB.nwkMaxDepth=0x05;        //the depth a device can have
+               nwk_IB.nwkMaxRouters=0x02;      //number of routers anyone device is allowed to have on its current network
+               //neighbortableentry nwkNeighborTable[];//null set
+               nwk_IB.nwkNetworkBroadcastDeliveryTime=( nwk_IB.nwkPassiveAckTimeout * nwk_IB.nwkMaxBroadcastRetries );
+               nwk_IB.nwkReportConstantCost=0x00;
+               nwk_IB.nwkRouteDiscoveryRetriesPermitted=nwkcDiscoveryRetryLimit;
+       //set? nwkRouteTable;//Null set
+               nwk_IB.nwkSymLink=0;
+               nwk_IB.nwkCapabilityInformation=0x00;
+               nwk_IB.nwkUseTreeAddrAlloc=1;
+               nwk_IB.nwkUseTreeRouting=1;
+               nwk_IB.nwkNextAddress=0x0000;
+               nwk_IB.nwkAvailableAddresses=0x0000;
+               nwk_IB.nwkAddressIncrement=0x0001;
+               nwk_IB.nwkTransactionPersistenceTime=0x01f4;
+       }
+
+
+  
+}
+
index a4eefd61f27b67cb38202827bc697f97bb96f08c..b5df87282fa5fa44fc9b2fa82117204771b694d7 100644 (file)
@@ -20,7 +20,7 @@
 #define DEVICE_DEPTH 0x01
 
 //used to operate in a fixed channel
-#define LOGICAL_CHANNEL 0x15
+#define LOGICAL_CHANNEL 0x1A
 
 //PAN VARIABLES
 //conflict error
diff --git a/tos/lib/net/zigbee/ieee802154/phy/Phy.nc b/tos/lib/net/zigbee/ieee802154/phy/Phy.nc
deleted file mode 100644 (file)
index a66da76..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-
-#include "CC2420.h"
-#include "IEEE802154.h"
-
-configuration Phy {
-
-  provides interface SplitControl;
-  
- // provides interface Test_send;
-  
-  
-  //ieee802.15.4 phy interfaces
-  provides interface PD_DATA;
-  
-  provides interface PLME_ED;
-  provides interface PLME_CCA;
-  provides interface PLME_SET;
-  provides interface PLME_GET;
-  provides interface PLME_SET_TRX_STATE;
-  
-}
-
-implementation {
-
-       components PhyM;
-       
-       components MainC;
-       MainC.SoftwareInit -> PhyM;
-       
-       
-       SplitControl = PhyM;
-       
-       //Test_send = PhyM;
-       
-       components CC2420ControlC;
-       PhyM.Resource -> CC2420ControlC;
-       PhyM.CC2420Power -> CC2420ControlC;
-       PhyM.CC2420Config ->CC2420ControlC;
-       
-       components CC2420TransmitC;
-       PhyM.SubControl -> CC2420TransmitC;
-       
-       PhyM.Sendframe ->CC2420TransmitC;
-       
-       components CC2420ReceiveC;
-       
-       //Receive = CC2420ReceiveC;
-       
-       
-       PhyM.SubControl -> CC2420ReceiveC;
-       
-       
-       PhyM.Receiveframe ->CC2420ReceiveC;
-       
-       
-       components RandomC;
-       PhyM.Random -> RandomC;
-       
-       components LedsC as Leds;
-       PhyM.Leds -> Leds;
-       
-       
-       PD_DATA=PhyM;
-       
-       PLME_ED=PhyM;
-       PLME_CCA=PhyM;
-       PLME_GET = PhyM;
-       PLME_SET=PhyM;
-       PLME_SET_TRX_STATE=PhyM;
-}
diff --git a/tos/lib/net/zigbee/ieee802154/phy/PhyC.nc b/tos/lib/net/zigbee/ieee802154/phy/PhyC.nc
new file mode 100644 (file)
index 0000000..c4a5ec5
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+
+#include "CC2420.h"
+#include "IEEE802154.h"
+
+configuration PhyC {
+
+  provides interface SplitControl;
+  
+ // provides interface Test_send;
+  
+  
+  //ieee802.15.4 phy interfaces
+  provides interface PD_DATA;
+  
+  provides interface PLME_ED;
+  provides interface PLME_CCA;
+  provides interface PLME_SET;
+  provides interface PLME_GET;
+  provides interface PLME_SET_TRX_STATE;
+  
+}
+
+implementation {
+
+       components PhyP;
+       
+       components MainC;
+       MainC.SoftwareInit -> PhyP;
+       
+       
+       SplitControl = PhyP;
+       
+       //Test_send = PhyP;
+       
+       components CC2420ControlC;
+       PhyP.Resource -> CC2420ControlC;
+       PhyP.CC2420Power -> CC2420ControlC;
+       PhyP.CC2420Config ->CC2420ControlC;
+       
+       components CC2420TransmitC;
+       PhyP.SubControl -> CC2420TransmitC;
+       
+       PhyP.Sendframe ->CC2420TransmitC;
+       
+       components CC2420ReceiveC;
+       
+       //Receive = CC2420ReceiveC;
+       
+       
+       PhyP.SubControl -> CC2420ReceiveC;
+       
+       
+       PhyP.Receiveframe ->CC2420ReceiveC;
+       
+       
+       components RandomC;
+       PhyP.Random -> RandomC;
+       
+       components LedsC as Leds;
+       PhyP.Leds -> Leds;
+       
+       
+       PD_DATA=PhyP;
+       
+       PLME_ED=PhyP;
+       PLME_CCA=PhyP;
+       PLME_GET = PhyP;
+       PLME_SET=PhyP;
+       PLME_SET_TRX_STATE=PhyP;
+}
diff --git a/tos/lib/net/zigbee/ieee802154/phy/PhyM.nc b/tos/lib/net/zigbee/ieee802154/phy/PhyM.nc
deleted file mode 100644 (file)
index 457f176..0000000
+++ /dev/null
@@ -1,345 +0,0 @@
-/*
- * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
- * @author Andre Cunha
- *
- */
-
-#include "frame_format.h"
-
-#include "phy_const.h"
-#include "phy_enumerations.h"
-
-module PhyM {
-
-       provides interface SplitControl;
-       // provides interface Test_send;
-       
-       
-       //ieee802.15.4 phy interfaces
-       provides interface PD_DATA;
-       
-       provides interface PLME_ED;
-       provides interface PLME_CCA;
-       provides interface PLME_SET;
-       provides interface PLME_GET;
-       provides interface PLME_SET_TRX_STATE;
-       
-       
-       provides interface Init;
-       
-       uses interface Resource;
-       uses interface CC2420Power;
-       uses interface CC2420Config;
-       uses interface StdControl as SubControl;
-       
-       uses interface Random;
-       uses interface Leds;
-       
-       uses interface Sendframe;
-       
-       uses interface Receiveframe;
-
-}
-
-implementation {
-
-
-       phyPIB phy_PIB;
-       
-       //transceiver current status
-       //it can only be PHY_TRX_OFF, PHY_RX_ON and PHY_TX_ON
-       uint8_t currentRxTxState = PHY_TRX_OFF;
-       
-       //message received
-       //norace MPDU rxmpdu;
-       MPDU *rxmpdu_ptr;
-
-  
-  error_t sendErr = SUCCESS;
-
-  
-  
-  /** TRUE if we are to use CCA when sending the current packet */
-  norace bool ccaOn;
-  
-  /****************** Prototypes ****************/
-  task void startDone_task();
-  task void startDone_task();
-  task void stopDone_task();
-  task void sendDone_task();
-  
-  void shutdown();
-
-
-
-/***************** Init Commands ****************/
-  command error_t Init.init() {
-  
-  //atomic rxmpdu_ptr = &rxmpdu;
-  
-  //TODO
-  /*
-       //PHY PIB initialization
-       //phy_PIB.phyCurrentChannel=INIT_CURRENTCHANNEL;
-       phy_PIB.phyCurrentChannel=LOGICAL_CHANNEL;
-       phy_PIB.phyChannelsSupported=INIT_CHANNELSSUPPORTED;
-       phy_PIB.phyTransmitPower=INIT_TRANSMITPOWER;
-       phy_PIB.phyCcaMode=INIT_CCA_MODE;
-  */
-  
-    return SUCCESS;
-  }
-
-
-  /***************** SplitControl Commands ****************/
-  command error_t SplitControl.start() {
-   
-               //arrancar o controlo
-   
-      call CC2420Power.startVReg();
-         
-               
-      return SUCCESS;
-    
-
-  }
-
-  command error_t SplitControl.stop() {
-    return EBUSY;
-  }
-
-  /***************** Send Commands ****************/
-
-
-    async event void Sendframe.sendDone(error_t error )
-       {
-       
-           atomic sendErr = error;
-               post sendDone_task();
-       
-       }
-  
-  
-  
-
-  /**************** Events ****************/
-  async event void CC2420Power.startVRegDone() {
-    call Resource.request();
-
-  }
-  
-  event void Resource.granted() {
-    call CC2420Power.startOscillator();
-  }
-
-  async event void CC2420Power.startOscillatorDone() {
-    post startDone_task();
-  }
-  
-  
-  
-  /***************** Tasks ****************/
-  task void sendDone_task() {
-    error_t packetErr;
-    atomic packetErr = sendErr;
-       
-   // signal Send.sendDone( m_msg, packetErr );
-  }
-
-  task void startDone_task() {
-    call SubControl.start();
-    call CC2420Power.rxOn();
-    call Resource.release();
-  
-    signal SplitControl.startDone( SUCCESS );
-  }
-  
-  task void stopDone_task() {
-    
-    signal SplitControl.stopDone( SUCCESS );
-  }
-  
-  
-  /***************** Functions ****************/
-  /**
-   * Shut down all sub-components and turn off the radio
-   */
-  void shutdown() {
-    call SubControl.stop();
-    call CC2420Power.stopVReg();
-    post stopDone_task();
-  }
-
-  /***************** Defaults ***************/
-  default event void SplitControl.startDone(error_t error) {
-  }
-  
-  default event void SplitControl.stopDone(error_t error) {
-  }
-  
-  
-  
-  async event void Receiveframe.receive(uint8_t* frame, uint8_t rssi)
-  {
-  
-    rxmpdu_ptr=(MPDU*)frame;
-               
-       signal PD_DATA.indication(rxmpdu_ptr->length,(uint8_t*)rxmpdu_ptr, rssi);
-  /*
-  printfUART("n %i\n", TOS_NODE_ID); 
-  
-       printfUART("l %i\n", rxmpdu_ptr->length); 
-  printfUART("fc1 %i\n", rxmpdu_ptr->frame_control1); 
-  printfUART("fc2 %i\n", rxmpdu_ptr->frame_control2); 
-       printfUART("seq %i\n", rxmpdu_ptr->seq_num); 
-  
-  for (i=0;i<120;i++)
-  {
-       printfUART("d %i %x\n",i, rxmpdu_ptr->data[i]); 
-  
-  }
-  */
-  
-  
-  }
-  
-  
-  
-  event void CC2420Config.syncDone( error_t error )
-  {
-  
-  
-  
-  return;
-  }
-  
-  
-/*****************************************************************************************************/  
-/**************************************PD-DATA********************************************************/
-/*****************************************************************************************************/  
-
-
-async command error_t PD_DATA.request(uint8_t psduLength, uint8_t* psdu) {
-       
-       
-       call Sendframe.send(psdu,psduLength);
-
-
-       return SUCCESS;
-}
-
-
-/*****************************************************************************************************/  
-/********************************************PLME-ED**************************************************/
-/*****************************************************************************************************/  
-
-command error_t PLME_ED.request(){
-       //MAC asking for energy detection
-       //TODO
-       
-       return SUCCESS;
-}
-
-/*****************************************************************************************************/  
-/********************************************PLME-CCA*************************************************/
-/*****************************************************************************************************/
-
-command error_t PLME_CCA.request(){
-//MAC asking for CCA
-//TODO
-               
-       
-       return SUCCESS;
-}
-/*****************************************************************************************************/  
-/********************************************PLME-GET*************************************************/
-/*****************************************************************************************************/
-
-command error_t PLME_GET.request(uint8_t PIBAttribute){
-//MAC asking for PIBAttribute value
-  switch(PIBAttribute)
-               {
-                       case PHYCURRENTCHANNEL:
-                               signal PLME_GET.confirm(PHY_SUCCESS, PIBAttribute, phy_PIB.phyCurrentChannel);
-                               break;
-
-                       case PHYCHANNELSSUPPORTED:
-                               signal PLME_GET.confirm(PHY_SUCCESS, PIBAttribute, phy_PIB.phyChannelsSupported);
-                               break;
-
-                       case PHYTRANSMITPOWER:
-                               signal PLME_GET.confirm(PHY_SUCCESS, PIBAttribute, phy_PIB.phyTransmitPower);
-                               break;
-                       case PHYCCAMODE:
-                               signal PLME_GET.confirm(PHY_SUCCESS, PIBAttribute, phy_PIB.phyCcaMode);
-                               break;
-                       default:
-                               signal PLME_GET.confirm(PHY_UNSUPPORTED_ATTRIBUTE, PIBAttribute, 0x00);
-                               break;
-               }
-               
-  
-  return SUCCESS;
-  }
-  
-/*****************************************************************************************************/  
-/********************************************PLME-SET*************************************************/
-/*****************************************************************************************************/
-command error_t PLME_SET.request(uint8_t PIBAttribute, uint8_t PIBAttributeValue){
-  
-
-         //MAC is demanding for PHY to write the indicated PIB value
-         switch(PIBAttribute)
-                       {
-                               case PHYCURRENTCHANNEL:
-                                       
-                                       phy_PIB.phyCurrentChannel = PIBAttributeValue;
-                                       
-                                       call CC2420Config.setChannel(phy_PIB.phyCurrentChannel);
-                                       
-                                       call CC2420Config.sync();
-                                       
-                                       //TunePreset(phy_PIB.phyCurrentChannel);
-                                       signal PLME_SET.confirm(PHY_SUCCESS, PIBAttribute);
-                                       break;
-       
-                               case PHYCHANNELSSUPPORTED:
-                                       phy_PIB.phyChannelsSupported = PIBAttributeValue;
-                                       signal PLME_SET.confirm(PHY_SUCCESS, PIBAttribute);
-                                       break;
-       
-                               case PHYTRANSMITPOWER:
-                                       phy_PIB.phyTransmitPower= PIBAttributeValue;
-                                       //SetRFPower(phy_PIB.phyTransmitPower);
-                                       signal PLME_SET.confirm(PHY_SUCCESS, PIBAttribute);
-                                       break;
-                               case PHYCCAMODE:
-                                       phy_PIB.phyCcaMode= PIBAttributeValue;
-                                       signal PLME_SET.confirm(PHY_SUCCESS, PIBAttribute);
-                                       break;
-                               default:
-                                       signal PLME_SET.confirm(PHY_UNSUPPORTED_ATTRIBUTE, PIBAttribute);
-                                       break;
-                       }
-         return SUCCESS;
-}  
-
-/*****************************************************************************************************/  
-/**********************************PLME_SET_TRX_STATE*************************************************/
-/*****************************************************************************************************/
-
-
-async command error_t PLME_SET_TRX_STATE.request(uint8_t state){
-
-
-return SUCCESS;
-
-}
-
-
-
-}
-
diff --git a/tos/lib/net/zigbee/ieee802154/phy/PhyP.nc b/tos/lib/net/zigbee/ieee802154/phy/PhyP.nc
new file mode 100644 (file)
index 0000000..ca9c842
--- /dev/null
@@ -0,0 +1,345 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ *
+ */
+
+#include "frame_format.h"
+
+#include "phy_const.h"
+#include "phy_enumerations.h"
+
+module PhyP {
+
+       provides interface SplitControl;
+       // provides interface Test_send;
+       
+       
+       //ieee802.15.4 phy interfaces
+       provides interface PD_DATA;
+       
+       provides interface PLME_ED;
+       provides interface PLME_CCA;
+       provides interface PLME_SET;
+       provides interface PLME_GET;
+       provides interface PLME_SET_TRX_STATE;
+       
+       
+       provides interface Init;
+       
+       uses interface Resource;
+       uses interface CC2420Power;
+       uses interface CC2420Config;
+       uses interface StdControl as SubControl;
+       
+       uses interface Random;
+       uses interface Leds;
+       
+       uses interface Sendframe;
+       
+       uses interface Receiveframe;
+
+}
+
+implementation {
+
+
+       phyPIB phy_PIB;
+       
+       //transceiver current status
+       //it can only be PHY_TRX_OFF, PHY_RX_ON and PHY_TX_ON
+       uint8_t currentRxTxState = PHY_TRX_OFF;
+       
+       //message received
+       //norace MPDU rxmpdu;
+       MPDU *rxmpdu_ptr;
+
+  
+  error_t sendErr = SUCCESS;
+
+  
+  
+  /** TRUE if we are to use CCA when sending the current packet */
+  norace bool ccaOn;
+  
+  /****************** Prototypes ****************/
+  task void startDone_task();
+  task void startDone_task();
+  task void stopDone_task();
+  task void sendDone_task();
+  
+  void shutdown();
+
+
+
+/***************** Init Commands ****************/
+  command error_t Init.init() {
+  
+  //atomic rxmpdu_ptr = &rxmpdu;
+  
+  //TODO
+  /*
+       //PHY PIB initialization
+       //phy_PIB.phyCurrentChannel=INIT_CURRENTCHANNEL;
+       phy_PIB.phyCurrentChannel=LOGICAL_CHANNEL;
+       phy_PIB.phyChannelsSupported=INIT_CHANNELSSUPPORTED;
+       phy_PIB.phyTransmitPower=INIT_TRANSMITPOWER;
+       phy_PIB.phyCcaMode=INIT_CCA_MODE;
+  */
+  
+    return SUCCESS;
+  }
+
+
+  /***************** SplitControl Commands ****************/
+  command error_t SplitControl.start() {
+   
+               //arrancar o controlo
+   
+      call CC2420Power.startVReg();
+         
+               
+      return SUCCESS;
+    
+
+  }
+
+  command error_t SplitControl.stop() {
+    return EBUSY;
+  }
+
+  /***************** Send Commands ****************/
+
+
+    async event void Sendframe.sendDone(error_t error )
+       {
+       
+           atomic sendErr = error;
+               post sendDone_task();
+       
+       }
+  
+  
+  
+
+  /**************** Events ****************/
+  async event void CC2420Power.startVRegDone() {
+    call Resource.request();
+
+  }
+  
+  event void Resource.granted() {
+    call CC2420Power.startOscillator();
+  }
+
+  async event void CC2420Power.startOscillatorDone() {
+    post startDone_task();
+  }
+  
+  
+  
+  /***************** Tasks ****************/
+  task void sendDone_task() {
+    error_t packetErr;
+    atomic packetErr = sendErr;
+       
+   // signal Send.sendDone( m_msg, packetErr );
+  }
+
+  task void startDone_task() {
+    call SubControl.start();
+    call CC2420Power.rxOn();
+    call Resource.release();
+  
+    signal SplitControl.startDone( SUCCESS );
+  }
+  
+  task void stopDone_task() {
+    
+    signal SplitControl.stopDone( SUCCESS );
+  }
+  
+  
+  /***************** Functions ****************/
+  /**
+   * Shut down all sub-components and turn off the radio
+   */
+  void shutdown() {
+    call SubControl.stop();
+    call CC2420Power.stopVReg();
+    post stopDone_task();
+  }
+
+  /***************** Defaults ***************/
+  default event void SplitControl.startDone(error_t error) {
+  }
+  
+  default event void SplitControl.stopDone(error_t error) {
+  }
+  
+  
+  
+  async event void Receiveframe.receive(uint8_t* frame, uint8_t rssi)
+  {
+  
+    rxmpdu_ptr=(MPDU*)frame;
+               
+       signal PD_DATA.indication(rxmpdu_ptr->length,(uint8_t*)rxmpdu_ptr, rssi);
+  /*
+  printfUART("n %i\n", TOS_NODE_ID); 
+  
+       printfUART("l %i\n", rxmpdu_ptr->length); 
+  printfUART("fc1 %i\n", rxmpdu_ptr->frame_control1); 
+  printfUART("fc2 %i\n", rxmpdu_ptr->frame_control2); 
+       printfUART("seq %i\n", rxmpdu_ptr->seq_num); 
+  
+  for (i=0;i<120;i++)
+  {
+       printfUART("d %i %x\n",i, rxmpdu_ptr->data[i]); 
+  
+  }
+  */
+  
+  
+  }
+  
+  
+  
+  event void CC2420Config.syncDone( error_t error )
+  {
+  
+  
+  
+  return;
+  }
+  
+  
+/*****************************************************************************************************/  
+/**************************************PD-DATA********************************************************/
+/*****************************************************************************************************/  
+
+
+async command error_t PD_DATA.request(uint8_t psduLength, uint8_t* psdu) {
+       
+       
+       call Sendframe.send(psdu,psduLength);
+
+
+       return SUCCESS;
+}
+
+
+/*****************************************************************************************************/  
+/********************************************PLME-ED**************************************************/
+/*****************************************************************************************************/  
+
+command error_t PLME_ED.request(){
+       //MAC asking for energy detection
+       //TODO
+       
+       return SUCCESS;
+}
+
+/*****************************************************************************************************/  
+/********************************************PLME-CCA*************************************************/
+/*****************************************************************************************************/
+
+command error_t PLME_CCA.request(){
+//MAC asking for CCA
+//TODO
+               
+       
+       return SUCCESS;
+}
+/*****************************************************************************************************/  
+/********************************************PLME-GET*************************************************/
+/*****************************************************************************************************/
+
+command error_t PLME_GET.request(uint8_t PIBAttribute){
+//MAC asking for PIBAttribute value
+  switch(PIBAttribute)
+               {
+                       case PHYCURRENTCHANNEL:
+                               signal PLME_GET.confirm(PHY_SUCCESS, PIBAttribute, phy_PIB.phyCurrentChannel);
+                               break;
+
+                       case PHYCHANNELSSUPPORTED:
+                               signal PLME_GET.confirm(PHY_SUCCESS, PIBAttribute, phy_PIB.phyChannelsSupported);
+                               break;
+
+                       case PHYTRANSMITPOWER:
+                               signal PLME_GET.confirm(PHY_SUCCESS, PIBAttribute, phy_PIB.phyTransmitPower);
+                               break;
+                       case PHYCCAMODE:
+                               signal PLME_GET.confirm(PHY_SUCCESS, PIBAttribute, phy_PIB.phyCcaMode);
+                               break;
+                       default:
+                               signal PLME_GET.confirm(PHY_UNSUPPORTED_ATTRIBUTE, PIBAttribute, 0x00);
+                               break;
+               }
+               
+  
+  return SUCCESS;
+  }
+  
+/*****************************************************************************************************/  
+/********************************************PLME-SET*************************************************/
+/*****************************************************************************************************/
+command error_t PLME_SET.request(uint8_t PIBAttribute, uint8_t PIBAttributeValue){
+  
+
+         //MAC is demanding for PHY to write the indicated PIB value
+         switch(PIBAttribute)
+                       {
+                               case PHYCURRENTCHANNEL:
+                                       
+                                       phy_PIB.phyCurrentChannel = PIBAttributeValue;
+                                       
+                                       call CC2420Config.setChannel(phy_PIB.phyCurrentChannel);
+                                       
+                                       call CC2420Config.sync();
+                                       
+                                       //TunePreset(phy_PIB.phyCurrentChannel);
+                                       signal PLME_SET.confirm(PHY_SUCCESS, PIBAttribute);
+                                       break;
+       
+                               case PHYCHANNELSSUPPORTED:
+                                       phy_PIB.phyChannelsSupported = PIBAttributeValue;
+                                       signal PLME_SET.confirm(PHY_SUCCESS, PIBAttribute);
+                                       break;
+       
+                               case PHYTRANSMITPOWER:
+                                       phy_PIB.phyTransmitPower= PIBAttributeValue;
+                                       //SetRFPower(phy_PIB.phyTransmitPower);
+                                       signal PLME_SET.confirm(PHY_SUCCESS, PIBAttribute);
+                                       break;
+                               case PHYCCAMODE:
+                                       phy_PIB.phyCcaMode= PIBAttributeValue;
+                                       signal PLME_SET.confirm(PHY_SUCCESS, PIBAttribute);
+                                       break;
+                               default:
+                                       signal PLME_SET.confirm(PHY_UNSUPPORTED_ATTRIBUTE, PIBAttribute);
+                                       break;
+                       }
+         return SUCCESS;
+}  
+
+/*****************************************************************************************************/  
+/**********************************PLME_SET_TRX_STATE*************************************************/
+/*****************************************************************************************************/
+
+
+async command error_t PLME_SET_TRX_STATE.request(uint8_t state){
+
+
+return SUCCESS;
+
+}
+
+
+
+}
+
index 2c9c5cf54f638dad5c96340261049dccd8f00d01..df5110e5ffc4638a5762c172f641d03b042dc722 100644 (file)
@@ -1,5 +1,6 @@
-Title: open-zb protocol stack implementation for TinyOS v2.0
-Author: André Cunha - IPP-HURRAY! http://www.open-zb.net
+Title: open-zb protocol stack implementation for TinyOS v2.x
+Author: Ricardo Severino - IPP-HURRAY! http://www.open-zb.net
+Author: Andr� Cunha - IPP-HURRAY! http://www.open-zb.net
 ----------------------------------------------
 
 Implementation of the ZigBee and the beacon-enabled mode of the IEEE 802.15.4.
@@ -10,12 +11,12 @@ mode of the IEEE 802.15.4 with the ZigBee network layer supporting the Cluster-t
 
 The current version of the implementation of the IEEE 802.15.4 beacon enabled mode supports the following functionalities:
 
--CSMA/CA algorithm \96 slotted version;
+-CSMA/CA algorithm ï¿½ slotted version;
 -GTS Mechanism;
 -Indirect transmission mechanism;
 -Direct / Indirect / GTS Data Transmission;
 -Beacon Management;
--Frame construction \96 Short Addressing Fields only and extended addressing
+-Frame construction ï¿½ Short Addressing Fields only and extended addressing
 fields in the association request;
 -Association/Disassociation Mechanism;
 -MAC PIB Management;
@@ -30,7 +31,7 @@ version of the implementation
 -Active and Orphan channel Scan;
 -Orphan Devices;
 -Frame Reception Conditions (Verify Conditions);
--Security \96 Out of the scope of this implementation;
+-Security ï¿½ Out of the scope of this implementation;
 
 The current version of the ZigBee Network Layer, besides the above functionalities, supports
 
@@ -67,16 +68,16 @@ devices have a depth of 1 and the coordinator a depth of 0).
 - ZigBee Network Layer with the TDBS
        
        -Test_APL
-This application uses the interfaces provided by the NWKM component and currently is customized
+This application uses the interfaces provided by the NWKP component and currently is customized
 to use with the TELOSB mote due to the interfacing with the mote user button. The TELOSB mote needs to
-\93warmup\94 before entering into normal operational behaviour, so, the user button is used to start the mote
+�warmup� before entering into normal operational behaviour, so, the user button is used to start the mote
 operation either by starting to send beacons, in the case of the ZigBee Coordinator, or to associate to a
 network in the case of ZigBee Routers or End Devices.
 In order to test the cluster-tree approach we have forced the association to a specific parent device by
 assigning some static parameters to the device. These parameters are located in the nwk_const.h file under
 the lib.nwk and are the following:
--TYPE_DEVICE \96 selecting the role of the device in the network;
--DEVICE_DEPTH \96 selecting the depth of the device in the network. This parameter in be used in
+-TYPE_DEVICE ï¿½ selecting the role of the device in the network;
+-DEVICE_DEPTH ï¿½ selecting the depth of the device in the network. This parameter in be used in
 computing the cskip functions used for the address assignment and for the tree-routing. This value
 will also be used to select the appropriate parent selected for the association.
 Depending of the selected depth the device will select the statically defined parent. The parent values are
diff --git a/tos/lib/net/zigbee/wrapper/WrapperC.nc b/tos/lib/net/zigbee/wrapper/WrapperC.nc
new file mode 100644 (file)
index 0000000..6b210a9
--- /dev/null
@@ -0,0 +1,94 @@
+ /*
+ * 
+ * Wrapper layer to use the TKN 154 MAC
+ * @author: Ricardo Severino <rars@isep.ipp.pt>
+ * ========================================================================
+ */ 
+
+// move to a header file?
+#define WRAPPER_MESSAGE_QUEUE_SIZE 5
+
+configuration WrapperC
+{
+  provides
+  {
+    interface OPENZB_MLME_RESET;
+    interface OPENZB_MLME_START;
+  
+    interface OPENZB_MLME_GET;
+    interface OPENZB_MLME_SET;
+  
+    interface OPENZB_MLME_BEACON_NOTIFY;
+    interface OPENZB_MLME_GTS;
+  
+    interface OPENZB_MLME_ASSOCIATE;
+    interface OPENZB_MLME_DISASSOCIATE;
+  
+    interface OPENZB_MLME_ORPHAN;
+    interface OPENZB_MLME_SYNC;
+    interface OPENZB_MLME_SYNC_LOSS;
+    interface OPENZB_MLME_SCAN;
+    
+    interface OPENZB_MCPS_DATA;
+
+
+  }
+
+}
+
+implementation
+{
+
+  components Ieee802154BeaconEnabledC as MAC; 
+  components WrapperP;
+
+  WrapperP.MLME_RESET -> MAC;
+  WrapperP.MLME_START -> MAC;
+  
+  WrapperP.MLME_GET -> MAC;
+  WrapperP.MLME_SET -> MAC;
+  
+  WrapperP.MLME_BEACON_NOTIFY -> MAC;
+  //WrapperP.MLME_GTS -> MAC;
+  
+  WrapperP.MLME_ASSOCIATE -> MAC;
+  WrapperP.MLME_DISASSOCIATE -> MAC;
+  
+  WrapperP.MLME_ORPHAN -> MAC;
+  WrapperP.MLME_SYNC -> MAC;
+  WrapperP.MLME_SYNC_LOSS -> MAC;
+  WrapperP.MLME_SCAN -> MAC;
+    
+  WrapperP.MCPS_DATA -> MAC;
+  WrapperP.IEEE154Frame -> MAC;
+  WrapperP.IEEE154BeaconFrame -> MAC;
+  WrapperP.Packet -> MAC;
+
+  components new PoolC(message_t, WRAPPER_MESSAGE_QUEUE_SIZE) as MessagePool;
+  WrapperP.MessagePool -> MessagePool;
+
+
+  OPENZB_MLME_RESET = WrapperP;
+  OPENZB_MLME_START = WrapperP;
+
+  OPENZB_MLME_GET = WrapperP;
+  OPENZB_MLME_SET = WrapperP;
+
+  OPENZB_MLME_BEACON_NOTIFY = WrapperP;
+  OPENZB_MLME_GTS = WrapperP;
+
+  OPENZB_MLME_ASSOCIATE = WrapperP;
+  OPENZB_MLME_DISASSOCIATE = WrapperP;
+
+  OPENZB_MLME_ORPHAN = WrapperP;
+  OPENZB_MLME_SYNC = WrapperP;
+  OPENZB_MLME_SYNC_LOSS = WrapperP;
+  OPENZB_MLME_SCAN = WrapperP;
+
+  OPENZB_MCPS_DATA = WrapperP;
+
+
+
+
+
+}
diff --git a/tos/lib/net/zigbee/wrapper/WrapperP.nc b/tos/lib/net/zigbee/wrapper/WrapperP.nc
new file mode 100644 (file)
index 0000000..d8db2eb
--- /dev/null
@@ -0,0 +1,602 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * @author: Ricardo Severino <rars@isep.ipp.pt>
+ * ========================================================================
+ */
+
+module WrapperP
+{
+  uses {
+    interface MLME_START;
+    interface MLME_SET;
+    interface MLME_GET;
+
+    interface MLME_ASSOCIATE;
+    interface MLME_DISASSOCIATE;
+
+    interface MLME_BEACON_NOTIFY;
+    interface MLME_GTS;
+
+    interface MLME_ORPHAN;
+
+    interface MLME_SYNC;
+    interface MLME_SYNC_LOSS;
+
+    interface MLME_RESET;
+
+    interface MLME_SCAN;
+
+    //MCPS
+    interface MCPS_DATA;
+    interface MCPS_PURGE;
+
+    interface IEEE154Frame;
+    interface IEEE154BeaconFrame;
+    interface Pool<message_t> as MessagePool;
+    interface Packet;
+  }
+
+  provides
+  {
+    interface OPENZB_MLME_RESET;
+    interface OPENZB_MLME_START;
+
+    interface OPENZB_MLME_GET;
+    interface OPENZB_MLME_SET;
+
+    interface OPENZB_MLME_BEACON_NOTIFY;
+    interface OPENZB_MLME_GTS;
+
+    interface OPENZB_MLME_ASSOCIATE;
+    interface OPENZB_MLME_DISASSOCIATE;
+
+    interface OPENZB_MLME_ORPHAN;
+    interface OPENZB_MLME_SYNC;
+    interface OPENZB_MLME_SYNC_LOSS;
+    interface OPENZB_MLME_SCAN;
+
+    interface OPENZB_MCPS_DATA;
+  }
+
+}
+implementation
+{
+
+  /* ----------------------- MLME-RESET ----------------------- */
+
+  command error_t OPENZB_MLME_RESET.request(uint8_t set_default_PIB)
+  {
+    return call MLME_RESET.request(set_default_PIB != 0);
+  }
+
+  event void MLME_RESET.confirm(ieee154_status_t status)
+  {
+    signal OPENZB_MLME_RESET.confirm(status);
+  }
+
+  /* ----------------------- MLME-ASSOCIATE ----------------------- */
+
+  command error_t OPENZB_MLME_ASSOCIATE.request(uint8_t LogicalChannel,uint8_t CoordAddrMode,
+      uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation,bool securityenable)
+  {
+    ieee154_CapabilityInformation_t capabilityInformation;
+    ieee154_address_t coordAddress;
+
+    if (securityenable)
+      return IEEE154_UNSUPPORTED_SECURITY;
+    memcpy(&coordAddress, CoordAddress, 8);
+    *((uint8_t*) &capabilityInformation) = CapabilityInformation; // TODO: check
+    return call MLME_ASSOCIATE.request  (
+                          LogicalChannel,
+                          0, // ChannelPage
+                          CoordAddrMode,
+                          CoordPANId,
+                          coordAddress,
+                          capabilityInformation,
+                          NULL //security
+                        );
+  }
+
+  event void MLME_ASSOCIATE.confirm    (
+      uint16_t AssocShortAddress,
+      uint8_t status,
+      ieee154_security_t *security
+      )
+  {
+    signal OPENZB_MLME_ASSOCIATE.confirm(AssocShortAddress, status);
+  }
+
+  command error_t OPENZB_MLME_ASSOCIATE.response(uint32_t DeviceAddress[], 
+      uint16_t AssocShortAddress, uint8_t status, bool securityenable)
+  {
+    uint64_t deviceAddress;
+
+    if (securityenable)
+      return IEEE154_UNSUPPORTED_SECURITY;
+    memcpy(&deviceAddress, DeviceAddress, 8);
+    return call MLME_ASSOCIATE.response  (
+                          deviceAddress,
+                          AssocShortAddress,
+                          status,
+                          NULL //security
+                        );
+  }
+
+  event void MLME_ASSOCIATE.indication (
+      uint64_t DeviceAddress,
+      ieee154_CapabilityInformation_t CapabilityInformation,
+      ieee154_security_t *security
+      )
+  {
+    uint32_t deviceAddress[2];
+    uint8_t capabilityInformation = *((uint8_t*) &CapabilityInformation);
+    memcpy(&DeviceAddress, deviceAddress, 8);
+    signal OPENZB_MLME_ASSOCIATE.indication(
+                          deviceAddress,
+                          capabilityInformation,
+                          FALSE, // SecurityUse
+                          0 //ACLEntry
+        );
+  }
+
+  /* ----------------------- MLME-DISASSOCIATE ----------------------- */
+
+  command error_t OPENZB_MLME_DISASSOCIATE.request(uint32_t DeviceAddress[], 
+      uint8_t disassociate_reason, bool securityenable)
+  {
+    // DeviceAddress is an extended address, c.f. Tab. 37 in 802.15.4-2003 
+    uint16_t panID = call MLME_GET.macPANId();
+    ieee154_address_t deviceAddress;
+    memcpy(&deviceAddress, DeviceAddress, 8);
+    return call MLME_DISASSOCIATE.request(
+                          ADDR_MODE_EXTENDED_ADDRESS, // DeviceAddrMode,
+                          panID,
+                          deviceAddress,
+                          disassociate_reason,
+                          FALSE, // TxIndirect,
+                          NULL // security
+                        );
+
+  }
+
+  event void MLME_DISASSOCIATE.indication (
+      uint64_t DeviceAddress,
+      ieee154_disassociation_reason_t DisassociateReason,
+      ieee154_security_t *security
+      )
+  {
+    uint32_t deviceAddress[2];
+    memcpy(&DeviceAddress, deviceAddress, 8);
+    signal OPENZB_MLME_DISASSOCIATE.indication(
+        deviceAddress, DisassociateReason, 0, 0);
+  }
+
+
+  event void MLME_DISASSOCIATE.confirm    (
+      ieee154_status_t status,
+      uint8_t DeviceAddrMode,
+      uint16_t DevicePANID,
+      ieee154_address_t DeviceAddress
+      )
+  {
+    signal OPENZB_MLME_DISASSOCIATE.confirm(status);
+  }
+
+  /* ----------------------- MLME-START ----------------------- */
+
+  command error_t OPENZB_MLME_START.request(uint32_t PANId, uint8_t LogicalChannel, 
+      uint8_t beacon_order, uint8_t superframe_order,bool pan_coodinator,
+      bool BatteryLifeExtension,bool CoordRealignment,bool securityenable,
+      uint32_t StartTime)
+  {
+    if (securityenable)
+      return IEEE154_UNSUPPORTED_SECURITY;
+    return call MLME_START.request (
+                          PANId,
+                          LogicalChannel,
+                          0, // ChannelPage,
+                          StartTime,
+                          beacon_order,
+                          superframe_order,
+                          pan_coodinator,
+                          BatteryLifeExtension,
+                          CoordRealignment,
+                          NULL, // coordRealignSecurity
+                          NULL  // beaconSecurity
+        );
+  }
+
+  event void MLME_START.confirm    (
+      ieee154_status_t status)
+  {
+    signal OPENZB_MLME_START.confirm(status);
+  }
+
+  /* ----------------------- MLME-SYNC ----------------------- */
+
+  command error_t OPENZB_MLME_SYNC.request(uint8_t logical_channel,uint8_t track_beacon)
+  {
+    return call MLME_SYNC.request(logical_channel, 0, // ChannelPage
+                               track_beacon);
+  }
+
+
+  event void MLME_SYNC_LOSS.indication (
+      ieee154_status_t lossReason,
+      uint16_t PANId,
+      uint8_t LogicalChannel,
+      uint8_t ChannelPage,
+      ieee154_security_t *security
+      )
+  {
+    signal OPENZB_MLME_SYNC_LOSS.indication(lossReason);
+  }
+
+  /* ----------------------- MLME-SCAN ----------------------- */
+
+  enum {
+    NUM_ENERGY_DETECT_LIST_ENTRIES = 16,
+    NUM_PANDESCRIPTOR_LIST_ENTRIES = 16,
+  };
+
+  bool isScanBusy = FALSE;
+  int8_t m_EnergyDetectList[NUM_ENERGY_DETECT_LIST_ENTRIES];
+  ieee154_PANDescriptor_t m_PANDescriptorList[NUM_PANDESCRIPTOR_LIST_ENTRIES];
+
+  command error_t OPENZB_MLME_SCAN.request(uint8_t ScanType, uint32_t ScanChannels, uint8_t ScanDuration)
+  {
+    if (isScanBusy)
+      return IEEE154_TRANSACTION_OVERFLOW;
+    isScanBusy = TRUE;
+    return call MLME_SCAN.request  (
+                          ScanType,
+                          ScanChannels,
+                          ScanDuration,
+                          0, // ChannelPage,
+                          NUM_ENERGY_DETECT_LIST_ENTRIES, // EnergyDetectListNumEntries,
+                          m_EnergyDetectList, // EnergyDetectList,
+                          NUM_PANDESCRIPTOR_LIST_ENTRIES, // PANDescriptorListNumEntries,
+                          m_PANDescriptorList, // PANDescriptorList,
+                          NULL //security
+                        );
+  }
+
+  event void MLME_SCAN.confirm    (
+      ieee154_status_t status,
+      uint8_t ScanType,
+      uint8_t ChannelPage,
+      uint32_t UnscannedChannels,
+      uint8_t EnergyDetectNumResults,
+      int8_t* EnergyDetectList,
+      uint8_t PANDescriptorListNumResults,
+      ieee154_PANDescriptor_t* PANDescriptorList
+      )
+  {
+    uint8_t i;
+    uint8_t numResults = (ScanType == ED_SCAN) ? EnergyDetectNumResults : PANDescriptorListNumResults;
+    SCAN_PANDescriptor pDescriptor[PANDescriptorListNumResults];
+    
+    isScanBusy = FALSE;
+    for (i=0; i<PANDescriptorListNumResults; i++) {
+      pDescriptor[i].CoordPANId = PANDescriptorList[i].CoordPANId;
+      pDescriptor[i].CoordAddress = PANDescriptorList[i].CoordAddress.shortAddress;
+      pDescriptor[i].LogicalChannel = PANDescriptorList[i].LogicalChannel;
+      memcpy(&pDescriptor[i].SuperframeSpec, &PANDescriptorList[i].SuperframeSpec, 2);
+      pDescriptor[i].lqi = PANDescriptorList[i].LinkQuality;
+    }
+    signal OPENZB_MLME_SCAN.confirm(status, ScanType, 
+         UnscannedChannels, numResults, (uint8_t*) EnergyDetectList, pDescriptor);
+  }
+
+  /* ----------------------- MLME-BEACON-NOTIFY ----------------------- */
+
+  enum {
+    MAX_NUM_PENDING_ADDRESSES = 10,
+  };
+
+  void convertPANDescriptor(ieee154_PANDescriptor_t* PANDescriptorTKN154, PANDescriptor *PANDescriptorOPENZB)
+  {
+    PANDescriptorOPENZB->CoordAddrMode = PANDescriptorTKN154->CoordAddrMode;
+    PANDescriptorOPENZB->CoordPANId = PANDescriptorTKN154->CoordPANId;
+    memcpy(&PANDescriptorOPENZB->CoordAddress0, &PANDescriptorTKN154->CoordAddress, 4);
+    memcpy(&PANDescriptorOPENZB->CoordAddress1, ((uint8_t*) &PANDescriptorTKN154->CoordAddress) + 4, 4);
+    PANDescriptorOPENZB->LogicalChannel = PANDescriptorTKN154->LogicalChannel;
+    memcpy(&PANDescriptorOPENZB->SuperframeSpec, &PANDescriptorTKN154->SuperframeSpec, 2);
+    PANDescriptorOPENZB->GTSPermit = PANDescriptorTKN154->GTSPermit;
+    PANDescriptorOPENZB->LinkQuality = PANDescriptorTKN154->LinkQuality;
+    PANDescriptorOPENZB->TimeStamp = PANDescriptorTKN154->TimeStamp;
+    PANDescriptorOPENZB->SecurityUse = 0;
+    PANDescriptorOPENZB->ACLEntry = 0;
+    PANDescriptorOPENZB->SecurityFailure = FALSE;
+  }
+
+  event message_t* MLME_BEACON_NOTIFY.indication ( message_t *beaconFrame )
+  {
+    uint8_t sdu[call IEEE154BeaconFrame.getBeaconPayloadLength(beaconFrame)];
+    uint8_t sduLength = call IEEE154BeaconFrame.getBeaconPayloadLength(beaconFrame);
+    uint8_t BSN = call IEEE154BeaconFrame.getBSN(beaconFrame);
+    ieee154_PANDescriptor_t PANDescriptorTKN154;
+    PANDescriptor PANDescriptorOPENZB; 
+    uint8_t PenAddrSpec;
+    ieee154_address_t buffer[MAX_NUM_PENDING_ADDRESSES];
+
+    call IEEE154BeaconFrame.getPendAddr(beaconFrame, ADDR_MODE_SHORT_ADDRESS, buffer, MAX_NUM_PENDING_ADDRESSES);
+    call IEEE154BeaconFrame.getPendAddrSpec(beaconFrame, &PenAddrSpec);
+    memcpy(sdu, call IEEE154BeaconFrame.getBeaconPayload(beaconFrame), sduLength);
+    call IEEE154BeaconFrame.parsePANDescriptor(beaconFrame, call MLME_GET.phyCurrentChannel(), 0, &PANDescriptorTKN154);
+    convertPANDescriptor(&PANDescriptorTKN154, &PANDescriptorOPENZB);
+    signal OPENZB_MLME_BEACON_NOTIFY.indication(
+      BSN, PANDescriptorOPENZB, PenAddrSpec, 
+      0, //TODO: this should be a list of device addresses -> wrong data type in the OpenZB interfaces 
+      sduLength, sdu);
+    return beaconFrame;
+  }
+
+  /* ----------------------- MLME-ORPHAN ----------------------- */
+
+  event void MLME_ORPHAN.indication (
+      uint64_t OrphanAddress,
+      ieee154_security_t *security
+      )
+  {
+    uint32_t orphanAddress[1]; // TODO: this should be 64 bit
+    memcpy(orphanAddress, &OrphanAddress, 4);
+    signal OPENZB_MLME_ORPHAN.indication(orphanAddress, 
+        0, // SecurityUse, 
+        0 // ACLEntry
+        );
+  }
+  
+  command error_t OPENZB_MLME_ORPHAN.response(uint32_t OrphanAddress[1],
+      uint16_t ShortAddress,uint8_t AssociatedMember, uint8_t security_enabled)
+  {
+    uint64_t orphanAddress;
+    if (security_enabled)
+      return IEEE154_UNSUPPORTED_SECURITY;
+    memcpy(&orphanAddress, OrphanAddress, 4); // see comment above
+    return call MLME_ORPHAN.response (
+                          orphanAddress,
+                          ShortAddress,
+                          AssociatedMember,
+                          0 // security
+                        );
+  }
+
+  /* ----------------------- MLME-GTS ----------------------- */
+
+  command error_t OPENZB_MLME_GTS.request(uint8_t GTSCharacteristics, bool security_enable)
+  {
+    if (security_enable)
+      return IEEE154_UNSUPPORTED_SECURITY;
+    return call MLME_GTS.request( GTSCharacteristics, 
+                          NULL //security
+                        );
+  }
+
+  event void MLME_GTS.confirm    (
+      uint8_t GtsCharacteristics,
+      ieee154_status_t status
+      )
+  {
+    signal OPENZB_MLME_GTS.confirm( GtsCharacteristics, status);
+  }
+
+  event void MLME_GTS.indication (
+      uint16_t DeviceAddress,
+      uint8_t GtsCharacteristics,
+      ieee154_security_t *security
+      )
+  {
+    signal OPENZB_MLME_GTS.indication(DeviceAddress, 
+        GtsCharacteristics, 
+        0, // SecurityUse
+        0 // ACLEntry
+        );
+  }
+
+  /* ----------------------- MCPS-DATA ----------------------- */
+
+  command error_t OPENZB_MCPS_DATA.request(uint8_t SrcAddrMode, uint16_t SrcPANId, 
+      uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], 
+      uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions)
+  {
+    // note: in 802.15.4-2006 SrcAddr/SrcPANId is not explicitly passed anymore
+    // (they are read by the MAC from the Pib)
+    ieee154_status_t status;
+    message_t *frame = call MessagePool.get();
+    ieee154_address_t dstAddr;
+    uint8_t *payload;
+
+    if (frame == NULL)
+      return IEEE154_TRANSACTION_OVERFLOW;
+    payload = call Packet.getPayload(frame, msduLength);
+    if (payload == NULL || msduLength > call Packet.maxPayloadLength()){
+      call MessagePool.put(frame);
+      return IEEE154_FRAME_TOO_LONG;
+    }
+    memcpy(payload, msdu, msduLength);
+    memcpy(&dstAddr, DstAddr, 8);
+    call IEEE154Frame.setAddressingFields(frame,
+                          SrcAddrMode,
+                          DstAddrMode,
+                          DestPANId,
+                          &dstAddr,
+                          NULL //security
+                          );
+    status = call MCPS_DATA.request (
+                          frame,
+                          msduLength,
+                          msduHandle,
+                          TxOptions
+                        ); 
+    if (status != IEEE154_SUCCESS)
+      call MessagePool.put(frame);
+    return status;   
+  }
+
+  event void MCPS_DATA.confirm    (  
+      message_t *frame,
+      uint8_t msduHandle,
+      ieee154_status_t status,
+      uint32_t Timestamp
+      )
+  {
+    signal OPENZB_MCPS_DATA.confirm(msduHandle, status);
+  }
+
+  event message_t* MCPS_DATA.indication ( message_t* frame )
+  {
+    uint16_t SrcAddrMode = call IEEE154Frame.getSrcAddrMode(frame);
+    uint16_t SrcPANId;
+    uint16_t DstAddrMode = call IEEE154Frame.getDstAddrMode(frame);
+    uint16_t DestPANId;
+    uint16_t msduLength = call IEEE154Frame.getPayloadLength(frame);
+    uint16_t mpduLinkQuality = call IEEE154Frame.getLinkQuality(frame);
+    uint16_t SecurityUse = 0;
+    uint16_t ACLEntry = 0;
+    uint8_t *payload = call IEEE154Frame.getPayload(frame);
+
+    ieee154_address_t srcAddr;
+    ieee154_address_t dstAddr;
+    uint32_t SrcAddr[2];
+    uint32_t DstAddr[2];
+    uint8_t msdu[100];
+
+    if (msduLength > 100)
+      return frame; // TODO: msdu should probably not an array
+    call IEEE154Frame.getSrcPANId(frame, &SrcPANId);
+    call IEEE154Frame.getDstPANId(frame, &DestPANId);
+    call IEEE154Frame.getSrcAddr(frame, &srcAddr);   
+    call IEEE154Frame.getDstAddr(frame, &dstAddr);
+    memcpy(msdu, payload, msduLength);
+    memcpy(SrcAddr, &srcAddr, 8);
+    memcpy(DstAddr, &dstAddr, 8);
+    signal OPENZB_MCPS_DATA.indication(SrcAddrMode, SrcPANId, SrcAddr, 
+        DstAddrMode, DestPANId, DstAddr, msduLength, 
+        msdu, mpduLinkQuality,  SecurityUse,  ACLEntry);
+    return frame;
+  }
+
+  /* ----------------------- MLME-SET/GET ----------------------- */
+
+  command error_t OPENZB_MLME_GET.request(uint8_t PIBAttribute)
+  {
+    uint8_t v[8];
+    switch (PIBAttribute)
+    {
+      case 0x41: { ieee154_macAssociationPermit_t x = call MLME_GET.macAssociationPermit(); memcpy(v, &x, sizeof(ieee154_macAssociationPermit_t)); break;}
+      case 0x42: { ieee154_macAutoRequest_t x = call MLME_GET.macAutoRequest(); memcpy(v, &x, sizeof(ieee154_macAutoRequest_t)); break;}
+      case 0x43: { ieee154_macBattLifeExt_t x = call MLME_GET.macBattLifeExt(); memcpy(v, &x, sizeof(ieee154_macBattLifeExt_t)); break;}
+      case 0x4D: { ieee154_macGTSPermit_t x = call MLME_GET.macGTSPermit(); memcpy(v, &x, sizeof(ieee154_macGTSPermit_t)); break;}
+      case 0x51: { ieee154_macPromiscuousMode_t x = call MLME_GET.macPromiscuousMode(); memcpy(v, &x, sizeof(ieee154_macPromiscuousMode_t)); break;}
+      case 0x52: { ieee154_macRxOnWhenIdle_t x = call MLME_GET.macRxOnWhenIdle(); memcpy(v, &x, sizeof(ieee154_macRxOnWhenIdle_t)); break;}
+      case 0x56: { ieee154_macAssociatedPANCoord_t x = call MLME_GET.macAssociatedPANCoord(); memcpy(v, &x, sizeof(ieee154_macAssociatedPANCoord_t)); break;}
+      case 0x5D: { ieee154_macSecurityEnabled_t x = call MLME_GET.macSecurityEnabled(); memcpy(v, &x, sizeof(ieee154_macSecurityEnabled_t)); break;}
+      case 0x00: { ieee154_phyCurrentChannel_t x = call MLME_GET.phyCurrentChannel(); memcpy(v, &x, sizeof(ieee154_phyCurrentChannel_t)); break;}
+      case 0x02: { ieee154_phyTransmitPower_t x = call MLME_GET.phyTransmitPower(); memcpy(v, &x, sizeof(ieee154_phyTransmitPower_t)); break;}
+      case 0x03: { ieee154_phyCCAMode_t x = call MLME_GET.phyCCAMode(); memcpy(v, &x, sizeof(ieee154_phyCCAMode_t)); break;}
+      case 0x04: { ieee154_phyCurrentPage_t x = call MLME_GET.phyCurrentPage(); memcpy(v, &x, sizeof(ieee154_phyCurrentPage_t)); break;}
+      case 0x44: { ieee154_macBattLifeExtPeriods_t x = call MLME_GET.macBattLifeExtPeriods(); memcpy(v, &x, sizeof(ieee154_macBattLifeExtPeriods_t)); break;}
+      case 0x47: { ieee154_macBeaconOrder_t x = call MLME_GET.macBeaconOrder(); memcpy(v, &x, sizeof(ieee154_macBeaconOrder_t)); break;}
+      case 0x49: { ieee154_macBSN_t x = call MLME_GET.macBSN(); memcpy(v, &x, sizeof(ieee154_macBSN_t)); break;}
+      case 0x4C: { ieee154_macDSN_t x = call MLME_GET.macDSN(); memcpy(v, &x, sizeof(ieee154_macDSN_t)); break;}
+      case 0x4E: { ieee154_macMaxCSMABackoffs_t x = call MLME_GET.macMaxCSMABackoffs(); memcpy(v, &x, sizeof(ieee154_macMaxCSMABackoffs_t)); break;}
+      case 0x4F: { ieee154_macMinBE_t x = call MLME_GET.macMinBE(); memcpy(v, &x, sizeof(ieee154_macMinBE_t)); break;}
+      case 0x54: { ieee154_macSuperframeOrder_t x = call MLME_GET.macSuperframeOrder(); memcpy(v, &x, sizeof(ieee154_macSuperframeOrder_t)); break;}
+      case 0x57: { ieee154_macMaxBE_t x = call MLME_GET.macMaxBE(); memcpy(v, &x, sizeof(ieee154_macMaxBE_t)); break;}
+      case 0x59: { ieee154_macMaxFrameRetries_t x = call MLME_GET.macMaxFrameRetries(); memcpy(v, &x, sizeof(ieee154_macMaxFrameRetries_t)); break;}
+      case 0x5a: { ieee154_macResponseWaitTime_t x = call MLME_GET.macResponseWaitTime(); memcpy(v, &x, sizeof(ieee154_macResponseWaitTime_t)); break;}
+      case 0x4B: { ieee154_macCoordShortAddress_t x = call MLME_GET.macCoordShortAddress(); memcpy(v, &x, sizeof(ieee154_macCoordShortAddress_t)); break;}
+      case 0x50: { ieee154_macPANId_t x = call MLME_GET.macPANId(); memcpy(v, &x, sizeof(ieee154_macPANId_t)); break;}
+      case 0x53: { ieee154_macShortAddress_t x = call MLME_GET.macShortAddress(); memcpy(v, &x, sizeof(ieee154_macShortAddress_t)); break;}
+      case 0x55: { ieee154_macTransactionPersistenceTime_t x = call MLME_GET.macTransactionPersistenceTime(); memcpy(v, &x, sizeof(ieee154_macTransactionPersistenceTime_t)); break;}
+      case 0x58: { ieee154_macMaxFrameTotalWaitTime_t x = call MLME_GET.macMaxFrameTotalWaitTime(); memcpy(v, &x, sizeof(ieee154_macMaxFrameTotalWaitTime_t)); break;}
+      case 0x48: { ieee154_macBeaconTxTime_t x = call MLME_GET.macBeaconTxTime(); memcpy(v, &x, sizeof(ieee154_macBeaconTxTime_t)); break;}
+      case 0x4A: { ieee154_macCoordExtendedAddress_t x = call MLME_GET.macCoordExtendedAddress(); memcpy(v, &x, sizeof(ieee154_macCoordExtendedAddress_t)); break;}
+      case 0x46: // macBeaconPayloadLength is set through the IEEE154TxBeaconPayload interface
+                 // fall through
+      default: return IEEE154_UNSUPPORTED_ATTRIBUTE;
+    }
+    signal OPENZB_MLME_GET.confirm(IEEE154_SUCCESS, PIBAttribute, v);
+    return IEEE154_SUCCESS;
+  }
+
+  command error_t OPENZB_MLME_SET.request(uint8_t PIBAttribute,uint8_t PIBAttributeValue[])
+  {
+    ieee154_status_t status;
+    switch (PIBAttribute)
+    {
+      case 0x41: status = call MLME_SET.macAssociationPermit(*((ieee154_macAssociationPermit_t*) PIBAttributeValue)); break;
+      case 0x42: status = call MLME_SET.macAutoRequest(*((ieee154_macAutoRequest_t*) PIBAttributeValue)); break;
+      case 0x43: status = call MLME_SET.macBattLifeExt(*((ieee154_macBattLifeExt_t*) PIBAttributeValue)); break;
+      case 0x4D: status = call MLME_SET.macGTSPermit(*((ieee154_macGTSPermit_t*) PIBAttributeValue)); break;
+      case 0x52: status = call MLME_SET.macRxOnWhenIdle(*((ieee154_macRxOnWhenIdle_t*) PIBAttributeValue)); break;
+      case 0x56: status = call MLME_SET.macAssociatedPANCoord(*((ieee154_macAssociatedPANCoord_t*) PIBAttributeValue)); break;
+      case 0x5D: status = call MLME_SET.macSecurityEnabled(*((ieee154_macSecurityEnabled_t*) PIBAttributeValue)); break;
+      case 0x00: status = call MLME_SET.phyCurrentChannel(*((ieee154_phyCurrentChannel_t*) PIBAttributeValue)); break;
+      case 0x02: status = call MLME_SET.phyTransmitPower(*((ieee154_phyTransmitPower_t*) PIBAttributeValue)); break;
+      case 0x03: status = call MLME_SET.phyCCAMode(*((ieee154_phyCCAMode_t*) PIBAttributeValue)); break;
+      case 0x04: status = call MLME_SET.phyCurrentPage(*((ieee154_phyCurrentPage_t*) PIBAttributeValue)); break;
+      case 0x44: status = call MLME_SET.macBattLifeExtPeriods(*((ieee154_macBattLifeExtPeriods_t*) PIBAttributeValue)); break;
+      case 0x47: status = call MLME_SET.macBeaconOrder(*((ieee154_macBeaconOrder_t*) PIBAttributeValue)); break;
+      case 0x49: status = call MLME_SET.macBSN(*((ieee154_macBSN_t*) PIBAttributeValue)); break;
+      case 0x4C: status = call MLME_SET.macDSN(*((ieee154_macDSN_t*) PIBAttributeValue)); break;
+      case 0x4E: status = call MLME_SET.macMaxCSMABackoffs(*((ieee154_macMaxCSMABackoffs_t*) PIBAttributeValue)); break;
+      case 0x4F: status = call MLME_SET.macMinBE(*((ieee154_macMinBE_t*) PIBAttributeValue)); break;
+      case 0x57: status = call MLME_SET.macMaxBE(*((ieee154_macMaxBE_t*) PIBAttributeValue)); break;
+      case 0x59: status = call MLME_SET.macMaxFrameRetries(*((ieee154_macMaxFrameRetries_t*) PIBAttributeValue)); break;
+      case 0x5a: status = call MLME_SET.macResponseWaitTime(*((ieee154_macResponseWaitTime_t*) PIBAttributeValue)); break;
+      case 0x4B: status = call MLME_SET.macCoordShortAddress(*((ieee154_macCoordShortAddress_t*) PIBAttributeValue)); break;
+      case 0x50: status = call MLME_SET.macPANId(*((ieee154_macPANId_t*) PIBAttributeValue)); break;
+      case 0x53: status = call MLME_SET.macShortAddress(*((ieee154_macShortAddress_t*) PIBAttributeValue)); break;
+      case 0x55: status = call MLME_SET.macTransactionPersistenceTime(*((ieee154_macTransactionPersistenceTime_t*) PIBAttributeValue)); break;
+      case 0x58: status = call MLME_SET.macMaxFrameTotalWaitTime(*((ieee154_macMaxFrameTotalWaitTime_t*) PIBAttributeValue)); break;
+      case 0x4A: status = call MLME_SET.macCoordExtendedAddress(*((ieee154_macCoordExtendedAddress_t*) PIBAttributeValue)); break;
+      case 0x48: // macBeaconTxTime  is read-only
+                 // fall through
+      case 0x54: // macSuperframeOrder is read-only
+                 // fall through
+      case 0x46: // macBeaconPayloadLength is set through the IEEE154TxBeaconPayload interface
+                 // fall through
+      case 0x51: // macPromiscousMode is set through a SplitControl
+                 // fall through
+      default: status = IEEE154_UNSUPPORTED_ATTRIBUTE; break;
+    }   
+    if (status == IEEE154_SUCCESS)
+      signal OPENZB_MLME_SET.confirm(status, PIBAttribute);
+    return status;
+  }
+}
+
+
+
+
diff --git a/tos/lib/net/zigbee/wrapper/includes/frame_format.h b/tos/lib/net/zigbee/wrapper/includes/frame_format.h
new file mode 100644 (file)
index 0000000..b8ddb79
--- /dev/null
@@ -0,0 +1,220 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author open-zb http://www.open-zb.net
+ * @author Andre Cunha
+ */
+
+//MAC frame Superstructure
+
+#ifndef __FRAME_FORMAT__
+#define __FRAME_FORMAT__
+
+
+#define MPDU_HEADER_LEN 5
+
+typedef struct MPDU
+{
+       uint8_t length;
+       //info on frame type/ack/etc
+       uint8_t frame_control1;
+       //info on addressing fields
+       uint8_t frame_control2;
+       //uint16_t frame_control;
+       uint8_t seq_num;
+       uint8_t data[120];
+}MPDU;
+
+typedef struct MPDUBuffer
+{
+       uint8_t length;
+       //uint16_t frame_control;
+       uint8_t frame_control1;
+       uint8_t frame_control2;
+       uint8_t seq_num;
+       uint8_t data[120];
+       uint8_t retransmission;
+       uint8_t indirect;
+}MPDUBuffer;
+
+//PD_DATA validation structures
+
+
+
+/*****************************************************/
+/*                             BEACON FRAME SCTRUCTURES                         */
+/*****************************************************/
+
+//#define beacon_addr_short_length 7
+//#define beacon_addr_long_length 12
+
+
+typedef struct beacon_addr_short
+{
+       uint16_t destination_PAN_identifier;
+       uint16_t destination_address;
+       uint16_t source_address;
+       uint16_t superframe_specification;
+}beacon_addr_short;
+/*
+typedef struct beacon_struct
+{
+       uint8_t length;
+       uint16_t frame_control;
+       uint8_t seq_num;
+       uint16_t source_PAN_identifier;
+       uint16_t destination_address;
+       uint16_t source_address;
+       uint16_t superframe_specification;
+}beacon_struct;
+*/
+/*
+typedef struct beacon_addr_long
+{
+       uint16_t source_PAN_identifier;
+       uint32_t source_address0;
+       uint32_t source_address1;
+       uint16_t superframe_specification;
+}beacon_addr_long;
+*/
+/*****************************************************/
+/*                             ACK FRAME Structures                             */
+/*****************************************************/
+
+typedef struct ACK
+{
+       uint8_t length;
+       uint8_t frame_control1;
+       uint8_t frame_control2;
+       //uint16_t frame_control;
+       uint8_t seq_num;
+}ACK;
+
+/*****************************************************/
+/*                             COMMAND FRAME Structures                         */
+/*****************************************************/
+
+typedef struct cmd_association_request
+{
+       uint8_t command_frame_identifier;
+       uint8_t capability_information;
+}cmd_association_request;
+
+typedef struct cmd_association_response
+{
+       uint8_t command_frame_identifier;
+       uint8_t short_address1;
+       uint8_t short_address2;
+       //uint16_t short_address;
+       uint8_t association_status;
+}cmd_association_response;
+
+//disassociacion notification command structure pag. 126
+typedef struct cmd_disassociation_notification
+{
+       uint16_t destination_PAN_identifier;
+       uint32_t destination_address0;
+       uint32_t destination_address1;
+       uint16_t source_PAN_identifier;
+       uint32_t source_address0;
+       uint32_t source_address1;
+       uint8_t command_frame_identifier;
+       uint8_t disassociation_reason;
+}cmd_disassociation_notification;
+
+//pag 130
+typedef struct cmd_beacon_request
+{
+       uint16_t destination_PAN_identifier;
+       uint16_t destination_address;
+       uint8_t command_frame_identifier;
+}cmd_beacon_request;
+
+
+//pag 132
+typedef struct cmd_gts_request
+{
+       uint16_t source_PAN_identifier;
+       uint16_t source_address;
+       uint8_t command_frame_identifier;
+       uint8_t gts_characteristics;
+}cmd_gts_request;
+
+typedef struct cmd_default
+{
+       uint8_t command_frame_identifier;
+}cmd_default;
+
+
+//131
+typedef struct cmd_coord_realignment
+{
+       uint8_t command_frame_identifier;
+       uint8_t PAN_identifier0;
+       uint8_t PAN_identifier1;
+       uint8_t coordinator_short_address0;
+       uint8_t coordinator_short_address1;
+       
+       /*
+       uint16_t PAN_identifier;
+       uint16_t coordinator_short_address;
+       */
+       uint8_t logical_channel;
+       uint16_t short_address;
+}cmd_coord_realignment;
+
+
+
+/*******************************************************/
+/*                             ADDRESSING FIELDS ONLY                             */
+/*******************************************************/
+#define DEST_SHORT_LEN 4
+#define DEST_LONG_LEN 10
+#define INTRA_PAN_SOURCE_SHORT_LEN 2
+#define INTRA_PAN_SOURCE_LONG_LEN 8
+#define SOURCE_SHORT_LEN 4
+#define SOURCE_LONG_LEN 10
+
+
+//DESTINATION
+typedef struct dest_short
+{
+       uint16_t destination_PAN_identifier;
+       uint16_t destination_address;
+}dest_short;
+
+typedef struct dest_long
+{
+       uint16_t destination_PAN_identifier;
+       uint32_t destination_address0;
+       uint32_t destination_address1;
+}dest_long;
+
+//SOURCE
+typedef struct intra_pan_source_short
+{
+       uint16_t source_address;
+}intra_pan_source_short;
+
+typedef struct intra_pan_source_long
+{
+       uint32_t source_address0;
+       uint32_t source_address1;
+}intra_pan_source_long;
+
+
+typedef struct source_short
+{
+       uint16_t source_PAN_identifier;
+       uint16_t source_address;
+}source_short;
+
+
+typedef struct source_long
+{
+       uint16_t source_PAN_identifier;
+       uint32_t source_address0;
+       uint32_t source_address1;
+}source_long;
+
+#endif
+
diff --git a/tos/lib/net/zigbee/wrapper/includes/mac_const.h b/tos/lib/net/zigbee/wrapper/includes/mac_const.h
new file mode 100644 (file)
index 0000000..8c61d05
--- /dev/null
@@ -0,0 +1,225 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author open-zb http://www.open-zb.net
+ * @author Andre Cunha
+ */
+
+// The MAC constants are defined in here.
+// Notice that these makes use of the PHY constants.
+//pag 134
+
+#ifndef __MAC_CONST__
+#define __MAC_CONST__
+
+
+#define aBaseSlotDuration          60
+#define aBaseSuperframeDuration    960 //aBaseSlotDuration*aNumSuperframeSlots
+
+//#define aExtendedAddress         // This should be defined by the device!
+
+#define aMaxBE                     5 //CSMA-CA
+
+#define aMaxBeaconOverhead         75
+#define aMaxBeaconPayloadLength    aMaxPHYPacketSize-aMaxBeaconOverhead
+#define aGTSDescPersistenceTime    4
+#define aMaxFrameOverhead          25
+#define aMaxFrameResponseTime      1220
+#define aMaxFrameRetries           1
+
+//(SYNC)number of beacons lost before sending a Beacon-Lost indication
+#define aMaxLostBeacons            4
+#define aMaxMACFrameSize           aMaxPHYPacketSize-aMaxFrameOverhead
+#define aMaxSIFSFrameSize          18
+#define aMinCAPLength              440
+#define aMinLIFSPeriod             40
+#define aMinSIFSPeriod             12
+#define aNumSuperframeSlots        16
+#define aResponseWaitTime          32*aBaseSuperframeDuration
+#define aUnitBackoffPeriod         20
+
+
+#define TYPE_BEACON 0
+#define TYPE_DATA 1
+#define TYPE_ACK 2
+#define TYPE_CMD 3
+
+#define SHORT_ADDRESS 2
+#define LONG_ADDRESS 3
+#define RESERVED_ADDRESS 1
+
+#define NUMBER_TIME_SLOTS 16
+
+#define ACK_LENGTH 5
+
+//buffer sizes
+#define MAX_GTS_BUFFER 7
+
+//#define MAX_GTS_PEND 2
+//#define MAX_GTS_IN_SLOT 1
+
+#define INDIRECT_BUFFER_SIZE 2
+#define RECEIVE_BUFFER_SIZE 4
+#define SEND_BUFFER_SIZE 3
+
+#define UPSTREAM_BUFFER_SIZE 3
+
+#define GTS_SEND_BUFFER_SIZE 3
+
+#define BACKOFF_PERIOD_MS 0.34724
+#define BACKOFF_PERIOD_US 347.24
+
+//value of each symbol in us
+#define EFFECTIVE_SYMBOL_VALUE 17.362
+
+// MAC PIB attribute
+typedef struct
+{
+       //pag 135
+       uint8_t macAckWaitDuration;
+       bool macAssociationPermit;//FDD
+       bool macAutoRequest;
+       bool macBattLifeExt;
+       uint8_t macBattLifeExtPeriods;
+       
+       uint8_t macBeaconPayload[aMaxBeaconPayloadLength];//FDD
+       
+       uint8_t macBeaconPayloadLenght;//FDD
+       uint8_t macBeaconOrder;//FDD
+       
+       uint32_t macBeaconTxTime;//FDD
+       uint8_t macBSN;//FDD
+       uint32_t macCoordExtendedAddress0;
+       uint32_t macCoordExtendedAddress1;
+       uint16_t macCoordShortAddress;
+       uint8_t macDSN;
+       bool macGTSPermit;//FDD
+       uint8_t macMaxCSMABackoffs;
+       uint8_t macMinBE;
+       uint16_t macPANId;
+       bool macPromiscuousMode;//FDD
+       bool macRxOnWhenIdle;
+       uint32_t macShortAddress;
+       uint8_t macSuperframeOrder;//FDD
+       uint32_t macTransactionPersistenceTime;//FDD
+       
+} macPIB;
+
+// MAC PIB security ACL entry descriptor
+typedef struct
+{
+       uint32_t ACLExtendedAddress[2];
+       uint16_t ACLShortAddress;
+       uint16_t ACLPANId;
+       uint8_t ACLSecurityMaterialLength;
+       //variable string
+       uint8_t ACLSecurityMaterial;
+       uint8_t ACLSecuritySuite;
+       
+}ACLDescriptor;
+
+// MAC PIB security attribute
+typedef struct
+{
+       //pag 138
+       ACLDescriptor macACLEntryDescriptorSet;
+       uint8_t macACLEntryDescriptorSetSize;
+       bool macDefaultSecurity;
+       uint8_t macDefaultSecurityMaterialLength;
+       //variable string
+       uint8_t macDefaultSecurityMaterial;
+       uint8_t macDefaultSecuritySuite;
+       uint8_t macSecurityMode;
+       
+}macPIBsec;
+
+//MAC PANDescriptor
+typedef struct
+{
+       //pag76
+       uint8_t CoordAddrMode;
+       uint16_t CoordPANId;
+       uint32_t CoordAddress0;
+       uint32_t CoordAddress1;
+       uint8_t LogicalChannel;
+       //superframe specification field
+       uint16_t SuperframeSpec;
+       bool GTSPermit;
+       uint8_t LinkQuality;
+       uint32_t TimeStamp;
+       bool SecurityUse;
+       uint8_t ACLEntry;
+       bool SecurityFailure;
+
+}PANDescriptor;
+
+//GTS entry (used in the PAN coordinator)
+typedef struct
+{
+       uint8_t gts_id;
+       uint8_t starting_slot;
+       uint8_t length;
+       uint8_t direction;
+       uint16_t DevAddressType;
+       uint8_t expiration;
+
+}GTSinfoEntryType;
+
+//GTS entry (used in the PAN coordinator)
+typedef struct
+{
+       uint8_t gts_id;
+       uint8_t starting_slot;
+       uint8_t length;
+       uint16_t DevAddressType;
+       uint8_t persistencetime;
+
+}GTSinfoEntryType_null;
+
+typedef struct
+{
+       uint8_t handler;
+       uint16_t transaction_persistent_time;
+       
+       //MPDU frame;
+       uint8_t frame[127];
+
+}indirect_transmission_element;
+
+typedef struct gts_slot_element
+{
+       uint8_t element_count;
+       uint8_t element_in;
+       uint8_t element_out;
+       uint8_t gts_send_frame_index[GTS_SEND_BUFFER_SIZE];
+
+}gts_slot_element;
+
+
+typedef struct time_stamp32
+{
+
+uint32_t time_stamp;
+
+}time_stamp32;
+
+typedef struct time_stamp16
+{
+
+uint16_t time_stamp;
+
+}time_stamp16;
+
+//MAC ACTIVE CHANNEL SCAN REDUCED PAN DESCRIPTOR (SHOR ADDRESS ONLY)
+typedef struct SCAN_PANDescriptor
+{
+       //pag76
+       uint16_t CoordPANId;
+       uint16_t CoordAddress;
+       uint8_t LogicalChannel;
+       //superframe specification field
+       uint16_t SuperframeSpec;
+       uint8_t lqi;
+}SCAN_PANDescriptor;
+
+
+#endif
diff --git a/tos/lib/net/zigbee/wrapper/includes/mac_enumerations.h b/tos/lib/net/zigbee/wrapper/includes/mac_enumerations.h
new file mode 100644 (file)
index 0000000..afde545
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author open-zb http://www.open-zb.net
+ * @author Andre Cunha
+ */
+#ifndef __MAC_ENUMERATIONS__
+#define __MAC_ENUMERATIONS__
+
+#include "TKN154.h"
+//Mac enumerations standard pag 110
+
+enum { 
+               MAC_SUCCESS = 0x00,
+        MAC_BEACON_LOSS = 0xE0,
+        MAC_CHANNEL_ACCESS_FAILURE = 0xE1,
+        MAC_DENIED = 0xE2,
+               //MLME-RESET
+        MAC_DISABLE_TRX_FAILURE = 0xE3,
+        MAC_FAILED_SECURITY_CHECK = 0xE4,
+        MAC_FRAME_TOO_LONG = 0xE5,
+        MAC_INVALID_GTS = 0xE6,
+        MAC_INVALID_HANDLE = 0xE7,
+        MAC_INVALID_PARAMETER = 0xE8,
+        MAC_NO_ACK = 0xE9,
+        MAC_NO_BEACON = 0xEA,
+        MAC_NO_DATA = 0xEB,
+        MAC_NO_SHORT_ADDRESS = 0xEC,
+        MAC_OUT_OF_CAP = 0xED,
+        MAC_PAN_ID_CONFLICT = 0xEE,
+        MAC_REALIGNMENT = 0xEF,
+        MAC_TRANSACTION_EXPIRED = 0xF0,
+        MAC_TRANSACTION_OVERFLOW = 0xF1,
+        MAC_TX_ACTIVE = 0xF2,
+        MAC_UNAVAILABLE_KEY = 0xF3,
+        MAC_UNSUPPORTED_ATTRIBUTE = 0xF4
+        };
+
+
+
+//mac dissassociation enums
+enum{
+               MAC_PAN_COORD_LEAVE = 0x01,
+        MAC_PAN_DEVICE_LEAVE = 0x02,
+
+};
+
+
+
+//mac commands enums
+enum {
+
+       CMD_ASSOCIATION_REQUEST = 0x01,
+       CMD_ASSOCIATION_RESPONSE = 0x02,
+       CMD_DISASSOCIATION_NOTIFICATION = 0x03,
+       CMD_DATA_REQUEST = 0x04,
+       CMD_PANID_CONFLICT = 0x05,
+       CMD_ORPHAN_NOTIFICATION = 0x06,
+       CMD_BEACON_REQUEST = 0x07,
+       CMD_COORDINATOR_REALIGNMENT = 0x08,
+       CMD_GTS_REQUEST = 0x09
+};
+
+
+//mac association responses
+enum {
+
+       CMD_RESP_ASSOCIATION_SUCCESSFUL = 0x00,
+       CMD_RESP_PAN_CAPACITY =0x01,
+       CMD_RESP_ACCESS_DENIED =0x02
+       
+};
+
+//MAC PIB Enumeration
+enum {
+
+       MACACKWAITDURATION = 0x40,
+       MACASSOCIATIONPERMIT=0x41,
+       MACAUTOREQUEST = 0x42,
+       MACBATTLIFEEXT=0x43,
+       MACBATTLIFEEXTPERIODS=0x44,
+       MACBEACONPAYLOAD=0x45,
+       MACMAXBEACONPAYLOADLENGTH=0x46,
+       MACBEACONORDER=0x47,
+       MACBEACONTXTIME=0x48,
+       MACBSN=0x49,
+       MACCOORDEXTENDEDADDRESS=0x4a,
+       MACCOORDSHORTADDRESS=0x4b,
+       MACDSN=0x4c,
+       MACGTSPERMIT=0x4d,
+       MACMAXCSMABACKOFFS=0x4e,
+       MACMINBE=0x4f,
+       MACPANID=0x50,
+       MACPROMISCUOUSMODE=0x51,
+       MACRXONWHENIDLE=0x52,
+       MACSHORTADDRESS=0x53,
+       MACSUPERFRAMEORDER=0x54,
+       MACTRANSACTIONPERSISTENCETIME=0x55
+
+};
+
+//gts enumerations
+enum{
+       GTS_TX_ONLY = 0x00,
+       GTS_RX_ONLY = 0x01
+};
+
+//channel scan enumerations
+
+enum{
+       ED_SCAN = 0x00,
+};
+
+
+
+#endif
+
diff --git a/tos/lib/net/zigbee/wrapper/includes/mac_func.h b/tos/lib/net/zigbee/wrapper/includes/mac_func.h
new file mode 100644 (file)
index 0000000..a4f1434
--- /dev/null
@@ -0,0 +1,384 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author open-zb http://www.open-zb.net
+ * @author Andre Cunha
+ */
+
+
+#ifndef __MAC_FUNC__
+#define __MAC_FUNC__
+
+/*******************************************************************************************************************/ 
+
+uint8_t set_capability_information(uint8_t alternate_PAN_coordinator, uint8_t device_type, uint8_t power_source, uint8_t receiver_on_when_idle, uint8_t security, uint8_t allocate_address)
+{
+       
+       return ((allocate_address << 7 ) | (security << 6 ) | (receiver_on_when_idle << 3 ) | (power_source << 2 ) | ( device_type << 1 ) | (alternate_PAN_coordinator << 0) );
+}
+
+uint8_t get_alternate_PAN_coordinator(uint8_t capability_information)
+{
+
+if ( (capability_information & 0x01) == 0x01)
+       return 1;
+else
+       return 0;
+
+}
+
+  
+/*******************************************************************************************************************/  
+/********************************FRAME CONTROL FUNCTIONS************************************************************/
+/*******************************************************************************************************************/
+  
+ //build MPDU frame control field
+uint16_t set_frame_control(uint8_t frame_type,uint8_t security,uint8_t frame_pending,uint8_t ack_request,uint8_t intra_pan,uint8_t dest_addr_mode,uint8_t source_addr_mode) 
+{
+         uint8_t fc_b1=0;
+         uint8_t fc_b2=0;
+         fc_b1 = ( (intra_pan << 6) | (ack_request << 5) | (frame_pending << 4) |
+                         (security << 3) | (frame_type << 0) );                                  
+         fc_b2 = ( (source_addr_mode << 6) | (dest_addr_mode << 2));
+         return ( (fc_b2 << 8 ) | (fc_b1 << 0) );
+
+} 
+
+
+//return the type of destination address specified in the frame control 
+
+uint8_t get_fc2_dest_addr(uint8_t frame_control)
+{
+       switch( frame_control & 0xC )
+       {
+       case 0x4:       return RESERVED_ADDRESS; 
+                                                       break;
+       case 0x8: return SHORT_ADDRESS;
+                                                break;
+       case 0xC: return LONG_ADDRESS;
+                                               break;
+       default:
+                       return 0; 
+                       break;
+       }
+}
+
+
+//return the type of source address specified in the frame control 
+
+uint8_t get_fc2_source_addr(uint8_t frame_control)
+{
+       switch(frame_control & 0xC0 )
+       {
+       case 0x40:      return RESERVED_ADDRESS; 
+                                                       break;
+       case 0x80: return SHORT_ADDRESS;
+                                                break;
+       case 0xC0: return LONG_ADDRESS;
+                                               break;
+       default:
+                       return 0; 
+                       break;
+       }
+}
+
+
+
+bool get_fc1_security(uint8_t frame_control)
+{
+
+if ( (frame_control & 0x8) == 0x8)
+       return 1;
+else
+       return 0;
+
+}
+
+bool get_fc1_frame_pending(uint8_t frame_control)
+{
+
+if ( (frame_control & 0x10) == 0x10)
+       return 1;
+else
+       return 0;
+       
+}
+
+bool get_fc1_ack_request(uint8_t frame_control)
+{
+
+if ( (frame_control & 0x20) == 0x20)
+       return 1;
+else
+       return 0;
+       
+}
+
+bool get_fc1_intra_pan(uint8_t frame_control)
+{
+
+if ( (frame_control & 0x40) == 0x40)
+       return 1;
+else
+       return 0;
+       
+} 
+  
+/*******************************************************************************************************************/  
+/********************************SUPERFRAME SPECIFICATION FUNCTIONS*************************************************/
+/*******************************************************************************************************************/
+
+//build beacon superframe specification
+uint16_t set_superframe_specification(uint8_t beacon_order,uint8_t superframe_order,uint8_t final_cap_slot,uint8_t battery_life_extension,uint8_t pan_coordinator,uint8_t association_permit)
+{
+         uint8_t sf_b1=0;
+         uint8_t sf_b2=0;
+         sf_b1 = ( (superframe_order << 4) | (beacon_order <<0));
+         sf_b2 = ( (association_permit << 7) | (pan_coordinator << 6) |
+                           (battery_life_extension << 4) | (final_cap_slot << 0) );
+          return  ( (sf_b2 <<8 ) | (sf_b1 << 0) );  
+   
+}
+
+uint8_t get_beacon_order(uint16_t superframe)
+{
+       return ((uint8_t)superframe &  0xF);
+}
+
+uint8_t get_superframe_order(uint16_t superframe)
+{
+       return (((uint8_t)superframe >> 4) &  0xF);
+}
+
+
+
+bool get_pan_coordinator(uint16_t superframe)
+{
+if ( ((uint8_t)superframe & 0x40) == 0x40)
+       return 1;
+else
+       return 0;
+       
+}
+
+bool get_association_permit(uint16_t superframe)
+{
+if ( ((uint8_t)superframe & 0x80) == 0x80)
+       return 1;
+else
+       return 0;       
+}
+
+bool get_battery_life_extention(uint16_t superframe)
+{
+if ( ((uint8_t)superframe & 0x10) == 0x10)
+       return 1;
+else
+       return 0;       
+}
+
+uint8_t get_final_cap_slot(uint16_t superframe)
+{
+return (((uint8_t)superframe >> 4) &  0xF);
+}
+
+
+/*******************************************************************************************************************/  
+/********************************      DATA TX OPTIONS   ************************************************************/
+/*******************************************************************************************************************/
+  
+  
+uint8_t set_txoptions(uint8_t ack, uint8_t gts, uint8_t indirect_transmission,uint8_t security)
+{
+return ( (ack << 0) | (gts << 1) | (indirect_transmission << 2) | (security << 3 ) );
+}  
+  
+bool get_txoptions_ack(uint8_t txoptions)
+{
+
+if ( (txoptions & 0x1) == 0x1)
+       return 1;
+else
+       return 0;
+
+}
+  
+bool get_txoptions_gts(uint8_t txoptions)
+{
+
+if ( (txoptions & 0x2) == 0x2)
+       return 1;
+else
+       return 0;
+
+}  
+
+bool get_txoptions_indirect_transmission(uint8_t txoptions)
+{
+
+if ( (txoptions & 0x4) == 0x4)
+       return 1;
+else
+       return 0;
+
+}  
+
+bool get_txoptions_security(uint8_t txoptions)
+{
+
+if ( (txoptions & 0x8) == 0x8)
+       return 1;
+else
+       return 0;
+}
+
+
+//BEACON SCHEDULING IMPLEMENTATION
+bool get_txoptions_upstream_buffer(uint8_t txoptions) 
+{
+
+if ( (txoptions & 0x10) == 0x10)
+       return 1;
+else
+       return 0;
+}
+
+uint8_t set_txoptions_upstream(uint8_t ack, uint8_t gts, uint8_t indirect_transmission,uint8_t security,uint8_t upstream)
+{
+return ( (ack << 0) | (gts << 1) | (indirect_transmission << 2) | (security << 3 ) | (upstream << 4) );
+} 
+
+
+/*******************************************************************************************************************/  
+/********************************PENDING ADDRESSES FUNCTIONS********************************************************/
+/*******************************************************************************************************************/
+uint8_t set_pending_address_specification(uint8_t number_short, uint8_t number_extended)
+{
+       return ( (number_extended << 4) | (number_short << 0) );
+}
+
+uint8_t get_number_short(uint8_t pending_specification)
+{
+       return (pending_specification & 0x07);
+}
+
+uint8_t get_number_extended(uint8_t pending_specification)
+{
+       return ( (pending_specification >> 4) & 0x07);
+}
+
+
+/*******************************************************************************************************************/  
+/********************************GTS FIELDS FUNCTIONS***************************************************************/
+/*******************************************************************************************************************/
+uint8_t set_gts_specification(uint8_t gts_descriptor_count, uint8_t gts_permit)
+{
+       return ( ( gts_descriptor_count << 0) | (gts_permit << 7) );  
+}
+
+uint8_t get_gts_permit(uint8_t gts_specification)
+{
+return ( (gts_specification >> 7) & 0x01);
+}
+
+
+///UNUSED
+uint8_t set_gts_directions(uint8_t gts1,uint8_t gts2,uint8_t gts3,uint8_t gts4,uint8_t gts5,uint8_t gts6,uint8_t gts7)
+{
+       return ((gts1 << 0) | (0 << 7));
+}
+
+
+uint8_t set_gts_descriptor(uint8_t GTS_starting_slot, uint8_t GTS_length)
+{
+//part of the descriptor list
+       return ( (GTS_starting_slot << 0) | (GTS_length << 4) );
+}
+
+uint8_t get_gts_descriptor_len(uint8_t gts_des_part)
+{
+       return ( (gts_des_part & 0xf0) >> 4);
+}
+
+uint8_t get_gts_descriptor_ss(uint8_t gts_des_part)
+{
+       return (gts_des_part & 0x0f);
+}
+
+
+
+/************************************************************************************************/  
+/********************************GTS CHARACTERISTICS*************************************************/
+/************************************************************************************************/
+uint8_t set_gts_characteristics(uint8_t gts_length, uint8_t gts_direction, uint8_t characteristic_type)
+{
+       return ( (gts_length << 0) | (gts_direction << 4) | (characteristic_type << 5));
+}  
+uint8_t get_gts_length(uint8_t gts_characteristics)
+{
+       return (gts_characteristics &  0xF);
+}
+
+bool get_gts_direction(uint8_t gts_characteristics)
+{
+       if ( (gts_characteristics & 0x10) == 0x10)
+               return 1;
+       else
+               return 0;
+}  
+
+uint8_t get_characteristic_type(uint8_t gts_characteristics)
+{
+       if ( (gts_characteristics & 0x20) == 0x20)
+               return 1;
+       else
+               return 0;
+} 
+
+
+/************************************************************************************************/  
+/********************************OTHER FUNCTIONS*************************************************/
+/************************************************************************************************/
+  /* A Task to calculate CRC for message transmission */
+  /*
+  task void CRCCalc() {
+    uint16_t length = txLength;
+    uint16_t crc = calcrc(sendPtr, length - 2);
+    
+    sendPtr[length - 2] = crc & 0xff;
+    sendPtr[length - 1] = (crc >> 8) & 0xff;
+    
+  }
+  */
+  
+uint16_t get_crcByte(uint16_t crc, uint8_t b)
+{
+  uint8_t i;
+  
+  crc = crc ^ b << 8;
+  i = 8;
+  do
+    if (crc & 0x8000)
+      crc = crc << 1 ^ 0x1021;
+    else
+      crc = crc << 1;
+  while (--i);
+
+  return crc;
+}
+  /* Internal function to calculate 16 bit CRC */
+  uint16_t calcrc(uint8_t *ptr, uint8_t count) {
+    uint16_t crc;
+    //uint8_t i;
+  
+    crc = 0;
+    while (count-- > 0)
+      crc = get_crcByte(crc, *ptr++);
+
+    return crc;
+  }
+
+#endif
+
diff --git a/tos/lib/net/zigbee/wrapper/includes/nwk_func.h b/tos/lib/net/zigbee/wrapper/includes/nwk_func.h
new file mode 100644 (file)
index 0000000..dbd3975
--- /dev/null
@@ -0,0 +1,141 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Andre Cunha
+ */
+
+#ifndef __NWK_FUNC__
+#define __NWK_FUNC__
+
+//TEST
+typedef struct associated_device
+{
+
+uint32_t address0;
+uint32_t address1;
+
+uint16_t pan_address;
+
+}associated_device;
+//END TEST
+
+typedef struct routing_fields
+{
+
+//uint8_t frame_control1;
+//uint8_t frame_control2;
+uint16_t frame_control;
+uint16_t destination_address;
+uint16_t source_address;
+uint8_t radius;
+uint8_t sequence_number;
+
+}routing_fields;
+
+/*******************************************************************************************************************/  
+/********************************NETWORK LAYER FRAME CONTROL FUNCTIONS************************************************************/
+/*******************************************************************************************************************/
+  
+ //build NPDU frame control field
+uint16_t set_route_frame_control(uint8_t Frame_type,uint8_t Protocol_version,uint8_t Discover_route,uint8_t Security) 
+{
+         uint8_t fc_byte1=0;
+         uint8_t fc_byte2=0;
+         fc_byte1 = ( (Discover_route << 6) | (Protocol_version << 2) | (Frame_type << 0) );                             
+         fc_byte2 = ((Security<< 2));
+         return ( (fc_byte2 <<8 ) | (fc_byte1 << 0) );
+
+}
+
+
+uint8_t route_fc1(uint8_t Security) 
+{
+       uint8_t fc;
+       fc = ((Security << 2));
+       return fc;
+}
+
+uint8_t route_fc2(uint8_t Frame_type,uint8_t Protocol_version,uint8_t Discover_route) 
+{
+       uint8_t fc;
+       fc = ( (Discover_route << 6) | (Protocol_version << 2) | (Frame_type << 0) );   
+       return fc;
+}
+
+uint8_t get_route_frame_type(uint16_t frame_control)
+{
+       return (frame_control & 0x3);
+}
+
+uint8_t get_route_protocol_version(uint16_t frame_control)
+{
+       return ( (frame_control >> 2) & 0xf);
+}
+
+uint8_t get_route_discover_route(uint16_t frame_control)
+{
+       return ( (frame_control >> 6) & 0x3);
+}
+
+uint8_t get_route_security(uint16_t frame_control)
+{
+       if( ((frame_control >> 8) & 0x2) == 0x2)
+               return 1;
+       else
+               return 0;
+}
+
+/*******************************************************************************************************************/  
+/********************************NETWORK LAYER BEACON PAYLOAD INFORMATION FUNCTIONS*********************************/
+/*******************************************************************************************************************/
+
+uint8_t nwk_payload_profile_protocolversion(uint8_t stackprofile,uint8_t nwkcprotocolversion)
+{
+
+return ((stackprofile << 0) | ( nwkcprotocolversion << 4));
+}
+
+uint8_t nwk_payload_capacity(uint8_t routercapacity,uint8_t devicedepth,uint8_t enddevicecapacity)
+{
+
+return ((enddevicecapacity << 7) | ( devicedepth << 3 ) | (routercapacity << 2 ) );
+}
+
+
+uint8_t get_protocolid(uint32_t nwk_information)
+{
+       return (uint8_t)((nwk_information & 0xFF000000) >> 24);
+}
+
+uint8_t get_stackprofile(uint32_t nwk_information)
+{
+       return (uint8_t)((nwk_information & 0x00F00000)>>20);
+}
+
+uint8_t get_nwkcprotocolversion(uint32_t nwk_information)
+{
+       return (uint8_t)((nwk_information & 0x000F0000)>>16);
+}
+
+uint8_t get_routercapacity(uint32_t nwk_information)
+{
+       if ( ( nwk_information & 0x00002000) == 0x00002000)
+               return 1;
+       else
+               return 0;
+}
+
+uint8_t get_devicedepth(uint32_t nwk_information)
+{
+       return (uint8_t)((nwk_information & 0x00001F00) >> 8);
+}
+
+uint8_t get_enddevicecapacity(uint32_t nwk_information)
+{
+       if ( ( nwk_information & 0x00000001) == 0x00000001)
+               return 1;
+       else
+               return 0;
+}
+
+#endif
diff --git a/tos/lib/net/zigbee/wrapper/includes/phy_const.h b/tos/lib/net/zigbee/wrapper/includes/phy_const.h
new file mode 100644 (file)
index 0000000..8ac3ced
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ */
+
+
+#ifndef __PHY_CONST__
+#define __PHY_CONST__
+// The PHY constants are defined here.
+#define aMaxPHYPacketSize  127
+#define aTurnaroundTime 12
+
+#define INIT_CURRENTCHANNEL 0x15
+#define INIT_CHANNELSSUPPORTED 0x0
+#define INIT_TRANSMITPOWER 15
+#define INIT_CCA_MODE 0
+
+#define CCA_IDLE 0
+#define CCA_BUSY 1
+
+// PHY PIB attribute and psdu
+typedef struct
+{
+       uint8_t phyCurrentChannel;
+       uint8_t phyChannelsSupported;
+       uint8_t phyTransmitPower;
+       uint8_t phyCcaMode;
+} phyPIB;
+
+#endif
+
diff --git a/tos/lib/net/zigbee/wrapper/includes/phy_enumerations.h b/tos/lib/net/zigbee/wrapper/includes/phy_enumerations.h
new file mode 100644 (file)
index 0000000..9059bf3
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author Andre Cunha
+ */
+#ifndef __PHY_ENUMERATIONS__
+#define __PHY_ENUMERATIONS__
+//phy status enumerations
+enum{
+       PHY_BUSY = 0x00,
+       PHY_BUSY_RX = 0x01,
+       PHY_BUSY_TX = 0x02,
+       PHY_FORCE_TRX_OFF = 0x03,
+       PHY_IDLE = 0x04,
+       PHY_INVALID_PARAMETER = 0x05,
+       PHY_RX_ON = 0x06,
+       PHY_SUCCESS = 0x07,
+       PHY_TRX_OFF = 0x08,
+       PHY_TX_ON = 0x09,
+       PHY_UNSUPPORTED_ATTRIBUTE = 0x0a
+};
+
+//phy PIB attributes enumerations
+enum{
+       PHYCURRENTCHANNEL = 0x00,
+       PHYCHANNELSSUPPORTED = 0X01,
+       PHYTRANSMITPOWER = 0X02,
+       PHYCCAMODE=0X03
+};
+
+#endif
diff --git a/tos/lib/net/zigbee/wrapper/includes/printfUART.h b/tos/lib/net/zigbee/wrapper/includes/printfUART.h
new file mode 100644 (file)
index 0000000..35a736f
--- /dev/null
@@ -0,0 +1,336 @@
+/*
+ * Copyright (c) 2005
+ *     The President and Fellows of Harvard College.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/* 
+ * Writes printf like output to the UART.  
+ * This works only on the AVR and MSP430 Microcontrollers!
+ * <p>
+ * Note: For AVR we explicitly place the print statements in ROM; for
+ * MSP430 this is done by default!  For AVR, if we don't place it
+ * explicitely in ROM, the statements will go in RAM, which will
+ * quickly cause a descent size program to run out of RAM.  By default
+ * it doesn't disable the interupts; disabling the interupts when
+ * writing to the UART, slows down/makes the mote quite unresponsive,
+ * and can lead to problems!  If you wish to disable all printfs to
+ * the UART, then comment the flag: <code>PRINTFUART_ENABLED</code>.
+
+ * <p> <pre>
+ * How to use:
+ *   // (1) Call printfUART_init() from your initialization function 
+ *   //     to initialize the UART
+ *   printfUART_init();
+ *   // (2) Set your UART client to the correct baud rate.  Look at 
+ *   //     the comments in printfUART_init(), to figure out what 
+ *   //     baud to use for your particular mote
+ *
+ *   // (3) Send printf statements like this:
+ *   printfUART("Hello World, we are in year= %i\n", 2004);
+ *
+ * Examples and caveats:
+ *   // (1) - If no parameters are passed, then the second quotes 
+ *            are required because of how the macro is defined
+ *   printfUART("Timer fired\n", ""); 
+ *   // (2) - Must use curly braces in single section statements
+ *   if (x < 3)
+ *       {printfUART("The value of x is %i\n", x);}
+ *   // (3) - Otherwise it more or less works like regular printf
+ *   printfUART("\nThe value of x=%i, and y=%i\n", x, y); 
+ * </pre>
+ * <pre>URL: http://www.eecs.harvard.edu/~konrad/projects/motetrack</pre>
+ * @author Konrad Lorincz
+ * @version 2.0, January 5, 2005
+ */
+#ifndef PRINTFUART_H
+#define PRINTFUART_H
+#include <stdarg.h>
+//#include <stdio.h>
+
+// Comment out the line below to DISABLE printf statements.
+#define PRINTFUART_ENABLED
+
+
+// -------------------------------------------------------------------
+#ifdef PRINTFUART_ENABLED
+    #define DEBUGBUF_SIZE 256
+    char debugbuf[DEBUGBUF_SIZE];
+    char debugbufROMtoRAM[DEBUGBUF_SIZE];
+
+    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
+        #define printfUART(__format, __args...) {                  \
+            static const char strROM[] PROGMEM = __format;         \
+            strcpy_P((char*) &debugbufROMtoRAM, (PGM_P) &strROM);  \
+            sprintf(debugbuf, debugbufROMtoRAM, __args);           \
+            writedebug();                                          \
+        }   
+    #else  // assume MSP430 architecture (e.g. TelosA, TelosB, etc.)
+        #define printfUART(__format, __args...) {      \
+            sprintf(debugbuf, __format, __args);       \
+            writedebug();                              \
+        }   
+    #endif
+#else
+    #define printfUART(__format, __args...)
+    void printfUART_init() {}
+#endif
+
+#define NOprintfUART(__format, __args...)
+
+
+/** Used for terminating the program from a non-nesc file. Calling <code>exit(1)</code> 
+ *  from a non-nesc file doesn't terminate the program immeditely
+ */
+static int EXIT_PROGRAM = 0;  
+
+
+
+// -------------------------------------------------------------------
+#ifdef PRINTFUART_ENABLED
+
+/**
+ * Initialize the UART port.  Call this from your startup routine.
+ */
+#define printfUART_init() {atomic printfUART_init_private();}
+void printfUART_init_private()
+{
+    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2)
+        // 56K baud
+        outp(0,UBRR0H);
+        outp(15, UBRR0L);                              //set baud rate
+        outp((1<<U2X),UCSR0A);                         // Set UART double speed
+        outp(((1 << UCSZ1) | (1 << UCSZ0)) , UCSR0C);  // Set frame format: 8 data-bits, 1 stop-bit
+        inp(UDR0);
+        outp((1 << TXEN) ,UCSR0B);   // Enable uart reciever and transmitter
+
+    #else
+      #if defined(PLATFORM_MICA2DOT)  
+        // 19.2K baud
+        outp(0,UBRR0H);            // Set baudrate to 19.2 KBps
+        outp(12, UBRR0L);
+        outp(0,UCSR0A);            // Disable U2X and MPCM
+        outp(((1 << UCSZ1) | (1 << UCSZ0)) , UCSR0C);
+        inp(UDR0);
+        outp((1 << TXEN) ,UCSR0B);
+  
+      #else  // assume TelosA, TelosB, etc.
+        //9.6K baud
+        uint16_t l_br = 0;
+        uint8_t l_mctl = 0;
+        uint8_t l_ssel = 0;
+
+
+        TOSH_SEL_UTXD1_MODFUNC();
+        TOSH_SEL_URXD1_MODFUNC();
+
+
+        UCTL1 = SWRST;  
+        UCTL1 |= CHAR;  // 8-bit char, UART-mode
+    
+        U1RCTL &= ~URXEIE;  // even erroneous characters trigger interrupts
+
+        UCTL1 = SWRST;
+        UCTL1 |= CHAR;  // 8-bit char, UART-mode
+
+        if (l_ssel & 0x80) {
+            U1TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
+            U1TCTL |= (l_ssel & 0x7F); 
+        }
+        else {
+            U1TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
+            U1TCTL |= SSEL_ACLK; // use ACLK, assuming 32khz
+        }
+
+        if ((l_mctl != 0) || (l_br != 0)) {
+            U1BR0 = l_br & 0x0FF;
+            U1BR1 = (l_br >> 8) & 0x0FF;
+            U1MCTL = l_mctl;
+        }
+        else {
+            U1BR0 = 0x03;   // 9600 baud
+            U1BR1 = 0x00;
+            U1MCTL = 0x4A;
+        }
+      
+        ME2 &= ~USPIE1;   // USART1 SPI module disable
+        ME2 |= (UTXE1 | URXE1);   // USART1 UART module enable
+      
+        U1CTL &= ~SWRST;
+    
+        IFG2 &= ~(UTXIFG1 | URXIFG1);
+        IE2 &= ~(UTXIE1 | URXIE1);  // interrupt disabled
+
+      #endif
+    #endif
+}
+
+#if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
+#else // assume AVR architecture (e.g. TelosA, TelosB)
+    bool isTxIntrPending()
+    {
+        if (U1TCTL & TXEPT) {
+            return TRUE;
+        }
+        return FALSE;
+    }
+#endif
+
+/**
+ * Outputs a char to the UART.
+ */
+void UARTPutChar(char c)
+{
+    if (c == '\n')
+        UARTPutChar('\r');
+
+
+    #if defined(PLATFORM_MICAZ) || defined(PLATFORM_MICA2) || defined(PLATFORM_MICA2DOT)
+        loop_until_bit_is_set(UCSR0A, UDRE);
+        outb(UDR0,c);
+    #else // assume AVR architecture (e.g. TelosA, TelosB)
+        U1TXBUF = c;  
+        while( !isTxIntrPending() )  
+            continue;
+    #endif
+}
+
+/**
+ * Outputs the entire debugbuf to the UART, or until it encounters '\0'.
+ */
+void writedebug()
+{
+    uint16_t i = 0;
+    
+    while (debugbuf[i] != '\0' && i < DEBUGBUF_SIZE)
+        UARTPutChar(debugbuf[i++]);
+}
+
+
+
+/**
+ * Simplified sprintf
+ */
+#define SCRATCH 16
+int sprintf(uint8_t *buf, const uint8_t *format, ...)
+{
+    uint8_t scratch[SCRATCH];
+    uint8_t format_flag;
+    uint32_t u_val=0, base;//modified by Andre Cunha
+    uint8_t *ptr;
+    va_list ap;
+
+   //memset(scratch, 0, SCRATCH);
+       
+    buf[0] = '\0';  // KLDEBUG - fixes subtle bug ...
+    va_start (ap, format);
+    for (;;){
+        while ((format_flag = *format++) != '%'){      // Until '%' or '\0'
+            if (!format_flag) {va_end (ap); return (0);}
+            *buf = format_flag; buf++; *buf=0;
+        }
+
+        switch (format_flag = *format++){
+
+        case 'c':
+            format_flag = va_arg(ap,int);
+        default:
+            *buf = format_flag; buf++; *buf=0;
+            continue;
+        case 'S':
+        case 's':
+            ptr = va_arg(ap,char *);
+            strcat(buf, ptr);
+            continue;
+        case 'o':
+            base = 8;
+            *buf = '0'; buf++; *buf=0;
+            goto CONVERSION_LOOP;
+        case 'i':
+            if (((int)u_val) < 0){
+                u_val = - u_val;
+                *buf = '-'; buf++; *buf=0;
+            }
+                       base = 10;
+            goto CONVERSION_LOOP;
+            // no break -> run into next case
+                case 'd'://added by Andre Cunha
+            if (((int32_t)u_val) < 0){
+                u_val = - u_val;
+                *buf = '-'; buf++; *buf=0;
+            }
+            
+                       base = 10;
+            goto CONVERSION_LOOP32;
+        case 'u':
+            base = 10;
+            goto CONVERSION_LOOP;
+        case 'x':
+            base = 16;
+                       goto CONVERSION_LOOP;
+                       
+               case 'y'://unsigned int 32 bits hexadecimal//added by Andre Cunha
+            base = 16;
+                       goto CONVERSION_LOOP32;
+                       
+        CONVERSION_LOOP:
+            u_val = va_arg(ap,int);
+            ptr = scratch + SCRATCH;
+            *--ptr = 0;
+            do {
+                char ch = u_val % base + '0';
+                if (ch > '9')
+                    ch += 'a' - '9' - 1;
+                *--ptr = ch;
+                u_val /= base;
+            } while (u_val);
+            strcat(buf, ptr);
+            buf += strlen(ptr);
+                       break;
+                       
+               CONVERSION_LOOP32:
+            u_val = va_arg(ap,int32_t);
+            ptr = scratch + SCRATCH;
+            *--ptr = 0;
+            do {
+                char ch = u_val % base + '0';
+                if (ch > '9')
+                    ch += 'a' - '9' - 1;
+                *--ptr = ch;
+                u_val /= base;
+            } while (u_val);
+            strcat(buf, ptr);
+            buf += strlen(ptr);
+        }
+    }
+}
+
+
+#endif  // PRINTFUART_ENABLED
+// -------------------------------------------------------------------
+
+#endif  // PRINTFUART_H
+
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MCPS_DATA.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MCPS_DATA.nc
new file mode 100644 (file)
index 0000000..983b808
--- /dev/null
@@ -0,0 +1,19 @@
+/**
+ * MCPS-DATA-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MCPS_DATA
+{ 
+  command error_t request(uint8_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[], uint8_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[], uint8_t msduLength, uint8_t msdu[],uint8_t msduHandle, uint8_t TxOptions);
+  
+  event error_t confirm(uint8_t msduHandle, uint8_t status);
+                                                                                                                                                                                                                                                                                                                               
+  event error_t indication(uint16_t SrcAddrMode, uint16_t SrcPANId, uint32_t SrcAddr[2], uint16_t DstAddrMode, uint16_t DestPANId, uint32_t DstAddr[2], uint16_t msduLength,uint8_t msdu[100],uint16_t mpduLinkQuality, uint16_t SecurityUse, uint16_t ACLEntry);  
+
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MCPS_PURGE.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MCPS_PURGE.nc
new file mode 100644 (file)
index 0000000..0685a48
--- /dev/null
@@ -0,0 +1,16 @@
+/**
+ * MCPS-PURGE-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+interface OPENZB_MCPS_PURGE
+{ 
+  command error_t request(uint8_t msduHandle);
+    
+  event error_t confirm(uint8_t msduHandle, uint8_t status);
+  
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_ASSOCIATE.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_ASSOCIATE.nc
new file mode 100644 (file)
index 0000000..cc5cf43
--- /dev/null
@@ -0,0 +1,22 @@
+/**
+ * MLME-ASSOCIATE-Service Access Point
+ *     std pag 65
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_ASSOCIATE
+{ 
+  command error_t request(uint8_t LogicalChannel,uint8_t CoordAddrMode,uint16_t CoordPANId,uint32_t CoordAddress[],uint8_t CapabilityInformation,bool SecurityEnable);
+  
+  event error_t indication(uint32_t DeviceAddress[], uint8_t CapabilityInformation, bool SecurityUse, uint8_t ACLEntry);
+  
+  command error_t response(uint32_t DeviceAddress[], uint16_t AssocShortAddress, uint8_t status, bool SecurityEnable);
+  
+  event error_t confirm(uint16_t AssocShortAddress, uint8_t status);
+  
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_BEACON_NOTIFY.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_BEACON_NOTIFY.nc
new file mode 100644 (file)
index 0000000..5e66c28
--- /dev/null
@@ -0,0 +1,17 @@
+/*
+ * MLME-BEACON-NOTIFY-Service Access Point
+ * std pag 75
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+includes mac_const;
+
+interface OPENZB_MLME_BEACON_NOTIFY
+{ 
+       event error_t indication(uint8_t BSN,PANDescriptor pan_descriptor, uint8_t PenAddrSpec, uint8_t AddrList, uint8_t sduLength, uint8_t sdu[]);
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_DISASSOCIATE.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_DISASSOCIATE.nc
new file mode 100644 (file)
index 0000000..9c2fc0e
--- /dev/null
@@ -0,0 +1,18 @@
+/**
+ * MLME-DISASSOCIATE-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+interface OPENZB_MLME_DISASSOCIATE
+{ 
+  command error_t request(uint32_t DeviceAddress[], uint8_t DisassociateReason, uint8_t SecurityEnable);
+  
+  event error_t indication(uint32_t DeviceAddress[], uint8_t DisassociateReason, uint8_t SecurityUse, uint8_t ACLEntry);
+  
+  event error_t confirm(uint8_t status);
+  
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_GET.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_GET.nc
new file mode 100644 (file)
index 0000000..4bd0ca3
--- /dev/null
@@ -0,0 +1,16 @@
+/**
+ * MLME-GET-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+interface OPENZB_MLME_GET
+{ 
+  command error_t request(uint8_t PIBAttribute);
+    
+  event error_t confirm(uint8_t status,uint8_t PIBAttribute, uint8_t PIBAttributeValue[]);
+  
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_GTS.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_GTS.nc
new file mode 100644 (file)
index 0000000..40dd8be
--- /dev/null
@@ -0,0 +1,17 @@
+/**
+ * MLME-GTS-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+interface OPENZB_MLME_GTS
+{ 
+  command error_t request(uint8_t GTSCharacteristics, uint8_t SecurityEnable);
+  
+  event error_t confirm(uint8_t GTSCharacteristics, uint8_t status);
+  
+  event error_t indication(uint16_t DevAddress, uint8_t GTSCharacteristics, uint8_t SecurityUse, uint8_t ACLEntry);
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_ORPHAN.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_ORPHAN.nc
new file mode 100644 (file)
index 0000000..6331dc3
--- /dev/null
@@ -0,0 +1,18 @@
+/**
+ * MLME-ORPHAN-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_ORPHAN
+{ 
+
+  event error_t indication(uint32_t OrphanAddress[1], uint8_t SecurityUse, uint8_t ACLEntry);
+  
+  command error_t response(uint32_t OrphanAddress[1],uint16_t ShortAddress,uint8_t AssociatedMember, uint8_t security_enabled);
+
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_POLL.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_POLL.nc
new file mode 100644 (file)
index 0000000..d337a90
--- /dev/null
@@ -0,0 +1,17 @@
+/**
+ * MLME-POOL-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_POLL
+{ 
+  command result_t request(uint8_t CoordAddrMode, uint16_t CoorPANId, uint32_t CoorAddress[], uint8_t Security);
+  
+  event result_t confirm(uint8_t status);
+  
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_RESET.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_RESET.nc
new file mode 100644 (file)
index 0000000..dcea1d4
--- /dev/null
@@ -0,0 +1,20 @@
+/**
+ * MLME-RESET-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_RESET
+{ 
+
+  command error_t request(uint8_t set_default_PIB);
+  
+  event error_t confirm(uint8_t status);
+  
+  
+
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_RX_ENABLE.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_RX_ENABLE.nc
new file mode 100644 (file)
index 0000000..d825f65
--- /dev/null
@@ -0,0 +1,20 @@
+/**
+ * MLME-RX-ENABLE-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_RX_ENABLE
+{ 
+
+  command result_t request(uint8_tDeferPermit, uint32_t RxOnTime, uint32_t RxOnDuration);
+  
+  event result_t confirm(uint8_t status);
+  
+  
+
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SCAN.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SCAN.nc
new file mode 100644 (file)
index 0000000..7683958
--- /dev/null
@@ -0,0 +1,19 @@
+/**
+ * MLME-SCAN-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_SCAN
+{ 
+
+  command error_t request(uint8_t ScanType, uint32_t ScanChannels, uint8_t ScanDuration);
+       
+  event error_t confirm(uint8_t status,uint8_t ScanType, uint32_t UnscannedChannels, uint8_t ResultListSize, uint8_t EnergyDetectList[], SCAN_PANDescriptor PANDescriptorList[]);
+                                                                                                                                                                               //NEED to explain the implementation
+                                                                                                                                                                               //Eache value in sequencial to the scanned channels
+       }
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SET.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SET.nc
new file mode 100644 (file)
index 0000000..51c9b27
--- /dev/null
@@ -0,0 +1,17 @@
+/**
+ * MLME-SET-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_SET
+{ 
+  command error_t request(uint8_t PIBAttribute,uint8_t PIBAttributeValue[]);
+
+  event error_t confirm(uint8_t status,uint8_t PIBAttribute);
+
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_START.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_START.nc
new file mode 100644 (file)
index 0000000..fc979ea
--- /dev/null
@@ -0,0 +1,19 @@
+/**
+ * MLME-START-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_START
+{ 
+
+  //request for the device to start using new superframe configuration
+  command error_t request(uint32_t PANId, uint8_t LogicalChannel, uint8_t BeaconOrder, uint8_t SuperframeOrder,uint8_t PANCoordinator,uint8_t BatteryLifeExtension,uint8_t CoordRealignment,uint8_t SecurityEnable,uint32_t StartTime);
+  
+  event error_t confirm(uint8_t status);
+  
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SYNC.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SYNC.nc
new file mode 100644 (file)
index 0000000..857ed04
--- /dev/null
@@ -0,0 +1,17 @@
+/**
+ * MLME-SYNC-Service Access Point
+ *
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_SYNC
+{ 
+//sd pag 105
+  command error_t request(uint8_t logical_channel,uint8_t track_beacon);
+
+}
diff --git a/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SYNC_LOSS.nc b/tos/lib/net/zigbee/wrapper/interfaces/mac/OPENZB_MLME_SYNC_LOSS.nc
new file mode 100644 (file)
index 0000000..ac133ba
--- /dev/null
@@ -0,0 +1,15 @@
+/**
+ * MLME-SYNC-LOSS-Service Access Point
+ *
+ * @author IPP HURRAY http://www.hurray.isep.ipp.pt/art-wise
+ * @author IPP HURRAY http://www.open-zb.net
+ * @author Ricardo Severino
+ *
+ *
+ */
+
+interface OPENZB_MLME_SYNC_LOSS
+{ 
+//pag 105
+   event error_t indication(uint8_t LossReason);
+}
index 250042cee03e3ff41a48bc5126890d4c8619c033..209b5ffcbad38767825644d862454b77ac431a87 100644 (file)
@@ -70,7 +70,8 @@ implementation {
     call TimerMilli.stop();
     stopTimer = FALSE;
     call StdControl.start();
-    call SplitControl.start();
+    if (call SplitControl.start()==EALREADY)
+      call ResourceDefaultOwner.release();
   }
 
   task void timerTask() { 
@@ -82,7 +83,7 @@ implementation {
       stopTimer = TRUE;
       post startTask();
     }
-    else atomic requested = TRUE;
+    else requested = TRUE;
   }
 
   async event void ResourceDefaultOwner.immediateRequested() {
@@ -105,11 +106,14 @@ implementation {
   }
 
   event void TimerMilli.fired() {
-    if(stopTimer == FALSE) {
-      stopping = TRUE;
-      call PowerDownCleanup.cleanup();
-      call StdControl.stop();
-      call SplitControl.stop();
+    atomic {
+      if(stopTimer == FALSE) {
+        stopping = TRUE;
+        call PowerDownCleanup.cleanup();
+        call StdControl.stop();
+        if (call SplitControl.stop()==EALREADY)
+          signal SplitControl.stopDone(SUCCESS);
+      }
     }
   }
 
index 0ea9b512861ef2d1d128494f97124f7c5d2457e9..b620e5e416f6a8b06caff9ade78afc9bb130ce7e 100644 (file)
@@ -163,11 +163,18 @@ implementation {
   
 #ifdef _H_msp430hardware_h
   int putchar(int c) __attribute__((noinline)) @C() @spontaneous() {
-#endif
+#else
 #ifdef _H_atmega128hardware_H
   int uart_putchar(char c, FILE *stream) __attribute__((noinline)) @C() @spontaneous() {
+#else
+#ifdef __M16C62PHARDWARE_H__
+  int lowlevel_putc(int c) __attribute__((noinline)) @C() @spontaneous() {
+#else
+  int lowlevel_putc(int c) __attribute__((noinline)) @C() @spontaneous() {
+#endif
+#endif
 #endif
-    if((state == S_STARTED) && (call Queue.size() >= 5*sizeof(printf_msg_t))) {
+    if((state == S_STARTED) && (call Queue.size() >= ((PRINTF_BUFFER_SIZE)/2))) {
       state = S_FLUSHING;
       sendNext();
     }
diff --git a/tos/lib/printf/generic_printf.h b/tos/lib/printf/generic_printf.h
new file mode 100644 (file)
index 0000000..3c14d56
--- /dev/null
@@ -0,0 +1,482 @@
+/****************************************************************
+  KPIT Cummins Infosystems Ltd, Pune, India. 1-April-2006.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+ *****************************************************************/
+
+/*
+   Written By:
+   Shrirang Khishti <shrirangk@kpitcummins.com>.
+
+   This is a smaller version of printf
+   Positive points about this function
+   1. Reduces code size considerably ,very useful in embedded applications
+   2. No malloc calls are used
+   3. Supports almost all the functionalities of GNU std printf routine.
+   4. If user dont want float_support in this customized printf
+   just undef macro float_support
+ */
+
+#ifndef  __M16C62P_PRINTF_H__
+#define __M16C62P_PRINTF_H__
+#include <stdarg.h>
+#include <string.h>
+
+#define printf _printf
+extern int lowlevel_putc(int c); 
+
+int left_val,right_val;
+
+#define condition *format!='f'&&*format!='d'&&*format!='c'&&*format!='s'&&*format!='l'&&*format!='u'&&*format!='\0'&&*format!=' '&&*format!='i'&&*format!='x'&&*format!='X'&&*format!='o'&&*format!='%'&&*format!='p'
+
+#define float_support
+
+long temp_arr[]={100000,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
+
+
+/**
+ * @fn
+ * @brief 
+ *
+ * @param c
+ */
+int
+_putchar(int c)
+{     
+  /* Convert CR to CR/LF */
+  if (c == '\n')
+    lowlevel_putc('\r');
+  lowlevel_putc(c);
+
+  return c;
+}
+
+
+/**
+ * @fn void _puts(const char *tempStr)
+ * @brief Prints a NULL-erminated string on UART 1
+ *
+ * @param s The string to output
+ *
+ */
+int
+_puts(const char *s)
+{
+  while( *s != '\0' )
+    _putchar(*s++);
+
+  return 0;
+}
+
+
+/**
+ * @fn void strrev(char *str)
+ * @brief Reverses a string
+ *
+ * @param str The string to reverse
+ */
+void
+strrev(char *str)
+{
+  char *temp, c;
+  int len=strlen(str) ;
+  temp = str + len -1;
+
+  while(str < temp ) {
+
+    c = *str;
+    *str = *temp;
+
+    *temp = c;
+    str++;
+    temp--;
+  }
+}
+
+
+static void print_hex_oct( long int temp_var,int _div,int corr_factor,int ret_val,int sign,int *cntr_val)
+{
+  unsigned long int i1,temp=temp_var;
+  int cntr=0,neg_flag=0;
+  char s1[40];
+
+  if(sign==1&&temp_var<0)
+  {
+    temp=-temp_var;
+    neg_flag=1;
+  }
+  if(temp==0)
+    s1[cntr++]='0';
+  while(temp>0)
+  {
+    i1=temp%_div;
+    temp=temp/_div;
+    if(i1<=9)
+      s1[cntr]=i1+'0';
+    else
+      s1[cntr]=i1+corr_factor-9;
+    cntr++;
+  }
+
+  while((left_val-(right_val>cntr?right_val:cntr+neg_flag))>0)
+  {
+    _putchar(' ');
+    left_val--;
+               (*cntr_val)++;
+       }
+
+       while(right_val-cntr>0)
+       {
+               s1[cntr++]='0';
+       }
+
+       if(neg_flag==1)
+       s1[cntr++]='-';
+
+       s1[cntr]='\0';
+       strrev(s1);
+       _puts(s1);
+       (*cntr_val)+=strlen(s1);
+}
+
+
+#ifdef float_support
+static void float_print(long double f1,long double f2,int multi,int *cntr_val)
+{
+       int temp,cntr=0,i1,neg_flag=0;
+       char s1[10];
+
+        if(f1<0)
+        {
+                f1=f1*-1;
+                neg_flag=1;
+                f2=f1;
+        }
+        temp=(int)f1;
+
+        f1=f1-temp;
+     f1=f1*multi;
+
+     temp=f1;
+
+     if(temp==0)
+       s1[cntr++]='0';
+     while(temp>0)
+     {
+         i1=temp%10;
+         temp=temp/10;
+         s1[cntr]=i1+0x30;
+         cntr++;
+     }
+
+     while(right_val<9&&(right_val -cntr)>0)
+          s1[cntr++]='0';
+          s1[cntr]='.';
+          cntr++;
+
+          temp=(int)f2;
+        if(temp==0)
+               s1[cntr++]='0';
+        while(temp>0)
+        {
+             i1=temp%10;
+             temp=temp/10;
+             s1[cntr]=i1+0x30;
+             cntr++;
+        }
+
+        while(left_val-- -cntr>0)
+               {
+                       _putchar(' ');
+                       (*cntr_val)++;
+               }
+                       if(neg_flag==1)
+           s1[cntr++]='-';
+           s1[cntr]='\0';
+           cntr--;
+               strrev(s1);
+       _puts(s1);
+               (*cntr_val)+=strlen(s1);
+               neg_flag=0;
+}
+
+#endif // float_support
+
+static int format_val(char *temp,long float_flag,int *cntr_val,int flag)
+{
+left_val=0;
+right_val=0;
+       if(*temp=='\0'&&flag==1)
+       {
+               right_val=3;
+               return 0;
+       }
+       while(*temp!='.'&&*temp!='\0')
+       {
+               if(*temp<'0'||*temp>'9')
+               {
+                       while(*temp)
+                       {
+                               _putchar(*temp++);
+                               (*cntr_val)++;
+                       }
+                       return -1;
+               }
+               else
+               left_val=left_val*10+*temp-'0';
+        temp++;
+       }
+    if(*temp)
+               temp++;
+               else
+               return left_val;
+       while(*temp)
+       {
+       if(*temp<'0'||*temp>'9')
+       {
+       while(*temp)
+               {
+                       _putchar(*temp++);
+                       (*cntr_val)++;
+               }
+       return -1;
+       }
+       else
+       right_val=right_val*10+*temp-'0';
+     temp++;
+       }
+
+return 0;
+}
+
+
+/**
+ * @fn int _printf(const char *format, ...)
+ * @brief Prints a formatted string on UART1
+ *
+ * @param format The string
+ */
+int _printf(const char *format, ...)
+{
+   int format_cntr=0;
+   char temp_str[20];
+   int return_flag=0,cntr_val;
+   long double f1,f2;
+   char *str_temp;
+   int *cntr=&cntr_val;
+
+   va_list ap;
+   va_start(ap, format);
+   *cntr=0;
+   while(*format) {
+     temp_str[format_cntr]='\0';
+     if(*format=='%')
+     {
+       *format++;
+       while(*format==' ')
+       {
+        format++;
+        _putchar(' ');
+       }
+       while(condition)
+
+       {
+        temp_str[format_cntr++]=*format++;
+       }
+       temp_str[format_cntr]='\0';
+       if(*format=='%')
+       {
+        _putchar('%');
+        (*cntr)++;
+        format_cntr=0;
+        format++;
+        continue;
+       }
+
+       /************** print unsigned ****************/
+       else if(*format=='u')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1)
+
+          print_hex_oct(va_arg(ap,unsigned int),10,0,return_flag,0,cntr);
+
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+       }
+       /*********** Print Integer Values **************/
+       else if(*format=='d'||*format=='i')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+
+        if(return_flag!=-1)
+
+          print_hex_oct(va_arg(ap,int),10,0,return_flag,1,cntr);
+
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+
+       }
+
+       /*********** Print hex,Octal values ******************/
+       else if(*format=='x'||*format=='X'||*format=='o'||*format=='p')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1) {
+
+          if(*format=='x'||*format=='p')
+            print_hex_oct(va_arg(ap,unsigned int),16,0x60,return_flag,0,cntr);
+          else if(*format=='X')
+            print_hex_oct(va_arg(ap,unsigned int),16,0x40,return_flag,0,cntr);
+          else
+            print_hex_oct(va_arg(ap,unsigned int),8,0,return_flag,0,cntr);
+        }
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+       }
+
+       /************ Character printing ****************88*/
+       else if(*format=='c')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1)
+        {
+          while(return_flag-->1)
+          {
+            _putchar(' ');
+            (*cntr)++;
+          }
+          _putchar(va_arg(ap,int));
+          (*cntr)+=2;
+        }
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+       }
+
+       /*************** Print String *****************/
+       else if(*format=='s')
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+        if(return_flag!=-1)
+        {
+          str_temp=va_arg(ap,char*);
+
+          while((return_flag--  -(int) strlen(str_temp))>0)
+          {
+            _putchar(' ');
+            (*cntr)++;
+
+          }
+          _puts(str_temp);
+          (*cntr)+=strlen(str_temp);
+        }
+        else
+        {
+          _putchar(*format);
+          (*cntr)++;
+        }
+        format++;
+        format_cntr=0;
+        continue;
+
+       }
+       /*************** Print floating point number *****************/
+       else if(*format=='f'||(*format=='l'&&*(format+1)=='f'))
+       {
+
+        return_flag=format_val(temp_str,1,cntr,1);
+        if(return_flag!=-1)
+        {
+          if(*format=='l')
+          {
+            f1=va_arg(ap,long double);
+            format+=2;
+          }
+          else
+          {
+            f1=va_arg(ap,double);
+            format++;
+          }
+          f2=f1;
+#ifdef float_support
+          right_val++;
+          float_print(f1,f2,temp_arr[right_val%10],cntr);
+#endif
+        }
+        else
+        {
+          _putchar(*format++);
+          (*cntr)++;
+        }
+        format_cntr=0;
+        continue;
+       }
+       else if(*format=='l'&&((*(format+1)=='d')||(*(format+1)=='u')))
+       {
+        return_flag=format_val(temp_str,0,cntr,0);
+
+        if((return_flag=-1)&&(*(format+1)=='d'))
+        {
+          print_hex_oct(va_arg(ap,long int),10,0x00,return_flag,1,cntr);
+        }
+
+        else if((return_flag=-1)&&(*(format+1)=='u'))
+        {
+          print_hex_oct(va_arg(ap,unsigned long int),10,0x00,return_flag,0,cntr);
+        }
+
+        else
+        {
+          _putchar(*format);
+          _putchar(*(format+1));
+          (*cntr)+=2;
+        }
+        format+=2;
+        format_cntr=0;
+        continue;
+       }
+       else
+       {
+        _puts(temp_str);
+        format_cntr=0;
+        continue;
+       }
+     }
+     _putchar(*format++);
+
+     (*cntr)++;
+   }
+   va_end(ap);
+   return cntr_val;
+}
+
+
+#endif // __M16C62P_PRINTF_H__
+
index a8cf26193433754283cf7f119539145d76e5e1ff..0f2f051746d70b088a4ebb843e911dd13d871f23 100644 (file)
 
 #ifdef _H_msp430hardware_h
   #include <stdio.h>
-#endif
+#else
 #ifdef _H_atmega128hardware_H
   #include "avr_stdio.h"
+#else
+#ifdef __M16C62PHARDWARE_H__ 
+  #include "m16c62p_printf.h"
+#else
+  #include "generic_printf.h"
+#endif
+#endif
 #endif
 #include "message.h"
 int printfflush();
 
+#ifndef PRINTF_MSG_LENGTH
 #define PRINTF_MSG_LENGTH      28
+#endif
 typedef nx_struct printf_msg {
   nx_uint8_t buffer[PRINTF_MSG_LENGTH];
 } printf_msg_t;
diff --git a/tos/lib/safe/SafeFailureHandlerC.nc b/tos/lib/safe/SafeFailureHandlerC.nc
new file mode 100644 (file)
index 0000000..ea8dd85
--- /dev/null
@@ -0,0 +1,13 @@
+
+#include "Timer.h"
+
+configuration SafeFailureHandlerC {
+}
+implementation {
+  components LedsC;
+  components SafeFailureHandlerP;
+  components BusyWaitMicroC as Wait;
+
+  SafeFailureHandlerP.Leds -> LedsC;
+  SafeFailureHandlerP.BusyWait -> Wait;
+}
diff --git a/tos/lib/safe/SafeFailureHandlerP.nc b/tos/lib/safe/SafeFailureHandlerP.nc
new file mode 100644 (file)
index 0000000..c8fb772
--- /dev/null
@@ -0,0 +1,143 @@
+
+#include "Timer.h"
+
+module SafeFailureHandlerP {
+  uses {
+    interface Leds;
+    interface BusyWait<TMicro, uint16_t>;
+  }
+}
+implementation {
+
+  #ifndef asmlinkage
+    #define asmlinkage
+  #endif
+
+  #ifndef noreturn
+    #define noreturn __attribute__((noreturn))
+  #endif
+
+  void delay (int len) 
+  {
+    volatile int x;
+    for (x=0; x<len; x++) { 
+      call BusyWait.wait(2000);
+    }
+  }
+
+  void v_short_delay (void) { delay (10); }
+
+  void short_delay (void) { delay (80); }
+
+  void long_delay (void) { delay (800); }
+
+  void flicker (void)
+  {
+    int i;
+    for (i=0; i<20; i++) {
+       delay (20);
+       call Leds.led0Off();
+       call Leds.led1Off();
+       call Leds.led2Off();
+       delay (20);
+       call Leds.led0On();
+       call Leds.led1On();
+       call Leds.led2On();
+    }
+    call Leds.led0Off();
+    call Leds.led1Off();
+    call Leds.led2Off();
+  }
+
+  void roll (void)
+  {
+    int i;
+    for (i=0; i<10; i++) {
+       delay (30);
+       call Leds.led0On();
+       call Leds.led2Off();
+       delay (30);
+       call Leds.led1On();
+       call Leds.led0Off();
+       delay (30);
+       call Leds.led2On();
+       call Leds.led1Off();
+    }
+    call Leds.led2Off();
+  }
+           
+  void separator (void)
+  {
+    call Leds.led0Off();
+    call Leds.led1Off();
+    call Leds.led2Off();
+    short_delay ();
+    call Leds.led0On();
+    call Leds.led1On();
+    call Leds.led2On();
+    v_short_delay ();
+    call Leds.led0Off();
+    call Leds.led1Off();
+    call Leds.led2Off();
+    short_delay ();
+  }
+
+  void display_b4 (int c) 
+  {
+    switch (c) {
+    case 3:
+      call Leds.led2On();
+    case 2:
+      call Leds.led1On();
+    case 1:
+      call Leds.led0On();
+    case 0:
+      long_delay ();
+      break;
+    default:
+      flicker ();
+    }
+    separator ();
+  }
+
+  void display_int (const unsigned int x)
+  {
+    int i = 14;
+    do {
+      display_b4 (0x3 & (x >> i));
+      i -= 2;
+    } while (i >= 0);
+  }
+
+  void display_int_flid (const unsigned int x)
+  {
+    roll ();
+    display_int (x);
+    roll ();
+  }
+
+  asmlinkage noreturn 
+  void deputy_fail_noreturn_fast (int flid) @C() @spontaneous()
+  {
+    atomic {
+#if defined(__AVR_ARCH__)
+      asm volatile ("break");
+#endif
+      while(1) {
+        display_int_flid(flid);
+      }
+    }
+  }
+
+  asmlinkage 
+  void deputy_fail_mayreturn(int flid) @C() @spontaneous()
+  {
+    deputy_fail_noreturn_fast(flid);
+  }
+
+  asmlinkage noreturn 
+  void deputy_fail_noreturn(int flid) @C() @spontaneous()
+  {
+    deputy_fail_noreturn_fast(flid);
+  }
+}
diff --git a/tos/lib/safe/avr/fail.c b/tos/lib/safe/avr/fail.c
deleted file mode 100644 (file)
index 32e5786..0000000
+++ /dev/null
@@ -1,184 +0,0 @@
-#undef SAFE_TINYOS
-
-#include <stdint.h>
-#include <avr/io.h>
-
-// #define SIMPLE_FAIL
-
-#ifndef SIMPLE_FAIL
-
-static void led_off_0 (void) 
-{ 
-  *(volatile unsigned char *)59U |= 1 << 0;
-}
-
-static void led_off_1 (void)  { 
-  *(volatile unsigned char *)59U |= 1 << 1;
-}
-
-static void led_off_2 (void)  {
-  *(volatile unsigned char *)59U |= 1 << 2;
-}
-
-static void led_on_0 (void) { 
-  *(volatile unsigned char *)59U &= ~(1 << 0);
-}
-
-static void led_on_1 (void) { 
-  *(volatile unsigned char *)59U &= ~(1 << 1);
-}
-
-static void led_on_2 (void) { 
-  *(volatile unsigned char *)59U &= ~(1 << 2);
-}
-
-static void delay (int len) 
-{
-  volatile int x, y;
-  for (x=0; x<len; x++) { 
-    for (y=0; y<1000; y++) { }
-  }
-}
-
-static void v_short_delay (void) { delay (10); }
-
-static void short_delay (void) { delay (80); }
-
-static void long_delay (void) { delay (800); }
-
-static void flicker (void)
-{
-    int i;
-    for (i=0; i<20; i++) {
-       delay (20);
-       led_off_0 ();
-       led_off_1 ();
-       led_off_2 ();
-       delay (20);
-       led_on_0 ();
-       led_on_1 ();
-       led_on_2 ();
-    }
-    led_off_0 ();
-    led_off_1 ();
-    led_off_2 ();
-}
-
-static void roll (void)
-{
-    int i;
-    for (i=0; i<10; i++) {
-       delay (30);
-       led_on_0 ();
-       led_off_2 ();
-       delay (30);
-       led_on_1 ();
-       led_off_0 ();
-       delay (30);
-       led_on_2 ();
-       led_off_1 ();
-    }
-    led_off_2 ();
-}
-           
-static void separator (void)
-{
-    led_off_0 ();
-    led_off_1 ();
-    led_off_2 ();
-    short_delay ();
-    led_on_0 ();
-    led_on_1 ();
-    led_on_2 ();
-    v_short_delay ();
-    led_off_0 ();
-    led_off_1 ();
-    led_off_2 ();
-    short_delay ();
-}
-
-static void display_b4 (int c) 
-{
-  switch (c) {
-  case 3:
-    led_on_2 ();
-  case 2:
-    led_on_1 ();
-  case 1:
-    led_on_0 ();
-  case 0:
-    long_delay ();
-    break;
-  default:
-    flicker ();
-  }
-  separator ();
-}
-
-static void display_int (const unsigned int x)
-{
-  int i = 14;
-  do {
-    display_b4 (0x3 & (x >> i));
-    i -= 2;
-  } while (i >= 0);
-}
-
-static void display_int_flid (const unsigned int x)
-{
-  roll ();
-  display_int (x);
-  roll ();
-}
-
-#endif // ndef SIMPLE_FAIL
-
-static inline void load_to_z_and_break (int value)
-{
-  asm volatile ("movw %0, %1" "\n\t"
-               "break"       "\n\t"
-               : "=z"(value)  : "r" (value));
-}
-
-void deputy_fail_noreturn_fast (int flid)
-{
-  asm volatile ("cli");
-  load_to_z_and_break (flid);
-  PORTA |= 7;
-
-#ifdef SIMPLE_FAIL
-
-  while (1) {
-    int i;
-    PORTA ^= 7;
-    for (i = 0; i < 10; i++) {
-      uint16_t dt = 50000;
-      /* loop takes 8 cycles. this is 1uS if running on an internal 8MHz
-        clock, and 1.09uS if running on the external crystal. */
-      asm volatile (
-                   "1: sbiw    %0,1\n"
-                   "   adiw    %0,1\n"
-                   "   sbiw    %0,1\n"
-                   "   brne    1b" : "+w" (dt));
-    }
-  }
-
-#else
-
-  while (1) {
-    display_int_flid (flid);
-  }
-
-#endif
-
-}
-
-void deputy_fail_mayreturn(int flid)
-{
-    deputy_fail_noreturn_fast(flid);
-}
-
-void deputy_fail_noreturn(int flid)
-{
-    deputy_fail_noreturn_fast(flid);
-}
index 61f935d936418072afa0386d24da6295396b54f7..f0582b8642264bd12bed9f6d64dc79fd3d041c97 100644 (file)
@@ -50,7 +50,7 @@ extern asmlinkage noreturn
 void deputy_fail_noreturn(__LOCATION__FORMALS);
 
 extern asmlinkage noreturn
-void deputy_fail_noreturn_fast(void);
+void deputy_fail_noreturn_fast(__LOCATION__FORMALS);
 
 /* Search for a NULL starting at e and return its index */
 extern asmlinkage
diff --git a/tos/lib/safe/msp430/fail.c b/tos/lib/safe/msp430/fail.c
deleted file mode 100644 (file)
index a1125c9..0000000
+++ /dev/null
@@ -1,152 +0,0 @@
-#undef SAFE_TINYOS
-
-static void led_off_0 (void) {
-    __asm__ volatile ("bis.b #16, &0x0031"); // telos
-    __asm__ volatile ("bis.b #1, &0x001D"); // shimmer
-}
-
-static void led_off_1 (void)  { 
-    __asm__ volatile ("bis.b #32, &0x0031"); // telos
-    __asm__ volatile ("bis.b #2, &0x001D"); // shimmer
-}
-
-static void led_off_2 (void)  {
-    __asm__ volatile ("bis.b #64, &0x0031"); // telos
-    __asm__ volatile ("bis.b #4, &0x001D"); // shimmer
-}
-
-static void led_on_0 (void) { 
-    __asm__ volatile ("bic.b #16, &0x0031"); // telos
-    __asm__ volatile ("bic.b #1, &0x001D"); // shimmer
-}
-
-static void led_on_1 (void) { 
-    __asm__ volatile ("bic.b #32, &0x0031"); // telos
-    __asm__ volatile ("bic.b #2, &0x001D"); // shimmer
-}
-
-static void led_on_2 (void) { 
-    __asm__ volatile ("bic.b #64, &0x0031"); // telos
-    __asm__ volatile ("bic.b #4, &0x001D"); // shimmer
-}
-
-static void delay (int len) 
-{
-  volatile int x, y;
-  for (x=0; x<len; x++) { 
-    for (y=0; y<1000; y++) { }
-  }
-}
-
-static void v_short_delay (void) { delay (10); }
-
-static void short_delay (void) { delay (80); }
-
-static void long_delay (void) { delay (800); }
-
-static void flicker (void)
-{
-    int i;
-    for (i=0; i<20; i++) {
-       delay (20);
-       led_off_0 ();
-       led_off_1 ();
-       led_off_2 ();
-       delay (20);
-       led_on_0 ();
-       led_on_1 ();
-       led_on_2 ();
-    }
-    led_off_0 ();
-    led_off_1 ();
-    led_off_2 ();
-}
-
-static void roll (void)
-{
-    int i;
-    for (i=0; i<10; i++) {
-       delay (30);
-       led_on_0 ();
-       led_off_2 ();
-       delay (30);
-       led_on_1 ();
-       led_off_0 ();
-       delay (30);
-       led_on_2 ();
-       led_off_1 ();
-    }
-    led_off_2 ();
-}
-           
-static void separator (void)
-{
-    led_off_0 ();
-    led_off_1 ();
-    led_off_2 ();
-    short_delay ();
-    led_on_0 ();
-    led_on_1 ();
-    led_on_2 ();
-    v_short_delay ();
-    led_off_0 ();
-    led_off_1 ();
-    led_off_2 ();
-    short_delay ();
-}
-
-static void display_b4 (int c) 
-{
-  switch (c) {
-  case 3:
-    led_on_2 ();
-  case 2:
-    led_on_1 ();
-  case 1:
-    led_on_0 ();
-  case 0:
-    long_delay ();
-    break;
-  default:
-    flicker ();
-  }
-  separator ();
-}
-
-static void display_int (const unsigned int x)
-{
-  int i = 14;
-  do {
-    display_b4 (0x3 & (x >> i));
-    i -= 2;
-  } while (i >= 0);
-}
-
-static void display_int_flid (const unsigned int x)
-{
-  roll ();
-  display_int (x);
-  roll ();
-}
-
-// Not sure how to do this in Telosb without looking it up
-void deputy_fail_noreturn_fast (int flid)
-{
-  // disable interrupts
-  // set LEDS to output
-
-  while (1) {
-    display_int_flid (flid);
-  }
-
-}
-
-void deputy_fail_mayreturn(int flid)
-{
-    deputy_fail_noreturn_fast(flid);
-}
-
-void deputy_fail_noreturn(int flid)
-{
-    deputy_fail_noreturn_fast(flid);
-}
index 0432ad2e98c46f0743bdf89dd2ce0fa84722b756..7bdc56382c65d5716fcff5c5d799098ab8a5955c 100644 (file)
@@ -58,6 +58,11 @@ implementation {
                                          message_t* msg,
                                          uint8_t len) {
     serial_header_t* header = getHeader(msg);
+
+    if (len > call Packet.maxPayloadLength()) {
+      return ESIZE;
+    }
+
     header->dest = dest;
     // Do not set the source address or group, as doing so
     // prevents transparent bridging. Need a better long-term
index 85f13e0718b8445ffe4a0b29b68826d531fcd776..fd2946b19ab33424ad271e944c92bd1980b85825 100644 (file)
@@ -186,7 +186,7 @@ implementation {
   }
 
   bool isCurrentBufferLocked() {
-    return (receiveState.which)? receiveState.bufZeroLocked : receiveState.bufOneLocked;
+    return (receiveState.which)? receiveState.bufOneLocked : receiveState.bufZeroLocked;
   }
 
   void lockCurrentBuffer() {
@@ -294,6 +294,9 @@ implementation {
         receiveTaskSize = recvIndex;
         receiveBufferSwap();
         receiveState.state = RECV_STATE_IDLE;
+      } else {
+        // we can't deliver the packet, better free the current buffer.
+        unlockBuffer(receiveState.which);
       }
     }
     if (postsignalreceive){
index e7c65d433ed434ca81228f431d941704d6180798..07180360d4ef584751a9d0697403f217b02f969a 100644 (file)
@@ -166,7 +166,7 @@ implementation
 
   // extended interface
   async command bool Alarm.isRunning[uint8_t id]() {
-    return m.isset[id];
+    atomic return m.isset[id];
   }
 
   async command void Alarm.startAt[uint8_t id]( size_type t0, size_type dt ) {
index 5551bc798d9bf26ae7fdc439b20d0c348e6d971e..3399b0eae127eca4bbda581cf7b8893ebe49fb25 100644 (file)
@@ -28,7 +28,7 @@
 # @author Jonathan Hui <jwhui@cs.berkeley.edu>
 #
 
-COMPONENT=TOSBoot
+COMPONENT=TosBootC
 TINYOS_NP=
 
 PFLAGS += -DNESC_BUILD_BINARY
@@ -67,11 +67,34 @@ endif
 
 ifeq ($(MAKECMDGOALS),telosb)
   CFLAGS += -DTOSBOOT_START=0x4000 -DTOSBOOT_END=0x4a00
-  CFLAGS += -Imsp430 -Istm25p -Itelosb -Ilib
+  CFLAGS += -Imsp430 -Imsp430f1611 -Istm25p -Itelosb -Ilib
   CFLAGS += -I../net/Deluge
   POST_BUILD_EXTRA_DEPS += strip_iv
 endif
 
+ifeq ($(MAKECMDGOALS),epic)
+  CFLAGS += -DTOSBOOT_START=0x4000 -DTOSBOOT_END=0x4a00
+  CFLAGS += -Imsp430 -Imsp430f1611 -Iepic -Ilib
+  CFLAGS += -I../net/Deluge
+  POST_BUILD_EXTRA_DEPS += strip_iv
+endif
+
+ifeq ($(MAKECMDGOALS),mulle)
+  CFLAGS += -DTOSBOOT_START=0xe0000 -DTOSBOOT_END=0xeffff
+  CFLAGS += -Iat45db -Imulle -Im16c62p -Ilib
+  CFLAGS += -I../net/Deluge -I../net/Deluge/extra/mulle
+  CFLAGS += -I../net/Deluge/extra/m16c62p
+endif
+
+ifeq ($(MAKECMDGOALS),tinynode)
+  CFLAGS += -DTOSBOOT_START=0x4000 -DTOSBOOT_END=0x4a00
+  CFLAGS += -Itinynode -Imsp430 -Imsp430f1611 -Iat45db -Ilib
+  CFLAGS += -I../net/Deluge
+  POST_BUILD_EXTRA_DEPS += strip_iv 
+endif
+
+
+
 strip_iv: FORCE
        @echo "    removing interrupt vector from binary"
        msp430-objcopy -j .text -j .data -O ihex $(BUILDDIR)/main.exe $(BUILDDIR)/main.ihex
diff --git a/tos/lib/tosboot/TOSBoot.h b/tos/lib/tosboot/TOSBoot.h
deleted file mode 100644 (file)
index d490a62..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-// $Id$
-
-/*
- * "Copyright (c) 2000-2005 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- */
-
-/**
- * @author  Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-#ifndef __TOSBOOT_H__
-#define __TOSBOOT_H__
-
-#include "TOSBoot_platform.h"
-
-#endif
diff --git a/tos/lib/tosboot/TOSBoot.nc b/tos/lib/tosboot/TOSBoot.nc
deleted file mode 100644 (file)
index 9bd5c2b..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2005 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-includes Deluge;
-includes DelugePageTransfer;
-includes TOSBoot;
-
-configuration TOSBoot {
-}
-implementation {
-
-  components
-    TOSBootM,
-    ExecC,
-    ExtFlashC,
-    HardwareC,
-    InternalFlashC as IntFlash,
-    LedsC,
-    PluginC,
-    ProgFlashM as ProgFlash,
-    VoltageC;
-
-  TOSBootM.SubInit -> ExtFlashC;
-  TOSBootM.SubControl -> ExtFlashC.StdControl;
-  TOSBootM.SubControl -> PluginC;
-
-  TOSBootM.Exec -> ExecC;
-  TOSBootM.ExtFlash -> ExtFlashC;
-  TOSBootM.Hardware -> HardwareC;
-  TOSBootM.IntFlash -> IntFlash;
-  TOSBootM.Leds -> LedsC;
-  TOSBootM.ProgFlash -> ProgFlash;
-  TOSBootM.Voltage -> VoltageC;
-
-}
diff --git a/tos/lib/tosboot/TOSBootM.nc b/tos/lib/tosboot/TOSBootM.nc
deleted file mode 100644 (file)
index fa1893c..0000000
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * "Copyright (c) 2000-2005 The Regents of the University  of California.
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- *
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- * Copyright (c) 2007 Johns Hopkins University.
- * All rights reserved.
- *
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
- * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
- */
-
-includes crc;
-includes hardware;
-
-module TOSBootM {
-  uses {
-    interface Exec;
-    interface ExtFlash;
-    interface Hardware;
-    interface InternalFlash as IntFlash;
-    interface Leds;
-    interface ProgFlash;
-    interface StdControl as SubControl;
-    interface Init as SubInit;
-    interface Voltage;
-  }
-}
-implementation {
-
-  enum {
-    LEDS_LOWBATT = 1,
-    LEDS_GESTURE = 7,
-  };
-
-  enum {
-    R_SUCCESS,
-    R_INVALID_IMAGE_ERROR,
-    R_PROGRAMMING_ERROR,
-  };
-
-  void startupLeds() {
-
-    uint8_t  output = 0x7;
-    uint8_t  i;
-
-    for (i = 3; i; i--, output >>= 1 )
-      call Leds.glow(output, output >> 1);
-
-  }
-
-  in_flash_addr_t extFlashReadAddr() {
-    in_flash_addr_t result = 0;
-    int8_t  i;
-    for ( i = 3; i >= 0; i-- )
-      result |= ((in_flash_addr_t)call ExtFlash.readByte() & 0xff) << (i*8);
-    return result;
-  }
-
-  bool verifyBlock(ex_flash_addr_t crcAddr, ex_flash_addr_t startAddr, uint16_t len)
-  {
-    uint16_t crcTarget, crcTmp;
-
-    // read crc
-    call ExtFlash.startRead(crcAddr);
-    crcTarget = (uint16_t)(call ExtFlash.readByte() & 0xff) << 8;
-    crcTarget |= (uint16_t)(call ExtFlash.readByte() & 0xff);
-    call ExtFlash.stopRead();
-
-    // compute crc
-    call ExtFlash.startRead(startAddr);
-    for ( crcTmp = 0; len; len-- )
-      crcTmp = crcByte(crcTmp, call ExtFlash.readByte());
-    call ExtFlash.stopRead();
-
-    return crcTarget == crcTmp;
-  }
-
-  bool verifyImage(ex_flash_addr_t startAddr) {
-    uint16_t addr;
-    uint8_t  numPgs;
-    uint8_t  i;
-
-    if (!verifyBlock(startAddr + offsetof(DelugeIdent,crc),
-                    startAddr, offsetof(DelugeIdent,crc)))
-      return FALSE;
-
-    // read size of image
-    call ExtFlash.startRead(startAddr + offsetof(DelugeIdent,numPgs));
-    numPgs = call ExtFlash.readByte();
-    call ExtFlash.stopRead();
-
-    if (numPgs == 0 || numPgs == 0xff)
-      return FALSE;
-
-    startAddr += DELUGE_IDENT_SIZE;
-    addr = DELUGE_CRC_BLOCK_SIZE;
-
-    for ( i = 0; i < numPgs; i++ ) {
-      if (!verifyBlock(startAddr + i*sizeof(uint16_t),
-                      startAddr + addr, DELUGE_BYTES_PER_PAGE)) {
-       if (i == 0)
-         while (1)
-           call Leds.flash(1);
-       return FALSE;
-      }
-      addr += DELUGE_BYTES_PER_PAGE;
-    }
-
-    return TRUE;
-  }
-
-  error_t programImage(ex_flash_addr_t startAddr) {
-    uint8_t  buf[TOSBOOT_INT_PAGE_SIZE];
-    uint16_t pageAddr, newPageAddr;
-    in_flash_addr_t intAddr;
-    in_flash_addr_t secLength;
-    ex_flash_addr_t curAddr;
-
-    if (!verifyImage(startAddr))
-      return R_INVALID_IMAGE_ERROR;
-
-    curAddr = startAddr + DELUGE_IDENT_SIZE + DELUGE_CRC_BLOCK_SIZE;
-
-    call ExtFlash.startRead(curAddr);
-
-    intAddr = extFlashReadAddr();
-    secLength = extFlashReadAddr();
-    curAddr = curAddr + 8;
-
-#if defined(PLATFORM_TELOSB)
-    if (intAddr != TOSBOOT_END) {
-#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_IRIS)
-    if (intAddr != 0) {
-#else
-  #error "Target platform is not currently supported by Deluge T2"
-#endif
-      call ExtFlash.stopRead();
-      return R_INVALID_IMAGE_ERROR;
-    }
-
-    call ExtFlash.stopRead();
-
-    while ( secLength ) {
-
-      pageAddr = newPageAddr = intAddr / TOSBOOT_INT_PAGE_SIZE;
-
-      call ExtFlash.startRead(curAddr);
-      // fill in ram buffer for internal program flash sector
-      do {
-
-       // check if secLength is all ones
-       if ( secLength == 0xffffffff ) {
-         call ExtFlash.stopRead();
-         return FAIL;
-       }
-
-       buf[(uint16_t)intAddr % TOSBOOT_INT_PAGE_SIZE] = call ExtFlash.readByte();
-       intAddr++; curAddr++;
-
-       if ( --secLength == 0 ) {
-         intAddr = extFlashReadAddr();
-         secLength = extFlashReadAddr();
-         curAddr = curAddr + 8;
-       }
-
-       newPageAddr = intAddr / TOSBOOT_INT_PAGE_SIZE;
-
-      } while ( pageAddr == newPageAddr && secLength );
-      call ExtFlash.stopRead();
-
-      call Leds.set(pageAddr);
-
-      // write out page
-      if (call ProgFlash.write(pageAddr*TOSBOOT_INT_PAGE_SIZE, buf,
-                              TOSBOOT_INT_PAGE_SIZE) == FAIL) {
-       return R_PROGRAMMING_ERROR;
-      }
-    }
-
-    return R_SUCCESS;
-
-  }
-
-  void runApp() {
-    call SubControl.stop();
-    call Exec.exec();
-  }
-
-  void startupSequence() {
-
-    BootArgs args;
-
-    // check voltage and make sure flash can be programmed
-    //   if not, just run the app, can't check for gestures
-    //   if we can't write to the internal flash anyway
-    if ( !call Voltage.okToProgram() ) {
-      // give user some time and count down LEDs
-      call Leds.flash(LEDS_LOWBATT);
-      startupLeds();
-      runApp();
-    }
-
-    // get current value of counter
-    call IntFlash.read((uint8_t*)TOSBOOT_ARGS_ADDR, &args, sizeof(args));
-
-    // increment gesture counter, see if it exceeds threshold
-    if ( ++args.gestureCount >= TOSBOOT_GESTURE_MAX_COUNT - 1 ) {
-      // gesture has been detected, display receipt of gesture on LEDs
-      call Leds.flash(LEDS_GESTURE);
-
-      // load golden image from flash
-      // if the golden image is invalid, forget about reprogramming
-      // if an error happened during reprogramming, reboot and try again
-      //   not much else we can do :-/
-      if (programImage(TOSBOOT_GOLDEN_IMG_ADDR) == R_PROGRAMMING_ERROR) {
-       call Hardware.reboot();
-      }
-    }
-    else {
-      // update gesture counter
-      call IntFlash.write((uint8_t*)TOSBOOT_ARGS_ADDR, &args, sizeof(args));
-      if ( !args.noReprogram ) {
-       // if an error happened during reprogramming, reboot and try again
-       //   after two tries, try programming the golden image
-       if (programImage(args.imageAddr) == R_PROGRAMMING_ERROR) {
-         call Hardware.reboot();
-       }
-      }
-    }
-
-    // give user some time and count down LEDs
-    startupLeds();
-
-    // reset counter and reprogramming flag
-    args.gestureCount = 0xff;
-    args.noReprogram = TRUE;
-    call IntFlash.write((uint8_t*)TOSBOOT_ARGS_ADDR, &args, sizeof(args));
-
-    runApp();
-
-  }
-
-  int main() @C() @spontaneous() {
-
-    __nesc_disable_interrupt();
-
-    TOSH_SET_PIN_DIRECTIONS();
-    call Hardware.init();
-
-    call SubInit.init();
-    call SubControl.start();
-
-    startupSequence();
-
-    return 0;
-
-  }
-
-}
diff --git a/tos/lib/tosboot/TosBoot.h b/tos/lib/tosboot/TosBoot.h
new file mode 100644 (file)
index 0000000..d490a62
--- /dev/null
@@ -0,0 +1,33 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * @author  Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#ifndef __TOSBOOT_H__
+#define __TOSBOOT_H__
+
+#include "TOSBoot_platform.h"
+
+#endif
diff --git a/tos/lib/tosboot/TosBootC.nc b/tos/lib/tosboot/TosBootC.nc
new file mode 100644 (file)
index 0000000..8317250
--- /dev/null
@@ -0,0 +1,62 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#include <Deluge.h>
+#include <DelugePageTransfer.h>
+#include "TosBoot.h"
+
+configuration TosBootC {
+}
+implementation {
+
+  components
+    TosBootP,
+    ExecC,
+    ExtFlashC,
+    HardwareC,
+    InternalFlashC as IntFlash,
+    LedsC,
+    PluginC,
+    ProgFlashC as ProgFlash,
+    VoltageC;
+
+  TosBootP.SubInit -> ExtFlashC;
+  TosBootP.SubControl -> ExtFlashC.StdControl;
+  TosBootP.SubControl -> PluginC;
+
+  TosBootP.Exec -> ExecC;
+  TosBootP.ExtFlash -> ExtFlashC;
+  TosBootP.Hardware -> HardwareC;
+  TosBootP.IntFlash -> IntFlash;
+  TosBootP.Leds -> LedsC;
+  TosBootP.ProgFlash -> ProgFlash;
+  TosBootP.Voltage -> VoltageC;
+
+}
diff --git a/tos/lib/tosboot/TosBootP.nc b/tos/lib/tosboot/TosBootP.nc
new file mode 100644 (file)
index 0000000..8336705
--- /dev/null
@@ -0,0 +1,279 @@
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2007 Johns Hopkins University.
+ * All rights reserved.
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ */
+
+#include "crc.h"
+#include <hardware.h>
+
+module TosBootP {
+  uses {
+    interface Exec;
+    interface ExtFlash;
+    interface Hardware;
+    interface InternalFlash as IntFlash;
+    interface Leds;
+    interface ProgFlash;
+    interface StdControl as SubControl;
+    interface Init as SubInit;
+    interface Voltage;
+  }
+}
+implementation {
+
+  enum {
+    LEDS_LOWBATT = 1,
+    LEDS_GESTURE = 7,
+  };
+
+  enum {
+    R_SUCCESS,
+    R_INVALID_IMAGE_ERROR,
+    R_PROGRAMMING_ERROR,
+  };
+
+  void startupLeds() {
+
+    uint8_t  output = 0x7;
+    uint8_t  i;
+
+    for (i = 3; i; i--, output >>= 1 )
+      call Leds.glow(output, output >> 1);
+
+  }
+
+  in_flash_addr_t extFlashReadAddr() {
+    in_flash_addr_t result = 0;
+    int8_t  i;
+    for ( i = 3; i >= 0; i-- )
+      result |= ((in_flash_addr_t)call ExtFlash.readByte() & 0xff) << (i*8);
+    return result;
+  }
+
+  bool verifyBlock(ex_flash_addr_t crcAddr, ex_flash_addr_t startAddr, uint16_t len)
+  {
+    uint16_t crcTarget, crcTmp;
+
+    // read crc
+    call ExtFlash.startRead(crcAddr);
+    crcTarget = (uint16_t)(call ExtFlash.readByte() & 0xff) << 8;
+    crcTarget |= (uint16_t)(call ExtFlash.readByte() & 0xff);
+    call ExtFlash.stopRead();
+
+    // compute crc
+    call ExtFlash.startRead(startAddr);
+    for ( crcTmp = 0; len; len-- )
+      crcTmp = crcByte(crcTmp, call ExtFlash.readByte());
+    call ExtFlash.stopRead();
+
+    return crcTarget == crcTmp;
+  }
+
+  bool verifyImage(ex_flash_addr_t startAddr) {
+    uint32_t addr;
+    uint8_t  numPgs;
+    uint8_t  i;
+
+
+    if (!verifyBlock(startAddr + offsetof(DelugeIdent,crc),
+                    startAddr, offsetof(DelugeIdent,crc)))
+      return FALSE;
+
+    // read size of image
+    call ExtFlash.startRead(startAddr + offsetof(DelugeIdent,numPgs));
+    numPgs = call ExtFlash.readByte();
+    call ExtFlash.stopRead();
+
+    if (numPgs == 0 || numPgs == 0xff)
+      return FALSE;
+
+    startAddr += DELUGE_IDENT_SIZE;
+    addr = DELUGE_CRC_BLOCK_SIZE;
+
+    for ( i = 0; i < numPgs; i++ ) {
+      if (!verifyBlock(startAddr + i*sizeof(uint16_t),
+                      startAddr + addr, DELUGE_BYTES_PER_PAGE)) {
+       return FALSE;
+      }
+      addr += DELUGE_BYTES_PER_PAGE;
+    }
+
+    return TRUE;
+  }
+
+  error_t programImage(ex_flash_addr_t startAddr) {
+    uint8_t  buf[TOSBOOT_INT_PAGE_SIZE];
+    uint32_t pageAddr, newPageAddr;
+    in_flash_addr_t intAddr;
+    in_flash_addr_t secLength;
+    ex_flash_addr_t curAddr;
+
+    if (!verifyImage(startAddr))
+      return R_INVALID_IMAGE_ERROR;
+
+    curAddr = startAddr + DELUGE_IDENT_SIZE + DELUGE_CRC_BLOCK_SIZE;
+
+    call ExtFlash.startRead(curAddr);
+
+    intAddr = extFlashReadAddr();
+    secLength = extFlashReadAddr();
+    curAddr = curAddr + 8;
+
+#if defined(PLATFORM_TELOSB) || defined (PLATFORM_EPIC) || defined (PLATFORM_TINYNODE)
+    if (intAddr != TOSBOOT_END) {
+#elif defined(PLATFORM_MICAZ) || defined(PLATFORM_IRIS)
+    if (intAddr != 0) {
+#elif defined(PLATFORM_MULLE)
+    if (intAddr != 0xA0000) {
+#else
+  #error "Target platform is not currently supported by Deluge T2"
+#endif
+      call ExtFlash.stopRead();
+      return R_INVALID_IMAGE_ERROR;
+    }
+
+    call ExtFlash.stopRead();
+
+    while ( secLength ) {
+
+      pageAddr = newPageAddr = intAddr / TOSBOOT_INT_PAGE_SIZE;
+
+      call ExtFlash.startRead(curAddr);
+      // fill in ram buffer for internal program flash sector
+      do {
+
+       // check if secLength is all ones
+       if ( secLength == 0xffffffff ) {
+         call ExtFlash.stopRead();
+         return FAIL;
+       }
+
+       buf[(uint16_t)intAddr % TOSBOOT_INT_PAGE_SIZE] = call ExtFlash.readByte();
+       intAddr++; curAddr++;
+
+       if ( --secLength == 0 ) {
+         intAddr = extFlashReadAddr();
+         secLength = extFlashReadAddr();
+         curAddr = curAddr + 8;
+       }
+
+       newPageAddr = intAddr / TOSBOOT_INT_PAGE_SIZE;
+
+      } while ( pageAddr == newPageAddr && secLength );
+      call ExtFlash.stopRead();
+
+      call Leds.set(pageAddr);
+
+      // write out page
+      if (call ProgFlash.write(pageAddr*TOSBOOT_INT_PAGE_SIZE, buf,
+                              TOSBOOT_INT_PAGE_SIZE) == FAIL) {
+       return R_PROGRAMMING_ERROR;
+      }
+    }
+
+    return R_SUCCESS;
+
+  }
+
+  void runApp() {
+    call SubControl.stop();
+    call Exec.exec();
+  }
+
+  void startupSequence() {
+
+    BootArgs args;
+
+    // check voltage and make sure flash can be programmed
+    //   if not, just run the app, can't check for gestures
+    //   if we can't write to the internal flash anyway
+    if ( !call Voltage.okToProgram() ) {
+      // give user some time and count down LEDs
+      call Leds.flash(LEDS_LOWBATT);
+      startupLeds();
+      runApp();
+    }
+
+    // get current value of counter
+    call IntFlash.read((uint8_t*)TOSBOOT_ARGS_ADDR, &args, sizeof(args));
+
+    // increment gesture counter, see if it exceeds threshold
+    if ( ++args.gestureCount >= TOSBOOT_GESTURE_MAX_COUNT - 1 ) {
+      // gesture has been detected, display receipt of gesture on LEDs
+      call Leds.flash(LEDS_GESTURE);
+
+      // load golden image from flash
+      // if the golden image is invalid, forget about reprogramming
+      // if an error happened during reprogramming, reboot and try again
+      //   not much else we can do :-/
+      if (programImage(TOSBOOT_GOLDEN_IMG_ADDR) == R_PROGRAMMING_ERROR) {
+       call Hardware.reboot();
+      }
+    }
+    else {
+      // update gesture counter
+      call IntFlash.write((uint8_t*)TOSBOOT_ARGS_ADDR, &args, sizeof(args));
+      if ( !args.noReprogram ) {
+       // if an error happened during reprogramming, reboot and try again
+       //   after two tries, try programming the golden image
+       if (programImage(args.imageAddr) == R_PROGRAMMING_ERROR) {
+         call Hardware.reboot();
+       }
+      }
+    }
+
+    // give user some time and count down LEDs
+    startupLeds();
+
+    // reset counter and reprogramming flag
+    args.gestureCount = 0xff;
+    args.noReprogram = TRUE;
+    call IntFlash.write((uint8_t*)TOSBOOT_ARGS_ADDR, &args, sizeof(args));
+
+    runApp();
+
+  }
+
+  int main() @C() @spontaneous() {
+
+    __nesc_disable_interrupt();
+
+    TOSH_SET_PIN_DIRECTIONS();
+    call Hardware.init();
+
+    call SubInit.init();
+    call SubControl.start();
+
+    startupSequence();
+
+    return 0;
+
+  }
+
+}
index 6bb2099ee9bf6e61599ddb2622a9bfc3ce40a9d8..6fd7ac9a426aa48a1b36cbb39919805bd54fe360 100644 (file)
@@ -92,10 +92,17 @@ implementation {
 
     addr = newAddr;
 
+#if defined(PLATFORM_MULLE)
+    cmdBuf[0] = 0x68;
+    cmdBuf[1] = (addr >> 15);
+    cmdBuf[2] = ((addr >> 7) & 0xFC) + ((addr >> 8) & 0x1);
+    cmdBuf[3] = addr & 0xff;
+#else
     cmdBuf[0] = 0x68;
     cmdBuf[1] = (addr >> 15) & 0xff;
     cmdBuf[2] = (addr >> 7) & 0xfe;
     cmdBuf[3] = addr & 0xff;
+#endif
     
     TOSH_CLR_FLASH_CLK_PIN();
     TOSH_CLR_FLASH_CS_PIN();
@@ -111,7 +118,11 @@ implementation {
   }
 
   command uint8_t ExtFlash.readByte() {
+#if defined(PLATFORM_MULLE)
+    if (!(addr & 0x1ff)) {
+#else
     if (!(addr & 0xff)) {
+#endif
       call ExtFlash.stopRead();
       call ExtFlash.startRead(addr);
     }
index 558f24266024e77eb23037b4e3382d94a47c174f..3b8803eb44c6ba3dbfede3dd346b2040017bd2ca 100644 (file)
@@ -28,7 +28,7 @@
  * @author Jonathan Hui <jwhui@cs.berkeley.edu>
  */
 
-includes InternalFlash;
+#include <InternalFlash.h>
 
 module InternalFlashC {
   provides interface InternalFlash;
diff --git a/tos/lib/tosboot/avr/ProgFlashC.nc b/tos/lib/tosboot/avr/ProgFlashC.nc
new file mode 100644 (file)
index 0000000..a3796ee
--- /dev/null
@@ -0,0 +1,65 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+module ProgFlashC {
+  provides {
+    interface ProgFlash;
+  }
+}
+
+implementation {
+
+#include <avr/boot.h>
+
+  command error_t ProgFlash.write(in_flash_addr_t addr, uint8_t* buf, in_flash_addr_t len) {
+
+    uint16_t* wordBuf = (uint16_t*)buf;
+    uint32_t i;
+
+    if ( addr + len > TOSBOOT_START )
+      return FAIL;    
+
+    boot_page_erase_safe( addr );
+    while( boot_rww_busy() )
+      boot_rww_enable_safe();
+    
+    for ( i = 0; i < len; i += 2 )
+      boot_page_fill_safe( addr + i, *wordBuf++ );
+
+    boot_page_write_safe( addr );
+    
+    while ( boot_rww_busy() )
+      boot_rww_enable_safe();
+    
+    return SUCCESS;
+    
+  }
+
+}
diff --git a/tos/lib/tosboot/avr/ProgFlashM.nc b/tos/lib/tosboot/avr/ProgFlashM.nc
deleted file mode 100644 (file)
index 898ebc6..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2005 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-module ProgFlashM {
-  provides {
-    interface ProgFlash;
-  }
-}
-
-implementation {
-
-#include <avr/boot.h>
-
-  command error_t ProgFlash.write(in_flash_addr_t addr, uint8_t* buf, in_flash_addr_t len) {
-
-    uint16_t* wordBuf = (uint16_t*)buf;
-    uint32_t i;
-
-    if ( addr + len > TOSBOOT_START )
-      return FAIL;    
-
-    boot_page_erase_safe( addr );
-    while( boot_rww_busy() )
-      boot_rww_enable_safe();
-    
-    for ( i = 0; i < len; i += 2 )
-      boot_page_fill_safe( addr + i, *wordBuf++ );
-
-    boot_page_write_safe( addr );
-    
-    while ( boot_rww_busy() )
-      boot_rww_enable_safe();
-    
-    return SUCCESS;
-    
-  }
-
-}
diff --git a/tos/lib/tosboot/epic/ExtFlashC.nc b/tos/lib/tosboot/epic/ExtFlashC.nc
new file mode 100644 (file)
index 0000000..34ada4e
--- /dev/null
@@ -0,0 +1,51 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+configuration ExtFlashC {
+  provides {
+    interface Init;
+    interface StdControl;
+    interface ExtFlash;
+  }
+}
+
+implementation {
+
+  components 
+    ExtFlashP,
+    HplUsart0C;
+
+  Init = ExtFlashP;
+  StdControl = ExtFlashP;
+  ExtFlash = ExtFlashP;
+
+  ExtFlashP.UsartControl -> HplUsart0C;
+
+}
diff --git a/tos/lib/tosboot/epic/ExtFlashP.nc b/tos/lib/tosboot/epic/ExtFlashP.nc
new file mode 100644 (file)
index 0000000..621ead1
--- /dev/null
@@ -0,0 +1,98 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ */
+
+module ExtFlashP {
+  provides {
+    interface StdControl;
+    interface Init;
+    interface ExtFlash;
+  }
+  uses {
+    interface HplUsartControl as UsartControl;
+  }
+}
+
+implementation {
+
+  uint32_t addr;
+
+  command error_t Init.init() {
+    TOSH_MAKE_FLASH_CS_OUTPUT();
+    TOSH_SET_FLASH_CS_PIN();
+    call UsartControl.setModeSPI();
+    return SUCCESS;
+  }
+
+  command error_t StdControl.start() { 
+    return SUCCESS; 
+  }
+
+  command error_t StdControl.stop() { 
+    call UsartControl.disableSPI();
+    return SUCCESS; 
+  }
+
+  command void ExtFlash.startRead(uint32_t newAddr) {
+
+    uint8_t cmd[4];
+    uint8_t i;
+    uint32_t page = newAddr / 512;
+    uint32_t offset = newAddr % 512;
+
+    addr = newAddr;
+
+    cmd[0] = 0x03;
+    cmd[1] = page >> 6;
+    cmd[2] = (page << 2) | (offset >> 8);
+    cmd[3] = offset;
+
+    TOSH_CLR_FLASH_CS_PIN();
+
+    for ( i = 0; i < sizeof(cmd); i++ ) {
+      call UsartControl.tx(cmd[i]);
+      while(call UsartControl.isTxEmpty() != SUCCESS);
+    }
+  }
+
+  command uint8_t ExtFlash.readByte() {
+    if (!(addr & 0x1ff)) {
+      call ExtFlash.stopRead();
+      call ExtFlash.startRead(addr);
+    }
+    addr++;
+    call UsartControl.rx();
+    call UsartControl.tx(0);
+    while(call UsartControl.isRxIntrPending() != SUCCESS);
+    return call UsartControl.rx();
+  }
+
+  command void ExtFlash.stopRead() {
+    TOSH_SET_FLASH_CS_PIN();
+  }
+
+}
diff --git a/tos/lib/tosboot/epic/hardware.h b/tos/lib/tosboot/epic/hardware.h
new file mode 100644 (file)
index 0000000..281de0a
--- /dev/null
@@ -0,0 +1,86 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#ifndef __HARDWARE_H__
+#define __HARDWARE_H__
+
+#include "msp430hardware.h"
+
+// internal flash is 16 bits in width
+typedef uint16_t in_flash_addr_t;
+// external flash is 32 bits in width
+typedef uint32_t ex_flash_addr_t;
+
+void wait(uint16_t t) {
+  for ( ; t > 0; t-- );
+}
+
+// LEDs
+TOSH_ASSIGN_PIN(RED_LED, 4, 0);
+TOSH_ASSIGN_PIN(GREEN_LED, 4, 3);
+TOSH_ASSIGN_PIN(YELLOW_LED, 4, 7);
+
+// UART pins
+TOSH_ASSIGN_PIN(SOMI0, 3, 2);
+TOSH_ASSIGN_PIN(SIMO0, 3, 1);
+TOSH_ASSIGN_PIN(UCLK0, 3, 3);
+TOSH_ASSIGN_PIN(UTXD0, 3, 4);
+TOSH_ASSIGN_PIN(URXD0, 3, 5);
+
+// User Interupt Pin
+TOSH_ASSIGN_PIN(USERINT, 2, 7);
+
+// FLASH
+TOSH_ASSIGN_PIN(FLASH_CS, 4, 4);
+
+void TOSH_SET_PIN_DIRECTIONS(void)
+{
+  P3SEL = 0x0E; // set SPI and I2C to mod func
+  
+  P1DIR = 0xe0;
+  P1OUT = 0x00;
+  
+  P2DIR = 0x7b;
+  P2OUT = 0x10;
+  
+  P3DIR = 0xf1;
+  P3OUT = 0x00;
+  
+  P4DIR = 0xfd;
+  P4OUT = 0xdd;
+  
+  P5DIR = 0xff;
+  P5OUT = 0xff;
+  
+  P6DIR = 0xff;
+  P6OUT = 0x00;
+}
+
+#endif
diff --git a/tos/lib/tosboot/iris/ProgFlashC.nc b/tos/lib/tosboot/iris/ProgFlashC.nc
new file mode 100644 (file)
index 0000000..3861a53
--- /dev/null
@@ -0,0 +1,65 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+#include <avr/boot.h>
+
+module ProgFlashC {
+  provides {
+    interface ProgFlash;
+  }
+}
+
+implementation {
+
+
+  command error_t ProgFlash.write(in_flash_addr_t addr, uint8_t* buf, in_flash_addr_t len) {
+
+    uint16_t* wordBuf = (uint16_t*)buf;
+    uint32_t i;
+
+    if ( addr + len > TOSBOOT_START )
+      return FAIL;
+
+    boot_page_erase( addr );
+    while( boot_rww_busy() )
+      boot_rww_enable();
+
+    for ( i = 0; i < len; i += 2 )
+      boot_page_fill( addr + i, *wordBuf++ );
+
+    boot_page_write( addr );
+
+    while ( boot_rww_busy() )
+      boot_rww_enable();
+
+    return SUCCESS;
+
+  }
+
+}
diff --git a/tos/lib/tosboot/iris/ProgFlashM.nc b/tos/lib/tosboot/iris/ProgFlashM.nc
deleted file mode 100644 (file)
index 34c6018..0000000
+++ /dev/null
@@ -1,65 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2005 The Regents of the University  of California.
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- *
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-#include <avr/boot.h>
-
-module ProgFlashM {
-  provides {
-    interface ProgFlash;
-  }
-}
-
-implementation {
-
-
-  command error_t ProgFlash.write(in_flash_addr_t addr, uint8_t* buf, in_flash_addr_t len) {
-
-    uint16_t* wordBuf = (uint16_t*)buf;
-    uint32_t i;
-
-    if ( addr + len > TOSBOOT_START )
-      return FAIL;
-
-    boot_page_erase( addr );
-    while( boot_rww_busy() )
-      boot_rww_enable();
-
-    for ( i = 0; i < len; i += 2 )
-      boot_page_fill( addr + i, *wordBuf++ );
-
-    boot_page_write( addr );
-
-    while ( boot_rww_busy() )
-      boot_rww_enable();
-
-    return SUCCESS;
-
-  }
-
-}
diff --git a/tos/lib/tosboot/m16c62p/HardwareC.nc b/tos/lib/tosboot/m16c62p/HardwareC.nc
new file mode 100644 (file)
index 0000000..3fc4f2a
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Hardware interface implementation for the M16c/62p MCU.
+ * The interface is responsible of initializing the mcu
+ * and rebooting it on request.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "NetProg_platform.h"
+
+module HardwareC
+{
+  provides interface Hardware;
+}
+
+implementation
+{
+  command void Hardware.init()
+  {
+    PRCR.BYTE = BIT1 | BIT0; // Turn off protection for the cpu and clock register
+
+    PM0.BYTE = BIT7;         // Single Chip mode. No BCLK output.
+    PM1.BYTE = BIT3;         // Expand internal memory, no global wait state.
+
+    CM0.BYTE = 0x0;          // No sub-clock (Xc) generation
+    CM1.BYTE = 0x0;          // CPU_CLOCK = MAIN_CLOCK, low drive on Xin
+
+    PRCR.BYTE = 0;           // Turn on protection on all registers.
+  }
+
+  
+  command void Hardware.reboot()
+  {
+    netprog_reboot();
+  }
+}
diff --git a/tos/lib/tosboot/m16c62p/ProgFlashC.nc b/tos/lib/tosboot/m16c62p/ProgFlashC.nc
new file mode 100644 (file)
index 0000000..131171e
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * Wiring so that the ProgFlashP module gets access to the HplM16c62pFlashC
+ * module.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration ProgFlashC
+{
+  provides interface ProgFlash;
+}
+implementation
+{
+  components ProgFlashP, HplM16c62pFlashC;
+  
+  ProgFlashP.Flash -> HplM16c62pFlashC;
+  ProgFlash = ProgFlashP;
+}
\ No newline at end of file
diff --git a/tos/lib/tosboot/m16c62p/ProgFlashP.nc b/tos/lib/tosboot/m16c62p/ProgFlashP.nc
new file mode 100644 (file)
index 0000000..6422f71
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Implementation of the ProgFlash interface for M16c/62p.
+ * The interface is responsible of reprogramming of the mcus
+ * program flash.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "M16c62pFlash.h"
+
+module ProgFlashP
+{
+  provides interface ProgFlash;
+  
+  uses interface HplM16c62pFlash as Flash;
+}
+
+implementation
+{
+
+  command error_t ProgFlash.write(in_flash_addr_t addr, uint8_t* buf, in_flash_addr_t len)
+  {
+    
+    // We dont need to rewrite the hw interrupt vector
+    if (addr >= 0xFFE00L)
+    {
+      return SUCCESS;
+    }
+
+    if (addr + len >= TOSBOOT_START)
+    {
+      return FAIL;
+    }
+
+    if (addr == 0xA0000L)
+    {
+      // Erase Block 10
+      if (call Flash.FlashErase(BLOCK_10) != 0 )
+      {
+        return FAIL;
+      }
+    }
+    else if ( addr == 0xB0000L )
+    {
+      // Erase Block 9
+      if (call Flash.FlashErase(BLOCK_9) != 0 )
+      {
+        return FAIL;
+      }
+    }
+    else if ( addr == 0xC0000L )
+    {
+      // Erase Block 8
+      if (call Flash.FlashErase(BLOCK_8) != 0 )
+      {
+        return FAIL;
+      }
+    }
+    else if ( addr == 0xD0000L )
+    {
+      // Erase Block 7
+      if (call Flash.FlashErase(BLOCK_7) != 0 )
+      {
+        return FAIL;
+      }
+    }
+
+    if (call Flash.FlashWrite(addr, (unsigned int*) buf, len) != 0)
+    {
+      return FAIL;
+    }
+    
+    return SUCCESS;
+    
+  }
+}
+
index 91300751999fd25c4b76d0d1a5c14e35a9f2a282..1747746144e3bdbec4aa185b88192c2d9caddbfc 100644 (file)
 #define __TOSBOOT_PLATFORM_H__
 
 enum {
-  // address of TOSBoot args in internal flash
-  TOSBOOT_ARGS_ADDR = 0xff0,
-  // number of resets to force golden image
-  TOSBOOT_GESTURE_MAX_COUNT = 3,
-  // address of the golden image in external flash
-  TOSBOOT_GOLDEN_IMG_ADDR = 0x0L,
-  // size of each internal program flash page
-  TOSBOOT_INT_PAGE_SIZE = SPM_PAGESIZE,
+  TOSBOOT_ARGS_ADDR = 0xff0,      // address of TOSBoot args in internal flash
+  TOSBOOT_GESTURE_MAX_COUNT = 3,  // number of resets to force golden image
+  TOSBOOT_GOLDEN_IMG_ADDR = 0x0L, // address of the golden image in external flash
+  TOSBOOT_INT_PAGE_SIZE = SPM_PAGESIZE, // size of each internal program flash page
 };
 
 enum {
index b5e88e129676bbb62c946d47f6be45303f6dbc8e..bcefd362cb34e0847b8e70d8fb56dc80c89da458 100644 (file)
 #include <atm128hardware.h>
 #include <avrhardware.h>
 
+#ifndef MHZ
+/* Clock rate is ~8MHz except if specified by user 
+   (this value must be a power of 2, see MicaTimer.h and MeasureClockC.nc) */
+#define MHZ 8
+#endif 
+
 typedef uint32_t in_flash_addr_t;
 typedef uint32_t ex_flash_addr_t;
 
diff --git a/tos/lib/tosboot/msp430/HPLUSART0M.nc b/tos/lib/tosboot/msp430/HPLUSART0M.nc
deleted file mode 100644 (file)
index 34e4422..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2005 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-module HPLUSART0M {
-  provides interface HPLUSARTControl;
-}
-implementation {
-
-  command void HPLUSARTControl.disableSPI() {
-    // USART0 SPI module disable
-    //ME1 &= ~USPIE0;
-
-    // set to PUC values
-    ME1 = 0;
-    U0CTL = 1;
-    U0TCTL = 1;
-    U0RCTL = 0;
-  }
-  
-  command void HPLUSARTControl.setModeSPI() {
-
-    //U0CTL = SWRST;
-
-    // 8-bit char, SPI-mode, USART as master
-    U0CTL = SWRST | CHAR | SYNC | MM;
-
-    // 3-pin + half-cycle delayed UCLK
-    U0TCTL |= STC + CKPH + SSEL_SMCLK; 
-
-    // as fast as possible
-    U0BR0 = 0x02;
-    U0BR1 = 0;
-
-    // enable SPI
-    ME1 |= USPIE0;
-
-    U0CTL &= ~SWRST;  
-    
-    // clear interrupts
-    IFG1 = 0;
-
-  }
-
-  command void HPLUSARTControl.disableI2C() {
-    /*
-    U0CTL = 1;
-    U0TCTL = 1;
-    I2CTCTL = 0;
-    */
-    U0CTL &= ~I2CEN;
-    U0CTL &= ~I2C;
-    I2CTCTL = 0;
-    call HPLUSARTControl.disableSPI();
-  }
-
-  command void HPLUSARTControl.setModeI2C() {
-   
-    // Recommended init procedure
-    U0CTL = I2C + SYNC + MST;
-
-    // use 1MHz SMCLK as the I2C reference
-    I2CTCTL |= I2CSSEL_2 | I2CTRX;
-
-    // Enable I2C
-    U0CTL |= I2CEN;
-
-    return;
-  }
-
-  command error_t HPLUSARTControl.isTxEmpty(){
-    if (U0TCTL & TXEPT) {
-      return SUCCESS;
-    }
-    return FAIL;
-  }
-  
-  command error_t HPLUSARTControl.isTxIntrPending(){
-    if (IFG1 & UTXIFG0){
-      IFG1 &= ~UTXIFG0;
-      return SUCCESS;
-    }
-    return FAIL;
-  }
-
-  command error_t HPLUSARTControl.isRxIntrPending(){
-    if (IFG1 & URXIFG0){
-      IFG1 &= ~URXIFG0;
-      return SUCCESS;
-    }
-    return FAIL;
-  }
-
-  command void HPLUSARTControl.tx(uint8_t data){
-    U0TXBUF = data;
-  }
-  
-  command uint8_t HPLUSARTControl.rx(){
-    return U0RXBUF;
-  }
-
-}
diff --git a/tos/lib/tosboot/msp430/HPLUSARTControl.nc b/tos/lib/tosboot/msp430/HPLUSARTControl.nc
deleted file mode 100644 (file)
index c0254b1..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2005 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-includes msp430usart;
-
-interface HPLUSARTControl {
-
-  command void disableSPI();
-  command void setModeSPI();
-  command void disableI2C();
-  command void setModeI2C();
-  command error_t isTxEmpty();
-  command error_t isTxIntrPending();
-  command error_t isRxIntrPending();
-  command void tx(uint8_t data);
-  command uint8_t rx();
-
-}
-
diff --git a/tos/lib/tosboot/msp430/HplUsart0C.nc b/tos/lib/tosboot/msp430/HplUsart0C.nc
new file mode 100644 (file)
index 0000000..e47ec50
--- /dev/null
@@ -0,0 +1,128 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+module HplUsart0C {
+  provides interface HplUsartControl;
+}
+implementation {
+
+  command void HplUsartControl.disableSPI() {
+    // USART0 SPI module disable
+    //ME1 &= ~USPIE0;
+
+    // set to PUC values
+    ME1 = 0;
+    U0CTL = 1;
+    U0TCTL = 1;
+    U0RCTL = 0;
+  }
+  
+  command void HplUsartControl.setModeSPI() {
+
+    //U0CTL = SWRST;
+
+    // 8-bit char, SPI-mode, USART as master
+    U0CTL = SWRST | CHAR | SYNC | MM;
+
+    // 3-pin + half-cycle delayed UCLK
+    U0TCTL |= STC + CKPH + SSEL_SMCLK; 
+
+    // as fast as possible
+    U0BR0 = 0x02;
+    U0BR1 = 0;
+
+    // enable SPI
+    ME1 |= USPIE0;
+
+    U0CTL &= ~SWRST;  
+    
+    // clear interrupts
+    IFG1 = 0;
+
+  }
+
+  command void HplUsartControl.disableI2C() {
+    /*
+    U0CTL = 1;
+    U0TCTL = 1;
+    I2CTCTL = 0;
+    */
+    U0CTL &= ~I2CEN;
+    U0CTL &= ~I2C;
+    I2CTCTL = 0;
+    call HplUsartControl.disableSPI();
+  }
+
+  command void HplUsartControl.setModeI2C() {
+   
+    // Recommended init procedure
+    U0CTL = I2C + SYNC + MST;
+
+    // use 1MHz SMCLK as the I2C reference
+    I2CTCTL |= I2CSSEL_2 | I2CTRX;
+
+    // Enable I2C
+    U0CTL |= I2CEN;
+
+    return;
+  }
+
+  command error_t HplUsartControl.isTxEmpty(){
+    if (U0TCTL & TXEPT) {
+      return SUCCESS;
+    }
+    return FAIL;
+  }
+  
+  command error_t HplUsartControl.isTxIntrPending(){
+    if (IFG1 & UTXIFG0){
+      IFG1 &= ~UTXIFG0;
+      return SUCCESS;
+    }
+    return FAIL;
+  }
+
+  command error_t HplUsartControl.isRxIntrPending(){
+    if (IFG1 & URXIFG0){
+      IFG1 &= ~URXIFG0;
+      return SUCCESS;
+    }
+    return FAIL;
+  }
+
+  command void HplUsartControl.tx(uint8_t data){
+    U0TXBUF = data;
+  }
+  
+  command uint8_t HplUsartControl.rx(){
+    return U0RXBUF;
+  }
+
+}
diff --git a/tos/lib/tosboot/msp430/HplUsartControl.nc b/tos/lib/tosboot/msp430/HplUsartControl.nc
new file mode 100644 (file)
index 0000000..02feb35
--- /dev/null
@@ -0,0 +1,46 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+#include <msp430usart.h>
+
+interface HplUsartControl {
+
+  command void disableSPI();
+  command void setModeSPI();
+  command void disableI2C();
+  command void setModeI2C();
+  command error_t isTxEmpty();
+  command error_t isTxIntrPending();
+  command error_t isRxIntrPending();
+  command void tx(uint8_t data);
+  command uint8_t rx();
+
+}
+
index 563720fa6e6857206b92b87f86e8c5346d90251a..c41e13a6d18070d9ef71dd03ace14c984a5fd98e 100644 (file)
@@ -39,8 +39,6 @@
  * @author Jonathan Hui <jwhui@cs.berkeley.edu>
  */
 
-includes InternalFlash;
-
 module InternalFlashC {
   provides interface InternalFlash;
 }
diff --git a/tos/lib/tosboot/msp430/ProgFlashC.nc b/tos/lib/tosboot/msp430/ProgFlashC.nc
new file mode 100644 (file)
index 0000000..2c87c6f
--- /dev/null
@@ -0,0 +1,70 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+module ProgFlashC {
+  provides {
+    interface ProgFlash;
+  }
+}
+
+implementation {
+
+  enum {
+    RESET_ADDR = 0xfffe,
+  };
+
+  command error_t ProgFlash.write(in_flash_addr_t addr, uint8_t* buf, uint16_t len) {
+
+    volatile uint16_t *flashAddr = (uint16_t*)(uint16_t)addr;
+    uint16_t *wordBuf = (uint16_t*)buf;
+    uint16_t i = 0;
+
+    // len is 16 bits so it can't be larger than 0xffff
+    // make sure we can't wrap around
+    if (addr < (0xffff - (len >> 1))) {
+      FCTL2 = FWKEY + FSSEL1 + FN2;
+      FCTL3 = FWKEY;
+      FCTL1 = FWKEY + ERASE;
+      *flashAddr = 0;
+      FCTL1 = FWKEY + WRT;
+      for (i = 0; i < (len >> 1); i++, flashAddr++) {
+       if ((uint16_t)flashAddr != RESET_ADDR)
+         *flashAddr = wordBuf[i];
+       else
+         *flashAddr = TOSBOOT_START;
+      }
+      FCTL1 = FWKEY;
+      FCTL3 = FWKEY + LOCK;
+      return SUCCESS;
+    }
+    return FAIL;
+  }
+
+}
diff --git a/tos/lib/tosboot/msp430/ProgFlashM.nc b/tos/lib/tosboot/msp430/ProgFlashM.nc
deleted file mode 100644 (file)
index aa0adcc..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2005 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-module ProgFlashM {
-  provides {
-    interface ProgFlash;
-  }
-}
-
-implementation {
-
-  enum {
-    RESET_ADDR = 0xfffe,
-  };
-
-  command error_t ProgFlash.write(in_flash_addr_t addr, uint8_t* buf, uint16_t len) {
-
-    volatile uint16_t *flashAddr = (uint16_t*)(uint16_t)addr;
-    uint16_t *wordBuf = (uint16_t*)buf;
-    uint16_t i = 0;
-
-    // len is 16 bits so it can't be larger than 0xffff
-    // make sure we can't wrap around
-    if (addr < (0xffff - (len >> 1))) {
-      FCTL2 = FWKEY + FSSEL1 + FN2;
-      FCTL3 = FWKEY;
-      FCTL1 = FWKEY + ERASE;
-      *flashAddr = 0;
-      FCTL1 = FWKEY + WRT;
-      for (i = 0; i < (len >> 1); i++, flashAddr++) {
-       if ((uint16_t)flashAddr != RESET_ADDR)
-         *flashAddr = wordBuf[i];
-       else
-         *flashAddr = TOSBOOT_START;
-      }
-      FCTL1 = FWKEY;
-      FCTL3 = FWKEY + LOCK;
-      return SUCCESS;
-    }
-    return FAIL;
-  }
-
-}
diff --git a/tos/lib/tosboot/msp430f1611/PluginC.nc b/tos/lib/tosboot/msp430f1611/PluginC.nc
new file mode 100644 (file)
index 0000000..738bcae
--- /dev/null
@@ -0,0 +1,46 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2004 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+configuration PluginC {
+  provides {
+    interface StdControl;
+  }
+}
+
+implementation {
+
+  components ExtFlashC, LedsC, PowerOffC;
+
+  StdControl = PowerOffC;
+
+  PowerOffC.Leds -> LedsC;
+  PowerOffC.SubControl -> ExtFlashC;
+
+}
diff --git a/tos/lib/tosboot/msp430f1611/PowerOffC.nc b/tos/lib/tosboot/msp430f1611/PowerOffC.nc
new file mode 100644 (file)
index 0000000..e998cc3
--- /dev/null
@@ -0,0 +1,85 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2004 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+module PowerOffC {
+  provides {
+    interface Init;
+    interface StdControl;
+  }
+  uses {
+    interface Leds;
+    interface StdControl as SubControl;
+  }
+}
+
+implementation {
+
+  void haltsystem() {
+
+    uint16_t _lpmreg;
+
+    TOSH_SET_PIN_DIRECTIONS();
+
+    call SubControl.stop();
+
+    call Leds.glow(0x7, 0x0);
+
+    _lpmreg = LPM4_bits;
+    _lpmreg |= SR_GIE;
+
+    __asm__ __volatile__( "bis  %0, r2" : : "m" ((uint16_t)_lpmreg) );
+
+  }
+
+  command error_t Init.init() {
+    return SUCCESS;
+  }
+
+  command error_t StdControl.start() {
+
+    int i;
+
+    // wait a short period for things to stabilize
+    for ( i = 0; i < 4; i++ )
+      wait(0xffff);
+
+    // if user button is pressed, power down
+    if (!TOSH_READ_USERINT_PIN())
+      haltsystem();
+
+    return SUCCESS;
+
+  }
+
+  command error_t StdControl.stop() {
+    return SUCCESS;
+  }
+
+}
diff --git a/tos/lib/tosboot/msp430f1611/TOSBoot_platform.h b/tos/lib/tosboot/msp430f1611/TOSBoot_platform.h
new file mode 100644 (file)
index 0000000..e880dd1
--- /dev/null
@@ -0,0 +1,43 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * @author  Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#ifndef __TOSBOOT_PLATFORM_H__
+#define __TOSBOOT_PLATFORM_H__
+
+enum {
+  TOSBOOT_ARGS_ADDR = 0x70,      // address of TOSBoot args in internal flash
+  TOSBOOT_GESTURE_MAX_COUNT = 3, // number of resets to force golden image
+  TOSBOOT_GOLDEN_IMG_ADDR = 0xf0000L, // address of the golden image in external flash
+  TOSBOOT_INT_PAGE_SIZE = 512L,  // size of each internal program flash page
+};
+
+enum {
+  DELUGE_MIN_ADV_PERIOD_LOG2 = 9,
+  DELUGE_QSIZE = 1,
+};
+
+#endif
diff --git a/tos/lib/tosboot/mulle/ExecC.nc b/tos/lib/tosboot/mulle/ExecC.nc
new file mode 100644 (file)
index 0000000..cf5dd9b
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Implementation of the Exec interface for the Mulle platform.
+ * The interface is responsible for starting the execution of
+ * the user program which is located with a starting address
+ * of 0xa0000 in the program flash.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "hardware.h"
+module ExecC
+{
+  provides
+  {
+    interface Exec;
+  }
+}
+
+implementation
+{  
+  command void Exec.exec()
+  {
+    asm volatile ("jmp.a 0xa0000");
+  }
+}
diff --git a/tos/lib/tosboot/mulle/PluginC.nc b/tos/lib/tosboot/mulle/PluginC.nc
new file mode 100644 (file)
index 0000000..e7fc7cb
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * No extra plugins are required to be started for tosboot.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+module PluginC
+{
+  provides
+  {
+    interface StdControl;
+  }
+}
+
+implementation 
+{
+  command error_t StdControl.start() { return SUCCESS; }
+  command error_t StdControl.stop() { return SUCCESS; }
+}
diff --git a/tos/lib/tosboot/mulle/VoltageC.nc b/tos/lib/tosboot/mulle/VoltageC.nc
new file mode 100644 (file)
index 0000000..e928bf5
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * VoltageC provides a implementation of the Voltage interface.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+module VoltageC
+{
+  provides
+  {
+    interface Voltage;
+  }
+}
+
+implementation
+{
+  command bool Voltage.okToProgram()
+  {
+    // TODO(henrik) Implement
+    return true;
+  }
+}
diff --git a/tos/lib/tosboot/mulle/hardware.h b/tos/lib/tosboot/mulle/hardware.h
new file mode 100644 (file)
index 0000000..3821fc1
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#ifndef __HARDWARE_H__
+#define __HARDWARE_H__
+
+#include <m16c62phardware.h>
+#include <m16chardware.h>
+
+typedef uint32_t in_flash_addr_t;
+typedef uint32_t ex_flash_addr_t;
+
+static inline void wait( uint16_t dt ) {
+  uint16_t i;
+  for (i = 0; i < dt; ++i) {
+    TOSH_wait();
+  }
+}
+
+// LED assignments
+TOSH_ASSIGN_PIN(RED_LED, 3, 6);
+TOSH_ASSIGN_PIN(GREEN_LED, 3, 7);
+TOSH_ASSIGN_PIN(YELLOW_LED, 3, 4);
+
+// Flash assignments
+TOSH_ASSIGN_PIN(FLASH_IN,  4, 0);
+TOSH_ASSIGN_PIN(FLASH_OUT,  4, 1);
+TOSH_ASSIGN_PIN(FLASH_CLK,  4, 2);
+TOSH_ASSIGN_PIN(FLASH_CS, 4, 5);
+TOSH_ASSIGN_PIN(FLASH_VCC, 3, 2);
+
+void TOSH_SET_PIN_DIRECTIONS(void)
+{
+  TOSH_MAKE_RED_LED_OUTPUT();
+  TOSH_MAKE_YELLOW_LED_OUTPUT();
+  TOSH_MAKE_GREEN_LED_OUTPUT();
+      
+  TOSH_MAKE_FLASH_VCC_OUTPUT();
+  TOSH_CLR_FLASH_VCC_PIN();
+}
+
+// TODO(henrik) Insert correct value
+enum {
+  VTHRESH = 0x0, // 0V
+};
+
+#endif  // __HARDWARE_H__
+
+
+
+
diff --git a/tos/lib/tosboot/mulle/m16chardware.h b/tos/lib/tosboot/mulle/m16chardware.h
new file mode 100644 (file)
index 0000000..656ba8f
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2003 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+
+/**
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @author Jason Hill
+ * @author Philip Levis
+ * @author Nelson Lee
+ */
+#ifndef __M16CHARDWARE_H__
+#define __M16CHARDWARE_H__
+
+#define sbi(port, bit) SET_BIT(port, bit)
+#define cbi(port, bit) CLR_BIT(port, bit)
+
+#define TOSH_ASSIGN_PIN(name, port, bit) \
+static inline void TOSH_SET_##name##_PIN() {sbi(P##port.BYTE , bit);} \
+static inline void TOSH_CLR_##name##_PIN() {cbi(P##port.BYTE , bit);} \
+static inline int TOSH_READ_##name##_PIN() \
+  {return ((P##port.BYTE) & (1 << bit)) != 0;} \
+static inline void TOSH_MAKE_##name##_OUTPUT() {sbi(PD##port.BYTE , bit);} \
+static inline void TOSH_MAKE_##name##_INPUT() {cbi(PD##port.BYTE , bit);} 
+
+
+
+#define TOSH_ASSIGN_OUTPUT_ONLY_PIN(name, port, bit) \
+static inline void TOSH_SET_##name##_PIN() {sbi(P##port , bit);} \
+static inline void TOSH_CLR_##name##_PIN() {cbi(P##port , bit);} \
+static inline void TOSH_MAKE_##name##_OUTPUT() {;} 
+
+#define TOSH_ALIAS_OUTPUT_ONLY_PIN(alias, connector)\
+static inline void TOSH_SET_##alias##_PIN() {TOSH_SET_##connector##_PIN();} \
+static inline void TOSH_CLR_##alias##_PIN() {TOSH_CLR_##connector##_PIN();} \
+static inline void TOSH_MAKE_##alias##_OUTPUT() {} \
+
+#define TOSH_ALIAS_PIN(alias, connector) \
+static inline void TOSH_SET_##alias##_PIN() {TOSH_SET_##connector##_PIN();} \
+static inline void TOSH_CLR_##alias##_PIN() {TOSH_CLR_##connector##_PIN();} \
+static inline char TOSH_READ_##alias##_PIN() {return TOSH_READ_##connector##_PIN();} \
+static inline void TOSH_MAKE_##alias##_OUTPUT() {TOSH_MAKE_##connector##_OUTPUT();} \
+static inline void TOSH_MAKE_##alias##_INPUT()  {TOSH_MAKE_##connector##_INPUT();} 
+
+
+
+void TOSH_wait()
+{
+  asm volatile("nop");
+  asm volatile("nop");
+  asm volatile("nop");
+  asm volatile("nop");
+  asm volatile("nop");
+  asm volatile("nop");
+  asm volatile("nop");
+  asm volatile("nop");
+  asm volatile("nop");
+  asm volatile("nop");
+}
+
+#endif  // __M16CHARDWARE_H__
index 9f7d5347d81edba56debc8bc18fdf6ef2453db41..34ada4e1008db21374c2b154f607b5563ec60fa3 100644 (file)
@@ -39,13 +39,13 @@ configuration ExtFlashC {
 implementation {
 
   components 
-    ExtFlashM,
-    HPLUSART0M;
+    ExtFlashP,
+    HplUsart0C;
 
-  Init = ExtFlashM;
-  StdControl = ExtFlashM;
-  ExtFlash = ExtFlashM;
+  Init = ExtFlashP;
+  StdControl = ExtFlashP;
+  ExtFlash = ExtFlashP;
 
-  ExtFlashM.USARTControl -> HPLUSART0M;
+  ExtFlashP.UsartControl -> HplUsart0C;
 
 }
diff --git a/tos/lib/tosboot/stm25p/ExtFlashM.nc b/tos/lib/tosboot/stm25p/ExtFlashM.nc
deleted file mode 100644 (file)
index b9909b2..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-// $Id$
-
-/*
- * "Copyright (c) 2000-2005 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-module ExtFlashM {
-  provides {
-    interface StdControl;
-    interface Init;
-    interface ExtFlash;
-  }
-  uses {
-    interface HPLUSARTControl as USARTControl;
-  }
-}
-
-implementation {
-
-  command error_t Init.init() {
-    TOSH_MAKE_FLASH_HOLD_OUTPUT();
-    TOSH_MAKE_FLASH_CS_OUTPUT();
-    TOSH_SET_FLASH_HOLD_PIN();
-    call USARTControl.setModeSPI();
-    return SUCCESS;
-  }
-
-  command error_t StdControl.start() { 
-    return SUCCESS; 
-  }
-
-  command error_t StdControl.stop() { 
-
-    TOSH_CLR_FLASH_CS_PIN();
-    
-    call USARTControl.tx(0xb9);
-    while(call USARTControl.isTxEmpty() != SUCCESS);
-
-    TOSH_SET_FLASH_CS_PIN();
-
-    call USARTControl.disableSPI();
-
-    return SUCCESS; 
-
-  }
-
-  void powerOnFlash() {
-
-    uint8_t i;
-
-    TOSH_CLR_FLASH_CS_PIN();
-
-    // command byte + 3 dummy bytes + signature
-    for ( i = 0; i < 5; i++ ) {
-      call USARTControl.tx(0xab);
-      while(call USARTControl.isTxIntrPending() != SUCCESS);
-    }
-    
-    TOSH_SET_FLASH_CS_PIN();
-
-  }
-
-  command void ExtFlash.startRead(uint32_t addr) {
-
-    uint8_t i;
-    
-    powerOnFlash();
-    
-    TOSH_CLR_FLASH_CS_PIN();
-    
-    // add command byte to address
-    addr |= (uint32_t)0x3 << 24;
-
-    // address
-    for ( i = 4; i > 0; i-- ) {
-      call USARTControl.tx((addr >> (i-1)*8) & 0xff);
-      while(call USARTControl.isTxIntrPending() != SUCCESS);
-    }    
-
-  }
-
-  command uint8_t ExtFlash.readByte() {
-    call USARTControl.rx();
-    call USARTControl.tx(0);
-    while(call USARTControl.isRxIntrPending() != SUCCESS);
-    return call USARTControl.rx();
-  }
-
-  command void ExtFlash.stopRead() {
-    TOSH_SET_FLASH_CS_PIN();
-  }
-
-}
diff --git a/tos/lib/tosboot/stm25p/ExtFlashP.nc b/tos/lib/tosboot/stm25p/ExtFlashP.nc
new file mode 100644 (file)
index 0000000..f1a6217
--- /dev/null
@@ -0,0 +1,114 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+module ExtFlashP {
+  provides {
+    interface StdControl;
+    interface Init;
+    interface ExtFlash;
+  }
+  uses {
+    interface HplUsartControl as UsartControl;
+  }
+}
+
+implementation {
+
+  command error_t Init.init() {
+    TOSH_MAKE_FLASH_HOLD_OUTPUT();
+    TOSH_MAKE_FLASH_CS_OUTPUT();
+    TOSH_SET_FLASH_HOLD_PIN();
+    call UsartControl.setModeSPI();
+    return SUCCESS;
+  }
+
+  command error_t StdControl.start() { 
+    return SUCCESS; 
+  }
+
+  command error_t StdControl.stop() { 
+
+    TOSH_CLR_FLASH_CS_PIN();
+    
+    call UsartControl.tx(0xb9);
+    while(call UsartControl.isTxEmpty() != SUCCESS);
+
+    TOSH_SET_FLASH_CS_PIN();
+
+    call UsartControl.disableSPI();
+
+    return SUCCESS; 
+
+  }
+
+  void powerOnFlash() {
+
+    uint8_t i;
+
+    TOSH_CLR_FLASH_CS_PIN();
+
+    // command byte + 3 dummy bytes + signature
+    for ( i = 0; i < 5; i++ ) {
+      call UsartControl.tx(0xab);
+      while(call UsartControl.isTxIntrPending() != SUCCESS);
+    }
+    
+    TOSH_SET_FLASH_CS_PIN();
+
+  }
+
+  command void ExtFlash.startRead(uint32_t addr) {
+
+    uint8_t i;
+    
+    powerOnFlash();
+    
+    TOSH_CLR_FLASH_CS_PIN();
+    
+    // add command byte to address
+    addr |= (uint32_t)0x3 << 24;
+
+    // address
+    for ( i = 4; i > 0; i-- ) {
+      call UsartControl.tx((addr >> (i-1)*8) & 0xff);
+      while(call UsartControl.isTxIntrPending() != SUCCESS);
+    }    
+
+  }
+
+  command uint8_t ExtFlash.readByte() {
+    call UsartControl.rx();
+    call UsartControl.tx(0);
+    while(call UsartControl.isRxIntrPending() != SUCCESS);
+    return call UsartControl.rx();
+  }
+
+  command void ExtFlash.stopRead() {
+    TOSH_SET_FLASH_CS_PIN();
+  }
+
+}
diff --git a/tos/lib/tosboot/telosb/InternalFlash.h b/tos/lib/tosboot/telosb/InternalFlash.h
deleted file mode 100644 (file)
index eca3667..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2004 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * InternalFlash.h - Internal flash implementation for telos msp
- * platform. On the msp, the flash must first be erased before a value
- * can be written. However, the msp can only erase the flash at a
- * segment granularity (128 bytes for the information section). This
- * module allows transparent read/write of individual bytes to the
- * information section by dynamically switching between the two
- * provided segments in the information section.
- *
- * Valid address range is 0x1000 - 0x107E (0x107F is used to store the
- * version number of the information segment).
- *
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-#ifndef __INTERNAL_FLASH_H__
-#define __INTERNAL_FLASH_H__
-
-#endif
diff --git a/tos/lib/tosboot/telosb/InternalFlash.nc b/tos/lib/tosboot/telosb/InternalFlash.nc
deleted file mode 100644 (file)
index d41d52b..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2004 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * InternalFlash.nc - A generic interface to read and store values in
- * the internal flash of a microcontroller.
- *
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-interface InternalFlash {
-  command error_t write(void* addr, void* buf, uint16_t size);
-  command error_t read(void* addr, void* buf, uint16_t size);
-}
diff --git a/tos/lib/tosboot/telosb/PluginC.nc b/tos/lib/tosboot/telosb/PluginC.nc
deleted file mode 100644 (file)
index 860b248..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2004 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-configuration PluginC {
-  provides {
-    interface StdControl;
-  }
-}
-
-implementation {
-
-  components ExtFlashC, LedsC, PowerOffM;
-
-  StdControl = PowerOffM;
-
-  PowerOffM.Leds -> LedsC;
-  PowerOffM.SubControl -> ExtFlashC;
-
-}
diff --git a/tos/lib/tosboot/telosb/PowerOffM.nc b/tos/lib/tosboot/telosb/PowerOffM.nc
deleted file mode 100644 (file)
index 94d8dc3..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-// $Id$
-
-/*
- *
- *
- * "Copyright (c) 2000-2004 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- */
-
-/**
- * @author Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-module PowerOffM {
-  provides {
-    interface Init;
-    interface StdControl;
-  }
-  uses {
-    interface Leds;
-    interface StdControl as SubControl;
-  }
-}
-
-implementation {
-
-  void haltsystem() {
-
-    uint16_t _lpmreg;
-
-    TOSH_SET_PIN_DIRECTIONS();
-
-    call SubControl.stop();
-
-    call Leds.glow(0x7, 0x0);
-
-    _lpmreg = LPM4_bits;
-    _lpmreg |= SR_GIE;
-
-    __asm__ __volatile__( "bis  %0, r2" : : "m" ((uint16_t)_lpmreg) );
-
-  }
-
-  command error_t Init.init() {
-    return SUCCESS;
-  }
-
-  command error_t StdControl.start() {
-
-    int i;
-
-    // wait a short period for things to stabilize
-    for ( i = 0; i < 4; i++ )
-      wait(0xffff);
-
-    // if user button is pressed, power down
-    if (!TOSH_READ_USERINT_PIN())
-      haltsystem();
-
-    return SUCCESS;
-
-  }
-
-  command error_t StdControl.stop() {
-    return SUCCESS;
-  }
-
-}
diff --git a/tos/lib/tosboot/telosb/TOSBoot_platform.h b/tos/lib/tosboot/telosb/TOSBoot_platform.h
deleted file mode 100644 (file)
index 0522d6b..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-// $Id$
-
-/*
- * "Copyright (c) 2000-2005 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- */
-
-/**
- * @author  Jonathan Hui <jwhui@cs.berkeley.edu>
- */
-
-#ifndef __TOSBOOT_PLATFORM_H__
-#define __TOSBOOT_PLATFORM_H__
-
-enum {
-  // address of TOSBoot args in internal flash
-  TOSBOOT_ARGS_ADDR = 0x70,
-  // number of resets to force golden image
-  TOSBOOT_GESTURE_MAX_COUNT = 3,
-  // address of the golden image in external flash
-  TOSBOOT_GOLDEN_IMG_ADDR = 0xf0000L,
-  // size of each internal program flash page
-  TOSBOOT_INT_PAGE_SIZE = 512L,
-};
-
-enum {
-  DELUGE_MIN_ADV_PERIOD_LOG2 = 9,
-  DELUGE_QSIZE = 1,
-};
-
-#endif
diff --git a/tos/lib/tosboot/tinynode/ExecC.nc b/tos/lib/tosboot/tinynode/ExecC.nc
new file mode 100644 (file)
index 0000000..0dee182
--- /dev/null
@@ -0,0 +1,45 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/*
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+module ExecC {
+  provides {
+    interface Exec;
+  }
+}
+
+implementation {
+
+  command void Exec.exec() {
+
+    //goto *(void*)(TOSBOOT_END);
+
+    typedef void __attribute__((noreturn)) (*tosboot_exec)();
+    ((tosboot_exec)TOSBOOT_END)();
+
+  }
+
+}
diff --git a/tos/lib/tosboot/tinynode/ExtFlashC.nc b/tos/lib/tosboot/tinynode/ExtFlashC.nc
new file mode 100644 (file)
index 0000000..859e040
--- /dev/null
@@ -0,0 +1,160 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ * @author Roland Flury <roland.flury@shockfish.com>
+ */
+
+module ExtFlashC {
+  provides {
+    interface Init;
+    interface StdControl;
+    interface ExtFlash;
+  }
+}
+
+/**
+ * Simple reader module to access the Atmel at45db041 flash chip
+ */
+implementation {
+
+  uint32_t addr;
+
+  command error_t Init.init() {
+
+    TOSH_SET_FLASH_CS_PIN(); // inverted, deselect by default
+    TOSH_MAKE_FLASH_CS_OUTPUT();
+
+    TOSH_CLR_FLASH_CLK_PIN();
+    TOSH_MAKE_FLASH_CLK_OUTPUT();
+
+    TOSH_SET_FLASH_OUT_PIN();
+    TOSH_MAKE_FLASH_OUT_OUTPUT();      
+
+    TOSH_MAKE_FLASH_IN_INPUT();
+
+               TOSH_SET_FLASH_RESET_PIN(); // inverted
+               TOSH_MAKE_FLASH_RESET_OUTPUT();
+
+    return SUCCESS; 
+  }
+
+  command error_t StdControl.start() { return SUCCESS; }
+  command error_t StdControl.stop() { return SUCCESS; }
+       
+       /**
+        * Write a Byte over the SPI bus and receive a Byte
+        *
+        * upon calling this function, /CS must be CLR
+        */
+  uint8_t SPIByte(uint8_t out) {
+    uint8_t in = 0;
+    uint8_t i;
+
+    for ( i = 0; i < 8; i++, out <<= 1 ) {
+      // write bit
+      if (out & 0x80) {
+                               TOSH_SET_FLASH_OUT_PIN();
+                       } else {
+                               TOSH_CLR_FLASH_OUT_PIN();
+                       }
+                       
+      // clock
+      TOSH_SET_FLASH_CLK_PIN();
+                       
+      // read bit
+      in <<= 1;
+      if (TOSH_READ_FLASH_IN_PIN()) {
+                               in |= 1;
+                       }
+                       
+      // clock
+      TOSH_CLR_FLASH_CLK_PIN();
+    }
+
+    return in;
+  }
+
+
+
+       /**
+        * Initializes the flash to read Byte after Byte starting
+        * from the given address. 
+        *
+        * Subsequent calls to readByte() will return the Bytes 
+        * starting from the specified address. 
+        *
+        * stopRead() terminates this process and disables the Flash. 
+        */
+  command void ExtFlash.startRead(uint32_t newAddr) {
+    uint8_t  cmdBuf[4];
+    uint8_t  i;
+
+               // we're using "Waveform 1 - Inactive Clock Polarity Low"
+               // see p.7 of data sheet
+    TOSH_CLR_FLASH_CLK_PIN(); 
+    TOSH_CLR_FLASH_CS_PIN(); // select the flash
+
+    addr = newAddr;
+
+               // we only use 256 Bytes per block (of 264 Bytes)
+    cmdBuf[0] = 0x52; // command for reading data starting at the following address
+    cmdBuf[1] = (addr >> 15) & 0xff; // 4 LSbits 
+    cmdBuf[2] = (addr >> 7) & 0xfe;  // 7 MSbits with the above 4 bits describe page to read
+    cmdBuf[3] = addr & 0xff;         // Offset to Byte in page to read
+
+               // transmit read command
+    for(i = 0; i < 4; i++) {
+      SPIByte(cmdBuf[i]);
+               }
+               // transmit 4 Bytes "don't care" as to spec
+    for(i = 0; i < 4; i++) {
+      SPIByte(0x0);
+               }
+    
+               // need to do one additional clock transition before reading
+               TOSH_SET_FLASH_CLK_PIN();
+               TOSH_CLR_FLASH_CLK_PIN();
+  }
+
+  command uint8_t ExtFlash.readByte() {
+               uint8_t b = SPIByte(0); // write anything, read Byte
+               addr++;
+               if(0 == (addr & 0xFF)) {
+                       // we've just read the last Byte from a page
+                       // initialize the Flash to continue reading on the new page
+      call ExtFlash.stopRead();
+      call ExtFlash.startRead(addr);
+               } 
+               return b;
+  }
+
+  command void ExtFlash.stopRead() {
+    TOSH_SET_FLASH_CS_PIN(); // disble Flash & tri-state the OUT-pin
+  }
+
+}
diff --git a/tos/lib/tosboot/tinynode/PowerOffC.nc b/tos/lib/tosboot/tinynode/PowerOffC.nc
new file mode 100644 (file)
index 0000000..a230222
--- /dev/null
@@ -0,0 +1,89 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2004 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+module PowerOffC {
+  provides {
+    interface Init;
+    interface StdControl;
+  }
+  uses {
+    interface Leds;
+    interface StdControl as SubControl;
+  }
+}
+
+implementation {
+
+  void haltsystem() {
+
+    uint16_t _lpmreg;
+
+    TOSH_SET_PIN_DIRECTIONS();
+
+    call SubControl.stop();
+
+    call Leds.glow(0x7, 0x0);
+
+    _lpmreg = LPM4_bits;
+    _lpmreg |= SR_GIE;
+
+    __asm__ __volatile__( "bis  %0, r2" : : "m" ((uint16_t)_lpmreg) );
+
+  }
+
+  command error_t Init.init() {
+    return SUCCESS;
+  }
+
+  command error_t StdControl.start() {
+
+    int i;
+
+    // wait a short period for things to stabilize
+    for ( i = 0; i < 4; i++ ) {
+      wait(0xffff);
+               }
+
+               // TinyNode: we don't have a user button
+
+    // if user button is pressed, power down
+    //if (!TOSH_READ_USERINT_PIN()) {
+               //haltsystem(); 
+               //}
+
+    return SUCCESS;
+
+  }
+
+  command error_t StdControl.stop() {
+    return SUCCESS;
+  }
+
+}
diff --git a/tos/lib/tosboot/tinynode/README b/tos/lib/tosboot/tinynode/README
new file mode 100644 (file)
index 0000000..86792ef
--- /dev/null
@@ -0,0 +1,15 @@
+Deluge T2 for TinyNode
+----------------------------------
+
+
+These files are needed by Deluge T2 to compile for the TinyNode platform. 
+
+Note: 
+
+Reprogramming fails if the voltage of the node is not above a given 
+threshold. Currently, this is set to 2.7V, which may be too high if 
+you run your mote on batteries. In this case, set the value of
+VTHRESH in the hardware.h file to a different value. 
+
+In case you wish not to test the voltage at all, modify VoltageC.nc
+s.t. the command Voltage.okToProgram() returns always TRUE. 
\ No newline at end of file
diff --git a/tos/lib/tosboot/tinynode/TOSBoot_platform.h b/tos/lib/tosboot/tinynode/TOSBoot_platform.h
new file mode 100644 (file)
index 0000000..9bcc776
--- /dev/null
@@ -0,0 +1,43 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * @author  Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+#ifndef __TOSBOOT_PLATFORM_H__
+#define __TOSBOOT_PLATFORM_H__
+
+enum {
+  TOSBOOT_ARGS_ADDR = 0x70,      // address of TOSBoot args in internal flash
+  TOSBOOT_GESTURE_MAX_COUNT = 3, // number of resets to force golden image
+  TOSBOOT_GOLDEN_IMG_ADDR = 0x0L, // address of the golden image in external flash
+  TOSBOOT_INT_PAGE_SIZE = 512L,  // size of each internal program flash page
+};
+
+enum {
+  DELUGE_MIN_ADV_PERIOD_LOG2 = 9,
+  DELUGE_QSIZE = 1,
+};
+
+#endif
diff --git a/tos/lib/tosboot/tinynode/VoltageC.nc b/tos/lib/tosboot/tinynode/VoltageC.nc
new file mode 100644 (file)
index 0000000..7a30610
--- /dev/null
@@ -0,0 +1,68 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2004 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ */
+
+module VoltageC {
+  provides {
+    interface Voltage;
+  }
+}
+
+implementation {
+
+  command bool Voltage.okToProgram() {
+
+               /** original code form the msp430 folder */
+    int i;
+
+    // Turn on and set up ADC12 with REF_1_5V
+    ADC12CTL0 = ADC12ON | SHT0_2 | REFON;
+    // Use sampling timer
+    ADC12CTL1 = SHP;
+    // Set up to sample voltage
+    ADC12MCTL0 = EOS | SREF_1 | INCH_11;
+    // Delay for reference start-up
+    for ( i=0; i<0x3600; i++ );
+
+    // Enable conversions
+    ADC12CTL0 |= ENC;
+    // Start conversion
+    ADC12CTL0 |= ADC12SC;
+    // Wait for completion
+    while ((ADC12IFG & BIT0) == 0);
+
+    // Turn off ADC12
+    ADC12CTL0 &= ~ENC;
+    ADC12CTL0 = 0;
+
+    // Check if voltage is greater than 2.7V
+    return ( ADC12MEM0 > VTHRESH );
+  }
+
+}
diff --git a/tos/lib/tosboot/tinynode/hardware.h b/tos/lib/tosboot/tinynode/hardware.h
new file mode 100644 (file)
index 0000000..4164dc4
--- /dev/null
@@ -0,0 +1,84 @@
+// $Id$
+
+/*
+ *
+ *
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * @author Jonathan Hui <jwhui@cs.berkeley.edu>
+ * @author Roland Flury <roland.flury@shockfish.com>
+ */
+
+#ifndef __HARDWARE_H__
+#define __HARDWARE_H__
+
+#include "msp430hardware.h"
+
+// internal flash is 16 bits in width
+typedef uint16_t in_flash_addr_t;
+// external flash is 32 bits in width
+typedef uint32_t ex_flash_addr_t;
+
+void wait(uint16_t t) {
+  for(; t > 0; t--);
+}
+enum {
+  VTHRESH = 0xE66, // 2.7V - threshold for reprogramming the node, if voltage is below, don't reprogram
+};
+
+// LEDs
+TOSH_ASSIGN_PIN(RED_LED2, 1, 5);               // on tinynode
+TOSH_ASSIGN_PIN(RED_LED, 1, 6);        // external
+TOSH_ASSIGN_PIN(GREEN_LED, 2, 3);
+TOSH_ASSIGN_PIN(YELLOW_LED, 2, 4);
+
+// FLASH at45db041
+TOSH_ASSIGN_PIN(FLASH_CS, 4, 7); // inverted
+TOSH_ASSIGN_PIN(FLASH_RESET, 4, 6); // inverted
+TOSH_ASSIGN_PIN(FLASH_CLK, 3, 3);
+TOSH_ASSIGN_PIN(FLASH_OUT, 3, 1); // MOSI - master OUT slave IN
+TOSH_ASSIGN_PIN(FLASH_IN, 3, 2); // MISO - master IN slave OUT
+
+void TOSH_SET_PIN_DIRECTIONS(void) {
+       
+       // FLASH at45db041
+  TOSH_SET_FLASH_CS_PIN(); // inverted 
+  TOSH_MAKE_FLASH_CS_OUTPUT();
+  TOSH_MAKE_FLASH_OUT_OUTPUT();
+  TOSH_MAKE_FLASH_CLK_OUTPUT();
+       TOSH_MAKE_FLASH_IN_INPUT();
+       TOSH_SET_FLASH_RESET_PIN(); // inverted
+       TOSH_MAKE_FLASH_RESET_OUTPUT();
+
+       // LEDs
+       TOSH_CLR_RED_LED2_PIN();
+       TOSH_CLR_RED_LED_PIN();
+       TOSH_CLR_YELLOW_LED_PIN();
+       TOSH_CLR_GREEN_LED_PIN();
+       TOSH_MAKE_RED_LED2_OUTPUT();            
+       TOSH_MAKE_RED_LED_OUTPUT();             
+       TOSH_MAKE_YELLOW_LED_OUTPUT();          
+       TOSH_MAKE_GREEN_LED_OUTPUT();           
+}
+
+#endif
index 167b6a8574a44df354025c3875cfe355bb7eefd2..4a84a278eed37e3a33d0358c9fda62a3131777db 100644 (file)
@@ -50,6 +50,8 @@ implementation {
   message_t* outgoing; // If I'm sending, this is my outgoing packet
   bool requestAck;
   bool receiving = 0;  // Whether or not I think I'm receiving a packet
+  bool transmitting = 0; // Whether or not I think I'm tranmitting a packet
+  sim_time_t transmissionEndTime; // to check pending transmission
   struct receive_message;
   typedef struct receive_message receive_message_t;
 
@@ -139,17 +141,16 @@ implementation {
   }
   
   double arr_estimate_from_snr(double SNR) {
-    double beta1 = 1.3687;
-    double beta2 = 0.9187;
-    double SNR_lin = pow(10.0, SNR/10.0);
-    double X = fabs(SNR_lin-beta2);
-    double PSE = 0.5*erfc(beta1*sqrt(X/2));
+    double beta1 = 0.9794;
+    double beta2 = 2.3851;
+    double X = SNR-beta2;
+    double PSE = 0.5*erfc(beta1*X/sqrt(2));
     double prr_hat = pow(1-PSE, 23*2);
     dbg("CpmModelC,SNRLoss", "SNR is %lf, ARR is %lf\n", SNR, prr_hat);
     if (prr_hat > 1)
-      prr_hat = 1;
+      prr_hat = 1.1;
     else if (prr_hat < 0)
-      prr_hat = 0;
+      prr_hat = -0.1;
        
     return prr_hat;
   }
@@ -157,7 +158,7 @@ implementation {
   int shouldAckReceive(double snr) {
     double prr = arr_estimate_from_snr(snr);
     double coin = RandomUniform();
-    if ( (prr != 0) && (prr != 1) ) {
+    if ( (prr >= 0) && (prr <= 1) ) {
       if (coin < prr)
        prr = 1.0;
       else
@@ -219,17 +220,19 @@ implementation {
   }
 
   double prr_estimate_from_snr(double SNR) {
-    double beta1 = 1.3687;
-    double beta2 = 0.9187;
-    double SNR_lin = pow(10.0, SNR/10.0);
-    double X = fabs(SNR_lin-beta2);
-    double PSE = 0.5*erfc(beta1*sqrt(X/2));
+    // Based on CC2420 measurement by Kannan.
+    // The updated function below fixes the problem of non-zero PRR
+    // at very low SNR. With this function PRR is 0 for SNR <= 3.
+    double beta1 = 0.9794;
+    double beta2 = 2.3851;
+    double X = SNR-beta2;
+    double PSE = 0.5*erfc(beta1*X/sqrt(2));
     double prr_hat = pow(1-PSE, 23*2);
     dbg("CpmModelC,SNR", "SNR is %lf, PRR is %lf\n", SNR, prr_hat);
     if (prr_hat > 1)
-      prr_hat = 1;
+      prr_hat = 1.1;
     else if (prr_hat < 0)
-      prr_hat = 0;
+      prr_hat = -0.1;
        
     return prr_hat;
   }
@@ -237,7 +240,7 @@ implementation {
   bool shouldReceive(double SNR) {
     double prr = prr_estimate_from_snr(SNR);
     double coin = RandomUniform();
-    if ( (prr != 0) && (prr != 1) ) {
+    if ( (prr >= 0) && (prr <= 1) ) {
       if (coin < prr)
        prr = 1.0;
       else
@@ -390,6 +393,10 @@ implementation {
       dbg("CpmModelC,SNRLoss", "Lost packet from %i due to %i being mid-reception\n", source, sim_node());
       rcv->lost = 1;
     }
+    else if (transmitting && (rcv->start < transmissionEndTime) && (transmissionEndTime <= rcv->end)) {
+      dbg("CpmModelC,SNRLoss", "Lost packet from %i due to %i being mid-transmission, transmissionEndTime %llu\n", source, sim_node(), transmissionEndTime);
+      rcv->lost = 1;
+    }
     else {
       receiving = 1;
     }
@@ -419,20 +426,33 @@ implementation {
   }
 
   command void Model.putOnAirTo(int dest, message_t* msg, bool ack, sim_time_t endTime, double power, double reversePower) {
+    receive_message_t* list;
     gain_entry_t* neighborEntry = sim_gain_first(sim_node());
     requestAck = ack;
     outgoing = msg;
+    transmissionEndTime = endTime;
     dbg("CpmModelC", "Node %i transmitting to %i, finishes at %llu.\n", sim_node(), dest, endTime);
 
     while (neighborEntry != NULL) {
       int other = neighborEntry->mote;
-      sim_gain_put(other, msg, endTime, ack && (other == dest), power + sim_gain_value(sim_node(), other), reversePower + sim_gain_value(other, sim_node()));
+      sim_gain_put(other, msg, endTime, ack, power + sim_gain_value(sim_node(), other), reversePower + sim_gain_value(other, sim_node()));
       neighborEntry = sim_gain_next(neighborEntry);
     }
+
+    list = outstandingReceptionHead;
+    while (list != NULL) {    
+      list->lost = 1;
+      dbg("CpmModelC,SNRLoss", "Lost packet from %i because %i has outstanding reception, startTime %llu endTime %llu\n", list->source, sim_node(), list->start, list->end);
+      list = list->next;
+    }
   }
     
 
-  
+  command void Model.setPendingTransmission() {
+    transmitting = TRUE;
+    dbg("CpmModelC", "setPendingTransmission: transmitting %i @ %s\n", transmitting, sim_time_string());
+  }
+
   
  default event void Model.receive(message_t* msg) {}
 
index 8a3a40f8dc76742d433d97610ec517f0ac574fa1..d7d7496f06c828f0b520429a10c6e00aba54f78d 100644 (file)
@@ -46,6 +46,7 @@ interface GainRadioModel {
 
   command void setClearValue(double value);
   command bool clearChannel();
+  command void setPendingTransmission();
   
   event void acked(message_t* msg);
   event void receive(message_t* msg);
diff --git a/tos/lib/tossim/HilTimerMilliC.nc b/tos/lib/tossim/HilTimerMilliC.nc
deleted file mode 100644 (file)
index 297c186..0000000
+++ /dev/null
@@ -1,173 +0,0 @@
-// $Id$
-/*
- * "Copyright (c) 2005 Stanford University. All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and
- * its documentation for any purpose, without fee, and without written
- * agreement is hereby granted, provided that the above copyright
- * notice, the following two paragraphs and the author appear in all
- * copies of this software.
- * 
- * IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
- * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
- * IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
- * DAMAGE.
- * 
- * STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
- * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
- * HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
- * ENHANCEMENTS, OR MODIFICATIONS."
- */
-
-/**
- * This is a TOSSIM-specific implementation of TimerMilliC that
- * directly emulates timers rather than their underlying hardware.  It
- * is intended to be a basic fill-in for microcontrollers that do not
- * have TOSSIM simulation support.
- *
- * @author Philip Levis
- * @date   December 1 2005
- */
-
-#include <Timer.h>
-
-module HilTimerMilliC {
-  provides interface Init;
-  provides interface Timer<TMilli> as TimerMilli[uint8_t num];
-}
-implementation {
-
-  enum {
-    TIMER_COUNT = uniqueCount(UQ_TIMER_MILLI)
-  };
-
-  typedef struct tossim_timer {
-    uint32_t t0;
-    uint32_t dt;
-    bool isPeriodic;
-    bool isActive;
-    sim_event_t* evt;
-  } tossim_timer_t;
-
-  tossim_timer_t timers[TIMER_COUNT];
-  sim_time_t initTime;
-
-  void initializeEvent(sim_event_t* evt, uint8_t timerID);
-  
-  sim_time_t clockToSim(sim_time_t clockVal) {
-    return (clockVal * sim_ticks_per_sec()) / 1024;
-  }
-
-  sim_time_t simToClock(sim_time_t sim) {
-    return (sim * 1024) / sim_ticks_per_sec();
-  }
-  
-  command error_t Init.init() {
-    memset(timers, 0, sizeof(timers));
-    initTime = sim_time();
-    return SUCCESS;
-  }
-  
-  command void TimerMilli.startPeriodic[uint8_t id]( uint32_t dt ) {
-    call TimerMilli.startPeriodicAt[id](call TimerMilli.getNow[id](), dt);
-  }
-  command void TimerMilli.startOneShot[uint8_t id]( uint32_t dt ) {
-    call TimerMilli.startOneShotAt[id](call TimerMilli.getNow[id](), dt);
-  }
-
-  command void TimerMilli.stop[uint8_t id]() {
-    timers[id].isActive = 0;
-    if (timers[0].evt != NULL) {
-      timers[0].evt->cancelled = 1;
-      timers[0].evt->cleanup = sim_queue_cleanup_total;
-      timers[0].evt = NULL;
-    }
-  }
-
-  // extended interface
-  command bool TimerMilli.isRunning[uint8_t id]() {return timers[id].isActive;}
-  command bool TimerMilli.isOneShot[uint8_t id]() {return !timers[id].isActive;}
-  
-  command void TimerMilli.startPeriodicAt[uint8_t id]( uint32_t t0, uint32_t dt ) {
-    call TimerMilli.startOneShotAt[id](t0, dt);
-    timers[id].isPeriodic = 1;
-  }
-  command void TimerMilli.startOneShotAt[uint8_t id]( uint32_t t0, uint32_t dt ) {
-    uint32_t currentTime = call TimerMilli.getNow[id]();
-    sim_time_t fireTime = sim_time();
-
-    call TimerMilli.stop[id]();
-    
-    timers[id].evt = sim_queue_allocate_event();
-    initializeEvent(timers[id].evt, id);
-
-    fireTime += clockToSim(dt);
-    
-    // Be careful about signing and casts, etc.
-    if (currentTime > t0) {
-      fireTime -= clockToSim(currentTime - t0);
-    }
-    else {
-      fireTime += clockToSim(t0 - currentTime);      
-    }
-
-    timers[id].evt->time = fireTime;
-    timers[id].isPeriodic = 0;
-    timers[id].isActive = 1;
-    timers[id].t0 = t0;
-    timers[id].dt = dt;
-
-    sim_queue_insert(timers[id].evt);
-  }
-    
-  command uint32_t TimerMilli.getNow[uint8_t id]() {
-    sim_time_t nowTime = sim_time();
-    nowTime -= initTime;
-    nowTime = simToClock(nowTime);
-    return nowTime & 0xffffffff;
-  }
-  
-  command uint32_t TimerMilli.gett0[uint8_t id]() {
-    return timers[id].t0;
-  }
-  command uint32_t TimerMilli.getdt[uint8_t id]() {
-    return timers[id].dt;
-  }
-
-  void tossim_timer_handle(sim_event_t* evt) {
-    uint8_t* datum = (uint8_t*)evt->data;
-    uint8_t id = *datum;
-    signal TimerMilli.fired[id]();
-
-    // We should only re-enqueue the event if it is a follow-up firing
-    // of the same timer.  If the timer is stopped, it's a one shot,
-    // or someone has started a new timer, don't re-enqueue it.
-    if (timers[id].isActive &&
-       timers[id].isPeriodic &&
-       timers[id].evt == evt) {
-      evt->time = evt->time += clockToSim(timers[id].dt);
-      sim_queue_insert(evt);
-    }
-    // If we aren't enqueueing it, and nobody has done something that
-    // would cause the event to have been garbage collected, then do
-    // so.
-    else if (timers[id].evt == evt) {
-      call TimerMilli.stop[id]();
-    }
-  }
-  
-  void initializeEvent(sim_event_t* evt, uint8_t timerID) {
-    uint8_t* data = (uint8_t*)malloc(sizeof(uint8_t));
-    *data = timerID;
-
-    evt->handle = tossim_timer_handle;
-    evt->cleanup = sim_queue_cleanup_none;
-    evt->data = data;
-  }
-
- default event void TimerMilli.fired[uint8_t id]() {}
-}
-
index 38406a8b5c32855f95f6e88c3eb8426ae93a7381..88fd9bfaf8b2dd02c1ccecba2873ba4464b420e0 100644 (file)
@@ -1,23 +1,43 @@
-# This file was created automatically by SWIG.
+# This file was automatically generated by SWIG (http://www.swig.org).
+# Version 1.3.33
+#
 # Don't modify this file, modify the SWIG interface instead.
 # This file is compatible with both classic and new-style classes.
+
 import _TOSSIM
-def _swig_setattr(self,class_type,name,value):
+import new
+new_instancemethod = new.instancemethod
+try:
+    _swig_property = property
+except NameError:
+    pass # Python < 2.2 doesn't have 'property'.
+def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
+    if (name == "thisown"): return self.this.own(value)
     if (name == "this"):
-        if isinstance(value, class_type):
-            self.__dict__[name] = value.this
-            if hasattr(value,"thisown"): self.__dict__["thisown"] = value.thisown
-            del value.thisown
+        if type(value).__name__ == 'PySwigObject':
+            self.__dict__[name] = value
             return
     method = class_type.__swig_setmethods__.get(name,None)
     if method: return method(self,value)
-    self.__dict__[name] = value
+    if (not static) or hasattr(self,name):
+        self.__dict__[name] = value
+    else:
+        raise AttributeError("You cannot add attributes to %s" % self)
+
+def _swig_setattr(self,class_type,name,value):
+    return _swig_setattr_nondynamic(self,class_type,name,value,0)
 
 def _swig_getattr(self,class_type,name):
+    if (name == "thisown"): return self.this.own()
     method = class_type.__swig_getmethods__.get(name,None)
     if method: return method(self)
     raise AttributeError,name
 
+def _swig_repr(self):
+    try: strthis = "proxy of " + self.this.__repr__()
+    except: strthis = ""
+    return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
+
 import types
 try:
     _object = types.ObjectType
@@ -25,6 +45,7 @@ try:
 except AttributeError:
     class _object : pass
     _newclass = 0
+del types
 
 
 class MAC(_object):
@@ -32,271 +53,216 @@ class MAC(_object):
     __setattr__ = lambda self, name, value: _swig_setattr(self, MAC, name, value)
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, MAC, name)
-    def __init__(self,*args):
-        _swig_setattr(self, MAC, 'this', apply(_TOSSIM.new_MAC,args))
-        _swig_setattr(self, MAC, 'thisown', 1)
-    def __del__(self, destroy= _TOSSIM.delete_MAC):
-        try:
-            if self.thisown: destroy(self)
-        except: pass
-    def initHigh(*args): return apply(_TOSSIM.MAC_initHigh,args)
-    def initLow(*args): return apply(_TOSSIM.MAC_initLow,args)
-    def high(*args): return apply(_TOSSIM.MAC_high,args)
-    def low(*args): return apply(_TOSSIM.MAC_low,args)
-    def symbolsPerSec(*args): return apply(_TOSSIM.MAC_symbolsPerSec,args)
-    def bitsPerSymbol(*args): return apply(_TOSSIM.MAC_bitsPerSymbol,args)
-    def preambleLength(*args): return apply(_TOSSIM.MAC_preambleLength,args)
-    def exponentBase(*args): return apply(_TOSSIM.MAC_exponentBase,args)
-    def maxIterations(*args): return apply(_TOSSIM.MAC_maxIterations,args)
-    def minFreeSamples(*args): return apply(_TOSSIM.MAC_minFreeSamples,args)
-    def rxtxDelay(*args): return apply(_TOSSIM.MAC_rxtxDelay,args)
-    def ackTime(*args): return apply(_TOSSIM.MAC_ackTime,args)
-    def setInitHigh(*args): return apply(_TOSSIM.MAC_setInitHigh,args)
-    def setInitLow(*args): return apply(_TOSSIM.MAC_setInitLow,args)
-    def setHigh(*args): return apply(_TOSSIM.MAC_setHigh,args)
-    def setLow(*args): return apply(_TOSSIM.MAC_setLow,args)
-    def setSymbolsPerSec(*args): return apply(_TOSSIM.MAC_setSymbolsPerSec,args)
-    def setBitsBerSymbol(*args): return apply(_TOSSIM.MAC_setBitsBerSymbol,args)
-    def setPreambleLength(*args): return apply(_TOSSIM.MAC_setPreambleLength,args)
-    def setExponentBase(*args): return apply(_TOSSIM.MAC_setExponentBase,args)
-    def setMaxIterations(*args): return apply(_TOSSIM.MAC_setMaxIterations,args)
-    def setMinFreeSamples(*args): return apply(_TOSSIM.MAC_setMinFreeSamples,args)
-    def setRxtxDelay(*args): return apply(_TOSSIM.MAC_setRxtxDelay,args)
-    def setAckTime(*args): return apply(_TOSSIM.MAC_setAckTime,args)
-    def __repr__(self):
-        return "<C MAC instance at %s>" % (self.this,)
-
-class MACPtr(MAC):
-    def __init__(self,this):
-        _swig_setattr(self, MAC, 'this', this)
-        if not hasattr(self,"thisown"): _swig_setattr(self, MAC, 'thisown', 0)
-        _swig_setattr(self, MAC,self.__class__,MAC)
-_TOSSIM.MAC_swigregister(MACPtr)
+    __repr__ = _swig_repr
+    def __init__(self, *args): 
+        this = _TOSSIM.new_MAC(*args)
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _TOSSIM.delete_MAC
+    __del__ = lambda self : None;
+    def initHigh(*args): return _TOSSIM.MAC_initHigh(*args)
+    def initLow(*args): return _TOSSIM.MAC_initLow(*args)
+    def high(*args): return _TOSSIM.MAC_high(*args)
+    def low(*args): return _TOSSIM.MAC_low(*args)
+    def symbolsPerSec(*args): return _TOSSIM.MAC_symbolsPerSec(*args)
+    def bitsPerSymbol(*args): return _TOSSIM.MAC_bitsPerSymbol(*args)
+    def preambleLength(*args): return _TOSSIM.MAC_preambleLength(*args)
+    def exponentBase(*args): return _TOSSIM.MAC_exponentBase(*args)
+    def maxIterations(*args): return _TOSSIM.MAC_maxIterations(*args)
+    def minFreeSamples(*args): return _TOSSIM.MAC_minFreeSamples(*args)
+    def rxtxDelay(*args): return _TOSSIM.MAC_rxtxDelay(*args)
+    def ackTime(*args): return _TOSSIM.MAC_ackTime(*args)
+    def setInitHigh(*args): return _TOSSIM.MAC_setInitHigh(*args)
+    def setInitLow(*args): return _TOSSIM.MAC_setInitLow(*args)
+    def setHigh(*args): return _TOSSIM.MAC_setHigh(*args)
+    def setLow(*args): return _TOSSIM.MAC_setLow(*args)
+    def setSymbolsPerSec(*args): return _TOSSIM.MAC_setSymbolsPerSec(*args)
+    def setBitsBerSymbol(*args): return _TOSSIM.MAC_setBitsBerSymbol(*args)
+    def setPreambleLength(*args): return _TOSSIM.MAC_setPreambleLength(*args)
+    def setExponentBase(*args): return _TOSSIM.MAC_setExponentBase(*args)
+    def setMaxIterations(*args): return _TOSSIM.MAC_setMaxIterations(*args)
+    def setMinFreeSamples(*args): return _TOSSIM.MAC_setMinFreeSamples(*args)
+    def setRxtxDelay(*args): return _TOSSIM.MAC_setRxtxDelay(*args)
+    def setAckTime(*args): return _TOSSIM.MAC_setAckTime(*args)
+MAC_swigregister = _TOSSIM.MAC_swigregister
+MAC_swigregister(MAC)
 
 class Radio(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, Radio, name, value)
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, Radio, name)
-    def __init__(self,*args):
-        _swig_setattr(self, Radio, 'this', apply(_TOSSIM.new_Radio,args))
-        _swig_setattr(self, Radio, 'thisown', 1)
-    def __del__(self, destroy= _TOSSIM.delete_Radio):
-        try:
-            if self.thisown: destroy(self)
-        except: pass
-    def add(*args): return apply(_TOSSIM.Radio_add,args)
-    def gain(*args): return apply(_TOSSIM.Radio_gain,args)
-    def connected(*args): return apply(_TOSSIM.Radio_connected,args)
-    def remove(*args): return apply(_TOSSIM.Radio_remove,args)
-    def setNoise(*args): return apply(_TOSSIM.Radio_setNoise,args)
-    def setSensitivity(*args): return apply(_TOSSIM.Radio_setSensitivity,args)
-    def __repr__(self):
-        return "<C Radio instance at %s>" % (self.this,)
-
-class RadioPtr(Radio):
-    def __init__(self,this):
-        _swig_setattr(self, Radio, 'this', this)
-        if not hasattr(self,"thisown"): _swig_setattr(self, Radio, 'thisown', 0)
-        _swig_setattr(self, Radio,self.__class__,Radio)
-_TOSSIM.Radio_swigregister(RadioPtr)
+    __repr__ = _swig_repr
+    def __init__(self, *args): 
+        this = _TOSSIM.new_Radio(*args)
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _TOSSIM.delete_Radio
+    __del__ = lambda self : None;
+    def add(*args): return _TOSSIM.Radio_add(*args)
+    def gain(*args): return _TOSSIM.Radio_gain(*args)
+    def connected(*args): return _TOSSIM.Radio_connected(*args)
+    def remove(*args): return _TOSSIM.Radio_remove(*args)
+    def setNoise(*args): return _TOSSIM.Radio_setNoise(*args)
+    def setSensitivity(*args): return _TOSSIM.Radio_setSensitivity(*args)
+Radio_swigregister = _TOSSIM.Radio_swigregister
+Radio_swigregister(Radio)
 
 class Packet(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, Packet, name, value)
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, Packet, name)
-    def __init__(self,*args):
-        _swig_setattr(self, Packet, 'this', apply(_TOSSIM.new_Packet,args))
-        _swig_setattr(self, Packet, 'thisown', 1)
-    def __del__(self, destroy= _TOSSIM.delete_Packet):
-        try:
-            if self.thisown: destroy(self)
-        except: pass
-    def setSource(*args): return apply(_TOSSIM.Packet_setSource,args)
-    def source(*args): return apply(_TOSSIM.Packet_source,args)
-    def setDestination(*args): return apply(_TOSSIM.Packet_setDestination,args)
-    def destination(*args): return apply(_TOSSIM.Packet_destination,args)
-    def setLength(*args): return apply(_TOSSIM.Packet_setLength,args)
-    def length(*args): return apply(_TOSSIM.Packet_length,args)
-    def setType(*args): return apply(_TOSSIM.Packet_setType,args)
-    def type(*args): return apply(_TOSSIM.Packet_type,args)
-    def data(*args): return apply(_TOSSIM.Packet_data,args)
-    def setData(*args): return apply(_TOSSIM.Packet_setData,args)
-    def maxLength(*args): return apply(_TOSSIM.Packet_maxLength,args)
-    def setStrength(*args): return apply(_TOSSIM.Packet_setStrength,args)
-    def deliver(*args): return apply(_TOSSIM.Packet_deliver,args)
-    def deliverNow(*args): return apply(_TOSSIM.Packet_deliverNow,args)
-    def __repr__(self):
-        return "<C Packet instance at %s>" % (self.this,)
-
-class PacketPtr(Packet):
-    def __init__(self,this):
-        _swig_setattr(self, Packet, 'this', this)
-        if not hasattr(self,"thisown"): _swig_setattr(self, Packet, 'thisown', 0)
-        _swig_setattr(self, Packet,self.__class__,Packet)
-_TOSSIM.Packet_swigregister(PacketPtr)
+    __repr__ = _swig_repr
+    def __init__(self, *args): 
+        this = _TOSSIM.new_Packet(*args)
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _TOSSIM.delete_Packet
+    __del__ = lambda self : None;
+    def setSource(*args): return _TOSSIM.Packet_setSource(*args)
+    def source(*args): return _TOSSIM.Packet_source(*args)
+    def setDestination(*args): return _TOSSIM.Packet_setDestination(*args)
+    def destination(*args): return _TOSSIM.Packet_destination(*args)
+    def setLength(*args): return _TOSSIM.Packet_setLength(*args)
+    def length(*args): return _TOSSIM.Packet_length(*args)
+    def setType(*args): return _TOSSIM.Packet_setType(*args)
+    def type(*args): return _TOSSIM.Packet_type(*args)
+    def data(*args): return _TOSSIM.Packet_data(*args)
+    def setData(*args): return _TOSSIM.Packet_setData(*args)
+    def maxLength(*args): return _TOSSIM.Packet_maxLength(*args)
+    def setStrength(*args): return _TOSSIM.Packet_setStrength(*args)
+    def deliver(*args): return _TOSSIM.Packet_deliver(*args)
+    def deliverNow(*args): return _TOSSIM.Packet_deliverNow(*args)
+Packet_swigregister = _TOSSIM.Packet_swigregister
+Packet_swigregister(Packet)
 
 class variable_string_t(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, variable_string_t, name, value)
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, variable_string_t, name)
+    __repr__ = _swig_repr
     __swig_setmethods__["type"] = _TOSSIM.variable_string_t_type_set
     __swig_getmethods__["type"] = _TOSSIM.variable_string_t_type_get
-    if _newclass:type = property(_TOSSIM.variable_string_t_type_get,_TOSSIM.variable_string_t_type_set)
+    if _newclass:type = _swig_property(_TOSSIM.variable_string_t_type_get, _TOSSIM.variable_string_t_type_set)
     __swig_setmethods__["ptr"] = _TOSSIM.variable_string_t_ptr_set
     __swig_getmethods__["ptr"] = _TOSSIM.variable_string_t_ptr_get
-    if _newclass:ptr = property(_TOSSIM.variable_string_t_ptr_get,_TOSSIM.variable_string_t_ptr_set)
+    if _newclass:ptr = _swig_property(_TOSSIM.variable_string_t_ptr_get, _TOSSIM.variable_string_t_ptr_set)
     __swig_setmethods__["len"] = _TOSSIM.variable_string_t_len_set
     __swig_getmethods__["len"] = _TOSSIM.variable_string_t_len_get
-    if _newclass:len = property(_TOSSIM.variable_string_t_len_get,_TOSSIM.variable_string_t_len_set)
+    if _newclass:len = _swig_property(_TOSSIM.variable_string_t_len_get, _TOSSIM.variable_string_t_len_set)
     __swig_setmethods__["isArray"] = _TOSSIM.variable_string_t_isArray_set
     __swig_getmethods__["isArray"] = _TOSSIM.variable_string_t_isArray_get
-    if _newclass:isArray = property(_TOSSIM.variable_string_t_isArray_get,_TOSSIM.variable_string_t_isArray_set)
-    def __init__(self,*args):
-        _swig_setattr(self, variable_string_t, 'this', apply(_TOSSIM.new_variable_string_t,args))
-        _swig_setattr(self, variable_string_t, 'thisown', 1)
-    def __del__(self, destroy= _TOSSIM.delete_variable_string_t):
-        try:
-            if self.thisown: destroy(self)
-        except: pass
-    def __repr__(self):
-        return "<C variable_string_t instance at %s>" % (self.this,)
-
-class variable_string_tPtr(variable_string_t):
-    def __init__(self,this):
-        _swig_setattr(self, variable_string_t, 'this', this)
-        if not hasattr(self,"thisown"): _swig_setattr(self, variable_string_t, 'thisown', 0)
-        _swig_setattr(self, variable_string_t,self.__class__,variable_string_t)
-_TOSSIM.variable_string_t_swigregister(variable_string_tPtr)
+    if _newclass:isArray = _swig_property(_TOSSIM.variable_string_t_isArray_get, _TOSSIM.variable_string_t_isArray_set)
+    def __init__(self, *args): 
+        this = _TOSSIM.new_variable_string_t(*args)
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _TOSSIM.delete_variable_string_t
+    __del__ = lambda self : None;
+variable_string_t_swigregister = _TOSSIM.variable_string_t_swigregister
+variable_string_t_swigregister(variable_string_t)
 
 class nesc_app_t(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, nesc_app_t, name, value)
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, nesc_app_t, name)
+    __repr__ = _swig_repr
     __swig_setmethods__["numVariables"] = _TOSSIM.nesc_app_t_numVariables_set
     __swig_getmethods__["numVariables"] = _TOSSIM.nesc_app_t_numVariables_get
-    if _newclass:numVariables = property(_TOSSIM.nesc_app_t_numVariables_get,_TOSSIM.nesc_app_t_numVariables_set)
+    if _newclass:numVariables = _swig_property(_TOSSIM.nesc_app_t_numVariables_get, _TOSSIM.nesc_app_t_numVariables_set)
     __swig_setmethods__["variableNames"] = _TOSSIM.nesc_app_t_variableNames_set
     __swig_getmethods__["variableNames"] = _TOSSIM.nesc_app_t_variableNames_get
-    if _newclass:variableNames = property(_TOSSIM.nesc_app_t_variableNames_get,_TOSSIM.nesc_app_t_variableNames_set)
+    if _newclass:variableNames = _swig_property(_TOSSIM.nesc_app_t_variableNames_get, _TOSSIM.nesc_app_t_variableNames_set)
     __swig_setmethods__["variableTypes"] = _TOSSIM.nesc_app_t_variableTypes_set
     __swig_getmethods__["variableTypes"] = _TOSSIM.nesc_app_t_variableTypes_get
-    if _newclass:variableTypes = property(_TOSSIM.nesc_app_t_variableTypes_get,_TOSSIM.nesc_app_t_variableTypes_set)
+    if _newclass:variableTypes = _swig_property(_TOSSIM.nesc_app_t_variableTypes_get, _TOSSIM.nesc_app_t_variableTypes_set)
     __swig_setmethods__["variableArray"] = _TOSSIM.nesc_app_t_variableArray_set
     __swig_getmethods__["variableArray"] = _TOSSIM.nesc_app_t_variableArray_get
-    if _newclass:variableArray = property(_TOSSIM.nesc_app_t_variableArray_get,_TOSSIM.nesc_app_t_variableArray_set)
-    def __init__(self,*args):
-        _swig_setattr(self, nesc_app_t, 'this', apply(_TOSSIM.new_nesc_app_t,args))
-        _swig_setattr(self, nesc_app_t, 'thisown', 1)
-    def __del__(self, destroy= _TOSSIM.delete_nesc_app_t):
-        try:
-            if self.thisown: destroy(self)
-        except: pass
-    def __repr__(self):
-        return "<C nesc_app_t instance at %s>" % (self.this,)
-
-class nesc_app_tPtr(nesc_app_t):
-    def __init__(self,this):
-        _swig_setattr(self, nesc_app_t, 'this', this)
-        if not hasattr(self,"thisown"): _swig_setattr(self, nesc_app_t, 'thisown', 0)
-        _swig_setattr(self, nesc_app_t,self.__class__,nesc_app_t)
-_TOSSIM.nesc_app_t_swigregister(nesc_app_tPtr)
+    if _newclass:variableArray = _swig_property(_TOSSIM.nesc_app_t_variableArray_get, _TOSSIM.nesc_app_t_variableArray_set)
+    def __init__(self, *args): 
+        this = _TOSSIM.new_nesc_app_t(*args)
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _TOSSIM.delete_nesc_app_t
+    __del__ = lambda self : None;
+nesc_app_t_swigregister = _TOSSIM.nesc_app_t_swigregister
+nesc_app_t_swigregister(nesc_app_t)
 
 class Variable(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, Variable, name, value)
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, Variable, name)
-    def __init__(self,*args):
-        _swig_setattr(self, Variable, 'this', apply(_TOSSIM.new_Variable,args))
-        _swig_setattr(self, Variable, 'thisown', 1)
-    def __del__(self, destroy= _TOSSIM.delete_Variable):
-        try:
-            if self.thisown: destroy(self)
-        except: pass
-    def getData(*args): return apply(_TOSSIM.Variable_getData,args)
-    def __repr__(self):
-        return "<C Variable instance at %s>" % (self.this,)
-
-class VariablePtr(Variable):
-    def __init__(self,this):
-        _swig_setattr(self, Variable, 'this', this)
-        if not hasattr(self,"thisown"): _swig_setattr(self, Variable, 'thisown', 0)
-        _swig_setattr(self, Variable,self.__class__,Variable)
-_TOSSIM.Variable_swigregister(VariablePtr)
+    __repr__ = _swig_repr
+    def __init__(self, *args): 
+        this = _TOSSIM.new_Variable(*args)
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _TOSSIM.delete_Variable
+    __del__ = lambda self : None;
+    def getData(*args): return _TOSSIM.Variable_getData(*args)
+Variable_swigregister = _TOSSIM.Variable_swigregister
+Variable_swigregister(Variable)
 
 class Mote(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, Mote, name, value)
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, Mote, name)
-    def __init__(self,*args):
-        _swig_setattr(self, Mote, 'this', apply(_TOSSIM.new_Mote,args))
-        _swig_setattr(self, Mote, 'thisown', 1)
-    def __del__(self, destroy= _TOSSIM.delete_Mote):
-        try:
-            if self.thisown: destroy(self)
-        except: pass
-    def id(*args): return apply(_TOSSIM.Mote_id,args)
-    def euid(*args): return apply(_TOSSIM.Mote_euid,args)
-    def setEuid(*args): return apply(_TOSSIM.Mote_setEuid,args)
-    def bootTime(*args): return apply(_TOSSIM.Mote_bootTime,args)
-    def bootAtTime(*args): return apply(_TOSSIM.Mote_bootAtTime,args)
-    def isOn(*args): return apply(_TOSSIM.Mote_isOn,args)
-    def turnOff(*args): return apply(_TOSSIM.Mote_turnOff,args)
-    def turnOn(*args): return apply(_TOSSIM.Mote_turnOn,args)
-    def getVariable(*args): return apply(_TOSSIM.Mote_getVariable,args)
-    def addNoiseTraceReading(*args): return apply(_TOSSIM.Mote_addNoiseTraceReading,args)
-    def createNoiseModel(*args): return apply(_TOSSIM.Mote_createNoiseModel,args)
-    def generateNoise(*args): return apply(_TOSSIM.Mote_generateNoise,args)
-    def __repr__(self):
-        return "<C Mote instance at %s>" % (self.this,)
-
-class MotePtr(Mote):
-    def __init__(self,this):
-        _swig_setattr(self, Mote, 'this', this)
-        if not hasattr(self,"thisown"): _swig_setattr(self, Mote, 'thisown', 0)
-        _swig_setattr(self, Mote,self.__class__,Mote)
-_TOSSIM.Mote_swigregister(MotePtr)
+    __repr__ = _swig_repr
+    def __init__(self, *args): 
+        this = _TOSSIM.new_Mote(*args)
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _TOSSIM.delete_Mote
+    __del__ = lambda self : None;
+    def id(*args): return _TOSSIM.Mote_id(*args)
+    def euid(*args): return _TOSSIM.Mote_euid(*args)
+    def setEuid(*args): return _TOSSIM.Mote_setEuid(*args)
+    def bootTime(*args): return _TOSSIM.Mote_bootTime(*args)
+    def bootAtTime(*args): return _TOSSIM.Mote_bootAtTime(*args)
+    def isOn(*args): return _TOSSIM.Mote_isOn(*args)
+    def turnOff(*args): return _TOSSIM.Mote_turnOff(*args)
+    def turnOn(*args): return _TOSSIM.Mote_turnOn(*args)
+    def getVariable(*args): return _TOSSIM.Mote_getVariable(*args)
+    def addNoiseTraceReading(*args): return _TOSSIM.Mote_addNoiseTraceReading(*args)
+    def createNoiseModel(*args): return _TOSSIM.Mote_createNoiseModel(*args)
+    def generateNoise(*args): return _TOSSIM.Mote_generateNoise(*args)
+Mote_swigregister = _TOSSIM.Mote_swigregister
+Mote_swigregister(Mote)
 
 class Tossim(_object):
     __swig_setmethods__ = {}
     __setattr__ = lambda self, name, value: _swig_setattr(self, Tossim, name, value)
     __swig_getmethods__ = {}
     __getattr__ = lambda self, name: _swig_getattr(self, Tossim, name)
-    def __init__(self,*args):
-        _swig_setattr(self, Tossim, 'this', apply(_TOSSIM.new_Tossim,args))
-        _swig_setattr(self, Tossim, 'thisown', 1)
-    def __del__(self, destroy= _TOSSIM.delete_Tossim):
-        try:
-            if self.thisown: destroy(self)
-        except: pass
-    def init(*args): return apply(_TOSSIM.Tossim_init,args)
-    def time(*args): return apply(_TOSSIM.Tossim_time,args)
-    def ticksPerSecond(*args): return apply(_TOSSIM.Tossim_ticksPerSecond,args)
-    def setTime(*args): return apply(_TOSSIM.Tossim_setTime,args)
-    def timeStr(*args): return apply(_TOSSIM.Tossim_timeStr,args)
-    def currentNode(*args): return apply(_TOSSIM.Tossim_currentNode,args)
-    def getNode(*args): return apply(_TOSSIM.Tossim_getNode,args)
-    def setCurrentNode(*args): return apply(_TOSSIM.Tossim_setCurrentNode,args)
-    def addChannel(*args): return apply(_TOSSIM.Tossim_addChannel,args)
-    def removeChannel(*args): return apply(_TOSSIM.Tossim_removeChannel,args)
-    def randomSeed(*args): return apply(_TOSSIM.Tossim_randomSeed,args)
-    def runNextEvent(*args): return apply(_TOSSIM.Tossim_runNextEvent,args)
-    def mac(*args): return apply(_TOSSIM.Tossim_mac,args)
-    def radio(*args): return apply(_TOSSIM.Tossim_radio,args)
-    def newPacket(*args): return apply(_TOSSIM.Tossim_newPacket,args)
-    def __repr__(self):
-        return "<C Tossim instance at %s>" % (self.this,)
+    __repr__ = _swig_repr
+    def __init__(self, *args): 
+        this = _TOSSIM.new_Tossim(*args)
+        try: self.this.append(this)
+        except: self.this = this
+    __swig_destroy__ = _TOSSIM.delete_Tossim
+    __del__ = lambda self : None;
+    def init(*args): return _TOSSIM.Tossim_init(*args)
+    def time(*args): return _TOSSIM.Tossim_time(*args)
+    def ticksPerSecond(*args): return _TOSSIM.Tossim_ticksPerSecond(*args)
+    def setTime(*args): return _TOSSIM.Tossim_setTime(*args)
+    def timeStr(*args): return _TOSSIM.Tossim_timeStr(*args)
+    def currentNode(*args): return _TOSSIM.Tossim_currentNode(*args)
+    def getNode(*args): return _TOSSIM.Tossim_getNode(*args)
+    def setCurrentNode(*args): return _TOSSIM.Tossim_setCurrentNode(*args)
+    def addChannel(*args): return _TOSSIM.Tossim_addChannel(*args)
+    def removeChannel(*args): return _TOSSIM.Tossim_removeChannel(*args)
+    def randomSeed(*args): return _TOSSIM.Tossim_randomSeed(*args)
+    def runNextEvent(*args): return _TOSSIM.Tossim_runNextEvent(*args)
+    def mac(*args): return _TOSSIM.Tossim_mac(*args)
+    def radio(*args): return _TOSSIM.Tossim_radio(*args)
+    def newPacket(*args): return _TOSSIM.Tossim_newPacket(*args)
+Tossim_swigregister = _TOSSIM.Tossim_swigregister
+Tossim_swigregister(Tossim)
 
-class TossimPtr(Tossim):
-    def __init__(self,this):
-        _swig_setattr(self, Tossim, 'this', this)
-        if not hasattr(self,"thisown"): _swig_setattr(self, Tossim, 'thisown', 0)
-        _swig_setattr(self, Tossim,self.__class__,Tossim)
-_TOSSIM.Tossim_swigregister(TossimPtr)
 
 
index 42f3f3443907b234f90098b1e013ce4e2e8eb984..f887efca2ce27ca22f1ff8f0f94f970bb4baf9b6 100644 (file)
@@ -214,6 +214,7 @@ implementation {
       delay *= (sim_ticks_per_sec() / sim_csma_symbols_per_sec());
       evt->time += delay;
       transmitting = TRUE;
+      call GainRadioModel.setPendingTransmission();
       evt->handle = send_transmit;
       sim_queue_insert(evt);
     }
index 5011855f0414fb97b30ce1d6d8a6072ba92a0ca9..74283ccfe6c923ce03992b9e3f7a050eb03ff0a8 100644 (file)
@@ -113,8 +113,8 @@ variable_string_t Variable::getData() {
     memcpy(data, ptr, len);
   }
   else {
-    str.ptr = "<no such variable>";
-    str.type = "<no such variable>";
+    str.ptr = (char*)"<no such variable>";
+    str.type = (char*)"<no such variable>";
     str.len = strlen("<no such variable>");
     str.isArray = 0;
   }
@@ -166,7 +166,7 @@ void Mote::setID(unsigned long val) {
 }
 
 Variable* Mote::getVariable(char* name) {
-  char* typeStr = "";
+  char* typeStr = (char*)"";
   int isArray;
   Variable* var;
   
index 49ec978850b9d30fea75e8ed404ebeb0df74947b..5735a1d5513d62efe7e1adf723255b77a0f4bc77 100644 (file)
@@ -298,8 +298,8 @@ PyObject* listFromArray(char* type, char* ptr, int len) {
         }
       }
       else {
-        app->variableNames[i] = "<bad string>";
-        app->variableTypes[i] = "<bad string>";
+        app->variableNames[i] = (char*)"<bad string>";
+        app->variableTypes[i] = (char*)"<bad string>";
       }
     }
 
index 92c30d107ad1b3edde49bb36b6320f5055947b3f..88071362ac24fd03feff6028a674226a604b731b 100644 (file)
@@ -1,6 +1,6 @@
 /* ----------------------------------------------------------------------------
  * This file was automatically generated by SWIG (http://www.swig.org).
- * Version 1.3.19
+ * Version 1.3.33
  * 
  * This file is not intended to be easily readable and contains a number of 
  * coding conventions designed to improve portability and efficiency. Do not make
  * ----------------------------------------------------------------------------- */
 
 #define SWIGPYTHON
+#define SWIG_PYTHON_DIRECTOR_NO_VTABLE
 
 #ifdef __cplusplus
-template<class T> class SwigValueWrapper {
+template<typename T> class SwigValueWrapper {
     T *tt;
 public:
-    inline SwigValueWrapper() : tt(0) { }
-    inline ~SwigValueWrapper() { if (tt) delete tt; } 
-    inline SwigValueWrapper& operator=(const T& t) { tt = new T(t); return *this; }
-    inline operator T&() const { return *tt; }
-    inline T *operator&() { return tt; }
-};                                                    
+    SwigValueWrapper() : tt(0) { }
+    SwigValueWrapper(const SwigValueWrapper<T>& rhs) : tt(new T(*rhs.tt)) { }
+    SwigValueWrapper(const T& t) : tt(new T(t)) { }
+    ~SwigValueWrapper() { delete tt; } 
+    SwigValueWrapper& operator=(const T& t) { delete tt; tt = new T(t); return *this; }
+    operator T&() const { return *tt; }
+    T *operator&() { return tt; }
+private:
+    SwigValueWrapper& operator=(const SwigValueWrapper<T>& rhs);
+};
+
+template <typename T> T SwigValueInit() {
+  return T();
+}
 #endif
 
+/* -----------------------------------------------------------------------------
+ *  This section contains generic SWIG labels for method/variable
+ *  declarations/attributes, and other compiler dependent labels.
+ * ----------------------------------------------------------------------------- */
 
-#include "Python.h"
+/* template workaround for compilers that cannot correctly implement the C++ standard */
+#ifndef SWIGTEMPLATEDISAMBIGUATOR
+# if defined(__SUNPRO_CC) && (__SUNPRO_CC <= 0x560)
+#  define SWIGTEMPLATEDISAMBIGUATOR template
+# elif defined(__HP_aCC)
+/* Needed even with `aCC -AA' when `aCC -V' reports HP ANSI C++ B3910B A.03.55 */
+/* If we find a maximum version that requires this, the test would be __HP_aCC <= 35500 for A.03.55 */
+#  define SWIGTEMPLATEDISAMBIGUATOR template
+# else
+#  define SWIGTEMPLATEDISAMBIGUATOR
+# endif
+#endif
 
-/***********************************************************************
- * common.swg
- *
- *     This file contains generic SWIG runtime support for pointer
- *     type checking as well as a few commonly used macros to control
- *     external linkage.
- *
- * Author : David Beazley (beazley@cs.uchicago.edu)
- *
- * Copyright (c) 1999-2000, The University of Chicago
- * 
- * This file may be freely redistributed without license or fee provided
- * this copyright message remains intact.
- ************************************************************************/
+/* inline attribute */
+#ifndef SWIGINLINE
+# if defined(__cplusplus) || (defined(__GNUC__) && !defined(__STRICT_ANSI__))
+#   define SWIGINLINE inline
+# else
+#   define SWIGINLINE
+# endif
+#endif
 
-#include <string.h>
+/* attribute recognised by some compilers to avoid 'unused' warnings */
+#ifndef SWIGUNUSED
+# if defined(__GNUC__)
+#   if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
+#     define SWIGUNUSED __attribute__ ((__unused__)) 
+#   else
+#     define SWIGUNUSED
+#   endif
+# elif defined(__ICC)
+#   define SWIGUNUSED __attribute__ ((__unused__)) 
+# else
+#   define SWIGUNUSED 
+# endif
+#endif
 
-#if defined(_WIN32) || defined(__WIN32__)
-#       if defined(_MSC_VER)
-#               if defined(STATIC_LINKED)
-#                       define SWIGEXPORT(a) a
-#                       define SWIGIMPORT(a) extern a
-#               else
-#                       define SWIGEXPORT(a) __declspec(dllexport) a
-#                       define SWIGIMPORT(a) extern a
-#               endif
-#       else
-#               if defined(__BORLANDC__)
-#                       define SWIGEXPORT(a) a _export
-#                       define SWIGIMPORT(a) a _export
-#               else
-#                       define SWIGEXPORT(a) a
-#                       define SWIGIMPORT(a) a
-#               endif
-#       endif
-#else
-#       define SWIGEXPORT(a) a
-#       define SWIGIMPORT(a) a
+#ifndef SWIGUNUSEDPARM
+# ifdef __cplusplus
+#   define SWIGUNUSEDPARM(p)
+# else
+#   define SWIGUNUSEDPARM(p) p SWIGUNUSED 
+# endif
 #endif
 
-#ifdef SWIG_GLOBAL
-#define SWIGRUNTIME(a) SWIGEXPORT(a)
-#else
-#define SWIGRUNTIME(a) static a
+/* internal SWIG method */
+#ifndef SWIGINTERN
+# define SWIGINTERN static SWIGUNUSED
 #endif
 
-#ifdef __cplusplus
-extern "C" {
+/* internal inline SWIG method */
+#ifndef SWIGINTERNINLINE
+# define SWIGINTERNINLINE SWIGINTERN SWIGINLINE
 #endif
 
-typedef void *(*swig_converter_func)(void *);
-typedef struct swig_type_info *(*swig_dycast_func)(void **);
+/* exporting methods */
+#if (__GNUC__ >= 4) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
+#  ifndef GCC_HASCLASSVISIBILITY
+#    define GCC_HASCLASSVISIBILITY
+#  endif
+#endif
 
-typedef struct swig_type_info {
-  const char             *name;                 
-  swig_converter_func     converter;
-  const char             *str;
-  void                   *clientdata;  
-  swig_dycast_func        dcast;
-  struct swig_type_info  *next;
-  struct swig_type_info  *prev;
-} swig_type_info;
+#ifndef SWIGEXPORT
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   if defined(STATIC_LINKED)
+#     define SWIGEXPORT
+#   else
+#     define SWIGEXPORT __declspec(dllexport)
+#   endif
+# else
+#   if defined(__GNUC__) && defined(GCC_HASCLASSVISIBILITY)
+#     define SWIGEXPORT __attribute__ ((visibility("default")))
+#   else
+#     define SWIGEXPORT
+#   endif
+# endif
+#endif
 
-#ifdef SWIG_NOINCLUDE
+/* calling conventions for Windows */
+#ifndef SWIGSTDCALL
+# if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#   define SWIGSTDCALL __stdcall
+# else
+#   define SWIGSTDCALL
+# endif 
+#endif
 
-SWIGIMPORT(swig_type_info *) SWIG_TypeRegister(swig_type_info *);
-SWIGIMPORT(swig_type_info *) SWIG_TypeCheck(char *c, swig_type_info *);
-SWIGIMPORT(void *)           SWIG_TypeCast(swig_type_info *, void *);
-SWIGIMPORT(swig_type_info *) SWIG_TypeDynamicCast(swig_type_info *, void **);
-SWIGIMPORT(const char *)     SWIG_TypeName(const swig_type_info *);
-SWIGIMPORT(swig_type_info *) SWIG_TypeQuery(const char *);
-SWIGIMPORT(void)             SWIG_TypeClientData(swig_type_info *, void *);
+/* Deal with Microsoft's attempt at deprecating C standard runtime functions */
+#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
+# define _CRT_SECURE_NO_DEPRECATE
+#endif
 
-#else
+/* Deal with Microsoft's attempt at deprecating methods in the standard C++ library */
+#if !defined(SWIG_NO_SCL_SECURE_NO_DEPRECATE) && defined(_MSC_VER) && !defined(_SCL_SECURE_NO_DEPRECATE)
+# define _SCL_SECURE_NO_DEPRECATE
+#endif
 
-static swig_type_info *swig_type_list = 0;
 
-/* Register a type mapping with the type-checking */
-SWIGRUNTIME(swig_type_info *)
-SWIG_TypeRegister(swig_type_info *ti)
-{
-  swig_type_info *tc, *head, *ret, *next;
-  /* Check to see if this type has already been registered */
-  tc = swig_type_list;
-  while (tc) {
-    if (strcmp(tc->name, ti->name) == 0) {
-      /* Already exists in the table.  Just add additional types to the list */
-      if (tc->clientdata) ti->clientdata = tc->clientdata;     
-      head = tc;
-      next = tc->next;
-      goto l1;
-    }
-    tc = tc->prev;
-  }
-  head = ti;
-  next = 0;
-
-  /* Place in list */
-  ti->prev = swig_type_list;
-  swig_type_list = ti;
-
-  /* Build linked lists */
- l1:
-  ret = head;
-  tc = ti + 1;
-  /* Patch up the rest of the links */
-  while (tc->name) {
-    head->next = tc;
-    tc->prev = head;
-    head = tc;
-    tc++;
-  }
-  if (next) next->prev = head;  /**/
-  head->next = next;
-  return ret;
-}
-
-/* Check the typename */
-SWIGRUNTIME(swig_type_info *) 
-SWIG_TypeCheck(char *c, swig_type_info *ty)
-{
-  swig_type_info *s;
-  if (!ty) return 0;        /* Void pointer */
-  s = ty->next;             /* First element always just a name */
-  do {
-    if (strcmp(s->name,c) == 0) {
-      if (s == ty->next) return s;
-      /* Move s to the top of the linked list */
-      s->prev->next = s->next;
-      if (s->next) {
-       s->next->prev = s->prev;
-      }
-      /* Insert s as second element in the list */
-      s->next = ty->next;
-      if (ty->next) ty->next->prev = s;
-      ty->next = s;
-      s->prev = ty;  /**/
-      return s;
-    }
-    s = s->next;
-  } while (s && (s != ty->next));
-  return 0;
-}
 
-/* Cast a pointer up an inheritance hierarchy */
-SWIGRUNTIME(void *) 
-SWIG_TypeCast(swig_type_info *ty, void *ptr) 
-{
-  if ((!ty) || (!ty->converter)) return ptr;
-  return (*ty->converter)(ptr);
-}
+/* Python.h has to appear first */
+#include <Python.h>
 
-/* Dynamic pointer casting. Down an inheritance hierarchy */
-SWIGRUNTIME(swig_type_info *) 
-SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) 
-{
-  swig_type_info *lastty = ty;
-  if (!ty || !ty->dcast) return ty;
-  while (ty && (ty->dcast)) {
-     ty = (*ty->dcast)(ptr);
-     if (ty) lastty = ty;
-  }
-  return lastty;
-}
+/* -----------------------------------------------------------------------------
+ * swigrun.swg
+ *
+ * This file contains generic CAPI SWIG runtime support for pointer
+ * type checking.
+ * ----------------------------------------------------------------------------- */
 
-/* Return the name associated with this type */
-SWIGRUNTIME(const char *)
-SWIG_TypeName(const swig_type_info *ty) {
-  return ty->name;
-}
+/* This should only be incremented when either the layout of swig_type_info changes,
+   or for whatever reason, the runtime changes incompatibly */
+#define SWIG_RUNTIME_VERSION "3"
 
-/* Search for a swig_type_info structure */
-SWIGRUNTIME(swig_type_info *)
-SWIG_TypeQuery(const char *name) {
-  swig_type_info *ty = swig_type_list;
-  while (ty) {
-    if (ty->str && (strcmp(name,ty->str) == 0)) return ty;
-    if (ty->name && (strcmp(name,ty->name) == 0)) return ty;
-    ty = ty->prev;
-  }
-  return 0;
-}
+/* define SWIG_TYPE_TABLE_NAME as "SWIG_TYPE_TABLE" */
+#ifdef SWIG_TYPE_TABLE
+# define SWIG_QUOTE_STRING(x) #x
+# define SWIG_EXPAND_AND_QUOTE_STRING(x) SWIG_QUOTE_STRING(x)
+# define SWIG_TYPE_TABLE_NAME SWIG_EXPAND_AND_QUOTE_STRING(SWIG_TYPE_TABLE)
+#else
+# define SWIG_TYPE_TABLE_NAME
+#endif
 
-/* Set the clientdata field for a type */
-SWIGRUNTIME(void)
-SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
-  swig_type_info *tc, *equiv;
-  if (ti->clientdata == clientdata) return;
-  ti->clientdata = clientdata;
-  equiv = ti->next;
-  while (equiv) {
-    if (!equiv->converter) {
-      tc = swig_type_list;
-      while (tc) {
-       if ((strcmp(tc->name, equiv->name) == 0))
-         SWIG_TypeClientData(tc,clientdata);
-       tc = tc->prev;
-      }
-    }
-    equiv = equiv->next;
-  }
-}
+/*
+  You can use the SWIGRUNTIME and SWIGRUNTIMEINLINE macros for
+  creating a static or dynamic library from the swig runtime code.
+  In 99.9% of the cases, swig just needs to declare them as 'static'.
+  
+  But only do this if is strictly necessary, ie, if you have problems
+  with your compiler or so.
+*/
+
+#ifndef SWIGRUNTIME
+# define SWIGRUNTIME SWIGINTERN
 #endif
 
-#ifdef __cplusplus
-}
+#ifndef SWIGRUNTIMEINLINE
+# define SWIGRUNTIMEINLINE SWIGRUNTIME SWIGINLINE
+#endif
 
+/*  Generic buffer size */
+#ifndef SWIG_BUFFER_SIZE
+# define SWIG_BUFFER_SIZE 1024
 #endif
 
-/***********************************************************************
- * python.swg
- *
- *     This file contains the runtime support for Python modules
- *     and includes code for managing global variables and pointer
- *     type checking.
- *
- * Author : David Beazley (beazley@cs.uchicago.edu)
- ************************************************************************/
+/* Flags for pointer conversions */
+#define SWIG_POINTER_DISOWN        0x1
 
-#include "Python.h"
+/* Flags for new pointer objects */
+#define SWIG_POINTER_OWN           0x1
 
-#ifdef __cplusplus
-extern "C" {
+
+/* 
+   Flags/methods for returning states.
+   
+   The swig conversion methods, as ConvertPtr, return and integer 
+   that tells if the conversion was successful or not. And if not,
+   an error code can be returned (see swigerrors.swg for the codes).
+   
+   Use the following macros/flags to set or process the returning
+   states.
+   
+   In old swig versions, you usually write code as:
+
+     if (SWIG_ConvertPtr(obj,vptr,ty.flags) != -1) {
+       // success code
+     } else {
+       //fail code
+     }
+
+   Now you can be more explicit as:
+
+    int res = SWIG_ConvertPtr(obj,vptr,ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+    } else {
+      // fail code
+    }
+
+   that seems to be the same, but now you can also do
+
+    Type *ptr;
+    int res = SWIG_ConvertPtr(obj,(void **)(&ptr),ty.flags);
+    if (SWIG_IsOK(res)) {
+      // success code
+      if (SWIG_IsNewObj(res) {
+        ...
+       delete *ptr;
+      } else {
+        ...
+      }
+    } else {
+      // fail code
+    }
+    
+   I.e., now SWIG_ConvertPtr can return new objects and you can
+   identify the case and take care of the deallocation. Of course that
+   requires also to SWIG_ConvertPtr to return new result values, as
+
+      int SWIG_ConvertPtr(obj, ptr,...) {         
+        if (<obj is ok>) {                            
+          if (<need new object>) {                    
+            *ptr = <ptr to new allocated object>; 
+            return SWIG_NEWOBJ;                       
+          } else {                                    
+            *ptr = <ptr to old object>;               
+            return SWIG_OLDOBJ;                       
+          }                                   
+        } else {                                      
+          return SWIG_BADOBJ;                 
+        }                                             
+      }
+
+   Of course, returning the plain '0(success)/-1(fail)' still works, but you can be
+   more explicit by returning SWIG_BADOBJ, SWIG_ERROR or any of the
+   swig errors code.
+
+   Finally, if the SWIG_CASTRANK_MODE is enabled, the result code
+   allows to return the 'cast rank', for example, if you have this
+
+       int food(double)
+       int fooi(int);
+
+   and you call
+      food(1)   // cast rank '1'  (1 -> 1.0)
+      fooi(1)   // cast rank '0'
+
+   just use the SWIG_AddCast()/SWIG_CheckState()
+
+
+ */
+#define SWIG_OK                    (0) 
+#define SWIG_ERROR                 (-1)
+#define SWIG_IsOK(r)               (r >= 0)
+#define SWIG_ArgError(r)           ((r != SWIG_ERROR) ? r : SWIG_TypeError)  
+
+/* The CastRankLimit says how many bits are used for the cast rank */
+#define SWIG_CASTRANKLIMIT         (1 << 8)
+/* The NewMask denotes the object was created (using new/malloc) */
+#define SWIG_NEWOBJMASK            (SWIG_CASTRANKLIMIT  << 1)
+/* The TmpMask is for in/out typemaps that use temporal objects */
+#define SWIG_TMPOBJMASK            (SWIG_NEWOBJMASK << 1)
+/* Simple returning values */
+#define SWIG_BADOBJ                (SWIG_ERROR)
+#define SWIG_OLDOBJ                (SWIG_OK)
+#define SWIG_NEWOBJ                (SWIG_OK | SWIG_NEWOBJMASK)
+#define SWIG_TMPOBJ                (SWIG_OK | SWIG_TMPOBJMASK)
+/* Check, add and del mask methods */
+#define SWIG_AddNewMask(r)         (SWIG_IsOK(r) ? (r | SWIG_NEWOBJMASK) : r)
+#define SWIG_DelNewMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_NEWOBJMASK) : r)
+#define SWIG_IsNewObj(r)           (SWIG_IsOK(r) && (r & SWIG_NEWOBJMASK))
+#define SWIG_AddTmpMask(r)         (SWIG_IsOK(r) ? (r | SWIG_TMPOBJMASK) : r)
+#define SWIG_DelTmpMask(r)         (SWIG_IsOK(r) ? (r & ~SWIG_TMPOBJMASK) : r)
+#define SWIG_IsTmpObj(r)           (SWIG_IsOK(r) && (r & SWIG_TMPOBJMASK))
+
+
+/* Cast-Rank Mode */
+#if defined(SWIG_CASTRANK_MODE)
+#  ifndef SWIG_TypeRank
+#    define SWIG_TypeRank             unsigned long
+#  endif
+#  ifndef SWIG_MAXCASTRANK            /* Default cast allowed */
+#    define SWIG_MAXCASTRANK          (2)
+#  endif
+#  define SWIG_CASTRANKMASK          ((SWIG_CASTRANKLIMIT) -1)
+#  define SWIG_CastRank(r)           (r & SWIG_CASTRANKMASK)
+SWIGINTERNINLINE int SWIG_AddCast(int r) { 
+  return SWIG_IsOK(r) ? ((SWIG_CastRank(r) < SWIG_MAXCASTRANK) ? (r + 1) : SWIG_ERROR) : r;
+}
+SWIGINTERNINLINE int SWIG_CheckState(int r) { 
+  return SWIG_IsOK(r) ? SWIG_CastRank(r) + 1 : 0; 
+}
+#else /* no cast-rank mode */
+#  define SWIG_AddCast
+#  define SWIG_CheckState(r) (SWIG_IsOK(r) ? 1 : 0)
 #endif
 
-#define SWIG_PY_INT     1
-#define SWIG_PY_FLOAT   2
-#define SWIG_PY_STRING  3
-#define SWIG_PY_POINTER 4
-#define SWIG_PY_BINARY  5
 
-/* Flags for pointer conversion */
 
-#define SWIG_POINTER_EXCEPTION     0x1
-#define SWIG_POINTER_DISOWN        0x2
 
-/* Exception handling in wrappers */
-#define SWIG_fail   goto fail
+#include <string.h>
 
-/* Constant information structure */
-typedef struct swig_const_info {
-    int type;
-    char *name;
-    long lvalue;
-    double dvalue;
-    void   *pvalue;
-    swig_type_info **ptype;
-} swig_const_info;
+#ifdef __cplusplus
+extern "C" {
+#endif
 
-#ifdef SWIG_NOINCLUDE
-
-SWIGEXPORT(PyObject *)        SWIG_newvarlink(void);
-SWIGEXPORT(void)              SWIG_addvarlink(PyObject *, char *, PyObject *(*)(void), int (*)(PyObject *));
-SWIGEXPORT(int)               SWIG_ConvertPtr(PyObject *, void **, swig_type_info *, int);
-SWIGEXPORT(int)               SWIG_ConvertPacked(PyObject *, void *, int sz, swig_type_info *, int);
-SWIGEXPORT(char *)            SWIG_PackData(char *c, void *, int);
-SWIGEXPORT(char *)            SWIG_UnpackData(char *c, void *, int);
-SWIGEXPORT(PyObject *)        SWIG_NewPointerObj(void *, swig_type_info *,int own);
-SWIGEXPORT(PyObject *)        SWIG_NewPackedObj(void *, int sz, swig_type_info *);
-SWIGEXPORT(void)              SWIG_InstallConstants(PyObject *d, swig_const_info constants[]);
-#else
+typedef void *(*swig_converter_func)(void *);
+typedef struct swig_type_info *(*swig_dycast_func)(void **);
 
-/* -----------------------------------------------------------------------------
- * global variable support code.
- * ----------------------------------------------------------------------------- */
+/* Structure to store inforomation on one type */
+typedef struct swig_type_info {
+  const char             *name;                        /* mangled name of this type */
+  const char             *str;                 /* human readable name of this type */
+  swig_dycast_func        dcast;               /* dynamic cast function down a hierarchy */
+  struct swig_cast_info  *cast;                        /* linked list of types that can cast into this type */
+  void                   *clientdata;          /* language specific type data */
+  int                    owndata;              /* flag if the structure owns the clientdata */
+} swig_type_info;
 
-typedef struct swig_globalvar {   
-  char       *name;                  /* Name of global variable */
-  PyObject *(*get_attr)(void);       /* Return the current value */
-  int       (*set_attr)(PyObject *); /* Set the value */
-  struct swig_globalvar *next;
-} swig_globalvar;
+/* Structure to store a type and conversion function used for casting */
+typedef struct swig_cast_info {
+  swig_type_info         *type;                        /* pointer to type that is equivalent to this type */
+  swig_converter_func     converter;           /* function to cast the void pointers */
+  struct swig_cast_info  *next;                        /* pointer to next cast in linked list */
+  struct swig_cast_info  *prev;                        /* pointer to the previous cast */
+} swig_cast_info;
+
+/* Structure used to store module information
+ * Each module generates one structure like this, and the runtime collects
+ * all of these structures and stores them in a circularly linked list.*/
+typedef struct swig_module_info {
+  swig_type_info         **types;              /* Array of pointers to swig_type_info structures that are in this module */
+  size_t                 size;                 /* Number of types in this module */
+  struct swig_module_info *next;               /* Pointer to next element in circularly linked list */
+  swig_type_info         **type_initial;       /* Array of initially generated type structures */
+  swig_cast_info         **cast_initial;       /* Array of initially generated casting structures */
+  void                    *clientdata;         /* Language specific module data */
+} swig_module_info;
+
+/* 
+  Compare two type names skipping the space characters, therefore
+  "char*" == "char *" and "Class<int>" == "Class<int >", etc.
+
+  Return 0 when the two name types are equivalent, as in
+  strncmp, but skipping ' '.
+*/
+SWIGRUNTIME int
+SWIG_TypeNameComp(const char *f1, const char *l1,
+                 const char *f2, const char *l2) {
+  for (;(f1 != l1) && (f2 != l2); ++f1, ++f2) {
+    while ((*f1 == ' ') && (f1 != l1)) ++f1;
+    while ((*f2 == ' ') && (f2 != l2)) ++f2;
+    if (*f1 != *f2) return (*f1 > *f2) ? 1 : -1;
+  }
+  return (int)((l1 - f1) - (l2 - f2));
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+  Return 0 if not equal, 1 if equal
+*/
+SWIGRUNTIME int
+SWIG_TypeEquiv(const char *nb, const char *tb) {
+  int equiv = 0;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (!equiv && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+
+/*
+  Check type equivalence in a name list like <name1>|<name2>|...
+  Return 0 if equal, -1 if nb < tb, 1 if nb > tb
+*/
+SWIGRUNTIME int
+SWIG_TypeCompare(const char *nb, const char *tb) {
+  int equiv = 0;
+  const char* te = tb + strlen(tb);
+  const char* ne = nb;
+  while (!equiv && *ne) {
+    for (nb = ne; *ne; ++ne) {
+      if (*ne == '|') break;
+    }
+    equiv = (SWIG_TypeNameComp(nb, ne, tb, te) == 0) ? 1 : 0;
+    if (*ne) ++ne;
+  }
+  return equiv;
+}
+
+
+/* think of this as a c++ template<> or a scheme macro */
+#define SWIG_TypeCheck_Template(comparison, ty)         \
+  if (ty) {                                             \
+    swig_cast_info *iter = ty->cast;                    \
+    while (iter) {                                      \
+      if (comparison) {                                 \
+        if (iter == ty->cast) return iter;              \
+        /* Move iter to the top of the linked list */   \
+        iter->prev->next = iter->next;                  \
+        if (iter->next)                                 \
+          iter->next->prev = iter->prev;                \
+        iter->next = ty->cast;                          \
+        iter->prev = 0;                                 \
+        if (ty->cast) ty->cast->prev = iter;            \
+        ty->cast = iter;                                \
+        return iter;                                    \
+      }                                                 \
+      iter = iter->next;                                \
+    }                                                   \
+  }                                                     \
+  return 0
+
+/*
+  Check the typename
+*/
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheck(const char *c, swig_type_info *ty) {
+  SWIG_TypeCheck_Template(strcmp(iter->type->name, c) == 0, ty);
+}
+
+/* Same as previous function, except strcmp is replaced with a pointer comparison */
+SWIGRUNTIME swig_cast_info *
+SWIG_TypeCheckStruct(swig_type_info *from, swig_type_info *into) {
+  SWIG_TypeCheck_Template(iter->type == from, into);
+}
+
+/*
+  Cast a pointer up an inheritance hierarchy
+*/
+SWIGRUNTIMEINLINE void *
+SWIG_TypeCast(swig_cast_info *ty, void *ptr) {
+  return ((!ty) || (!ty->converter)) ? ptr : (*ty->converter)(ptr);
+}
+
+/* 
+   Dynamic pointer casting. Down an inheritance hierarchy
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeDynamicCast(swig_type_info *ty, void **ptr) {
+  swig_type_info *lastty = ty;
+  if (!ty || !ty->dcast) return ty;
+  while (ty && (ty->dcast)) {
+    ty = (*ty->dcast)(ptr);
+    if (ty) lastty = ty;
+  }
+  return lastty;
+}
 
-typedef struct swig_varlinkobject {
-  PyObject_HEAD
-  swig_globalvar *vars;
-} swig_varlinkobject;
+/*
+  Return the name associated with this type
+*/
+SWIGRUNTIMEINLINE const char *
+SWIG_TypeName(const swig_type_info *ty) {
+  return ty->name;
+}
 
-static PyObject *
-swig_varlink_repr(swig_varlinkobject *v) {
-  v = v;
-  return PyString_FromString("<Global variables>");
+/*
+  Return the pretty name associated with this type,
+  that is an unmangled type name in a form presentable to the user.
+*/
+SWIGRUNTIME const char *
+SWIG_TypePrettyName(const swig_type_info *type) {
+  /* The "str" field contains the equivalent pretty names of the
+     type, separated by vertical-bar characters.  We choose
+     to print the last name, as it is often (?) the most
+     specific. */
+  if (!type) return NULL;
+  if (type->str != NULL) {
+    const char *last_name = type->str;
+    const char *s;
+    for (s = type->str; *s; s++)
+      if (*s == '|') last_name = s+1;
+    return last_name;
+  }
+  else
+    return type->name;
 }
 
-static int
-swig_varlink_print(swig_varlinkobject *v, FILE *fp, int flags) {
-  swig_globalvar  *var;
-  flags = flags;
-  fprintf(fp,"Global variables { ");
-  for (var = v->vars; var; var=var->next) {
-    fprintf(fp,"%s", var->name);
-    if (var->next) fprintf(fp,", ");
+/* 
+   Set the clientdata field for a type
+*/
+SWIGRUNTIME void
+SWIG_TypeClientData(swig_type_info *ti, void *clientdata) {
+  swig_cast_info *cast = ti->cast;
+  /* if (ti->clientdata == clientdata) return; */
+  ti->clientdata = clientdata;
+  
+  while (cast) {
+    if (!cast->converter) {
+      swig_type_info *tc = cast->type;
+      if (!tc->clientdata) {
+       SWIG_TypeClientData(tc, clientdata);
+      }
+    }    
+    cast = cast->next;
   }
-  fprintf(fp," }\n");
+}
+SWIGRUNTIME void
+SWIG_TypeNewClientData(swig_type_info *ti, void *clientdata) {
+  SWIG_TypeClientData(ti, clientdata);
+  ti->owndata = 1;
+}
+  
+/*
+  Search for a swig_type_info structure only by mangled name
+  Search is a O(log #types)
+  
+  We start searching at module start, and finish searching when start == end.  
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_MangledTypeQueryModule(swig_module_info *start, 
+                            swig_module_info *end, 
+                           const char *name) {
+  swig_module_info *iter = start;
+  do {
+    if (iter->size) {
+      register size_t l = 0;
+      register size_t r = iter->size - 1;
+      do {
+       /* since l+r >= 0, we can (>> 1) instead (/ 2) */
+       register size_t i = (l + r) >> 1; 
+       const char *iname = iter->types[i]->name;
+       if (iname) {
+         register int compare = strcmp(name, iname);
+         if (compare == 0) {       
+           return iter->types[i];
+         } else if (compare < 0) {
+           if (i) {
+             r = i - 1;
+           } else {
+             break;
+           }
+         } else if (compare > 0) {
+           l = i + 1;
+         }
+       } else {
+         break; /* should never happen */
+       }
+      } while (l <= r);
+    }
+    iter = iter->next;
+  } while (iter != end);
   return 0;
 }
 
-static PyObject *
-swig_varlink_getattr(swig_varlinkobject *v, char *n) {
-  swig_globalvar *var = v->vars;
-  while (var) {
-    if (strcmp(var->name,n) == 0) {
-      return (*var->get_attr)();
-    }
-    var = var->next;
-  }
-  PyErr_SetString(PyExc_NameError,"Unknown C global variable");
-  return NULL;
-}
-
-static int
-swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) {
-  swig_globalvar *var = v->vars;
-  while (var) {
-    if (strcmp(var->name,n) == 0) {
-      return (*var->set_attr)(p);
-    }
-    var = var->next;
-  }
-  PyErr_SetString(PyExc_NameError,"Unknown C global variable");
-  return 1;
-}
-
-statichere PyTypeObject varlinktype = {
-  PyObject_HEAD_INIT(0)              
-  0,
-  (char *)"swigvarlink",                      /* Type name    */
-  sizeof(swig_varlinkobject),         /* Basic size   */
-  0,                                  /* Itemsize     */
-  0,                                  /* Deallocator  */ 
-  (printfunc) swig_varlink_print,     /* Print        */
-  (getattrfunc) swig_varlink_getattr, /* get attr     */
-  (setattrfunc) swig_varlink_setattr, /* Set attr     */
-  0,                                  /* tp_compare   */
-  (reprfunc) swig_varlink_repr,       /* tp_repr      */    
-  0,                                  /* tp_as_number */
-  0,                                  /* tp_as_mapping*/
-  0,                                  /* tp_hash      */
-};
+/*
+  Search for a swig_type_info structure for either a mangled name or a human readable name.
+  It first searches the mangled names of the types, which is a O(log #types)
+  If a type is not found it then searches the human readable names, which is O(#types).
+  
+  We start searching at module start, and finish searching when start == end.  
+  Note: if start == end at the beginning of the function, we go all the way around
+  the circular list.
+*/
+SWIGRUNTIME swig_type_info *
+SWIG_TypeQueryModule(swig_module_info *start, 
+                     swig_module_info *end, 
+                    const char *name) {
+  /* STEP 1: Search the name field using binary search */
+  swig_type_info *ret = SWIG_MangledTypeQueryModule(start, end, name);
+  if (ret) {
+    return ret;
+  } else {
+    /* STEP 2: If the type hasn't been found, do a complete search
+       of the str field (the human readable name) */
+    swig_module_info *iter = start;
+    do {
+      register size_t i = 0;
+      for (; i < iter->size; ++i) {
+       if (iter->types[i]->str && (SWIG_TypeEquiv(iter->types[i]->str, name)))
+         return iter->types[i];
+      }
+      iter = iter->next;
+    } while (iter != end);
+  }
+  
+  /* neither found a match */
+  return 0;
+}
 
-/* Create a variable linking object for use later */
-SWIGRUNTIME(PyObject *)
-SWIG_newvarlink(void) {
-  swig_varlinkobject *result = 0;
-  result = PyMem_NEW(swig_varlinkobject,1);
-  varlinktype.ob_type = &PyType_Type;    /* Patch varlinktype into a PyType */
-  result->ob_type = &varlinktype;
-  result->vars = 0;
-  result->ob_refcnt = 0;
-  Py_XINCREF((PyObject *) result);
-  return ((PyObject*) result);
-}
-
-SWIGRUNTIME(void)
-SWIG_addvarlink(PyObject *p, char *name,
-          PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {
-  swig_varlinkobject *v;
-  swig_globalvar *gv;
-  v= (swig_varlinkobject *) p;
-  gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));
-  gv->name = (char *) malloc(strlen(name)+1);
-  strcpy(gv->name,name);
-  gv->get_attr = get_attr;
-  gv->set_attr = set_attr;
-  gv->next = v->vars;
-  v->vars = gv;
-}
-
-/* Pack binary data into a string */
-SWIGRUNTIME(char *)
-SWIG_PackData(char *c, void *ptr, int sz) {
-  static char hex[17] = "0123456789abcdef";
-  int i;
-  unsigned char *u = (unsigned char *) ptr;
-  register unsigned char uu;
-  for (i = 0; i < sz; i++,u++) {
-    uu = *u;
+/* 
+   Pack binary data into a string
+*/
+SWIGRUNTIME char *
+SWIG_PackData(char *c, void *ptr, size_t sz) {
+  static const char hex[17] = "0123456789abcdef";
+  register const unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu =  u + sz;
+  for (; u != eu; ++u) {
+    register unsigned char uu = *u;
     *(c++) = hex[(uu & 0xf0) >> 4];
     *(c++) = hex[uu & 0xf];
   }
   return c;
 }
 
-/* Unpack binary data from a string */
-SWIGRUNTIME(char *)
-SWIG_UnpackData(char *c, void *ptr, int sz) {
-  register unsigned char uu = 0;
-  register int d;
-  unsigned char *u = (unsigned char *) ptr;
-  int i;
-  for (i = 0; i < sz; i++, u++) {
-    d = *(c++);
+/* 
+   Unpack binary data from a string
+*/
+SWIGRUNTIME const char *
+SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
+  register unsigned char *u = (unsigned char *) ptr;
+  register const unsigned char *eu = u + sz;
+  for (; u != eu; ++u) {
+    register char d = *(c++);
+    register unsigned char uu;
     if ((d >= '0') && (d <= '9'))
       uu = ((d - '0') << 4);
     else if ((d >= 'a') && (d <= 'f'))
       uu = ((d - ('a'-10)) << 4);
+    else 
+      return (char *) 0;
     d = *(c++);
     if ((d >= '0') && (d <= '9'))
       uu |= (d - '0');
     else if ((d >= 'a') && (d <= 'f'))
       uu |= (d - ('a'-10));
+    else 
+      return (char *) 0;
     *u = uu;
   }
   return c;
 }
 
-/* Convert a pointer value */
-SWIGRUNTIME(int)
-SWIG_ConvertPtr(PyObject *obj, void **ptr, swig_type_info *ty, int flags) {
-  swig_type_info *tc;
-  char  *c;
-  static PyObject *SWIG_this = 0;
-  int    newref = 0;
-  PyObject  *pyobj = 0;
-
-  if (!obj) return 0;
-  if (obj == Py_None) {
-    *ptr = 0;
-    return 0;
-  }
-#ifdef SWIG_COBJECT_TYPES
-  if (!(PyCObject_Check(obj))) {
-    if (!SWIG_this)
-      SWIG_this = PyString_FromString("this");
-    pyobj = obj;
-    obj = PyObject_GetAttr(obj,SWIG_this);
-    newref = 1;
-    if (!obj) goto type_error;
-    if (!PyCObject_Check(obj)) {
-      Py_DECREF(obj);
-      goto type_error;
-    }
-  }  
-  *ptr = PyCObject_AsVoidPtr(obj);
-  c = (char *) PyCObject_GetDesc(obj);
-  if (newref) Py_DECREF(obj);
-  goto cobject;
-#else
-  if (!(PyString_Check(obj))) {
-    if (!SWIG_this)
-      SWIG_this = PyString_FromString("this");
-    pyobj = obj;
-    obj = PyObject_GetAttr(obj,SWIG_this);
-    newref = 1;
-    if (!obj) goto type_error;
-    if (!PyString_Check(obj)) {
-      Py_DECREF(obj);
-      goto type_error;
-    }
-  } 
-  c = PyString_AsString(obj);
-  /* Pointer values must start with leading underscore */
+/* 
+   Pack 'void *' into a string buffer.
+*/
+SWIGRUNTIME char *
+SWIG_PackVoidPtr(char *buff, void *ptr, const char *name, size_t bsz) {
+  char *r = buff;
+  if ((2*sizeof(void *) + 2) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,&ptr,sizeof(void *));
+  if (strlen(name) + 1 > (bsz - (r - buff))) return 0;
+  strcpy(r,name);
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackVoidPtr(const char *c, void **ptr, const char *name) {
   if (*c != '_') {
-    *ptr = (void *) 0;
     if (strcmp(c,"NULL") == 0) {
-      if (newref) { Py_DECREF(obj); }
+      *ptr = (void *) 0;
+      return name;
+    } else {
       return 0;
+    }
+  }
+  return SWIG_UnpackData(++c,ptr,sizeof(void *));
+}
+
+SWIGRUNTIME char *
+SWIG_PackDataName(char *buff, void *ptr, size_t sz, const char *name, size_t bsz) {
+  char *r = buff;
+  size_t lname = (name ? strlen(name) : 0);
+  if ((2*sz + 2 + lname) > bsz) return 0;
+  *(r++) = '_';
+  r = SWIG_PackData(r,ptr,sz);
+  if (lname) {
+    strncpy(r,name,lname+1);
+  } else {
+    *r = 0;
+  }
+  return buff;
+}
+
+SWIGRUNTIME const char *
+SWIG_UnpackDataName(const char *c, void *ptr, size_t sz, const char *name) {
+  if (*c != '_') {
+    if (strcmp(c,"NULL") == 0) {
+      memset(ptr,0,sz);
+      return name;
     } else {
-      if (newref) { Py_DECREF(obj); }
-      goto type_error;
+      return 0;
     }
   }
-  c++;
-  c = SWIG_UnpackData(c,ptr,sizeof(void *));
-  if (newref) { Py_DECREF(obj); }
+  return SWIG_UnpackData(++c,ptr,sz);
+}
+
+#ifdef __cplusplus
+}
 #endif
 
-#ifdef SWIG_COBJECT_TYPES
-cobject:
+/*  Errors in SWIG */
+#define  SWIG_UnknownError        -1 
+#define  SWIG_IOError             -2 
+#define  SWIG_RuntimeError        -3 
+#define  SWIG_IndexError          -4 
+#define  SWIG_TypeError           -5 
+#define  SWIG_DivisionByZero      -6 
+#define  SWIG_OverflowError       -7 
+#define  SWIG_SyntaxError         -8 
+#define  SWIG_ValueError          -9 
+#define  SWIG_SystemError         -10
+#define  SWIG_AttributeError      -11
+#define  SWIG_MemoryError         -12 
+#define  SWIG_NullReferenceError   -13
+
+
+
+
+/* Add PyOS_snprintf for old Pythons */
+#if PY_VERSION_HEX < 0x02020000
+# if defined(_MSC_VER) || defined(__BORLANDC__) || defined(_WATCOM)
+#  define PyOS_snprintf _snprintf
+# else
+#  define PyOS_snprintf snprintf
+# endif
 #endif
 
-  if (ty) {
-    tc = SWIG_TypeCheck(c,ty);
-    if (!tc) goto type_error;
-    *ptr = SWIG_TypeCast(tc,(void*) *ptr);
-  }
+/* A crude PyString_FromFormat implementation for old Pythons */
+#if PY_VERSION_HEX < 0x02020000
 
-  if ((pyobj) && (flags & SWIG_POINTER_DISOWN)) {
-      PyObject *zero = PyInt_FromLong(0);
-      PyObject_SetAttrString(pyobj,(char*)"thisown",zero);
-      Py_DECREF(zero);
-  }
-  return 0;
+#ifndef SWIG_PYBUFFER_SIZE
+# define SWIG_PYBUFFER_SIZE 1024
+#endif
 
-type_error:
-  if (flags & SWIG_POINTER_EXCEPTION) {
-    if (ty) {
-      char *temp = (char *) malloc(64+strlen(ty->name));
-      sprintf(temp,"Type error. Expected %s", ty->name);
-      PyErr_SetString(PyExc_TypeError, temp);
-      free((char *) temp);
-    } else {
-      PyErr_SetString(PyExc_TypeError,"Expected a pointer");
-    }
-  }
-  return -1;
+static PyObject *
+PyString_FromFormat(const char *fmt, ...) {
+  va_list ap;
+  char buf[SWIG_PYBUFFER_SIZE * 2];
+  int res;
+  va_start(ap, fmt);
+  res = vsnprintf(buf, sizeof(buf), fmt, ap);
+  va_end(ap);
+  return (res < 0 || res >= (int)sizeof(buf)) ? 0 : PyString_FromString(buf);
 }
+#endif
 
-/* Convert a packed value value */
-SWIGRUNTIME(int)
-SWIG_ConvertPacked(PyObject *obj, void *ptr, int sz, swig_type_info *ty, int flags) {
-  swig_type_info *tc;
-  char  *c;
-
-  if ((!obj) || (!PyString_Check(obj))) goto type_error;
-  c = PyString_AsString(obj);
-  /* Pointer values must start with leading underscore */
-  if (*c != '_') goto type_error;
-  c++;
-  c = SWIG_UnpackData(c,ptr,sz);
-  if (ty) {
-    tc = SWIG_TypeCheck(c,ty);
-    if (!tc) goto type_error;
-  }
-  return 0;
+/* Add PyObject_Del for old Pythons */
+#if PY_VERSION_HEX < 0x01060000
+# define PyObject_Del(op) PyMem_DEL((op))
+#endif
+#ifndef PyObject_DEL
+# define PyObject_DEL PyObject_Del
+#endif
 
-type_error:
+/* A crude PyExc_StopIteration exception for old Pythons */
+#if PY_VERSION_HEX < 0x02020000
+# ifndef PyExc_StopIteration
+#  define PyExc_StopIteration PyExc_RuntimeError
+# endif
+# ifndef PyObject_GenericGetAttr
+#  define PyObject_GenericGetAttr 0
+# endif
+#endif
+/* Py_NotImplemented is defined in 2.1 and up. */
+#if PY_VERSION_HEX < 0x02010000
+# ifndef Py_NotImplemented
+#  define Py_NotImplemented PyExc_RuntimeError
+# endif
+#endif
 
-  if (flags) {
-    if (ty) {
-      char *temp = (char *) malloc(64+strlen(ty->name));
-      sprintf(temp,"Type error. Expected %s", ty->name);
-      PyErr_SetString(PyExc_TypeError, temp);
-      free((char *) temp);
-    } else {
-      PyErr_SetString(PyExc_TypeError,"Expected a pointer");
-    }
-  }
-  return -1;
+
+/* A crude PyString_AsStringAndSize implementation for old Pythons */
+#if PY_VERSION_HEX < 0x02010000
+# ifndef PyString_AsStringAndSize
+#  define PyString_AsStringAndSize(obj, s, len) {*s = PyString_AsString(obj); *len = *s ? strlen(*s) : 0;}
+# endif
+#endif
+
+/* PySequence_Size for old Pythons */
+#if PY_VERSION_HEX < 0x02000000
+# ifndef PySequence_Size
+#  define PySequence_Size PySequence_Length
+# endif
+#endif
+
+
+/* PyBool_FromLong for old Pythons */
+#if PY_VERSION_HEX < 0x02030000
+static
+PyObject *PyBool_FromLong(long ok)
+{
+  PyObject *result = ok ? Py_True : Py_False;
+  Py_INCREF(result);
+  return result;
 }
+#endif
 
-/* Create a new pointer object */
-SWIGRUNTIME(PyObject *)
-SWIG_NewPointerObj(void *ptr, swig_type_info *type, int own) {
-  PyObject *robj;
-  if (!ptr) {
-    Py_INCREF(Py_None);
-    return Py_None;
-  }
-#ifdef SWIG_COBJECT_TYPES
-  robj = PyCObject_FromVoidPtrAndDesc((void *) ptr, (char *) type->name, NULL);
-#else
-  {
-    char result[1024];
-    char *r = result;
-    *(r++) = '_';
-    r = SWIG_PackData(r,&ptr,sizeof(void *));
-    strcpy(r,type->name);
-    robj = PyString_FromString(result);
-  }
-#endif
-  if (!robj || (robj == Py_None)) return robj;
-  if (type->clientdata) {
-    PyObject *inst;
-    PyObject *args = Py_BuildValue((char*)"(O)", robj);
-    Py_DECREF(robj);
-    inst = PyObject_CallObject((PyObject *) type->clientdata, args);
-    Py_DECREF(args);
-    if (inst) {
-      if (own) {
-       PyObject *n = PyInt_FromLong(1);
-       PyObject_SetAttrString(inst,(char*)"thisown",n);
-       Py_DECREF(n);
-      }
-      robj = inst;
-    }
+/* Py_ssize_t for old Pythons */
+/* This code is as recommended by: */
+/* http://www.python.org/dev/peps/pep-0353/#conversion-guidelines */
+#if PY_VERSION_HEX < 0x02050000 && !defined(PY_SSIZE_T_MIN)
+typedef int Py_ssize_t;
+# define PY_SSIZE_T_MAX INT_MAX
+# define PY_SSIZE_T_MIN INT_MIN
+#endif
+
+/* -----------------------------------------------------------------------------
+ * error manipulation
+ * ----------------------------------------------------------------------------- */
+
+SWIGRUNTIME PyObject*
+SWIG_Python_ErrorType(int code) {
+  PyObject* type = 0;
+  switch(code) {
+  case SWIG_MemoryError:
+    type = PyExc_MemoryError;
+    break;
+  case SWIG_IOError:
+    type = PyExc_IOError;
+    break;
+  case SWIG_RuntimeError:
+    type = PyExc_RuntimeError;
+    break;
+  case SWIG_IndexError:
+    type = PyExc_IndexError;
+    break;
+  case SWIG_TypeError:
+    type = PyExc_TypeError;
+    break;
+  case SWIG_DivisionByZero:
+    type = PyExc_ZeroDivisionError;
+    break;
+  case SWIG_OverflowError:
+    type = PyExc_OverflowError;
+    break;
+  case SWIG_SyntaxError:
+    type = PyExc_SyntaxError;
+    break;
+  case SWIG_ValueError:
+    type = PyExc_ValueError;
+    break;
+  case SWIG_SystemError:
+    type = PyExc_SystemError;
+    break;
+  case SWIG_AttributeError:
+    type = PyExc_AttributeError;
+    break;
+  default:
+    type = PyExc_RuntimeError;
   }
-  return robj;
+  return type;
 }
 
-SWIGRUNTIME(PyObject *)
-SWIG_NewPackedObj(void *ptr, int sz, swig_type_info *type) {
-  char result[1024];
-  char *r = result;
-  if ((2*sz + 1 + strlen(type->name)) > 1000) return 0;
-  *(r++) = '_';
-  r = SWIG_PackData(r,ptr,sz);
-  strcpy(r,type->name);
-  return PyString_FromString(result);
-}
 
-/* Install Constants */
-SWIGRUNTIME(void)
-SWIG_InstallConstants(PyObject *d, swig_const_info constants[]) {
-  int i;
-  PyObject *obj;
-  for (i = 0; constants[i].type; i++) {
-    switch(constants[i].type) {
-    case SWIG_PY_INT:
-      obj = PyInt_FromLong(constants[i].lvalue);
-      break;
-    case SWIG_PY_FLOAT:
-      obj = PyFloat_FromDouble(constants[i].dvalue);
-      break;
-    case SWIG_PY_STRING:
-      obj = PyString_FromString((char *) constants[i].pvalue);
-      break;
-    case SWIG_PY_POINTER:
-      obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);
-      break;
-    case SWIG_PY_BINARY:
-      obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));
-      break;
-    default:
-      obj = 0;
-      break;
-    }
-    if (obj) {
-      PyDict_SetItemString(d,constants[i].name,obj);
-      Py_DECREF(obj);
-    }
+SWIGRUNTIME void
+SWIG_Python_AddErrorMsg(const char* mesg)
+{
+  PyObject *type = 0;
+  PyObject *value = 0;
+  PyObject *traceback = 0;
+
+  if (PyErr_Occurred()) PyErr_Fetch(&type, &value, &traceback);
+  if (value) {
+    PyObject *old_str = PyObject_Str(value);
+    PyErr_Clear();
+    Py_XINCREF(type);
+    PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
+    Py_DECREF(old_str);
+    Py_DECREF(value);
+  } else {
+    PyErr_Format(PyExc_RuntimeError, mesg);
   }
 }
 
+
+
+#if defined(SWIG_PYTHON_NO_THREADS)
+#  if defined(SWIG_PYTHON_THREADS)
+#    undef SWIG_PYTHON_THREADS
+#  endif
+#endif
+#if defined(SWIG_PYTHON_THREADS) /* Threading support is enabled */
+#  if !defined(SWIG_PYTHON_USE_GIL) && !defined(SWIG_PYTHON_NO_USE_GIL)
+#    if (PY_VERSION_HEX >= 0x02030000) /* For 2.3 or later, use the PyGILState calls */
+#      define SWIG_PYTHON_USE_GIL
+#    endif
+#  endif
+#  if defined(SWIG_PYTHON_USE_GIL) /* Use PyGILState threads calls */
+#    ifndef SWIG_PYTHON_INITIALIZE_THREADS
+#     define SWIG_PYTHON_INITIALIZE_THREADS  PyEval_InitThreads() 
+#    endif
+#    ifdef __cplusplus /* C++ code */
+       class SWIG_Python_Thread_Block {
+         bool status;
+         PyGILState_STATE state;
+       public:
+         void end() { if (status) { PyGILState_Release(state); status = false;} }
+         SWIG_Python_Thread_Block() : status(true), state(PyGILState_Ensure()) {}
+         ~SWIG_Python_Thread_Block() { end(); }
+       };
+       class SWIG_Python_Thread_Allow {
+         bool status;
+         PyThreadState *save;
+       public:
+         void end() { if (status) { PyEval_RestoreThread(save); status = false; }}
+         SWIG_Python_Thread_Allow() : status(true), save(PyEval_SaveThread()) {}
+         ~SWIG_Python_Thread_Allow() { end(); }
+       };
+#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   SWIG_Python_Thread_Block _swig_thread_block
+#      define SWIG_PYTHON_THREAD_END_BLOCK     _swig_thread_block.end()
+#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   SWIG_Python_Thread_Allow _swig_thread_allow
+#      define SWIG_PYTHON_THREAD_END_ALLOW     _swig_thread_allow.end()
+#    else /* C code */
+#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK   PyGILState_STATE _swig_thread_block = PyGILState_Ensure()
+#      define SWIG_PYTHON_THREAD_END_BLOCK     PyGILState_Release(_swig_thread_block)
+#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW   PyThreadState *_swig_thread_allow = PyEval_SaveThread()
+#      define SWIG_PYTHON_THREAD_END_ALLOW     PyEval_RestoreThread(_swig_thread_allow)
+#    endif
+#  else /* Old thread way, not implemented, user must provide it */
+#    if !defined(SWIG_PYTHON_INITIALIZE_THREADS)
+#      define SWIG_PYTHON_INITIALIZE_THREADS
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_BEGIN_BLOCK)
+#      define SWIG_PYTHON_THREAD_BEGIN_BLOCK
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_END_BLOCK)
+#      define SWIG_PYTHON_THREAD_END_BLOCK
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_BEGIN_ALLOW)
+#      define SWIG_PYTHON_THREAD_BEGIN_ALLOW
+#    endif
+#    if !defined(SWIG_PYTHON_THREAD_END_ALLOW)
+#      define SWIG_PYTHON_THREAD_END_ALLOW
+#    endif
+#  endif
+#else /* No thread support */
+#  define SWIG_PYTHON_INITIALIZE_THREADS
+#  define SWIG_PYTHON_THREAD_BEGIN_BLOCK
+#  define SWIG_PYTHON_THREAD_END_BLOCK
+#  define SWIG_PYTHON_THREAD_BEGIN_ALLOW
+#  define SWIG_PYTHON_THREAD_END_ALLOW
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Python API portion that goes into the runtime
+ * ----------------------------------------------------------------------------- */
+
+#ifdef __cplusplus
+extern "C" {
+#if 0
+} /* cc-mode */
 #endif
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Constant declarations
+ * ----------------------------------------------------------------------------- */
+
+/* Constant Types */
+#define SWIG_PY_POINTER 4
+#define SWIG_PY_BINARY  5
+
+/* Constant information structure */
+typedef struct swig_const_info {
+  int type;
+  char *name;
+  long lvalue;
+  double dvalue;
+  void   *pvalue;
+  swig_type_info **ptype;
+} swig_const_info;
 
 #ifdef __cplusplus
+#if 0
+{ /* cc-mode */
+#endif
 }
 #endif
 
 
+/* -----------------------------------------------------------------------------
+ * See the LICENSE file for information on copyright, usage and redistribution
+ * of SWIG, and the README file for authors - http://www.swig.org/release.html.
+ *
+ * pyrun.swg
+ *
+ * This file contains the runtime support for Python modules
+ * and includes code for managing global variables and pointer
+ * type checking.
+ *
+ * ----------------------------------------------------------------------------- */
 
+/* Common SWIG API */
 
+/* for raw pointers */
+#define SWIG_Python_ConvertPtr(obj, pptr, type, flags)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, 0)
+#define SWIG_ConvertPtr(obj, pptr, type, flags)         SWIG_Python_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_ConvertPtrAndOwn(obj,pptr,type,flags,own)  SWIG_Python_ConvertPtrAndOwn(obj, pptr, type, flags, own)
+#define SWIG_NewPointerObj(ptr, type, flags)            SWIG_Python_NewPointerObj(ptr, type, flags)
+#define SWIG_CheckImplicit(ty)                          SWIG_Python_CheckImplicit(ty) 
+#define SWIG_AcquirePtr(ptr, src)                       SWIG_Python_AcquirePtr(ptr, src)
+#define swig_owntype                                    int
 
+/* for raw packed data */
+#define SWIG_ConvertPacked(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewPackedObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)
 
+/* for class or struct pointers */
+#define SWIG_ConvertInstance(obj, pptr, type, flags)    SWIG_ConvertPtr(obj, pptr, type, flags)
+#define SWIG_NewInstanceObj(ptr, type, flags)           SWIG_NewPointerObj(ptr, type, flags)
 
+/* for C or C++ function pointers */
+#define SWIG_ConvertFunctionPtr(obj, pptr, type)        SWIG_Python_ConvertFunctionPtr(obj, pptr, type)
+#define SWIG_NewFunctionPtrObj(ptr, type)               SWIG_Python_NewPointerObj(ptr, type, 0)
 
-/* -------- TYPES TABLE (BEGIN) -------- */
+/* for C++ member pointers, ie, member methods */
+#define SWIG_ConvertMember(obj, ptr, sz, ty)            SWIG_Python_ConvertPacked(obj, ptr, sz, ty)
+#define SWIG_NewMemberObj(ptr, sz, type)                SWIG_Python_NewPackedObj(ptr, sz, type)
 
-#define  SWIGTYPE_p_Radio swig_types[0] 
-#define  SWIGTYPE_p_nesc_app_t swig_types[1] 
-#define  SWIGTYPE_p_FILE swig_types[2] 
-#define  SWIGTYPE_p_MAC swig_types[3] 
-#define  SWIGTYPE_p_Packet swig_types[4] 
-#define  SWIGTYPE_p_Variable swig_types[5] 
-#define  SWIGTYPE_p_Tossim swig_types[6] 
-#define  SWIGTYPE_p_variable_string_t swig_types[7] 
-#define  SWIGTYPE_p_Mote swig_types[8] 
-#define  SWIGTYPE_p_p_char swig_types[9] 
-#define  SWIGTYPE_p_int swig_types[10] 
-static swig_type_info *swig_types[12];
 
-/* -------- TYPES TABLE (END) -------- */
+/* Runtime API */
 
+#define SWIG_GetModule(clientdata)                      SWIG_Python_GetModule()
+#define SWIG_SetModule(clientdata, pointer)             SWIG_Python_SetModule(pointer)
+#define SWIG_NewClientData(obj)                         PySwigClientData_New(obj)
 
-/*-----------------------------------------------
-              @(target):= _TOSSIM.so
-  ------------------------------------------------*/
-#define SWIG_init    init_TOSSIM
+#define SWIG_SetErrorObj                                SWIG_Python_SetErrorObj                            
+#define SWIG_SetErrorMsg                               SWIG_Python_SetErrorMsg                            
+#define SWIG_ErrorType(code)                           SWIG_Python_ErrorType(code)                        
+#define SWIG_Error(code, msg)                          SWIG_Python_SetErrorMsg(SWIG_ErrorType(code), msg) 
+#define SWIG_fail                                      goto fail                                          
 
-#define SWIG_name    "_TOSSIM"
 
-#include <memory.h>
-#include <tossim.h>
+/* Runtime API implementation */
 
-enum {
-  PRIMITIVE_INTEGER      = 0,
-  PRIMITIVE_FLOAT   = 1,
-  PRIMITIVE_UNKNOWN = 2
-};
+/* Error manipulation */
 
-int lengthOfType(char* type) {
-  if (strcmp(type, "uint8_t") == 0) {
-    return sizeof(uint8_t);
-  }
-  else if (strcmp(type, "uint16_t") == 0) {
+SWIGINTERN void 
+SWIG_Python_SetErrorObj(PyObject *errtype, PyObject *obj) {
+  SWIG_PYTHON_THREAD_BEGIN_BLOCK; 
+  PyErr_SetObject(errtype, obj);
+  Py_DECREF(obj);
+  SWIG_PYTHON_THREAD_END_BLOCK;
+}
+
+SWIGINTERN void 
+SWIG_Python_SetErrorMsg(PyObject *errtype, const char *msg) {
+  SWIG_PYTHON_THREAD_BEGIN_BLOCK;
+  PyErr_SetString(errtype, (char *) msg);
+  SWIG_PYTHON_THREAD_END_BLOCK;
+}
+
+#define SWIG_Python_Raise(obj, type, desc)  SWIG_Python_SetErrorObj(SWIG_Python_ExceptionType(desc), obj)
+
+/* Set a constant value */
+
+SWIGINTERN void
+SWIG_Python_SetConstant(PyObject *d, const char *name, PyObject *obj) {   
+  PyDict_SetItemString(d, (char*) name, obj);
+  Py_DECREF(obj);                            
+}
+
+/* Append a value to the result obj */
+
+SWIGINTERN PyObject*
+SWIG_Python_AppendOutput(PyObject* result, PyObject* obj) {
+#if !defined(SWIG_PYTHON_OUTPUT_TUPLE)
+  if (!result) {
+    result = obj;
+  } else if (result == Py_None) {
+    Py_DECREF(result);
+    result = obj;
+  } else {
+    if (!PyList_Check(result)) {
+      PyObject *o2 = result;
+      result = PyList_New(1);
+      PyList_SetItem(result, 0, o2);
+    }
+    PyList_Append(result,obj);
+    Py_DECREF(obj);
+  }
+  return result;
+#else
+  PyObject*   o2;
+  PyObject*   o3;
+  if (!result) {
+    result = obj;
+  } else if (result == Py_None) {
+    Py_DECREF(result);
+    result = obj;
+  } else {
+    if (!PyTuple_Check(result)) {
+      o2 = result;
+      result = PyTuple_New(1);
+      PyTuple_SET_ITEM(result, 0, o2);
+    }
+    o3 = PyTuple_New(1);
+    PyTuple_SET_ITEM(o3, 0, obj);
+    o2 = result;
+    result = PySequence_Concat(o2, o3);
+    Py_DECREF(o2);
+    Py_DECREF(o3);
+  }
+  return result;
+#endif
+}
+
+/* Unpack the argument tuple */
+
+SWIGINTERN int
+SWIG_Python_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, PyObject **objs)
+{
+  if (!args) {
+    if (!min && !max) {
+      return 1;
+    } else {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got none", 
+                  name, (min == max ? "" : "at least "), (int)min);
+      return 0;
+    }
+  }  
+  if (!PyTuple_Check(args)) {
+    PyErr_SetString(PyExc_SystemError, "UnpackTuple() argument list is not a tuple");
+    return 0;
+  } else {
+    register Py_ssize_t l = PyTuple_GET_SIZE(args);
+    if (l < min) {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
+                  name, (min == max ? "" : "at least "), (int)min, (int)l);
+      return 0;
+    } else if (l > max) {
+      PyErr_Format(PyExc_TypeError, "%s expected %s%d arguments, got %d", 
+                  name, (min == max ? "" : "at most "), (int)max, (int)l);
+      return 0;
+    } else {
+      register int i;
+      for (i = 0; i < l; ++i) {
+       objs[i] = PyTuple_GET_ITEM(args, i);
+      }
+      for (; l < max; ++l) {
+       objs[l] = 0;
+      }
+      return i + 1;
+    }    
+  }
+}
+
+/* A functor is a function object with one single object argument */
+#if PY_VERSION_HEX >= 0x02020000
+#define SWIG_Python_CallFunctor(functor, obj)          PyObject_CallFunctionObjArgs(functor, obj, NULL);
+#else
+#define SWIG_Python_CallFunctor(functor, obj)          PyObject_CallFunction(functor, "O", obj);
+#endif
+
+/*
+  Helper for static pointer initialization for both C and C++ code, for example
+  static PyObject *SWIG_STATIC_POINTER(MyVar) = NewSomething(...);
+*/
+#ifdef __cplusplus
+#define SWIG_STATIC_POINTER(var)  var
+#else
+#define SWIG_STATIC_POINTER(var)  var = 0; if (!var) var
+#endif
+
+/* -----------------------------------------------------------------------------
+ * Pointer declarations
+ * ----------------------------------------------------------------------------- */
+
+/* Flags for new pointer objects */
+#define SWIG_POINTER_NOSHADOW       (SWIG_POINTER_OWN      << 1)
+#define SWIG_POINTER_NEW            (SWIG_POINTER_NOSHADOW | SWIG_POINTER_OWN)
+
+#define SWIG_POINTER_IMPLICIT_CONV  (SWIG_POINTER_DISOWN   << 1)
+
+#ifdef __cplusplus
+extern "C" {
+#if 0
+} /* cc-mode */
+#endif
+#endif
+
+/*  How to access Py_None */
+#if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
+#  ifndef SWIG_PYTHON_NO_BUILD_NONE
+#    ifndef SWIG_PYTHON_BUILD_NONE
+#      define SWIG_PYTHON_BUILD_NONE
+#    endif
+#  endif
+#endif
+
+#ifdef SWIG_PYTHON_BUILD_NONE
+#  ifdef Py_None
+#   undef Py_None
+#   define Py_None SWIG_Py_None()
+#  endif
+SWIGRUNTIMEINLINE PyObject * 
+_SWIG_Py_None(void)
+{
+  PyObject *none = Py_BuildValue((char*)"");
+  Py_DECREF(none);
+  return none;
+}
+SWIGRUNTIME PyObject * 
+SWIG_Py_None(void)
+{
+  static PyObject *SWIG_STATIC_POINTER(none) = _SWIG_Py_None();
+  return none;
+}
+#endif
+
+/* The python void return value */
+
+SWIGRUNTIMEINLINE PyObject * 
+SWIG_Py_Void(void)
+{
+  PyObject *none = Py_None;
+  Py_INCREF(none);
+  return none;
+}
+
+/* PySwigClientData */
+
+typedef struct {
+  PyObject *klass;
+  PyObject *newraw;
+  PyObject *newargs;
+  PyObject *destroy;
+  int delargs;
+  int implicitconv;
+} PySwigClientData;
+
+SWIGRUNTIMEINLINE int 
+SWIG_Python_CheckImplicit(swig_type_info *ty)
+{
+  PySwigClientData *data = (PySwigClientData *)ty->clientdata;
+  return data ? data->implicitconv : 0;
+}
+
+SWIGRUNTIMEINLINE PyObject *
+SWIG_Python_ExceptionType(swig_type_info *desc) {
+  PySwigClientData *data = desc ? (PySwigClientData *) desc->clientdata : 0;
+  PyObject *klass = data ? data->klass : 0;
+  return (klass ? klass : PyExc_RuntimeError);
+}
+
+
+SWIGRUNTIME PySwigClientData * 
+PySwigClientData_New(PyObject* obj)
+{
+  if (!obj) {
+    return 0;
+  } else {
+    PySwigClientData *data = (PySwigClientData *)malloc(sizeof(PySwigClientData));
+    /* the klass element */
+    data->klass = obj;
+    Py_INCREF(data->klass);
+    /* the newraw method and newargs arguments used to create a new raw instance */
+    if (PyClass_Check(obj)) {
+      data->newraw = 0;
+      data->newargs = obj;
+      Py_INCREF(obj);
+    } else {
+#if (PY_VERSION_HEX < 0x02020000)
+      data->newraw = 0;
+#else
+      data->newraw = PyObject_GetAttrString(data->klass, (char *)"__new__");
+#endif
+      if (data->newraw) {
+       Py_INCREF(data->newraw);
+       data->newargs = PyTuple_New(1);
+       PyTuple_SetItem(data->newargs, 0, obj);
+      } else {
+       data->newargs = obj;
+      }
+      Py_INCREF(data->newargs);
+    }
+    /* the destroy method, aka as the C++ delete method */
+    data->destroy = PyObject_GetAttrString(data->klass, (char *)"__swig_destroy__");
+    if (PyErr_Occurred()) {
+      PyErr_Clear();
+      data->destroy = 0;
+    }
+    if (data->destroy) {
+      int flags;
+      Py_INCREF(data->destroy);
+      flags = PyCFunction_GET_FLAGS(data->destroy);
+#ifdef METH_O
+      data->delargs = !(flags & (METH_O));
+#else
+      data->delargs = 0;
+#endif
+    } else {
+      data->delargs = 0;
+    }
+    data->implicitconv = 0;
+    return data;
+  }
+}
+
+SWIGRUNTIME void 
+PySwigClientData_Del(PySwigClientData* data)
+{
+  Py_XDECREF(data->newraw);
+  Py_XDECREF(data->newargs);
+  Py_XDECREF(data->destroy);
+}
+
+/* =============== PySwigObject =====================*/
+
+typedef struct {
+  PyObject_HEAD
+  void *ptr;
+  swig_type_info *ty;
+  int own;
+  PyObject *next;
+} PySwigObject;
+
+SWIGRUNTIME PyObject *
+PySwigObject_long(PySwigObject *v)
+{
+  return PyLong_FromVoidPtr(v->ptr);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_format(const char* fmt, PySwigObject *v)
+{
+  PyObject *res = NULL;
+  PyObject *args = PyTuple_New(1);
+  if (args) {
+    if (PyTuple_SetItem(args, 0, PySwigObject_long(v)) == 0) {
+      PyObject *ofmt = PyString_FromString(fmt);
+      if (ofmt) {
+       res = PyString_Format(ofmt,args);
+       Py_DECREF(ofmt);
+      }
+      Py_DECREF(args);
+    }
+  }
+  return res;
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_oct(PySwigObject *v)
+{
+  return PySwigObject_format("%o",v);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_hex(PySwigObject *v)
+{
+  return PySwigObject_format("%x",v);
+}
+
+SWIGRUNTIME PyObject *
+#ifdef METH_NOARGS
+PySwigObject_repr(PySwigObject *v)
+#else
+PySwigObject_repr(PySwigObject *v, PyObject *args)
+#endif
+{
+  const char *name = SWIG_TypePrettyName(v->ty);
+  PyObject *hex = PySwigObject_hex(v);    
+  PyObject *repr = PyString_FromFormat("<Swig Object of type '%s' at 0x%s>", name, PyString_AsString(hex));
+  Py_DECREF(hex);
+  if (v->next) {
+#ifdef METH_NOARGS
+    PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next);
+#else
+    PyObject *nrep = PySwigObject_repr((PySwigObject *)v->next, args);
+#endif
+    PyString_ConcatAndDel(&repr,nrep);
+  }
+  return repr;  
+}
+
+SWIGRUNTIME int
+PySwigObject_print(PySwigObject *v, FILE *fp, int SWIGUNUSEDPARM(flags))
+{
+#ifdef METH_NOARGS
+  PyObject *repr = PySwigObject_repr(v);
+#else
+  PyObject *repr = PySwigObject_repr(v, NULL);
+#endif
+  if (repr) {
+    fputs(PyString_AsString(repr), fp);
+    Py_DECREF(repr);
+    return 0; 
+  } else {
+    return 1; 
+  }
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_str(PySwigObject *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  return SWIG_PackVoidPtr(result, v->ptr, v->ty->name, sizeof(result)) ?
+    PyString_FromString(result) : 0;
+}
+
+SWIGRUNTIME int
+PySwigObject_compare(PySwigObject *v, PySwigObject *w)
+{
+  void *i = v->ptr;
+  void *j = w->ptr;
+  return (i < j) ? -1 : ((i > j) ? 1 : 0);
+}
+
+SWIGRUNTIME PyTypeObject* _PySwigObject_type(void);
+
+SWIGRUNTIME PyTypeObject*
+PySwigObject_type(void) {
+  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigObject_type();
+  return type;
+}
+
+SWIGRUNTIMEINLINE int
+PySwigObject_Check(PyObject *op) {
+  return ((op)->ob_type == PySwigObject_type())
+    || (strcmp((op)->ob_type->tp_name,"PySwigObject") == 0);
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_New(void *ptr, swig_type_info *ty, int own);
+
+SWIGRUNTIME void
+PySwigObject_dealloc(PyObject *v)
+{
+  PySwigObject *sobj = (PySwigObject *) v;
+  PyObject *next = sobj->next;
+  if (sobj->own) {
+    swig_type_info *ty = sobj->ty;
+    PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;
+    PyObject *destroy = data ? data->destroy : 0;
+    if (destroy) {
+      /* destroy is always a VARARGS method */
+      PyObject *res;
+      if (data->delargs) {
+       /* we need to create a temporal object to carry the destroy operation */
+       PyObject *tmp = PySwigObject_New(sobj->ptr, ty, 0);
+       res = SWIG_Python_CallFunctor(destroy, tmp);
+       Py_DECREF(tmp);
+      } else {
+       PyCFunction meth = PyCFunction_GET_FUNCTION(destroy);
+       PyObject *mself = PyCFunction_GET_SELF(destroy);
+       res = ((*meth)(mself, v));
+      }
+      Py_XDECREF(res);
+    } else {
+      const char *name = SWIG_TypePrettyName(ty);
+#if !defined(SWIG_PYTHON_SILENT_MEMLEAK)
+      printf("swig/python detected a memory leak of type '%s', no destructor found.\n", name);
+#endif
+    }
+  } 
+  Py_XDECREF(next);
+  PyObject_DEL(v);
+}
+
+SWIGRUNTIME PyObject* 
+PySwigObject_append(PyObject* v, PyObject* next)
+{
+  PySwigObject *sobj = (PySwigObject *) v;
+#ifndef METH_O
+  PyObject *tmp = 0;
+  if (!PyArg_ParseTuple(next,(char *)"O:append", &tmp)) return NULL;
+  next = tmp;
+#endif
+  if (!PySwigObject_Check(next)) {
+    return NULL;
+  }
+  sobj->next = next;
+  Py_INCREF(next);
+  return SWIG_Py_Void();
+}
+
+SWIGRUNTIME PyObject* 
+#ifdef METH_NOARGS
+PySwigObject_next(PyObject* v)
+#else
+PySwigObject_next(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+#endif
+{
+  PySwigObject *sobj = (PySwigObject *) v;
+  if (sobj->next) {    
+    Py_INCREF(sobj->next);
+    return sobj->next;
+  } else {
+    return SWIG_Py_Void();
+  }
+}
+
+SWIGINTERN PyObject*
+#ifdef METH_NOARGS
+PySwigObject_disown(PyObject *v)
+#else
+PySwigObject_disown(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+#endif
+{
+  PySwigObject *sobj = (PySwigObject *)v;
+  sobj->own = 0;
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject*
+#ifdef METH_NOARGS
+PySwigObject_acquire(PyObject *v)
+#else
+PySwigObject_acquire(PyObject* v, PyObject *SWIGUNUSEDPARM(args))
+#endif
+{
+  PySwigObject *sobj = (PySwigObject *)v;
+  sobj->own = SWIG_POINTER_OWN;
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject*
+PySwigObject_own(PyObject *v, PyObject *args)
+{
+  PyObject *val = 0;
+#if (PY_VERSION_HEX < 0x02020000)
+  if (!PyArg_ParseTuple(args,(char *)"|O:own",&val))
+#else
+  if (!PyArg_UnpackTuple(args, (char *)"own", 0, 1, &val)) 
+#endif
+    {
+      return NULL;
+    } 
+  else
+    {
+      PySwigObject *sobj = (PySwigObject *)v;
+      PyObject *obj = PyBool_FromLong(sobj->own);
+      if (val) {
+#ifdef METH_NOARGS
+       if (PyObject_IsTrue(val)) {
+         PySwigObject_acquire(v);
+       } else {
+         PySwigObject_disown(v);
+       }
+#else
+       if (PyObject_IsTrue(val)) {
+         PySwigObject_acquire(v,args);
+       } else {
+         PySwigObject_disown(v,args);
+       }
+#endif
+      } 
+      return obj;
+    }
+}
+
+#ifdef METH_O
+static PyMethodDef
+swigobject_methods[] = {
+  {(char *)"disown",  (PyCFunction)PySwigObject_disown,  METH_NOARGS,  (char *)"releases ownership of the pointer"},
+  {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_NOARGS,  (char *)"aquires ownership of the pointer"},
+  {(char *)"own",     (PyCFunction)PySwigObject_own,     METH_VARARGS, (char *)"returns/sets ownership of the pointer"},
+  {(char *)"append",  (PyCFunction)PySwigObject_append,  METH_O,       (char *)"appends another 'this' object"},
+  {(char *)"next",    (PyCFunction)PySwigObject_next,    METH_NOARGS,  (char *)"returns the next 'this' object"},
+  {(char *)"__repr__",(PyCFunction)PySwigObject_repr,    METH_NOARGS,  (char *)"returns object representation"},
+  {0, 0, 0, 0}  
+};
+#else
+static PyMethodDef
+swigobject_methods[] = {
+  {(char *)"disown",  (PyCFunction)PySwigObject_disown,  METH_VARARGS,  (char *)"releases ownership of the pointer"},
+  {(char *)"acquire", (PyCFunction)PySwigObject_acquire, METH_VARARGS,  (char *)"aquires ownership of the pointer"},
+  {(char *)"own",     (PyCFunction)PySwigObject_own,     METH_VARARGS,  (char *)"returns/sets ownership of the pointer"},
+  {(char *)"append",  (PyCFunction)PySwigObject_append,  METH_VARARGS,  (char *)"appends another 'this' object"},
+  {(char *)"next",    (PyCFunction)PySwigObject_next,    METH_VARARGS,  (char *)"returns the next 'this' object"},
+  {(char *)"__repr__",(PyCFunction)PySwigObject_repr,   METH_VARARGS,  (char *)"returns object representation"},
+  {0, 0, 0, 0}  
+};
+#endif
+
+#if PY_VERSION_HEX < 0x02020000
+SWIGINTERN PyObject *
+PySwigObject_getattr(PySwigObject *sobj,char *name)
+{
+  return Py_FindMethod(swigobject_methods, (PyObject *)sobj, name);
+}
+#endif
+
+SWIGRUNTIME PyTypeObject*
+_PySwigObject_type(void) {
+  static char swigobject_doc[] = "Swig object carries a C/C++ instance pointer";
+  
+  static PyNumberMethods PySwigObject_as_number = {
+    (binaryfunc)0, /*nb_add*/
+    (binaryfunc)0, /*nb_subtract*/
+    (binaryfunc)0, /*nb_multiply*/
+    (binaryfunc)0, /*nb_divide*/
+    (binaryfunc)0, /*nb_remainder*/
+    (binaryfunc)0, /*nb_divmod*/
+    (ternaryfunc)0,/*nb_power*/
+    (unaryfunc)0,  /*nb_negative*/
+    (unaryfunc)0,  /*nb_positive*/
+    (unaryfunc)0,  /*nb_absolute*/
+    (inquiry)0,    /*nb_nonzero*/
+    0,            /*nb_invert*/
+    0,            /*nb_lshift*/
+    0,            /*nb_rshift*/
+    0,            /*nb_and*/
+    0,            /*nb_xor*/
+    0,            /*nb_or*/
+    (coercion)0,   /*nb_coerce*/
+    (unaryfunc)PySwigObject_long, /*nb_int*/
+    (unaryfunc)PySwigObject_long, /*nb_long*/
+    (unaryfunc)0,                 /*nb_float*/
+    (unaryfunc)PySwigObject_oct,  /*nb_oct*/
+    (unaryfunc)PySwigObject_hex,  /*nb_hex*/
+#if PY_VERSION_HEX >= 0x02050000 /* 2.5.0 */
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_index */
+#elif PY_VERSION_HEX >= 0x02020000 /* 2.2.0 */
+    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_true_divide */
+#elif PY_VERSION_HEX >= 0x02000000 /* 2.0.0 */
+    0,0,0,0,0,0,0,0,0,0,0 /* nb_inplace_add -> nb_inplace_or */
+#endif
+  };
+
+  static PyTypeObject pyswigobject_type;  
+  static int type_init = 0;
+  if (!type_init) {
+    const PyTypeObject tmp
+      = {
+       PyObject_HEAD_INIT(NULL)
+       0,                                  /* ob_size */
+       (char *)"PySwigObject",             /* tp_name */
+       sizeof(PySwigObject),               /* tp_basicsize */
+       0,                                  /* tp_itemsize */
+       (destructor)PySwigObject_dealloc,   /* tp_dealloc */
+       (printfunc)PySwigObject_print,      /* tp_print */
+#if PY_VERSION_HEX < 0x02020000
+       (getattrfunc)PySwigObject_getattr,  /* tp_getattr */ 
+#else
+       (getattrfunc)0,                     /* tp_getattr */ 
+#endif
+       (setattrfunc)0,                     /* tp_setattr */ 
+       (cmpfunc)PySwigObject_compare,      /* tp_compare */ 
+       (reprfunc)PySwigObject_repr,        /* tp_repr */    
+       &PySwigObject_as_number,            /* tp_as_number */
+       0,                                  /* tp_as_sequence */
+       0,                                  /* tp_as_mapping */
+       (hashfunc)0,                        /* tp_hash */
+       (ternaryfunc)0,                     /* tp_call */
+       (reprfunc)PySwigObject_str,         /* tp_str */
+       PyObject_GenericGetAttr,            /* tp_getattro */
+       0,                                  /* tp_setattro */
+       0,                                  /* tp_as_buffer */
+       Py_TPFLAGS_DEFAULT,                 /* tp_flags */
+       swigobject_doc,                     /* tp_doc */        
+       0,                                  /* tp_traverse */
+       0,                                  /* tp_clear */
+       0,                                  /* tp_richcompare */
+       0,                                  /* tp_weaklistoffset */
+#if PY_VERSION_HEX >= 0x02020000
+       0,                                  /* tp_iter */
+       0,                                  /* tp_iternext */
+       swigobject_methods,                 /* tp_methods */ 
+       0,                                  /* tp_members */
+       0,                                  /* tp_getset */             
+       0,                                  /* tp_base */               
+       0,                                  /* tp_dict */               
+       0,                                  /* tp_descr_get */          
+       0,                                  /* tp_descr_set */          
+       0,                                  /* tp_dictoffset */         
+       0,                                  /* tp_init */               
+       0,                                  /* tp_alloc */              
+       0,                                  /* tp_new */                
+       0,                                  /* tp_free */          
+        0,                                  /* tp_is_gc */  
+       0,                                  /* tp_bases */   
+       0,                                  /* tp_mro */
+       0,                                  /* tp_cache */   
+       0,                                  /* tp_subclasses */
+       0,                                  /* tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+       0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+       0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+      };
+    pyswigobject_type = tmp;
+    pyswigobject_type.ob_type = &PyType_Type;
+    type_init = 1;
+  }
+  return &pyswigobject_type;
+}
+
+SWIGRUNTIME PyObject *
+PySwigObject_New(void *ptr, swig_type_info *ty, int own)
+{
+  PySwigObject *sobj = PyObject_NEW(PySwigObject, PySwigObject_type());
+  if (sobj) {
+    sobj->ptr  = ptr;
+    sobj->ty   = ty;
+    sobj->own  = own;
+    sobj->next = 0;
+  }
+  return (PyObject *)sobj;
+}
+
+/* -----------------------------------------------------------------------------
+ * Implements a simple Swig Packed type, and use it instead of string
+ * ----------------------------------------------------------------------------- */
+
+typedef struct {
+  PyObject_HEAD
+  void *pack;
+  swig_type_info *ty;
+  size_t size;
+} PySwigPacked;
+
+SWIGRUNTIME int
+PySwigPacked_print(PySwigPacked *v, FILE *fp, int SWIGUNUSEDPARM(flags))
+{
+  char result[SWIG_BUFFER_SIZE];
+  fputs("<Swig Packed ", fp); 
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+    fputs("at ", fp); 
+    fputs(result, fp); 
+  }
+  fputs(v->ty->name,fp); 
+  fputs(">", fp);
+  return 0; 
+}
+  
+SWIGRUNTIME PyObject *
+PySwigPacked_repr(PySwigPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))) {
+    return PyString_FromFormat("<Swig Packed at %s%s>", result, v->ty->name);
+  } else {
+    return PyString_FromFormat("<Swig Packed %s>", v->ty->name);
+  }  
+}
+
+SWIGRUNTIME PyObject *
+PySwigPacked_str(PySwigPacked *v)
+{
+  char result[SWIG_BUFFER_SIZE];
+  if (SWIG_PackDataName(result, v->pack, v->size, 0, sizeof(result))){
+    return PyString_FromFormat("%s%s", result, v->ty->name);
+  } else {
+    return PyString_FromString(v->ty->name);
+  }  
+}
+
+SWIGRUNTIME int
+PySwigPacked_compare(PySwigPacked *v, PySwigPacked *w)
+{
+  size_t i = v->size;
+  size_t j = w->size;
+  int s = (i < j) ? -1 : ((i > j) ? 1 : 0);
+  return s ? s : strncmp((char *)v->pack, (char *)w->pack, 2*v->size);
+}
+
+SWIGRUNTIME PyTypeObject* _PySwigPacked_type(void);
+
+SWIGRUNTIME PyTypeObject*
+PySwigPacked_type(void) {
+  static PyTypeObject *SWIG_STATIC_POINTER(type) = _PySwigPacked_type();
+  return type;
+}
+
+SWIGRUNTIMEINLINE int
+PySwigPacked_Check(PyObject *op) {
+  return ((op)->ob_type == _PySwigPacked_type()) 
+    || (strcmp((op)->ob_type->tp_name,"PySwigPacked") == 0);
+}
+
+SWIGRUNTIME void
+PySwigPacked_dealloc(PyObject *v)
+{
+  if (PySwigPacked_Check(v)) {
+    PySwigPacked *sobj = (PySwigPacked *) v;
+    free(sobj->pack);
+  }
+  PyObject_DEL(v);
+}
+
+SWIGRUNTIME PyTypeObject*
+_PySwigPacked_type(void) {
+  static char swigpacked_doc[] = "Swig object carries a C/C++ instance pointer";
+  static PyTypeObject pyswigpacked_type;
+  static int type_init = 0;  
+  if (!type_init) {
+    const PyTypeObject tmp
+      = {
+       PyObject_HEAD_INIT(NULL)
+       0,                                  /* ob_size */       
+       (char *)"PySwigPacked",             /* tp_name */       
+       sizeof(PySwigPacked),               /* tp_basicsize */  
+       0,                                  /* tp_itemsize */   
+       (destructor)PySwigPacked_dealloc,   /* tp_dealloc */    
+       (printfunc)PySwigPacked_print,      /* tp_print */      
+       (getattrfunc)0,                     /* tp_getattr */    
+       (setattrfunc)0,                     /* tp_setattr */    
+       (cmpfunc)PySwigPacked_compare,      /* tp_compare */    
+       (reprfunc)PySwigPacked_repr,        /* tp_repr */       
+       0,                                  /* tp_as_number */  
+       0,                                  /* tp_as_sequence */
+       0,                                  /* tp_as_mapping */ 
+       (hashfunc)0,                        /* tp_hash */       
+       (ternaryfunc)0,                     /* tp_call */       
+       (reprfunc)PySwigPacked_str,         /* tp_str */        
+       PyObject_GenericGetAttr,            /* tp_getattro */
+       0,                                  /* tp_setattro */
+       0,                                  /* tp_as_buffer */
+       Py_TPFLAGS_DEFAULT,                 /* tp_flags */
+       swigpacked_doc,                     /* tp_doc */
+       0,                                  /* tp_traverse */
+       0,                                  /* tp_clear */
+       0,                                  /* tp_richcompare */
+       0,                                  /* tp_weaklistoffset */
+#if PY_VERSION_HEX >= 0x02020000
+       0,                                  /* tp_iter */
+       0,                                  /* tp_iternext */
+       0,                                  /* tp_methods */ 
+       0,                                  /* tp_members */
+       0,                                  /* tp_getset */             
+       0,                                  /* tp_base */               
+       0,                                  /* tp_dict */               
+       0,                                  /* tp_descr_get */          
+       0,                                  /* tp_descr_set */          
+       0,                                  /* tp_dictoffset */         
+       0,                                  /* tp_init */               
+       0,                                  /* tp_alloc */              
+       0,                                  /* tp_new */                
+       0,                                  /* tp_free */          
+        0,                                  /* tp_is_gc */  
+       0,                                  /* tp_bases */   
+       0,                                  /* tp_mro */
+       0,                                  /* tp_cache */   
+       0,                                  /* tp_subclasses */
+       0,                                  /* tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+       0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+       0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+      };
+    pyswigpacked_type = tmp;
+    pyswigpacked_type.ob_type = &PyType_Type;
+    type_init = 1;
+  }
+  return &pyswigpacked_type;
+}
+
+SWIGRUNTIME PyObject *
+PySwigPacked_New(void *ptr, size_t size, swig_type_info *ty)
+{
+  PySwigPacked *sobj = PyObject_NEW(PySwigPacked, PySwigPacked_type());
+  if (sobj) {
+    void *pack = malloc(size);
+    if (pack) {
+      memcpy(pack, ptr, size);
+      sobj->pack = pack;
+      sobj->ty   = ty;
+      sobj->size = size;
+    } else {
+      PyObject_DEL((PyObject *) sobj);
+      sobj = 0;
+    }
+  }
+  return (PyObject *) sobj;
+}
+
+SWIGRUNTIME swig_type_info *
+PySwigPacked_UnpackData(PyObject *obj, void *ptr, size_t size)
+{
+  if (PySwigPacked_Check(obj)) {
+    PySwigPacked *sobj = (PySwigPacked *)obj;
+    if (sobj->size != size) return 0;
+    memcpy(ptr, sobj->pack, size);
+    return sobj->ty;
+  } else {
+    return 0;
+  }
+}
+
+/* -----------------------------------------------------------------------------
+ * pointers/data manipulation
+ * ----------------------------------------------------------------------------- */
+
+SWIGRUNTIMEINLINE PyObject *
+_SWIG_This(void)
+{
+  return PyString_FromString("this");
+}
+
+SWIGRUNTIME PyObject *
+SWIG_This(void)
+{
+  static PyObject *SWIG_STATIC_POINTER(swig_this) = _SWIG_This();
+  return swig_this;
+}
+
+/* #define SWIG_PYTHON_SLOW_GETSET_THIS */
+
+SWIGRUNTIME PySwigObject *
+SWIG_Python_GetSwigThis(PyObject *pyobj) 
+{
+  if (PySwigObject_Check(pyobj)) {
+    return (PySwigObject *) pyobj;
+  } else {
+    PyObject *obj = 0;
+#if (!defined(SWIG_PYTHON_SLOW_GETSET_THIS) && (PY_VERSION_HEX >= 0x02030000))
+    if (PyInstance_Check(pyobj)) {
+      obj = _PyInstance_Lookup(pyobj, SWIG_This());      
+    } else {
+      PyObject **dictptr = _PyObject_GetDictPtr(pyobj);
+      if (dictptr != NULL) {
+       PyObject *dict = *dictptr;
+       obj = dict ? PyDict_GetItem(dict, SWIG_This()) : 0;
+      } else {
+#ifdef PyWeakref_CheckProxy
+       if (PyWeakref_CheckProxy(pyobj)) {
+         PyObject *wobj = PyWeakref_GET_OBJECT(pyobj);
+         return wobj ? SWIG_Python_GetSwigThis(wobj) : 0;
+       }
+#endif
+       obj = PyObject_GetAttr(pyobj,SWIG_This());
+       if (obj) {
+         Py_DECREF(obj);
+       } else {
+         if (PyErr_Occurred()) PyErr_Clear();
+         return 0;
+       }
+      }
+    }
+#else
+    obj = PyObject_GetAttr(pyobj,SWIG_This());
+    if (obj) {
+      Py_DECREF(obj);
+    } else {
+      if (PyErr_Occurred()) PyErr_Clear();
+      return 0;
+    }
+#endif
+    if (obj && !PySwigObject_Check(obj)) {
+      /* a PyObject is called 'this', try to get the 'real this'
+        PySwigObject from it */ 
+      return SWIG_Python_GetSwigThis(obj);
+    }
+    return (PySwigObject *)obj;
+  }
+}
+
+/* Acquire a pointer value */
+
+SWIGRUNTIME int
+SWIG_Python_AcquirePtr(PyObject *obj, int own) {
+  if (own) {
+    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);
+    if (sobj) {
+      int oldown = sobj->own;
+      sobj->own = own;
+      return oldown;
+    }
+  }
+  return 0;
+}
+
+/* Convert a pointer value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertPtrAndOwn(PyObject *obj, void **ptr, swig_type_info *ty, int flags, int *own) {
+  if (!obj) return SWIG_ERROR;
+  if (obj == Py_None) {
+    if (ptr) *ptr = 0;
+    return SWIG_OK;
+  } else {
+    PySwigObject *sobj = SWIG_Python_GetSwigThis(obj);
+    while (sobj) {
+      void *vptr = sobj->ptr;
+      if (ty) {
+       swig_type_info *to = sobj->ty;
+       if (to == ty) {
+         /* no type cast needed */
+         if (ptr) *ptr = vptr;
+         break;
+       } else {
+         swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+         if (!tc) {
+           sobj = (PySwigObject *)sobj->next;
+         } else {
+           if (ptr) *ptr = SWIG_TypeCast(tc,vptr);
+           break;
+         }
+       }
+      } else {
+       if (ptr) *ptr = vptr;
+       break;
+      }
+    }
+    if (sobj) {
+      if (own) *own = sobj->own;
+      if (flags & SWIG_POINTER_DISOWN) {
+       sobj->own = 0;
+      }
+      return SWIG_OK;
+    } else {
+      int res = SWIG_ERROR;
+      if (flags & SWIG_POINTER_IMPLICIT_CONV) {
+       PySwigClientData *data = ty ? (PySwigClientData *) ty->clientdata : 0;
+       if (data && !data->implicitconv) {
+         PyObject *klass = data->klass;
+         if (klass) {
+           PyObject *impconv;
+           data->implicitconv = 1; /* avoid recursion and call 'explicit' constructors*/
+           impconv = SWIG_Python_CallFunctor(klass, obj);
+           data->implicitconv = 0;
+           if (PyErr_Occurred()) {
+             PyErr_Clear();
+             impconv = 0;
+           }
+           if (impconv) {
+             PySwigObject *iobj = SWIG_Python_GetSwigThis(impconv);
+             if (iobj) {
+               void *vptr;
+               res = SWIG_Python_ConvertPtrAndOwn((PyObject*)iobj, &vptr, ty, 0, 0);
+               if (SWIG_IsOK(res)) {
+                 if (ptr) {
+                   *ptr = vptr;
+                   /* transfer the ownership to 'ptr' */
+                   iobj->own = 0;
+                   res = SWIG_AddCast(res);
+                   res = SWIG_AddNewMask(res);
+                 } else {
+                   res = SWIG_AddCast(res);                
+                 }
+               }
+             }
+             Py_DECREF(impconv);
+           }
+         }
+       }
+      }
+      return res;
+    }
+  }
+}
+
+/* Convert a function ptr value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertFunctionPtr(PyObject *obj, void **ptr, swig_type_info *ty) {
+  if (!PyCFunction_Check(obj)) {
+    return SWIG_ConvertPtr(obj, ptr, ty, 0);
+  } else {
+    void *vptr = 0;
+    
+    /* here we get the method pointer for callbacks */
+    const char *doc = (((PyCFunctionObject *)obj) -> m_ml -> ml_doc);
+    const char *desc = doc ? strstr(doc, "swig_ptr: ") : 0;
+    if (desc) {
+      desc = ty ? SWIG_UnpackVoidPtr(desc + 10, &vptr, ty->name) : 0;
+      if (!desc) return SWIG_ERROR;
+    }
+    if (ty) {
+      swig_cast_info *tc = SWIG_TypeCheck(desc,ty);
+      if (!tc) return SWIG_ERROR;
+      *ptr = SWIG_TypeCast(tc,vptr);
+    } else {
+      *ptr = vptr;
+    }
+    return SWIG_OK;
+  }
+}
+
+/* Convert a packed value value */
+
+SWIGRUNTIME int
+SWIG_Python_ConvertPacked(PyObject *obj, void *ptr, size_t sz, swig_type_info *ty) {
+  swig_type_info *to = PySwigPacked_UnpackData(obj, ptr, sz);
+  if (!to) return SWIG_ERROR;
+  if (ty) {
+    if (to != ty) {
+      /* check type cast? */
+      swig_cast_info *tc = SWIG_TypeCheck(to->name,ty);
+      if (!tc) return SWIG_ERROR;
+    }
+  }
+  return SWIG_OK;
+}  
+
+/* -----------------------------------------------------------------------------
+ * Create a new pointer object
+ * ----------------------------------------------------------------------------- */
+
+/*
+  Create a new instance object, whitout calling __init__, and set the
+  'this' attribute.
+*/
+
+SWIGRUNTIME PyObject* 
+SWIG_Python_NewShadowInstance(PySwigClientData *data, PyObject *swig_this)
+{
+#if (PY_VERSION_HEX >= 0x02020000)
+  PyObject *inst = 0;
+  PyObject *newraw = data->newraw;
+  if (newraw) {
+    inst = PyObject_Call(newraw, data->newargs, NULL);
+    if (inst) {
+#if !defined(SWIG_PYTHON_SLOW_GETSET_THIS)
+      PyObject **dictptr = _PyObject_GetDictPtr(inst);
+      if (dictptr != NULL) {
+       PyObject *dict = *dictptr;
+       if (dict == NULL) {
+         dict = PyDict_New();
+         *dictptr = dict;
+         PyDict_SetItem(dict, SWIG_This(), swig_this);
+       }
+      }
+#else
+      PyObject *key = SWIG_This();
+      PyObject_SetAttr(inst, key, swig_this);
+#endif
+    }
+  } else {
+    PyObject *dict = PyDict_New();
+    PyDict_SetItem(dict, SWIG_This(), swig_this);
+    inst = PyInstance_NewRaw(data->newargs, dict);
+    Py_DECREF(dict);
+  }
+  return inst;
+#else
+#if (PY_VERSION_HEX >= 0x02010000)
+  PyObject *inst;
+  PyObject *dict = PyDict_New();
+  PyDict_SetItem(dict, SWIG_This(), swig_this);
+  inst = PyInstance_NewRaw(data->newargs, dict);
+  Py_DECREF(dict);
+  return (PyObject *) inst;
+#else
+  PyInstanceObject *inst = PyObject_NEW(PyInstanceObject, &PyInstance_Type);
+  if (inst == NULL) {
+    return NULL;
+  }
+  inst->in_class = (PyClassObject *)data->newargs;
+  Py_INCREF(inst->in_class);
+  inst->in_dict = PyDict_New();
+  if (inst->in_dict == NULL) {
+    Py_DECREF(inst);
+    return NULL;
+  }
+#ifdef Py_TPFLAGS_HAVE_WEAKREFS
+  inst->in_weakreflist = NULL;
+#endif
+#ifdef Py_TPFLAGS_GC
+  PyObject_GC_Init(inst);
+#endif
+  PyDict_SetItem(inst->in_dict, SWIG_This(), swig_this);
+  return (PyObject *) inst;
+#endif
+#endif
+}
+
+SWIGRUNTIME void
+SWIG_Python_SetSwigThis(PyObject *inst, PyObject *swig_this)
+{
+ PyObject *dict;
+#if (PY_VERSION_HEX >= 0x02020000) && !defined(SWIG_PYTHON_SLOW_GETSET_THIS)
+ PyObject **dictptr = _PyObject_GetDictPtr(inst);
+ if (dictptr != NULL) {
+   dict = *dictptr;
+   if (dict == NULL) {
+     dict = PyDict_New();
+     *dictptr = dict;
+   }
+   PyDict_SetItem(dict, SWIG_This(), swig_this);
+   return;
+ }
+#endif
+ dict = PyObject_GetAttrString(inst, (char*)"__dict__");
+ PyDict_SetItem(dict, SWIG_This(), swig_this);
+ Py_DECREF(dict);
+} 
+
+
+SWIGINTERN PyObject *
+SWIG_Python_InitShadowInstance(PyObject *args) {
+  PyObject *obj[2];
+  if (!SWIG_Python_UnpackTuple(args,(char*)"swiginit", 2, 2, obj)) {
+    return NULL;
+  } else {
+    PySwigObject *sthis = SWIG_Python_GetSwigThis(obj[0]);
+    if (sthis) {
+      PySwigObject_append((PyObject*) sthis, obj[1]);
+    } else {
+      SWIG_Python_SetSwigThis(obj[0], obj[1]);
+    }
+    return SWIG_Py_Void();
+  }
+}
+
+/* Create a new pointer object */
+
+SWIGRUNTIME PyObject *
+SWIG_Python_NewPointerObj(void *ptr, swig_type_info *type, int flags) {
+  if (!ptr) {
+    return SWIG_Py_Void();
+  } else {
+    int own = (flags & SWIG_POINTER_OWN) ? SWIG_POINTER_OWN : 0;
+    PyObject *robj = PySwigObject_New(ptr, type, own);
+    PySwigClientData *clientdata = type ? (PySwigClientData *)(type->clientdata) : 0;
+    if (clientdata && !(flags & SWIG_POINTER_NOSHADOW)) {
+      PyObject *inst = SWIG_Python_NewShadowInstance(clientdata, robj);
+      if (inst) {
+       Py_DECREF(robj);
+       robj = inst;
+      }
+    }
+    return robj;
+  }
+}
+
+/* Create a new packed object */
+
+SWIGRUNTIMEINLINE PyObject *
+SWIG_Python_NewPackedObj(void *ptr, size_t sz, swig_type_info *type) {
+  return ptr ? PySwigPacked_New((void *) ptr, sz, type) : SWIG_Py_Void();
+}
+
+/* -----------------------------------------------------------------------------*
+ *  Get type list 
+ * -----------------------------------------------------------------------------*/
+
+#ifdef SWIG_LINK_RUNTIME
+void *SWIG_ReturnGlobalTypeList(void *);
+#endif
+
+SWIGRUNTIME swig_module_info *
+SWIG_Python_GetModule(void) {
+  static void *type_pointer = (void *)0;
+  /* first check if module already created */
+  if (!type_pointer) {
+#ifdef SWIG_LINK_RUNTIME
+    type_pointer = SWIG_ReturnGlobalTypeList((void *)0);
+#else
+    type_pointer = PyCObject_Import((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION,
+                                   (char*)"type_pointer" SWIG_TYPE_TABLE_NAME);
+    if (PyErr_Occurred()) {
+      PyErr_Clear();
+      type_pointer = (void *)0;
+    }
+#endif
+  }
+  return (swig_module_info *) type_pointer;
+}
+
+#if PY_MAJOR_VERSION < 2
+/* PyModule_AddObject function was introduced in Python 2.0.  The following function
+   is copied out of Python/modsupport.c in python version 2.3.4 */
+SWIGINTERN int
+PyModule_AddObject(PyObject *m, char *name, PyObject *o)
+{
+  PyObject *dict;
+  if (!PyModule_Check(m)) {
+    PyErr_SetString(PyExc_TypeError,
+                   "PyModule_AddObject() needs module as first arg");
+    return SWIG_ERROR;
+  }
+  if (!o) {
+    PyErr_SetString(PyExc_TypeError,
+                   "PyModule_AddObject() needs non-NULL value");
+    return SWIG_ERROR;
+  }
+  
+  dict = PyModule_GetDict(m);
+  if (dict == NULL) {
+    /* Internal error -- modules must have a dict! */
+    PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
+                PyModule_GetName(m));
+    return SWIG_ERROR;
+  }
+  if (PyDict_SetItemString(dict, name, o))
+    return SWIG_ERROR;
+  Py_DECREF(o);
+  return SWIG_OK;
+}
+#endif
+
+SWIGRUNTIME void
+SWIG_Python_DestroyModule(void *vptr)
+{
+  swig_module_info *swig_module = (swig_module_info *) vptr;
+  swig_type_info **types = swig_module->types;
+  size_t i;
+  for (i =0; i < swig_module->size; ++i) {
+    swig_type_info *ty = types[i];
+    if (ty->owndata) {
+      PySwigClientData *data = (PySwigClientData *) ty->clientdata;
+      if (data) PySwigClientData_Del(data);
+    }
+  }
+  Py_DECREF(SWIG_This());
+}
+
+SWIGRUNTIME void
+SWIG_Python_SetModule(swig_module_info *swig_module) {
+  static PyMethodDef swig_empty_runtime_method_table[] = { {NULL, NULL, 0, NULL} };/* Sentinel */
+
+  PyObject *module = Py_InitModule((char*)"swig_runtime_data" SWIG_RUNTIME_VERSION,
+                                  swig_empty_runtime_method_table);
+  PyObject *pointer = PyCObject_FromVoidPtr((void *) swig_module, SWIG_Python_DestroyModule);
+  if (pointer && module) {
+    PyModule_AddObject(module, (char*)"type_pointer" SWIG_TYPE_TABLE_NAME, pointer);
+  } else {
+    Py_XDECREF(pointer);
+  }
+}
+
+/* The python cached type query */
+SWIGRUNTIME PyObject *
+SWIG_Python_TypeCache(void) {
+  static PyObject *SWIG_STATIC_POINTER(cache) = PyDict_New();
+  return cache;
+}
+
+SWIGRUNTIME swig_type_info *
+SWIG_Python_TypeQuery(const char *type)
+{
+  PyObject *cache = SWIG_Python_TypeCache();
+  PyObject *key = PyString_FromString(type); 
+  PyObject *obj = PyDict_GetItem(cache, key);
+  swig_type_info *descriptor;
+  if (obj) {
+    descriptor = (swig_type_info *) PyCObject_AsVoidPtr(obj);
+  } else {
+    swig_module_info *swig_module = SWIG_Python_GetModule();
+    descriptor = SWIG_TypeQueryModule(swig_module, swig_module, type);
+    if (descriptor) {
+      obj = PyCObject_FromVoidPtr(descriptor, NULL);
+      PyDict_SetItem(cache, key, obj);
+      Py_DECREF(obj);
+    }
+  }
+  Py_DECREF(key);
+  return descriptor;
+}
+
+/* 
+   For backward compatibility only
+*/
+#define SWIG_POINTER_EXCEPTION  0
+#define SWIG_arg_fail(arg)      SWIG_Python_ArgFail(arg)
+#define SWIG_MustGetPtr(p, type, argnum, flags)  SWIG_Python_MustGetPtr(p, type, argnum, flags)
+
+SWIGRUNTIME int
+SWIG_Python_AddErrMesg(const char* mesg, int infront)
+{
+  if (PyErr_Occurred()) {
+    PyObject *type = 0;
+    PyObject *value = 0;
+    PyObject *traceback = 0;
+    PyErr_Fetch(&type, &value, &traceback);
+    if (value) {
+      PyObject *old_str = PyObject_Str(value);
+      Py_XINCREF(type);
+      PyErr_Clear();
+      if (infront) {
+       PyErr_Format(type, "%s %s", mesg, PyString_AsString(old_str));
+      } else {
+       PyErr_Format(type, "%s %s", PyString_AsString(old_str), mesg);
+      }
+      Py_DECREF(old_str);
+    }
+    return 1;
+  } else {
+    return 0;
+  }
+}
+  
+SWIGRUNTIME int
+SWIG_Python_ArgFail(int argnum)
+{
+  if (PyErr_Occurred()) {
+    /* add information about failing argument */
+    char mesg[256];
+    PyOS_snprintf(mesg, sizeof(mesg), "argument number %d:", argnum);
+    return SWIG_Python_AddErrMesg(mesg, 1);
+  } else {
+    return 0;
+  }
+}
+
+SWIGRUNTIMEINLINE const char *
+PySwigObject_GetDesc(PyObject *self)
+{
+  PySwigObject *v = (PySwigObject *)self;
+  swig_type_info *ty = v ? v->ty : 0;
+  return ty ? ty->str : (char*)"";
+}
+
+SWIGRUNTIME void
+SWIG_Python_TypeError(const char *type, PyObject *obj)
+{
+  if (type) {
+#if defined(SWIG_COBJECT_TYPES)
+    if (obj && PySwigObject_Check(obj)) {
+      const char *otype = (const char *) PySwigObject_GetDesc(obj);
+      if (otype) {
+       PyErr_Format(PyExc_TypeError, "a '%s' is expected, 'PySwigObject(%s)' is received",
+                    type, otype);
+       return;
+      }
+    } else 
+#endif      
+    {
+      const char *otype = (obj ? obj->ob_type->tp_name : 0); 
+      if (otype) {
+       PyObject *str = PyObject_Str(obj);
+       const char *cstr = str ? PyString_AsString(str) : 0;
+       if (cstr) {
+         PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s(%s)' is received",
+                      type, otype, cstr);
+       } else {
+         PyErr_Format(PyExc_TypeError, "a '%s' is expected, '%s' is received",
+                      type, otype);
+       }
+       Py_XDECREF(str);
+       return;
+      }
+    }   
+    PyErr_Format(PyExc_TypeError, "a '%s' is expected", type);
+  } else {
+    PyErr_Format(PyExc_TypeError, "unexpected type is received");
+  }
+}
+
+
+/* Convert a pointer value, signal an exception on a type mismatch */
+SWIGRUNTIME void *
+SWIG_Python_MustGetPtr(PyObject *obj, swig_type_info *ty, int argnum, int flags) {
+  void *result;
+  if (SWIG_Python_ConvertPtr(obj, &result, ty, flags) == -1) {
+    PyErr_Clear();
+    if (flags & SWIG_POINTER_EXCEPTION) {
+      SWIG_Python_TypeError(SWIG_TypePrettyName(ty), obj);
+      SWIG_Python_ArgFail(argnum);
+    }
+  }
+  return result;
+}
+
+
+#ifdef __cplusplus
+#if 0
+{ /* cc-mode */
+#endif
+}
+#endif
+
+
+
+#define SWIG_exception_fail(code, msg) do { SWIG_Error(code, msg); SWIG_fail; } while(0) 
+
+#define SWIG_contract_assert(expr, msg) if (!(expr)) { SWIG_Error(SWIG_RuntimeError, msg); SWIG_fail; } else 
+
+
+
+/* -------- TYPES TABLE (BEGIN) -------- */
+
+#define SWIGTYPE_p_FILE swig_types[0]
+#define SWIGTYPE_p_MAC swig_types[1]
+#define SWIGTYPE_p_Mote swig_types[2]
+#define SWIGTYPE_p_Packet swig_types[3]
+#define SWIGTYPE_p_Radio swig_types[4]
+#define SWIGTYPE_p_Tossim swig_types[5]
+#define SWIGTYPE_p_Variable swig_types[6]
+#define SWIGTYPE_p_char swig_types[7]
+#define SWIGTYPE_p_int swig_types[8]
+#define SWIGTYPE_p_nesc_app swig_types[9]
+#define SWIGTYPE_p_p_char swig_types[10]
+#define SWIGTYPE_p_var_string swig_types[11]
+static swig_type_info *swig_types[13];
+static swig_module_info swig_module = {swig_types, 12, 0, 0, 0, 0};
+#define SWIG_TypeQuery(name) SWIG_TypeQueryModule(&swig_module, &swig_module, name)
+#define SWIG_MangledTypeQuery(name) SWIG_MangledTypeQueryModule(&swig_module, &swig_module, name)
+
+/* -------- TYPES TABLE (END) -------- */
+
+#if (PY_VERSION_HEX <= 0x02000000)
+# if !defined(SWIG_PYTHON_CLASSIC)
+#  error "This python version requires swig to be run with the '-classic' option"
+# endif
+#endif
+
+/*-----------------------------------------------
+              @(target):= _TOSSIM.so
+  ------------------------------------------------*/
+#define SWIG_init    init_TOSSIM
+
+#define SWIG_name    "_TOSSIM"
+
+#define SWIGVERSION 0x010333 
+#define SWIG_VERSION SWIGVERSION
+
+
+#define SWIG_as_voidptr(a) const_cast< void * >(static_cast< const void * >(a)) 
+#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),reinterpret_cast< void** >(a)) 
+
+
+#include <stdexcept>
+
+
+namespace swig {
+  class PyObject_ptr {
+  protected:
+    PyObject *_obj;
+
+  public:
+    PyObject_ptr() :_obj(0)
+    {
+    }
+
+    PyObject_ptr(const PyObject_ptr& item) : _obj(item._obj)
+    {
+      Py_XINCREF(_obj);      
+    }
+    
+    PyObject_ptr(PyObject *obj, bool initial_ref = true) :_obj(obj)
+    {
+      if (initial_ref) Py_XINCREF(_obj);
+    }
+    
+    PyObject_ptr & operator=(const PyObject_ptr& item) 
+    {
+      Py_XINCREF(item._obj);
+      Py_XDECREF(_obj);
+      _obj = item._obj;
+      return *this;      
+    }
+    
+    ~PyObject_ptr() 
+    {
+      Py_XDECREF(_obj);
+    }
+    
+    operator PyObject *() const
+    {
+      return _obj;
+    }
+
+    PyObject *operator->() const
+    {
+      return _obj;
+    }
+  };
+}
+
+
+namespace swig {
+  struct PyObject_var : PyObject_ptr {
+    PyObject_var(PyObject* obj = 0) : PyObject_ptr(obj, false) { }
+    
+    PyObject_var & operator = (PyObject* obj)
+    {
+      Py_XDECREF(_obj);
+      _obj = obj;
+      return *this;      
+    }
+  };
+}
+
+
+#include <memory.h>
+#include <tossim.h>
+
+enum {
+  PRIMITIVE_INTEGER      = 0,
+  PRIMITIVE_FLOAT   = 1,
+  PRIMITIVE_UNKNOWN = 2
+};
+
+int lengthOfType(char* type) {
+  if (strcmp(type, "uint8_t") == 0) {
+    return sizeof(uint8_t);
+  }
+  else if (strcmp(type, "uint16_t") == 0) {
     return sizeof(uint16_t);
   }
   else if (strcmp(type, "uint32_t") == 0) {
@@ -873,2625 +2776,4379 @@ PyObject* listFromArray(char* type, char* ptr, int len) {
 #include <mac.h>
 
 
+  #define SWIG_From_long   PyInt_FromLong 
+
+
+SWIGINTERNINLINE PyObject *
+SWIG_From_int  (int value)
+{    
+  return SWIG_From_long  (value);
+}
+
+
+#include <limits.h>
+#if !defined(SWIG_NO_LLONG_MAX)
+# if !defined(LLONG_MAX) && defined(__GNUC__) && defined (__LONG_LONG_MAX__)
+#   define LLONG_MAX __LONG_LONG_MAX__
+#   define LLONG_MIN (-LLONG_MAX - 1LL)
+#   define ULLONG_MAX (LLONG_MAX * 2ULL + 1ULL)
+# endif
+#endif
+
+
+SWIGINTERN int
+SWIG_AsVal_double (PyObject *obj, double *val)
+{
+  int res = SWIG_TypeError;
+  if (PyFloat_Check(obj)) {
+    if (val) *val = PyFloat_AsDouble(obj);
+    return SWIG_OK;
+  } else if (PyInt_Check(obj)) {
+    if (val) *val = PyInt_AsLong(obj);
+    return SWIG_OK;
+  } else if (PyLong_Check(obj)) {
+    double v = PyLong_AsDouble(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  }
+#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    int dispatch = 0;
+    double d = PyFloat_AsDouble(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = d;
+      return SWIG_AddCast(SWIG_OK);
+    } else {
+      PyErr_Clear();
+    }
+    if (!dispatch) {
+      long v = PyLong_AsLong(obj);
+      if (!PyErr_Occurred()) {
+       if (val) *val = v;
+       return SWIG_AddCast(SWIG_AddCast(SWIG_OK));
+      } else {
+       PyErr_Clear();
+      }
+    }
+  }
+#endif
+  return res;
+}
+
+
+#include <float.h>
+
+
+#include <math.h>
+
+
+SWIGINTERNINLINE int
+SWIG_CanCastAsInteger(double *d, double min, double max) {
+  double x = *d;
+  if ((min <= x && x <= max)) {
+   double fx = floor(x);
+   double cx = ceil(x);
+   double rd =  ((x - fx) < 0.5) ? fx : cx; /* simple rint */
+   if ((errno == EDOM) || (errno == ERANGE)) {
+     errno = 0;
+   } else {
+     double summ, reps, diff;
+     if (rd < x) {
+       diff = x - rd;
+     } else if (rd > x) {
+       diff = rd - x;
+     } else {
+       return 1;
+     }
+     summ = rd + x;
+     reps = diff/summ;
+     if (reps < 8*DBL_EPSILON) {
+       *d = rd;
+       return 1;
+     }
+   }
+  }
+  return 0;
+}
+
+
+SWIGINTERN int
+SWIG_AsVal_long (PyObject *obj, long* val)
+{
+  if (PyInt_Check(obj)) {
+    if (val) *val = PyInt_AsLong(obj);
+    return SWIG_OK;
+  } else if (PyLong_Check(obj)) {
+    long v = PyLong_AsLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  }
+#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    int dispatch = 0;
+    long v = PyInt_AsLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_AddCast(SWIG_OK);
+    } else {
+      PyErr_Clear();
+    }
+    if (!dispatch) {
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d));
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, LONG_MIN, LONG_MAX)) {
+       if (val) *val = (long)(d);
+       return res;
+      }
+    }
+  }
+#endif
+  return SWIG_TypeError;
+}
+
+
+SWIGINTERN int
+SWIG_AsVal_int (PyObject * obj, int *val)
+{
+  long v;
+  int res = SWIG_AsVal_long (obj, &v);
+  if (SWIG_IsOK(res)) {
+    if ((v < INT_MIN || v > INT_MAX)) {
+      return SWIG_OverflowError;
+    } else {
+      if (val) *val = static_cast< int >(v);
+    }
+  }  
+  return res;
+}
+
+
 #include <radio.h>
 
 
+  #define SWIG_From_double   PyFloat_FromDouble 
+
+
+SWIGINTERNINLINE PyObject*
+  SWIG_From_bool  (bool value)
+{
+  return PyBool_FromLong(value ? 1 : 0);
+}
+
+
 #include <packet.h>
 
+
+SWIGINTERN swig_type_info*
+SWIG_pchar_descriptor(void)
+{
+  static int init = 0;
+  static swig_type_info* info = 0;
+  if (!init) {
+    info = SWIG_TypeQuery("_p_char");
+    init = 1;
+  }
+  return info;
+}
+
+
+SWIGINTERNINLINE PyObject *
+SWIG_FromCharPtrAndSize(const char* carray, size_t size)
+{
+  if (carray) {
+    if (size > INT_MAX) {
+      swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
+      return pchar_descriptor ? 
+       SWIG_NewPointerObj(const_cast< char * >(carray), pchar_descriptor, 0) : SWIG_Py_Void();
+    } else {
+      return PyString_FromStringAndSize(carray, static_cast< int >(size));
+    }
+  } else {
+    return SWIG_Py_Void();
+  }
+}
+
+
+SWIGINTERNINLINE PyObject * 
+SWIG_FromCharPtr(const char *cptr)
+{ 
+  return SWIG_FromCharPtrAndSize(cptr, (cptr ? strlen(cptr) : 0));
+}
+
+
+SWIGINTERN int
+SWIG_AsCharPtrAndSize(PyObject *obj, char** cptr, size_t* psize, int *alloc)
+{
+  if (PyString_Check(obj)) {
+    char *cstr; Py_ssize_t len;
+    PyString_AsStringAndSize(obj, &cstr, &len);
+    if (cptr)  {
+      if (alloc) {
+       /* 
+          In python the user should not be able to modify the inner
+          string representation. To warranty that, if you define
+          SWIG_PYTHON_SAFE_CSTRINGS, a new/copy of the python string
+          buffer is always returned.
+
+          The default behavior is just to return the pointer value,
+          so, be careful.
+       */ 
+#if defined(SWIG_PYTHON_SAFE_CSTRINGS)
+       if (*alloc != SWIG_OLDOBJ) 
+#else
+       if (*alloc == SWIG_NEWOBJ) 
+#endif
+         {
+           *cptr = reinterpret_cast< char* >(memcpy((new char[len + 1]), cstr, sizeof(char)*(len + 1)));
+           *alloc = SWIG_NEWOBJ;
+         }
+       else {
+         *cptr = cstr;
+         *alloc = SWIG_OLDOBJ;
+       }
+      } else {
+       *cptr = PyString_AsString(obj);
+      }
+    }
+    if (psize) *psize = len + 1;
+    return SWIG_OK;
+  } else {
+    swig_type_info* pchar_descriptor = SWIG_pchar_descriptor();
+    if (pchar_descriptor) {
+      void* vptr = 0;
+      if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) {
+       if (cptr) *cptr = (char *) vptr;
+       if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0;
+       if (alloc) *alloc = SWIG_OLDOBJ;
+       return SWIG_OK;
+      }
+    }
+  }
+  return SWIG_TypeError;
+}
+
+
+
+
+
+SWIGINTERN int
+SWIG_AsVal_long_SS_long (PyObject *obj, long long *val)
+{
+  int res = SWIG_TypeError;
+  if (PyLong_Check(obj)) {
+    long long v = PyLong_AsLongLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  } else {
+    long v;
+    res = SWIG_AsVal_long (obj,&v);
+    if (SWIG_IsOK(res)) {
+      if (val) *val = v;
+      return res;
+    }
+  }
+#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    const double mant_max = 1LL << DBL_MANT_DIG;
+    const double mant_min = -mant_max;
+    double d;
+    res = SWIG_AsVal_double (obj,&d);
+    if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, mant_min, mant_max)) {
+      if (val) *val = (long long)(d);
+      return SWIG_AddCast(res);
+    }
+    res = SWIG_TypeError;
+  }
+#endif
+  return res;
+}
+
+
+SWIGINTERNINLINE PyObject* 
+SWIG_From_unsigned_SS_long  (unsigned long value)
+{
+  return (value > LONG_MAX) ?
+    PyLong_FromUnsignedLong(value) : PyInt_FromLong(static_cast< long >(value)); 
+}
+
+
+SWIGINTERNINLINE PyObject* 
+SWIG_From_long_SS_long  (long long value)
+{
+  return ((value < LONG_MIN) || (value > LONG_MAX)) ?
+    PyLong_FromLongLong(value) : PyInt_FromLong(static_cast< long >(value)); 
+}
+
+
+SWIGINTERN int
+SWIG_AsVal_unsigned_SS_long (PyObject *obj, unsigned long *val) 
+{
+  if (PyInt_Check(obj)) {
+    long v = PyInt_AsLong(obj);
+    if (v >= 0) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      return SWIG_OverflowError;
+    }
+  } else if (PyLong_Check(obj)) {
+    unsigned long v = PyLong_AsUnsignedLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_OK;
+    } else {
+      PyErr_Clear();
+    }
+  }
+#ifdef SWIG_PYTHON_CAST_MODE
+  {
+    int dispatch = 0;
+    unsigned long v = PyLong_AsUnsignedLong(obj);
+    if (!PyErr_Occurred()) {
+      if (val) *val = v;
+      return SWIG_AddCast(SWIG_OK);
+    } else {
+      PyErr_Clear();
+    }
+    if (!dispatch) {
+      double d;
+      int res = SWIG_AddCast(SWIG_AsVal_double (obj,&d));
+      if (SWIG_IsOK(res) && SWIG_CanCastAsInteger(&d, 0, ULONG_MAX)) {
+       if (val) *val = (unsigned long)(d);
+       return res;
+      }
+    }
+  }
+#endif
+  return SWIG_TypeError;
+}
+
 #ifdef __cplusplus
 extern "C" {
 #endif
-static PyObject *_wrap_new_MAC(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *result;
-    
-    if(!PyArg_ParseTuple(args,(char *)":new_MAC")) goto fail;
-    result = (MAC *)new MAC();
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_MAC, 1);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_new_MAC(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)":new_MAC")) SWIG_fail;
+  result = (MAC *)new MAC();
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_MAC, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_delete_MAC(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:delete_MAC",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    delete arg1;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_delete_MAC(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_MAC",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_MAC" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  delete arg1;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_initHigh(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_initHigh",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->initHigh();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_initHigh(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_initHigh",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_initHigh" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->initHigh();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_initLow(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_initLow",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->initLow();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_initLow(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_initLow",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_initLow" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->initLow();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_high(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_high",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->high();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_high(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_high",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_high" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->high();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_low(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_low",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->low();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_low(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_low",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_low" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->low();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_symbolsPerSec(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_symbolsPerSec",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->symbolsPerSec();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_symbolsPerSec(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_symbolsPerSec",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_symbolsPerSec" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->symbolsPerSec();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_bitsPerSymbol(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_bitsPerSymbol",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->bitsPerSymbol();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_bitsPerSymbol(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_bitsPerSymbol",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_bitsPerSymbol" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->bitsPerSymbol();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_preambleLength(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_preambleLength",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->preambleLength();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_preambleLength(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_preambleLength",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_preambleLength" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->preambleLength();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_exponentBase(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_exponentBase",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->exponentBase();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_exponentBase(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_exponentBase",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_exponentBase" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->exponentBase();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_maxIterations(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_maxIterations",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->maxIterations();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_maxIterations(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_maxIterations",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_maxIterations" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->maxIterations();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_minFreeSamples(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_minFreeSamples",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->minFreeSamples();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_minFreeSamples(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_minFreeSamples",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_minFreeSamples" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->minFreeSamples();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_rxtxDelay(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_rxtxDelay",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->rxtxDelay();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_rxtxDelay(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_rxtxDelay",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_rxtxDelay" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->rxtxDelay();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_ackTime(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:MAC_ackTime",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->ackTime();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_ackTime(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:MAC_ackTime",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_ackTime" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  result = (int)(arg1)->ackTime();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setInitHigh(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setInitHigh",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setInitHigh(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setInitHigh(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setInitHigh",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setInitHigh" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setInitHigh" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setInitHigh(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setInitLow(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setInitLow",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setInitLow(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setInitLow(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setInitLow",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setInitLow" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setInitLow" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setInitLow(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setHigh(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setHigh",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setHigh(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setHigh(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setHigh",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setHigh" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setHigh" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setHigh(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setLow(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setLow",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setLow(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setLow(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setLow",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setLow" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setLow" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setLow(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setSymbolsPerSec(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setSymbolsPerSec",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setSymbolsPerSec(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setSymbolsPerSec(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setSymbolsPerSec",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setSymbolsPerSec" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setSymbolsPerSec" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setSymbolsPerSec(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setBitsBerSymbol(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setBitsBerSymbol",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setBitsBerSymbol(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setBitsBerSymbol(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setBitsBerSymbol",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setBitsBerSymbol" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setBitsBerSymbol" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setBitsBerSymbol(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setPreambleLength(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setPreambleLength",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setPreambleLength(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setPreambleLength(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setPreambleLength",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setPreambleLength" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setPreambleLength" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setPreambleLength(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setExponentBase(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setExponentBase",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setExponentBase(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setExponentBase(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setExponentBase",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setExponentBase" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setExponentBase" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setExponentBase(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setMaxIterations(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setMaxIterations",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setMaxIterations(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setMaxIterations(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setMaxIterations",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setMaxIterations" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setMaxIterations" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setMaxIterations(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setMinFreeSamples(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setMinFreeSamples",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setMinFreeSamples(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setMinFreeSamples(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setMinFreeSamples",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setMinFreeSamples" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setMinFreeSamples" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setMinFreeSamples(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setRxtxDelay(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setRxtxDelay",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setRxtxDelay(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setRxtxDelay(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setRxtxDelay",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setRxtxDelay" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setRxtxDelay" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setRxtxDelay(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_MAC_setAckTime(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    MAC *arg1 = (MAC *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:MAC_setAckTime",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_MAC,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setAckTime(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_MAC_setAckTime(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  MAC *arg1 = (MAC *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:MAC_setAckTime",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_MAC, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "MAC_setAckTime" "', argument " "1"" of type '" "MAC *""'"); 
+  }
+  arg1 = reinterpret_cast< MAC * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "MAC_setAckTime" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setAckTime(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject * MAC_swigregister(PyObject *self, PyObject *args) {
-    PyObject *obj;
-    if (!PyArg_ParseTuple(args,(char*)"O", &obj)) return NULL;
-    SWIG_TypeClientData(SWIGTYPE_p_MAC, obj);
-    Py_INCREF(obj);
-    return Py_BuildValue((char *)"");
-}
-static PyObject *_wrap_new_Radio(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Radio *result;
-    
-    if(!PyArg_ParseTuple(args,(char *)":new_Radio")) goto fail;
-    result = (Radio *)new Radio();
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Radio, 1);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *MAC_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O|swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_MAC, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_new_Radio(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Radio *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)":new_Radio")) SWIG_fail;
+  result = (Radio *)new Radio();
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Radio, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_delete_Radio(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Radio *arg1 = (Radio *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:delete_Radio",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Radio,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    delete arg1;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_delete_Radio(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Radio *arg1 = (Radio *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_Radio",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Radio, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_Radio" "', argument " "1"" of type '" "Radio *""'"); 
+  }
+  arg1 = reinterpret_cast< Radio * >(argp1);
+  delete arg1;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Radio_add(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Radio *arg1 = (Radio *) 0 ;
-    int arg2 ;
-    int arg3 ;
-    double arg4 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oiid:Radio_add",&obj0,&arg2,&arg3,&arg4)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Radio,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->add(arg2,arg3,arg4);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Radio_add(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Radio *arg1 = (Radio *) 0 ;
+  int arg2 ;
+  int arg3 ;
+  double arg4 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  double val4 ;
+  int ecode4 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  PyObject * obj3 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OOOO:Radio_add",&obj0,&obj1,&obj2,&obj3)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Radio, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Radio_add" "', argument " "1"" of type '" "Radio *""'"); 
+  }
+  arg1 = reinterpret_cast< Radio * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Radio_add" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  ecode3 = SWIG_AsVal_int(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Radio_add" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_double(obj3, &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "Radio_add" "', argument " "4"" of type '" "double""'");
+  } 
+  arg4 = static_cast< double >(val4);
+  (arg1)->add(arg2,arg3,arg4);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Radio_gain(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Radio *arg1 = (Radio *) 0 ;
-    int arg2 ;
-    int arg3 ;
-    double result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oii:Radio_gain",&obj0,&arg2,&arg3)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Radio,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (double)(arg1)->gain(arg2,arg3);
-    
-    resultobj = PyFloat_FromDouble(result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Radio_gain(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Radio *arg1 = (Radio *) 0 ;
+  int arg2 ;
+  int arg3 ;
+  double result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OOO:Radio_gain",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Radio, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Radio_gain" "', argument " "1"" of type '" "Radio *""'"); 
+  }
+  arg1 = reinterpret_cast< Radio * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Radio_gain" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  ecode3 = SWIG_AsVal_int(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Radio_gain" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  result = (double)(arg1)->gain(arg2,arg3);
+  resultobj = SWIG_From_double(static_cast< double >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Radio_connected(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Radio *arg1 = (Radio *) 0 ;
-    int arg2 ;
-    int arg3 ;
-    bool result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oii:Radio_connected",&obj0,&arg2,&arg3)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Radio,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (bool)(arg1)->connected(arg2,arg3);
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Radio_connected(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Radio *arg1 = (Radio *) 0 ;
+  int arg2 ;
+  int arg3 ;
+  bool result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OOO:Radio_connected",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Radio, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Radio_connected" "', argument " "1"" of type '" "Radio *""'"); 
+  }
+  arg1 = reinterpret_cast< Radio * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Radio_connected" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  ecode3 = SWIG_AsVal_int(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Radio_connected" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  result = (bool)(arg1)->connected(arg2,arg3);
+  resultobj = SWIG_From_bool(static_cast< bool >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Radio_remove(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Radio *arg1 = (Radio *) 0 ;
-    int arg2 ;
-    int arg3 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oii:Radio_remove",&obj0,&arg2,&arg3)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Radio,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->remove(arg2,arg3);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Radio_remove(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Radio *arg1 = (Radio *) 0 ;
+  int arg2 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OOO:Radio_remove",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Radio, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Radio_remove" "', argument " "1"" of type '" "Radio *""'"); 
+  }
+  arg1 = reinterpret_cast< Radio * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Radio_remove" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  ecode3 = SWIG_AsVal_int(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Radio_remove" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  (arg1)->remove(arg2,arg3);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Radio_setNoise(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Radio *arg1 = (Radio *) 0 ;
-    int arg2 ;
-    double arg3 ;
-    double arg4 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oidd:Radio_setNoise",&obj0,&arg2,&arg3,&arg4)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Radio,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setNoise(arg2,arg3,arg4);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Radio_setNoise(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Radio *arg1 = (Radio *) 0 ;
+  int arg2 ;
+  double arg3 ;
+  double arg4 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  double val3 ;
+  int ecode3 = 0 ;
+  double val4 ;
+  int ecode4 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  PyObject * obj3 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OOOO:Radio_setNoise",&obj0,&obj1,&obj2,&obj3)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Radio, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Radio_setNoise" "', argument " "1"" of type '" "Radio *""'"); 
+  }
+  arg1 = reinterpret_cast< Radio * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Radio_setNoise" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  ecode3 = SWIG_AsVal_double(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Radio_setNoise" "', argument " "3"" of type '" "double""'");
+  } 
+  arg3 = static_cast< double >(val3);
+  ecode4 = SWIG_AsVal_double(obj3, &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "Radio_setNoise" "', argument " "4"" of type '" "double""'");
+  } 
+  arg4 = static_cast< double >(val4);
+  (arg1)->setNoise(arg2,arg3,arg4);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Radio_setSensitivity(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Radio *arg1 = (Radio *) 0 ;
-    double arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Od:Radio_setSensitivity",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Radio,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setSensitivity(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Radio_setSensitivity(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Radio *arg1 = (Radio *) 0 ;
+  double arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  double val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Radio_setSensitivity",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Radio, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Radio_setSensitivity" "', argument " "1"" of type '" "Radio *""'"); 
+  }
+  arg1 = reinterpret_cast< Radio * >(argp1);
+  ecode2 = SWIG_AsVal_double(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Radio_setSensitivity" "', argument " "2"" of type '" "double""'");
+  } 
+  arg2 = static_cast< double >(val2);
+  (arg1)->setSensitivity(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject * Radio_swigregister(PyObject *self, PyObject *args) {
-    PyObject *obj;
-    if (!PyArg_ParseTuple(args,(char*)"O", &obj)) return NULL;
-    SWIG_TypeClientData(SWIGTYPE_p_Radio, obj);
-    Py_INCREF(obj);
-    return Py_BuildValue((char *)"");
-}
-static PyObject *_wrap_new_Packet(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *result;
-    
-    if(!PyArg_ParseTuple(args,(char *)":new_Packet")) goto fail;
-    result = (Packet *)new Packet();
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Packet, 1);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *Radio_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O|swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_Radio, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_new_Packet(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)":new_Packet")) SWIG_fail;
+  result = (Packet *)new Packet();
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Packet, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_delete_Packet(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:delete_Packet",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    delete arg1;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_delete_Packet(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_Packet",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_Packet" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  delete arg1;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_setSource(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:Packet_setSource",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setSource(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_setSource(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Packet_setSource",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_setSource" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Packet_setSource" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setSource(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_source(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Packet_source",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->source();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_source(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Packet_source",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_source" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  result = (int)(arg1)->source();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_setDestination(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:Packet_setDestination",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setDestination(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_setDestination(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Packet_setDestination",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_setDestination" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Packet_setDestination" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setDestination(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_destination(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Packet_destination",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->destination();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_destination(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Packet_destination",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_destination" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  result = (int)(arg1)->destination();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_setLength(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:Packet_setLength",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setLength(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_setLength(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Packet_setLength",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_setLength" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Packet_setLength" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setLength(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_length(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Packet_length",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->length();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_length(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Packet_length",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_length" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  result = (int)(arg1)->length();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_setType(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:Packet_setType",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setType(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_setType(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Packet_setType",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_setType" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Packet_setType" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setType(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_type(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Packet_type",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->type();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_type(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Packet_type",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_type" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  result = (int)(arg1)->type();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_data(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    char *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Packet_data",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (char *)(arg1)->data();
-    
-    resultobj = result ? PyString_FromString(result) : Py_BuildValue((char*)"");
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_data(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  char *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Packet_data",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_data" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  result = (char *)(arg1)->data();
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_setData(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    char *arg2 ;
-    int arg3 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:Packet_setData",&obj0,&obj1)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    {
-        arg2 = (char *) PyString_AsString(obj1);
-        arg3 = (int) PyString_Size(obj1);
-    }
-    (arg1)->setData(arg2,arg3);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_setData(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  char *arg2 = (char *) 0 ;
+  int arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int res2 ;
+  char *buf2 = 0 ;
+  size_t size2 = 0 ;
+  int alloc2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Packet_setData",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_setData" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, &size2, &alloc2);
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Packet_setData" "', argument " "2"" of type '" "char *""'");
+  }  
+  arg2 = reinterpret_cast< char * >(buf2);
+  arg3 = static_cast< int >(size2 - 1);
+  (arg1)->setData(arg2,arg3);
+  resultobj = SWIG_Py_Void();
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return resultobj;
+fail:
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_maxLength(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Packet_maxLength",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->maxLength();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_maxLength(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Packet_maxLength",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_maxLength" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  result = (int)(arg1)->maxLength();
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_setStrength(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:Packet_setStrength",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->setStrength(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_setStrength(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Packet_setStrength",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_setStrength" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Packet_setStrength" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->setStrength(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_deliver(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int arg2 ;
-    long long arg3 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj2 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OiO:Packet_deliver",&obj0,&arg2,&obj2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    arg3 = (long long) PyLong_AsLongLong(obj2);
-    if (PyErr_Occurred()) SWIG_fail;
-    (arg1)->deliver(arg2,arg3);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_deliver(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int arg2 ;
+  long long arg3 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  long long val3 ;
+  int ecode3 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OOO:Packet_deliver",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_deliver" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Packet_deliver" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  ecode3 = SWIG_AsVal_long_SS_long(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "Packet_deliver" "', argument " "3"" of type '" "long long""'");
+  } 
+  arg3 = static_cast< long long >(val3);
+  (arg1)->deliver(arg2,arg3);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Packet_deliverNow(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Packet *arg1 = (Packet *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:Packet_deliverNow",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Packet,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->deliverNow(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Packet_deliverNow(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Packet *arg1 = (Packet *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Packet_deliverNow",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Packet, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Packet_deliverNow" "', argument " "1"" of type '" "Packet *""'"); 
+  }
+  arg1 = reinterpret_cast< Packet * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Packet_deliverNow" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->deliverNow(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject * Packet_swigregister(PyObject *self, PyObject *args) {
-    PyObject *obj;
-    if (!PyArg_ParseTuple(args,(char*)"O", &obj)) return NULL;
-    SWIG_TypeClientData(SWIGTYPE_p_Packet, obj);
-    Py_INCREF(obj);
-    return Py_BuildValue((char *)"");
-}
-static PyObject *_wrap_variable_string_t_type_set(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *arg1 = (variable_string_t *) 0 ;
-    char *arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Os:variable_string_t_type_set",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_variable_string_t,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    {
-        if (arg1->type) delete [] arg1->type;
-        if (arg2) {
-            arg1->type = (char *) (new char[strlen(arg2)+1]);
-            strcpy((char *) arg1->type,arg2);
-        }else {
-            arg1->type = 0;
-        }
-    }
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *Packet_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O|swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_Packet, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_variable_string_t_type_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *arg1 = (variable_string_t *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int res2 ;
+  char *buf2 = 0 ;
+  int alloc2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:variable_string_t_type_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_var_string, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "variable_string_t_type_set" "', argument " "1"" of type '" "variable_string_t *""'"); 
+  }
+  arg1 = reinterpret_cast< variable_string_t * >(argp1);
+  res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2);
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "variable_string_t_type_set" "', argument " "2"" of type '" "char *""'");
+  }
+  arg2 = reinterpret_cast< char * >(buf2);
+  if (arg1->type) delete[] arg1->type;
+  if (arg2) {
+    size_t size = strlen(reinterpret_cast< const char * >(arg2)) + 1;
+    arg1->type = (char *)reinterpret_cast< char* >(memcpy((new char[size]), reinterpret_cast< const char * >(arg2), sizeof(char)*(size)));
+  } else {
+    arg1->type = 0;
+  }
+  resultobj = SWIG_Py_Void();
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return resultobj;
+fail:
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return NULL;
 }
 
 
-static PyObject *_wrap_variable_string_t_type_get(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *arg1 = (variable_string_t *) 0 ;
-    char *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:variable_string_t_type_get",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_variable_string_t,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (char *) ((arg1)->type);
-    
-    resultobj = result ? PyString_FromString(result) : Py_BuildValue((char*)"");
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_variable_string_t_type_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *arg1 = (variable_string_t *) 0 ;
+  char *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:variable_string_t_type_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_var_string, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "variable_string_t_type_get" "', argument " "1"" of type '" "variable_string_t *""'"); 
+  }
+  arg1 = reinterpret_cast< variable_string_t * >(argp1);
+  result = (char *) ((arg1)->type);
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_variable_string_t_ptr_set(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *arg1 = (variable_string_t *) 0 ;
-    char *arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Os:variable_string_t_ptr_set",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_variable_string_t,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    {
-        if (arg1->ptr) delete [] arg1->ptr;
-        if (arg2) {
-            arg1->ptr = (char *) (new char[strlen(arg2)+1]);
-            strcpy((char *) arg1->ptr,arg2);
-        }else {
-            arg1->ptr = 0;
-        }
-    }
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_variable_string_t_ptr_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *arg1 = (variable_string_t *) 0 ;
+  char *arg2 = (char *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int res2 ;
+  char *buf2 = 0 ;
+  int alloc2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:variable_string_t_ptr_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_var_string, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "variable_string_t_ptr_set" "', argument " "1"" of type '" "variable_string_t *""'"); 
+  }
+  arg1 = reinterpret_cast< variable_string_t * >(argp1);
+  res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2);
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "variable_string_t_ptr_set" "', argument " "2"" of type '" "char *""'");
+  }
+  arg2 = reinterpret_cast< char * >(buf2);
+  if (arg1->ptr) delete[] arg1->ptr;
+  if (arg2) {
+    size_t size = strlen(reinterpret_cast< const char * >(arg2)) + 1;
+    arg1->ptr = (char *)reinterpret_cast< char* >(memcpy((new char[size]), reinterpret_cast< const char * >(arg2), sizeof(char)*(size)));
+  } else {
+    arg1->ptr = 0;
+  }
+  resultobj = SWIG_Py_Void();
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return resultobj;
+fail:
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return NULL;
 }
 
 
-static PyObject *_wrap_variable_string_t_ptr_get(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *arg1 = (variable_string_t *) 0 ;
-    char *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:variable_string_t_ptr_get",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_variable_string_t,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (char *) ((arg1)->ptr);
-    
-    resultobj = result ? PyString_FromString(result) : Py_BuildValue((char*)"");
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_variable_string_t_ptr_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *arg1 = (variable_string_t *) 0 ;
+  char *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:variable_string_t_ptr_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_var_string, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "variable_string_t_ptr_get" "', argument " "1"" of type '" "variable_string_t *""'"); 
+  }
+  arg1 = reinterpret_cast< variable_string_t * >(argp1);
+  result = (char *) ((arg1)->ptr);
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_variable_string_t_len_set(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *arg1 = (variable_string_t *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:variable_string_t_len_set",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_variable_string_t,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    if (arg1) (arg1)->len = arg2;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_variable_string_t_len_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *arg1 = (variable_string_t *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:variable_string_t_len_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_var_string, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "variable_string_t_len_set" "', argument " "1"" of type '" "variable_string_t *""'"); 
+  }
+  arg1 = reinterpret_cast< variable_string_t * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "variable_string_t_len_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  if (arg1) (arg1)->len = arg2;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_variable_string_t_len_get(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *arg1 = (variable_string_t *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:variable_string_t_len_get",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_variable_string_t,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int) ((arg1)->len);
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_variable_string_t_len_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *arg1 = (variable_string_t *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:variable_string_t_len_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_var_string, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "variable_string_t_len_get" "', argument " "1"" of type '" "variable_string_t *""'"); 
+  }
+  arg1 = reinterpret_cast< variable_string_t * >(argp1);
+  result = (int) ((arg1)->len);
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_variable_string_t_isArray_set(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *arg1 = (variable_string_t *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:variable_string_t_isArray_set",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_variable_string_t,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    if (arg1) (arg1)->isArray = arg2;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_variable_string_t_isArray_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *arg1 = (variable_string_t *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:variable_string_t_isArray_set",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_var_string, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "variable_string_t_isArray_set" "', argument " "1"" of type '" "variable_string_t *""'"); 
+  }
+  arg1 = reinterpret_cast< variable_string_t * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "variable_string_t_isArray_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  if (arg1) (arg1)->isArray = arg2;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_variable_string_t_isArray_get(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *arg1 = (variable_string_t *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:variable_string_t_isArray_get",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_variable_string_t,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int) ((arg1)->isArray);
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_variable_string_t_isArray_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *arg1 = (variable_string_t *) 0 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:variable_string_t_isArray_get",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_var_string, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "variable_string_t_isArray_get" "', argument " "1"" of type '" "variable_string_t *""'"); 
+  }
+  arg1 = reinterpret_cast< variable_string_t * >(argp1);
+  result = (int) ((arg1)->isArray);
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_new_variable_string_t(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *result;
-    
-    if(!PyArg_ParseTuple(args,(char *)":new_variable_string_t")) goto fail;
-    result = (variable_string_t *)new variable_string_t();
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_variable_string_t, 1);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_new_variable_string_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)":new_variable_string_t")) SWIG_fail;
+  result = (variable_string_t *)new variable_string_t();
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_var_string, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_delete_variable_string_t(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    variable_string_t *arg1 = (variable_string_t *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:delete_variable_string_t",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_variable_string_t,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    delete arg1;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_delete_variable_string_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  variable_string_t *arg1 = (variable_string_t *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_variable_string_t",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_var_string, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_variable_string_t" "', argument " "1"" of type '" "variable_string_t *""'"); 
+  }
+  arg1 = reinterpret_cast< variable_string_t * >(argp1);
+  delete arg1;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject * variable_string_t_swigregister(PyObject *self, PyObject *args) {
-    PyObject *obj;
-    if (!PyArg_ParseTuple(args,(char*)"O", &obj)) return NULL;
-    SWIG_TypeClientData(SWIGTYPE_p_variable_string_t, obj);
-    Py_INCREF(obj);
-    return Py_BuildValue((char *)"");
-}
-static PyObject *_wrap_nesc_app_t_numVariables_set(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:nesc_app_t_numVariables_set",&obj0,&arg2)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *variable_string_t_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O|swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_var_string, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_nesc_app_t_numVariables_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  int arg2 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:nesc_app_t_numVariables_set",&obj0,&obj1)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    if (arg1) (arg1)->numVariables = arg2;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "nesc_app_t_numVariables_set" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  if (arg1) (arg1)->numVariables = arg2;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_nesc_app_t_numVariables_get(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:nesc_app_t_numVariables_get",&obj0)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *_wrap_nesc_app_t_numVariables_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  int result;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:nesc_app_t_numVariables_get",&obj0)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    result = (int) ((arg1)->numVariables);
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  result = (int) ((arg1)->numVariables);
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_nesc_app_t_variableNames_set(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    char **arg2 = (char **) 0 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:nesc_app_t_variableNames_set",&obj0,&obj1)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *_wrap_nesc_app_t_variableNames_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  char **arg2 = (char **) 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:nesc_app_t_variableNames_set",&obj0,&obj1)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    if ((SWIG_ConvertPtr(obj1,(void **) &arg2, SWIGTYPE_p_p_char,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    if (arg1) (arg1)->variableNames = arg2;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_p_char, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nesc_app_t_variableNames_set" "', argument " "2"" of type '" "char **""'"); 
+  }
+  arg2 = reinterpret_cast< char ** >(argp2);
+  if (arg1) (arg1)->variableNames = arg2;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_nesc_app_t_variableNames_get(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    char **result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:nesc_app_t_variableNames_get",&obj0)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *_wrap_nesc_app_t_variableNames_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  char **result = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:nesc_app_t_variableNames_get",&obj0)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    result = (char **) ((arg1)->variableNames);
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_p_char, 0);
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  result = (char **) ((arg1)->variableNames);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_p_char, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_nesc_app_t_variableTypes_set(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    char **arg2 = (char **) 0 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:nesc_app_t_variableTypes_set",&obj0,&obj1)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *_wrap_nesc_app_t_variableTypes_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  char **arg2 = (char **) 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:nesc_app_t_variableTypes_set",&obj0,&obj1)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    if ((SWIG_ConvertPtr(obj1,(void **) &arg2, SWIGTYPE_p_p_char,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    if (arg1) (arg1)->variableTypes = arg2;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_p_char, 0 |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nesc_app_t_variableTypes_set" "', argument " "2"" of type '" "char **""'"); 
+  }
+  arg2 = reinterpret_cast< char ** >(argp2);
+  if (arg1) (arg1)->variableTypes = arg2;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_nesc_app_t_variableTypes_get(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    char **result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:nesc_app_t_variableTypes_get",&obj0)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *_wrap_nesc_app_t_variableTypes_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  char **result = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:nesc_app_t_variableTypes_get",&obj0)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    result = (char **) ((arg1)->variableTypes);
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_p_char, 0);
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  result = (char **) ((arg1)->variableTypes);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_p_char, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_nesc_app_t_variableArray_set(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    int *arg2 = (int *) 0 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:nesc_app_t_variableArray_set",&obj0,&obj1)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *_wrap_nesc_app_t_variableArray_set(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  int *arg2 = (int *) 0 ;
+  void *argp2 = 0 ;
+  int res2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:nesc_app_t_variableArray_set",&obj0,&obj1)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    if ((SWIG_ConvertPtr(obj1,(void **) &arg2, SWIGTYPE_p_int,SWIG_POINTER_EXCEPTION | SWIG_POINTER_DISOWN )) == -1) SWIG_fail;
-    if (arg1) (arg1)->variableArray = arg2;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  res2 = SWIG_ConvertPtr(obj1, &argp2,SWIGTYPE_p_int, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "nesc_app_t_variableArray_set" "', argument " "2"" of type '" "int *""'"); 
+  }
+  arg2 = reinterpret_cast< int * >(argp2);
+  if (arg1) (arg1)->variableArray = arg2;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_nesc_app_t_variableArray_get(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    int *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:nesc_app_t_variableArray_get",&obj0)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *_wrap_nesc_app_t_variableArray_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  int *result = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:nesc_app_t_variableArray_get",&obj0)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    result = (int *) ((arg1)->variableArray);
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_int, 0);
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  result = (int *) ((arg1)->variableArray);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_int, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_new_nesc_app_t(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *result;
-    
-    if(!PyArg_ParseTuple(args,(char *)":new_nesc_app_t")) goto fail;
-    result = (nesc_app_t *)new nesc_app_t();
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_nesc_app_t, 1);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_new_nesc_app_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *result = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)":new_nesc_app_t")) SWIG_fail;
+  result = (nesc_app_t *)new nesc_app_t();
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_nesc_app, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_delete_nesc_app_t(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:delete_nesc_app_t",&obj0)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *_wrap_delete_nesc_app_t(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_nesc_app_t",&obj0)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    delete arg1;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  delete arg1;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject * nesc_app_t_swigregister(PyObject *self, PyObject *args) {
-    PyObject *obj;
-    if (!PyArg_ParseTuple(args,(char*)"O", &obj)) return NULL;
-    SWIG_TypeClientData(SWIGTYPE_p_nesc_app_t, obj);
-    Py_INCREF(obj);
-    return Py_BuildValue((char *)"");
-}
-static PyObject *_wrap_new_Variable(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    char *arg1 ;
-    char *arg2 ;
-    int arg3 ;
-    int arg4 ;
-    Variable *result;
-    
-    if(!PyArg_ParseTuple(args,(char *)"ssii:new_Variable",&arg1,&arg2,&arg3,&arg4)) goto fail;
-    result = (Variable *)new Variable(arg1,arg2,arg3,arg4);
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Variable, 1);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *nesc_app_t_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O|swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_nesc_app, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_new_Variable(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  char *arg1 = (char *) 0 ;
+  char *arg2 = (char *) 0 ;
+  int arg3 ;
+  int arg4 ;
+  Variable *result = 0 ;
+  int res1 ;
+  char *buf1 = 0 ;
+  int alloc1 = 0 ;
+  int res2 ;
+  char *buf2 = 0 ;
+  int alloc2 = 0 ;
+  int val3 ;
+  int ecode3 = 0 ;
+  int val4 ;
+  int ecode4 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  PyObject * obj3 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OOOO:new_Variable",&obj0,&obj1,&obj2,&obj3)) SWIG_fail;
+  res1 = SWIG_AsCharPtrAndSize(obj0, &buf1, NULL, &alloc1);
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "new_Variable" "', argument " "1"" of type '" "char *""'");
+  }
+  arg1 = reinterpret_cast< char * >(buf1);
+  res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2);
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "new_Variable" "', argument " "2"" of type '" "char *""'");
+  }
+  arg2 = reinterpret_cast< char * >(buf2);
+  ecode3 = SWIG_AsVal_int(obj2, &val3);
+  if (!SWIG_IsOK(ecode3)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode3), "in method '" "new_Variable" "', argument " "3"" of type '" "int""'");
+  } 
+  arg3 = static_cast< int >(val3);
+  ecode4 = SWIG_AsVal_int(obj3, &val4);
+  if (!SWIG_IsOK(ecode4)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode4), "in method '" "new_Variable" "', argument " "4"" of type '" "int""'");
+  } 
+  arg4 = static_cast< int >(val4);
+  result = (Variable *)new Variable(arg1,arg2,arg3,arg4);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Variable, SWIG_POINTER_NEW |  0 );
+  if (alloc1 == SWIG_NEWOBJ) delete[] buf1;
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return resultobj;
+fail:
+  if (alloc1 == SWIG_NEWOBJ) delete[] buf1;
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return NULL;
 }
 
 
-static PyObject *_wrap_delete_Variable(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Variable *arg1 = (Variable *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:delete_Variable",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Variable,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    delete arg1;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_delete_Variable(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Variable *arg1 = (Variable *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_Variable",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Variable, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_Variable" "', argument " "1"" of type '" "Variable *""'"); 
+  }
+  arg1 = reinterpret_cast< Variable * >(argp1);
+  delete arg1;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Variable_getData(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Variable *arg1 = (Variable *) 0 ;
-    variable_string_t result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Variable_getData",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Variable,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (arg1)->getData();
-    
-    {
-        if ((&result)->isArray) {
-            //printf("Generating array %s\n", (&result)->type);
-            resultobj = listFromArray  ((&result)->type, (&result)->ptr, (&result)->len);
-        }
-        else {
-            //printf("Generating scalar %s\n", (&result)->type);
-            resultobj = valueFromScalar((&result)->type, (&result)->ptr, (&result)->len);
-        }
-        if (resultobj == NULL) {
-            PyErr_SetString(PyExc_RuntimeError, "Error generating Python type from TinyOS variable.");
-        }
+SWIGINTERN PyObject *_wrap_Variable_getData(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Variable *arg1 = (Variable *) 0 ;
+  variable_string_t result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Variable_getData",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Variable, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Variable_getData" "', argument " "1"" of type '" "Variable *""'"); 
+  }
+  arg1 = reinterpret_cast< Variable * >(argp1);
+  result = (arg1)->getData();
+  {
+    if ((&result)->isArray) {
+      //printf("Generating array %s\n", (&result)->type);
+      resultobj = listFromArray  ((&result)->type, (&result)->ptr, (&result)->len);
     }
-    return resultobj;
-    fail:
-    return NULL;
+    else {
+      //printf("Generating scalar %s\n", (&result)->type);
+      resultobj = valueFromScalar((&result)->type, (&result)->ptr, (&result)->len);
+    }
+    if (resultobj == NULL) {
+      PyErr_SetString(PyExc_RuntimeError, "Error generating Python type from TinyOS variable.");
+    }
+  }
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject * Variable_swigregister(PyObject *self, PyObject *args) {
-    PyObject *obj;
-    if (!PyArg_ParseTuple(args,(char*)"O", &obj)) return NULL;
-    SWIG_TypeClientData(SWIGTYPE_p_Variable, obj);
-    Py_INCREF(obj);
-    return Py_BuildValue((char *)"");
-}
-static PyObject *_wrap_new_Mote(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    Mote *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:new_Mote",&obj0)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+SWIGINTERN PyObject *Variable_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O|swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_Variable, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_new_Mote(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  Mote *result = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:new_Mote",&obj0)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    result = (Mote *)new Mote(arg1);
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Mote, 1);
-    return resultobj;
-    fail:
-    return NULL;
-}
-
-
-static PyObject *_wrap_delete_Mote(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:delete_Mote",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    delete arg1;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  result = (Mote *)new Mote(arg1);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Mote, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_id(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    unsigned long result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Mote_id",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (unsigned long)(arg1)->id();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_delete_Mote(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_Mote",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_Mote" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  delete arg1;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_euid(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    long long result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Mote_euid",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (long long)(arg1)->euid();
-    
-    resultobj = PyLong_FromLongLong(result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_id(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  unsigned long result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Mote_id",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_id" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  result = (unsigned long)(arg1)->id();
+  resultobj = SWIG_From_unsigned_SS_long(static_cast< unsigned long >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_setEuid(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    long long arg2 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:Mote_setEuid",&obj0,&obj1)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    arg2 = (long long) PyLong_AsLongLong(obj1);
-    if (PyErr_Occurred()) SWIG_fail;
-    (arg1)->setEuid(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_euid(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  long long result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Mote_euid",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_euid" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  result = (long long)(arg1)->euid();
+  resultobj = SWIG_From_long_SS_long(static_cast< long long >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_bootTime(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    long long result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Mote_bootTime",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (long long)(arg1)->bootTime();
-    
-    resultobj = PyLong_FromLongLong(result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_setEuid(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  long long arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  long long val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Mote_setEuid",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_setEuid" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  ecode2 = SWIG_AsVal_long_SS_long(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Mote_setEuid" "', argument " "2"" of type '" "long long""'");
+  } 
+  arg2 = static_cast< long long >(val2);
+  (arg1)->setEuid(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_bootAtTime(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    long long arg2 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:Mote_bootAtTime",&obj0,&obj1)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    arg2 = (long long) PyLong_AsLongLong(obj1);
-    if (PyErr_Occurred()) SWIG_fail;
-    (arg1)->bootAtTime(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_bootTime(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  long long result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Mote_bootTime",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_bootTime" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  result = (long long)(arg1)->bootTime();
+  resultobj = SWIG_From_long_SS_long(static_cast< long long >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_isOn(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    bool result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Mote_isOn",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (bool)(arg1)->isOn();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_bootAtTime(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  long long arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  long long val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Mote_bootAtTime",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_bootAtTime" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  ecode2 = SWIG_AsVal_long_SS_long(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Mote_bootAtTime" "', argument " "2"" of type '" "long long""'");
+  } 
+  arg2 = static_cast< long long >(val2);
+  (arg1)->bootAtTime(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_turnOff(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Mote_turnOff",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->turnOff();
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_isOn(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  bool result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Mote_isOn",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_isOn" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  result = (bool)(arg1)->isOn();
+  resultobj = SWIG_From_bool(static_cast< bool >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_turnOn(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Mote_turnOn",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->turnOn();
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_turnOff(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Mote_turnOff",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_turnOff" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  (arg1)->turnOff();
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_getVariable(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    char *arg2 ;
-    Variable *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Os:Mote_getVariable",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (Variable *)(arg1)->getVariable(arg2);
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Variable, 0);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_turnOn(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Mote_turnOn",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_turnOn" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  (arg1)->turnOn();
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_addNoiseTraceReading(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:Mote_addNoiseTraceReading",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->addNoiseTraceReading(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_getVariable(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  char *arg2 = (char *) 0 ;
+  Variable *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int res2 ;
+  char *buf2 = 0 ;
+  int alloc2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Mote_getVariable",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_getVariable" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2);
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Mote_getVariable" "', argument " "2"" of type '" "char *""'");
+  }
+  arg2 = reinterpret_cast< char * >(buf2);
+  result = (Variable *)(arg1)->getVariable(arg2);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Variable, 0 |  0 );
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return resultobj;
+fail:
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_createNoiseModel(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Mote_createNoiseModel",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->createNoiseModel();
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_addNoiseTraceReading(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Mote_addNoiseTraceReading",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_addNoiseTraceReading" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Mote_addNoiseTraceReading" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->addNoiseTraceReading(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Mote_generateNoise(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Mote *arg1 = (Mote *) 0 ;
-    int arg2 ;
-    int result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:Mote_generateNoise",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Mote,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (int)(arg1)->generateNoise(arg2);
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Mote_createNoiseModel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Mote_createNoiseModel",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_createNoiseModel" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  (arg1)->createNoiseModel();
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject * Mote_swigregister(PyObject *self, PyObject *args) {
-    PyObject *obj;
-    if (!PyArg_ParseTuple(args,(char*)"O", &obj)) return NULL;
-    SWIG_TypeClientData(SWIGTYPE_p_Mote, obj);
-    Py_INCREF(obj);
-    return Py_BuildValue((char *)"");
+SWIGINTERN PyObject *_wrap_Mote_generateNoise(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Mote *arg1 = (Mote *) 0 ;
+  int arg2 ;
+  int result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Mote_generateNoise",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Mote, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Mote_generateNoise" "', argument " "1"" of type '" "Mote *""'"); 
+  }
+  arg1 = reinterpret_cast< Mote * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Mote_generateNoise" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  result = (int)(arg1)->generateNoise(arg2);
+  resultobj = SWIG_From_int(static_cast< int >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
-static PyObject *_wrap_new_Tossim(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    nesc_app_t *arg1 = (nesc_app_t *) 0 ;
-    Tossim *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:new_Tossim",&obj0)) goto fail;
-    {
-        if (!PyList_Check(obj0)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
-            return NULL;
+
+
+SWIGINTERN PyObject *Mote_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O|swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_Mote, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
+}
+
+SWIGINTERN PyObject *_wrap_new_Tossim(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  nesc_app_t *arg1 = (nesc_app_t *) 0 ;
+  Tossim *result = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:new_Tossim",&obj0)) SWIG_fail;
+  {
+    if (!PyList_Check(obj0)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a list as a parameter.");
+      return NULL;
+    }
+    else {
+      int size = PyList_Size(obj0);
+      int i = 0;
+      nesc_app_t* app;
+      
+      if (size % 3 != 0) {
+        PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
+        return NULL;
+      }
+      
+      app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
+      
+      app->numVariables = size / 3;
+      app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
+      app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
+      
+      memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
+      memset(app->variableArray, 0, sizeof(int) * app->numVariables);
+      
+      for (i = 0; i < app->numVariables; i++) {
+        PyObject* name = PyList_GetItem(obj0, 3 * i);
+        PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
+        PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
+        if (PyString_Check(name) && PyString_Check(format)) {
+          app->variableNames[i] = PyString_AsString(name);
+          app->variableTypes[i] = PyString_AsString(format);
+          if (strcmp(PyString_AsString(array), "array") == 0) {
+            app->variableArray[i] = 1;
+            //printf("%s is an array\n", PyString_AsString(name));
+          }
+          else {
+            app->variableArray[i] = 0;
+            //printf("%s is a scalar\n", PyString_AsString(name));
+          }
         }
         else {
-            int size = PyList_Size(obj0);
-            int i = 0;
-            nesc_app_t* app;
-            
-            if (size % 3 != 0) {
-                PyErr_SetString(PyExc_RuntimeError, "List must have 2*N elements.");
-                return NULL;
-            }
-            
-            app = (nesc_app_t*)malloc(sizeof(nesc_app_t));
-            
-            app->numVariables = size / 3;
-            app->variableNames = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableTypes = (char**)malloc(sizeof(char*) * app->numVariables);
-            app->variableArray = (int*)malloc(sizeof(int) * app->numVariables);
-            
-            memset(app->variableNames, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableTypes, 0, sizeof(char*) * app->numVariables);
-            memset(app->variableArray, 0, sizeof(int) * app->numVariables);
-            
-            for (i = 0; i < app->numVariables; i++) {
-                PyObject* name = PyList_GetItem(obj0, 3 * i);
-                PyObject* array = PyList_GetItem(obj0, (3 * i) + 1);
-                PyObject* format = PyList_GetItem(obj0, (3 * i) + 2);
-                if (PyString_Check(name) && PyString_Check(format)) {
-                    app->variableNames[i] = PyString_AsString(name);
-                    app->variableTypes[i] = PyString_AsString(format);
-                    if (strcmp(PyString_AsString(array), "array") == 0) {
-                        app->variableArray[i] = 1;
-                        //printf("%s is an array\n", PyString_AsString(name));
-                    }
-                    else {
-                        app->variableArray[i] = 0;
-                        //printf("%s is a scalar\n", PyString_AsString(name));
-                    }
-                }
-                else {
-                    app->variableNames[i] = "<bad string>";
-                    app->variableTypes[i] = "<bad string>";
-                }
-            }
-            
-            arg1 = app;
+          app->variableNames[i] = (char*)"<bad string>";
+          app->variableTypes[i] = (char*)"<bad string>";
         }
+      }
+      
+      arg1 = app;
     }
-    result = (Tossim *)new Tossim(arg1);
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Tossim, 1);
-    return resultobj;
-    fail:
-    return NULL;
+  }
+  result = (Tossim *)new Tossim(arg1);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Tossim, SWIG_POINTER_NEW |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_delete_Tossim(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:delete_Tossim",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    delete arg1;
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_delete_Tossim(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:delete_Tossim",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, SWIG_POINTER_DISOWN |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "delete_Tossim" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  delete arg1;
+  
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_init(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Tossim_init",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->init();
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_init(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Tossim_init",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_init" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  (arg1)->init();
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_time(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    long long result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Tossim_time",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (long long)(arg1)->time();
-    
-    resultobj = PyLong_FromLongLong(result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_time(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  long long result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Tossim_time",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_time" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  result = (long long)(arg1)->time();
+  resultobj = SWIG_From_long_SS_long(static_cast< long long >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_ticksPerSecond(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    long long result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Tossim_ticksPerSecond",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (long long)(arg1)->ticksPerSecond();
-    
-    resultobj = PyLong_FromLongLong(result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_ticksPerSecond(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  long long result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Tossim_ticksPerSecond",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_ticksPerSecond" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  result = (long long)(arg1)->ticksPerSecond();
+  resultobj = SWIG_From_long_SS_long(static_cast< long long >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_setTime(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    long long arg2 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:Tossim_setTime",&obj0,&obj1)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    arg2 = (long long) PyLong_AsLongLong(obj1);
-    if (PyErr_Occurred()) SWIG_fail;
-    (arg1)->setTime(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_setTime(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  long long arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  long long val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Tossim_setTime",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_setTime" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  ecode2 = SWIG_AsVal_long_SS_long(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Tossim_setTime" "', argument " "2"" of type '" "long long""'");
+  } 
+  arg2 = static_cast< long long >(val2);
+  (arg1)->setTime(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_timeStr(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    char *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Tossim_timeStr",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (char *)(arg1)->timeStr();
-    
-    resultobj = result ? PyString_FromString(result) : Py_BuildValue((char*)"");
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_timeStr(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  char *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Tossim_timeStr",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_timeStr" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  result = (char *)(arg1)->timeStr();
+  resultobj = SWIG_FromCharPtr((const char *)result);
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_currentNode(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    Mote *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Tossim_currentNode",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (Mote *)(arg1)->currentNode();
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Mote, 0);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_currentNode(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  Mote *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Tossim_currentNode",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_currentNode" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  result = (Mote *)(arg1)->currentNode();
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Mote, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_getNode(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    unsigned long arg2 ;
-    Mote *result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:Tossim_getNode",&obj0,&obj1)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    arg2 = (unsigned long) PyInt_AsLong(obj1);
-    if (PyErr_Occurred()) SWIG_fail;
-    result = (Mote *)(arg1)->getNode(arg2);
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Mote, 0);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_getNode(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  unsigned long arg2 ;
+  Mote *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  unsigned long val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Tossim_getNode",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_getNode" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  ecode2 = SWIG_AsVal_unsigned_SS_long(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Tossim_getNode" "', argument " "2"" of type '" "unsigned long""'");
+  } 
+  arg2 = static_cast< unsigned long >(val2);
+  result = (Mote *)(arg1)->getNode(arg2);
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Mote, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_setCurrentNode(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    unsigned long arg2 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj1 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OO:Tossim_setCurrentNode",&obj0,&obj1)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    arg2 = (unsigned long) PyInt_AsLong(obj1);
-    if (PyErr_Occurred()) SWIG_fail;
-    (arg1)->setCurrentNode(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_setCurrentNode(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  unsigned long arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  unsigned long val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Tossim_setCurrentNode",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_setCurrentNode" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  ecode2 = SWIG_AsVal_unsigned_SS_long(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Tossim_setCurrentNode" "', argument " "2"" of type '" "unsigned long""'");
+  } 
+  arg2 = static_cast< unsigned long >(val2);
+  (arg1)->setCurrentNode(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_addChannel(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    char *arg2 ;
-    FILE *arg3 = (FILE *) 0 ;
-    PyObject * obj0 = 0 ;
-    PyObject * obj2 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OsO:Tossim_addChannel",&obj0,&arg2,&obj2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    {
-        if (!PyFile_Check(obj2)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a file as a parameter.");
-            return NULL;
-        }
-        arg3 = PyFile_AsFile(obj2);
+SWIGINTERN PyObject *_wrap_Tossim_addChannel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  char *arg2 = (char *) 0 ;
+  FILE *arg3 = (FILE *) 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int res2 ;
+  char *buf2 = 0 ;
+  int alloc2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OOO:Tossim_addChannel",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_addChannel" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2);
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Tossim_addChannel" "', argument " "2"" of type '" "char *""'");
+  }
+  arg2 = reinterpret_cast< char * >(buf2);
+  {
+    if (!PyFile_Check(obj2)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a file as a parameter.");
+      return NULL;
     }
-    (arg1)->addChannel(arg2,arg3);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+    arg3 = PyFile_AsFile(obj2);
+  }
+  (arg1)->addChannel(arg2,arg3);
+  resultobj = SWIG_Py_Void();
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return resultobj;
+fail:
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_removeChannel(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    char *arg2 ;
-    FILE *arg3 = (FILE *) 0 ;
-    bool result;
-    PyObject * obj0 = 0 ;
-    PyObject * obj2 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"OsO:Tossim_removeChannel",&obj0,&arg2,&obj2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    {
-        if (!PyFile_Check(obj2)) {
-            PyErr_SetString(PyExc_TypeError, "Requires a file as a parameter.");
-            return NULL;
-        }
-        arg3 = PyFile_AsFile(obj2);
+SWIGINTERN PyObject *_wrap_Tossim_removeChannel(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  char *arg2 = (char *) 0 ;
+  FILE *arg3 = (FILE *) 0 ;
+  bool result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int res2 ;
+  char *buf2 = 0 ;
+  int alloc2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  PyObject * obj2 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OOO:Tossim_removeChannel",&obj0,&obj1,&obj2)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_removeChannel" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  res2 = SWIG_AsCharPtrAndSize(obj1, &buf2, NULL, &alloc2);
+  if (!SWIG_IsOK(res2)) {
+    SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "Tossim_removeChannel" "', argument " "2"" of type '" "char *""'");
+  }
+  arg2 = reinterpret_cast< char * >(buf2);
+  {
+    if (!PyFile_Check(obj2)) {
+      PyErr_SetString(PyExc_TypeError, "Requires a file as a parameter.");
+      return NULL;
     }
-    result = (bool)(arg1)->removeChannel(arg2,arg3);
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+    arg3 = PyFile_AsFile(obj2);
+  }
+  result = (bool)(arg1)->removeChannel(arg2,arg3);
+  resultobj = SWIG_From_bool(static_cast< bool >(result));
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return resultobj;
+fail:
+  if (alloc2 == SWIG_NEWOBJ) delete[] buf2;
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_randomSeed(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    int arg2 ;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"Oi:Tossim_randomSeed",&obj0,&arg2)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    (arg1)->randomSeed(arg2);
-    
-    Py_INCREF(Py_None); resultobj = Py_None;
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_randomSeed(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  int arg2 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  int val2 ;
+  int ecode2 = 0 ;
+  PyObject * obj0 = 0 ;
+  PyObject * obj1 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"OO:Tossim_randomSeed",&obj0,&obj1)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_randomSeed" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  ecode2 = SWIG_AsVal_int(obj1, &val2);
+  if (!SWIG_IsOK(ecode2)) {
+    SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "Tossim_randomSeed" "', argument " "2"" of type '" "int""'");
+  } 
+  arg2 = static_cast< int >(val2);
+  (arg1)->randomSeed(arg2);
+  resultobj = SWIG_Py_Void();
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_runNextEvent(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    bool result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Tossim_runNextEvent",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (bool)(arg1)->runNextEvent();
-    
-    resultobj = PyInt_FromLong((long)result);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_runNextEvent(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  bool result;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Tossim_runNextEvent",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_runNextEvent" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  result = (bool)(arg1)->runNextEvent();
+  resultobj = SWIG_From_bool(static_cast< bool >(result));
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_mac(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    MAC *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Tossim_mac",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (MAC *)(arg1)->mac();
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_MAC, 0);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_mac(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  MAC *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Tossim_mac",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_mac" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  result = (MAC *)(arg1)->mac();
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_MAC, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_radio(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    Radio *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Tossim_radio",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (Radio *)(arg1)->radio();
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Radio, 0);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_radio(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  Radio *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Tossim_radio",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_radio" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  result = (Radio *)(arg1)->radio();
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Radio, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject *_wrap_Tossim_newPacket(PyObject *self, PyObject *args) {
-    PyObject *resultobj;
-    Tossim *arg1 = (Tossim *) 0 ;
-    Packet *result;
-    PyObject * obj0 = 0 ;
-    
-    if(!PyArg_ParseTuple(args,(char *)"O:Tossim_newPacket",&obj0)) goto fail;
-    if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Tossim,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail;
-    result = (Packet *)(arg1)->newPacket();
-    
-    resultobj = SWIG_NewPointerObj((void *) result, SWIGTYPE_p_Packet, 0);
-    return resultobj;
-    fail:
-    return NULL;
+SWIGINTERN PyObject *_wrap_Tossim_newPacket(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *resultobj = 0;
+  Tossim *arg1 = (Tossim *) 0 ;
+  Packet *result = 0 ;
+  void *argp1 = 0 ;
+  int res1 = 0 ;
+  PyObject * obj0 = 0 ;
+  
+  if (!PyArg_ParseTuple(args,(char *)"O:Tossim_newPacket",&obj0)) SWIG_fail;
+  res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_Tossim, 0 |  0 );
+  if (!SWIG_IsOK(res1)) {
+    SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Tossim_newPacket" "', argument " "1"" of type '" "Tossim *""'"); 
+  }
+  arg1 = reinterpret_cast< Tossim * >(argp1);
+  result = (Packet *)(arg1)->newPacket();
+  resultobj = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Packet, 0 |  0 );
+  return resultobj;
+fail:
+  return NULL;
 }
 
 
-static PyObject * Tossim_swigregister(PyObject *self, PyObject *args) {
-    PyObject *obj;
-    if (!PyArg_ParseTuple(args,(char*)"O", &obj)) return NULL;
-    SWIG_TypeClientData(SWIGTYPE_p_Tossim, obj);
-    Py_INCREF(obj);
-    return Py_BuildValue((char *)"");
+SWIGINTERN PyObject *Tossim_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
+  PyObject *obj;
+  if (!PyArg_ParseTuple(args,(char*)"O|swigregister", &obj)) return NULL;
+  SWIG_TypeNewClientData(SWIGTYPE_p_Tossim, SWIG_NewClientData(obj));
+  return SWIG_Py_Void();
 }
+
 static PyMethodDef SwigMethods[] = {
-        { (char *)"new_MAC", _wrap_new_MAC, METH_VARARGS },
-        { (char *)"delete_MAC", _wrap_delete_MAC, METH_VARARGS },
-        { (char *)"MAC_initHigh", _wrap_MAC_initHigh, METH_VARARGS },
-        { (char *)"MAC_initLow", _wrap_MAC_initLow, METH_VARARGS },
-        { (char *)"MAC_high", _wrap_MAC_high, METH_VARARGS },
-        { (char *)"MAC_low", _wrap_MAC_low, METH_VARARGS },
-        { (char *)"MAC_symbolsPerSec", _wrap_MAC_symbolsPerSec, METH_VARARGS },
-        { (char *)"MAC_bitsPerSymbol", _wrap_MAC_bitsPerSymbol, METH_VARARGS },
-        { (char *)"MAC_preambleLength", _wrap_MAC_preambleLength, METH_VARARGS },
-        { (char *)"MAC_exponentBase", _wrap_MAC_exponentBase, METH_VARARGS },
-        { (char *)"MAC_maxIterations", _wrap_MAC_maxIterations, METH_VARARGS },
-        { (char *)"MAC_minFreeSamples", _wrap_MAC_minFreeSamples, METH_VARARGS },
-        { (char *)"MAC_rxtxDelay", _wrap_MAC_rxtxDelay, METH_VARARGS },
-        { (char *)"MAC_ackTime", _wrap_MAC_ackTime, METH_VARARGS },
-        { (char *)"MAC_setInitHigh", _wrap_MAC_setInitHigh, METH_VARARGS },
-        { (char *)"MAC_setInitLow", _wrap_MAC_setInitLow, METH_VARARGS },
-        { (char *)"MAC_setHigh", _wrap_MAC_setHigh, METH_VARARGS },
-        { (char *)"MAC_setLow", _wrap_MAC_setLow, METH_VARARGS },
-        { (char *)"MAC_setSymbolsPerSec", _wrap_MAC_setSymbolsPerSec, METH_VARARGS },
-        { (char *)"MAC_setBitsBerSymbol", _wrap_MAC_setBitsBerSymbol, METH_VARARGS },
-        { (char *)"MAC_setPreambleLength", _wrap_MAC_setPreambleLength, METH_VARARGS },
-        { (char *)"MAC_setExponentBase", _wrap_MAC_setExponentBase, METH_VARARGS },
-        { (char *)"MAC_setMaxIterations", _wrap_MAC_setMaxIterations, METH_VARARGS },
-        { (char *)"MAC_setMinFreeSamples", _wrap_MAC_setMinFreeSamples, METH_VARARGS },
-        { (char *)"MAC_setRxtxDelay", _wrap_MAC_setRxtxDelay, METH_VARARGS },
-        { (char *)"MAC_setAckTime", _wrap_MAC_setAckTime, METH_VARARGS },
-        { (char *)"MAC_swigregister", MAC_swigregister, METH_VARARGS },
-        { (char *)"new_Radio", _wrap_new_Radio, METH_VARARGS },
-        { (char *)"delete_Radio", _wrap_delete_Radio, METH_VARARGS },
-        { (char *)"Radio_add", _wrap_Radio_add, METH_VARARGS },
-        { (char *)"Radio_gain", _wrap_Radio_gain, METH_VARARGS },
-        { (char *)"Radio_connected", _wrap_Radio_connected, METH_VARARGS },
-        { (char *)"Radio_remove", _wrap_Radio_remove, METH_VARARGS },
-        { (char *)"Radio_setNoise", _wrap_Radio_setNoise, METH_VARARGS },
-        { (char *)"Radio_setSensitivity", _wrap_Radio_setSensitivity, METH_VARARGS },
-        { (char *)"Radio_swigregister", Radio_swigregister, METH_VARARGS },
-        { (char *)"new_Packet", _wrap_new_Packet, METH_VARARGS },
-        { (char *)"delete_Packet", _wrap_delete_Packet, METH_VARARGS },
-        { (char *)"Packet_setSource", _wrap_Packet_setSource, METH_VARARGS },
-        { (char *)"Packet_source", _wrap_Packet_source, METH_VARARGS },
-        { (char *)"Packet_setDestination", _wrap_Packet_setDestination, METH_VARARGS },
-        { (char *)"Packet_destination", _wrap_Packet_destination, METH_VARARGS },
-        { (char *)"Packet_setLength", _wrap_Packet_setLength, METH_VARARGS },
-        { (char *)"Packet_length", _wrap_Packet_length, METH_VARARGS },
-        { (char *)"Packet_setType", _wrap_Packet_setType, METH_VARARGS },
-        { (char *)"Packet_type", _wrap_Packet_type, METH_VARARGS },
-        { (char *)"Packet_data", _wrap_Packet_data, METH_VARARGS },
-        { (char *)"Packet_setData", _wrap_Packet_setData, METH_VARARGS },
-        { (char *)"Packet_maxLength", _wrap_Packet_maxLength, METH_VARARGS },
-        { (char *)"Packet_setStrength", _wrap_Packet_setStrength, METH_VARARGS },
-        { (char *)"Packet_deliver", _wrap_Packet_deliver, METH_VARARGS },
-        { (char *)"Packet_deliverNow", _wrap_Packet_deliverNow, METH_VARARGS },
-        { (char *)"Packet_swigregister", Packet_swigregister, METH_VARARGS },
-        { (char *)"variable_string_t_type_set", _wrap_variable_string_t_type_set, METH_VARARGS },
-        { (char *)"variable_string_t_type_get", _wrap_variable_string_t_type_get, METH_VARARGS },
-        { (char *)"variable_string_t_ptr_set", _wrap_variable_string_t_ptr_set, METH_VARARGS },
-        { (char *)"variable_string_t_ptr_get", _wrap_variable_string_t_ptr_get, METH_VARARGS },
-        { (char *)"variable_string_t_len_set", _wrap_variable_string_t_len_set, METH_VARARGS },
-        { (char *)"variable_string_t_len_get", _wrap_variable_string_t_len_get, METH_VARARGS },
-        { (char *)"variable_string_t_isArray_set", _wrap_variable_string_t_isArray_set, METH_VARARGS },
-        { (char *)"variable_string_t_isArray_get", _wrap_variable_string_t_isArray_get, METH_VARARGS },
-        { (char *)"new_variable_string_t", _wrap_new_variable_string_t, METH_VARARGS },
-        { (char *)"delete_variable_string_t", _wrap_delete_variable_string_t, METH_VARARGS },
-        { (char *)"variable_string_t_swigregister", variable_string_t_swigregister, METH_VARARGS },
-        { (char *)"nesc_app_t_numVariables_set", _wrap_nesc_app_t_numVariables_set, METH_VARARGS },
-        { (char *)"nesc_app_t_numVariables_get", _wrap_nesc_app_t_numVariables_get, METH_VARARGS },
-        { (char *)"nesc_app_t_variableNames_set", _wrap_nesc_app_t_variableNames_set, METH_VARARGS },
-        { (char *)"nesc_app_t_variableNames_get", _wrap_nesc_app_t_variableNames_get, METH_VARARGS },
-        { (char *)"nesc_app_t_variableTypes_set", _wrap_nesc_app_t_variableTypes_set, METH_VARARGS },
-        { (char *)"nesc_app_t_variableTypes_get", _wrap_nesc_app_t_variableTypes_get, METH_VARARGS },
-        { (char *)"nesc_app_t_variableArray_set", _wrap_nesc_app_t_variableArray_set, METH_VARARGS },
-        { (char *)"nesc_app_t_variableArray_get", _wrap_nesc_app_t_variableArray_get, METH_VARARGS },
-        { (char *)"new_nesc_app_t", _wrap_new_nesc_app_t, METH_VARARGS },
-        { (char *)"delete_nesc_app_t", _wrap_delete_nesc_app_t, METH_VARARGS },
-        { (char *)"nesc_app_t_swigregister", nesc_app_t_swigregister, METH_VARARGS },
-        { (char *)"new_Variable", _wrap_new_Variable, METH_VARARGS },
-        { (char *)"delete_Variable", _wrap_delete_Variable, METH_VARARGS },
-        { (char *)"Variable_getData", _wrap_Variable_getData, METH_VARARGS },
-        { (char *)"Variable_swigregister", Variable_swigregister, METH_VARARGS },
-        { (char *)"new_Mote", _wrap_new_Mote, METH_VARARGS },
-        { (char *)"delete_Mote", _wrap_delete_Mote, METH_VARARGS },
-        { (char *)"Mote_id", _wrap_Mote_id, METH_VARARGS },
-        { (char *)"Mote_euid", _wrap_Mote_euid, METH_VARARGS },
-        { (char *)"Mote_setEuid", _wrap_Mote_setEuid, METH_VARARGS },
-        { (char *)"Mote_bootTime", _wrap_Mote_bootTime, METH_VARARGS },
-        { (char *)"Mote_bootAtTime", _wrap_Mote_bootAtTime, METH_VARARGS },
-        { (char *)"Mote_isOn", _wrap_Mote_isOn, METH_VARARGS },
-        { (char *)"Mote_turnOff", _wrap_Mote_turnOff, METH_VARARGS },
-        { (char *)"Mote_turnOn", _wrap_Mote_turnOn, METH_VARARGS },
-        { (char *)"Mote_getVariable", _wrap_Mote_getVariable, METH_VARARGS },
-        { (char *)"Mote_addNoiseTraceReading", _wrap_Mote_addNoiseTraceReading, METH_VARARGS },
-        { (char *)"Mote_createNoiseModel", _wrap_Mote_createNoiseModel, METH_VARARGS },
-        { (char *)"Mote_generateNoise", _wrap_Mote_generateNoise, METH_VARARGS },
-        { (char *)"Mote_swigregister", Mote_swigregister, METH_VARARGS },
-        { (char *)"new_Tossim", _wrap_new_Tossim, METH_VARARGS },
-        { (char *)"delete_Tossim", _wrap_delete_Tossim, METH_VARARGS },
-        { (char *)"Tossim_init", _wrap_Tossim_init, METH_VARARGS },
-        { (char *)"Tossim_time", _wrap_Tossim_time, METH_VARARGS },
-        { (char *)"Tossim_ticksPerSecond", _wrap_Tossim_ticksPerSecond, METH_VARARGS },
-        { (char *)"Tossim_setTime", _wrap_Tossim_setTime, METH_VARARGS },
-        { (char *)"Tossim_timeStr", _wrap_Tossim_timeStr, METH_VARARGS },
-        { (char *)"Tossim_currentNode", _wrap_Tossim_currentNode, METH_VARARGS },
-        { (char *)"Tossim_getNode", _wrap_Tossim_getNode, METH_VARARGS },
-        { (char *)"Tossim_setCurrentNode", _wrap_Tossim_setCurrentNode, METH_VARARGS },
-        { (char *)"Tossim_addChannel", _wrap_Tossim_addChannel, METH_VARARGS },
-        { (char *)"Tossim_removeChannel", _wrap_Tossim_removeChannel, METH_VARARGS },
-        { (char *)"Tossim_randomSeed", _wrap_Tossim_randomSeed, METH_VARARGS },
-        { (char *)"Tossim_runNextEvent", _wrap_Tossim_runNextEvent, METH_VARARGS },
-        { (char *)"Tossim_mac", _wrap_Tossim_mac, METH_VARARGS },
-        { (char *)"Tossim_radio", _wrap_Tossim_radio, METH_VARARGS },
-        { (char *)"Tossim_newPacket", _wrap_Tossim_newPacket, METH_VARARGS },
-        { (char *)"Tossim_swigregister", Tossim_swigregister, METH_VARARGS },
-        { NULL, NULL }
+        { (char *)"new_MAC", _wrap_new_MAC, METH_VARARGS, NULL},
+        { (char *)"delete_MAC", _wrap_delete_MAC, METH_VARARGS, NULL},
+        { (char *)"MAC_initHigh", _wrap_MAC_initHigh, METH_VARARGS, NULL},
+        { (char *)"MAC_initLow", _wrap_MAC_initLow, METH_VARARGS, NULL},
+        { (char *)"MAC_high", _wrap_MAC_high, METH_VARARGS, NULL},
+        { (char *)"MAC_low", _wrap_MAC_low, METH_VARARGS, NULL},
+        { (char *)"MAC_symbolsPerSec", _wrap_MAC_symbolsPerSec, METH_VARARGS, NULL},
+        { (char *)"MAC_bitsPerSymbol", _wrap_MAC_bitsPerSymbol, METH_VARARGS, NULL},
+        { (char *)"MAC_preambleLength", _wrap_MAC_preambleLength, METH_VARARGS, NULL},
+        { (char *)"MAC_exponentBase", _wrap_MAC_exponentBase, METH_VARARGS, NULL},
+        { (char *)"MAC_maxIterations", _wrap_MAC_maxIterations, METH_VARARGS, NULL},
+        { (char *)"MAC_minFreeSamples", _wrap_MAC_minFreeSamples, METH_VARARGS, NULL},
+        { (char *)"MAC_rxtxDelay", _wrap_MAC_rxtxDelay, METH_VARARGS, NULL},
+        { (char *)"MAC_ackTime", _wrap_MAC_ackTime, METH_VARARGS, NULL},
+        { (char *)"MAC_setInitHigh", _wrap_MAC_setInitHigh, METH_VARARGS, NULL},
+        { (char *)"MAC_setInitLow", _wrap_MAC_setInitLow, METH_VARARGS, NULL},
+        { (char *)"MAC_setHigh", _wrap_MAC_setHigh, METH_VARARGS, NULL},
+        { (char *)"MAC_setLow", _wrap_MAC_setLow, METH_VARARGS, NULL},
+        { (char *)"MAC_setSymbolsPerSec", _wrap_MAC_setSymbolsPerSec, METH_VARARGS, NULL},
+        { (char *)"MAC_setBitsBerSymbol", _wrap_MAC_setBitsBerSymbol, METH_VARARGS, NULL},
+        { (char *)"MAC_setPreambleLength", _wrap_MAC_setPreambleLength, METH_VARARGS, NULL},
+        { (char *)"MAC_setExponentBase", _wrap_MAC_setExponentBase, METH_VARARGS, NULL},
+        { (char *)"MAC_setMaxIterations", _wrap_MAC_setMaxIterations, METH_VARARGS, NULL},
+        { (char *)"MAC_setMinFreeSamples", _wrap_MAC_setMinFreeSamples, METH_VARARGS, NULL},
+        { (char *)"MAC_setRxtxDelay", _wrap_MAC_setRxtxDelay, METH_VARARGS, NULL},
+        { (char *)"MAC_setAckTime", _wrap_MAC_setAckTime, METH_VARARGS, NULL},
+        { (char *)"MAC_swigregister", MAC_swigregister, METH_VARARGS, NULL},
+        { (char *)"new_Radio", _wrap_new_Radio, METH_VARARGS, NULL},
+        { (char *)"delete_Radio", _wrap_delete_Radio, METH_VARARGS, NULL},
+        { (char *)"Radio_add", _wrap_Radio_add, METH_VARARGS, NULL},
+        { (char *)"Radio_gain", _wrap_Radio_gain, METH_VARARGS, NULL},
+        { (char *)"Radio_connected", _wrap_Radio_connected, METH_VARARGS, NULL},
+        { (char *)"Radio_remove", _wrap_Radio_remove, METH_VARARGS, NULL},
+        { (char *)"Radio_setNoise", _wrap_Radio_setNoise, METH_VARARGS, NULL},
+        { (char *)"Radio_setSensitivity", _wrap_Radio_setSensitivity, METH_VARARGS, NULL},
+        { (char *)"Radio_swigregister", Radio_swigregister, METH_VARARGS, NULL},
+        { (char *)"new_Packet", _wrap_new_Packet, METH_VARARGS, NULL},
+        { (char *)"delete_Packet", _wrap_delete_Packet, METH_VARARGS, NULL},
+        { (char *)"Packet_setSource", _wrap_Packet_setSource, METH_VARARGS, NULL},
+        { (char *)"Packet_source", _wrap_Packet_source, METH_VARARGS, NULL},
+        { (char *)"Packet_setDestination", _wrap_Packet_setDestination, METH_VARARGS, NULL},
+        { (char *)"Packet_destination", _wrap_Packet_destination, METH_VARARGS, NULL},
+        { (char *)"Packet_setLength", _wrap_Packet_setLength, METH_VARARGS, NULL},
+        { (char *)"Packet_length", _wrap_Packet_length, METH_VARARGS, NULL},
+        { (char *)"Packet_setType", _wrap_Packet_setType, METH_VARARGS, NULL},
+        { (char *)"Packet_type", _wrap_Packet_type, METH_VARARGS, NULL},
+        { (char *)"Packet_data", _wrap_Packet_data, METH_VARARGS, NULL},
+        { (char *)"Packet_setData", _wrap_Packet_setData, METH_VARARGS, NULL},
+        { (char *)"Packet_maxLength", _wrap_Packet_maxLength, METH_VARARGS, NULL},
+        { (char *)"Packet_setStrength", _wrap_Packet_setStrength, METH_VARARGS, NULL},
+        { (char *)"Packet_deliver", _wrap_Packet_deliver, METH_VARARGS, NULL},
+        { (char *)"Packet_deliverNow", _wrap_Packet_deliverNow, METH_VARARGS, NULL},
+        { (char *)"Packet_swigregister", Packet_swigregister, METH_VARARGS, NULL},
+        { (char *)"variable_string_t_type_set", _wrap_variable_string_t_type_set, METH_VARARGS, NULL},
+        { (char *)"variable_string_t_type_get", _wrap_variable_string_t_type_get, METH_VARARGS, NULL},
+        { (char *)"variable_string_t_ptr_set", _wrap_variable_string_t_ptr_set, METH_VARARGS, NULL},
+        { (char *)"variable_string_t_ptr_get", _wrap_variable_string_t_ptr_get, METH_VARARGS, NULL},
+        { (char *)"variable_string_t_len_set", _wrap_variable_string_t_len_set, METH_VARARGS, NULL},
+        { (char *)"variable_string_t_len_get", _wrap_variable_string_t_len_get, METH_VARARGS, NULL},
+        { (char *)"variable_string_t_isArray_set", _wrap_variable_string_t_isArray_set, METH_VARARGS, NULL},
+        { (char *)"variable_string_t_isArray_get", _wrap_variable_string_t_isArray_get, METH_VARARGS, NULL},
+        { (char *)"new_variable_string_t", _wrap_new_variable_string_t, METH_VARARGS, NULL},
+        { (char *)"delete_variable_string_t", _wrap_delete_variable_string_t, METH_VARARGS, NULL},
+        { (char *)"variable_string_t_swigregister", variable_string_t_swigregister, METH_VARARGS, NULL},
+        { (char *)"nesc_app_t_numVariables_set", _wrap_nesc_app_t_numVariables_set, METH_VARARGS, NULL},
+        { (char *)"nesc_app_t_numVariables_get", _wrap_nesc_app_t_numVariables_get, METH_VARARGS, NULL},
+        { (char *)"nesc_app_t_variableNames_set", _wrap_nesc_app_t_variableNames_set, METH_VARARGS, NULL},
+        { (char *)"nesc_app_t_variableNames_get", _wrap_nesc_app_t_variableNames_get, METH_VARARGS, NULL},
+        { (char *)"nesc_app_t_variableTypes_set", _wrap_nesc_app_t_variableTypes_set, METH_VARARGS, NULL},
+        { (char *)"nesc_app_t_variableTypes_get", _wrap_nesc_app_t_variableTypes_get, METH_VARARGS, NULL},
+        { (char *)"nesc_app_t_variableArray_set", _wrap_nesc_app_t_variableArray_set, METH_VARARGS, NULL},
+        { (char *)"nesc_app_t_variableArray_get", _wrap_nesc_app_t_variableArray_get, METH_VARARGS, NULL},
+        { (char *)"new_nesc_app_t", _wrap_new_nesc_app_t, METH_VARARGS, NULL},
+        { (char *)"delete_nesc_app_t", _wrap_delete_nesc_app_t, METH_VARARGS, NULL},
+        { (char *)"nesc_app_t_swigregister", nesc_app_t_swigregister, METH_VARARGS, NULL},
+        { (char *)"new_Variable", _wrap_new_Variable, METH_VARARGS, NULL},
+        { (char *)"delete_Variable", _wrap_delete_Variable, METH_VARARGS, NULL},
+        { (char *)"Variable_getData", _wrap_Variable_getData, METH_VARARGS, NULL},
+        { (char *)"Variable_swigregister", Variable_swigregister, METH_VARARGS, NULL},
+        { (char *)"new_Mote", _wrap_new_Mote, METH_VARARGS, NULL},
+        { (char *)"delete_Mote", _wrap_delete_Mote, METH_VARARGS, NULL},
+        { (char *)"Mote_id", _wrap_Mote_id, METH_VARARGS, NULL},
+        { (char *)"Mote_euid", _wrap_Mote_euid, METH_VARARGS, NULL},
+        { (char *)"Mote_setEuid", _wrap_Mote_setEuid, METH_VARARGS, NULL},
+        { (char *)"Mote_bootTime", _wrap_Mote_bootTime, METH_VARARGS, NULL},
+        { (char *)"Mote_bootAtTime", _wrap_Mote_bootAtTime, METH_VARARGS, NULL},
+        { (char *)"Mote_isOn", _wrap_Mote_isOn, METH_VARARGS, NULL},
+        { (char *)"Mote_turnOff", _wrap_Mote_turnOff, METH_VARARGS, NULL},
+        { (char *)"Mote_turnOn", _wrap_Mote_turnOn, METH_VARARGS, NULL},
+        { (char *)"Mote_getVariable", _wrap_Mote_getVariable, METH_VARARGS, NULL},
+        { (char *)"Mote_addNoiseTraceReading", _wrap_Mote_addNoiseTraceReading, METH_VARARGS, NULL},
+        { (char *)"Mote_createNoiseModel", _wrap_Mote_createNoiseModel, METH_VARARGS, NULL},
+        { (char *)"Mote_generateNoise", _wrap_Mote_generateNoise, METH_VARARGS, NULL},
+        { (char *)"Mote_swigregister", Mote_swigregister, METH_VARARGS, NULL},
+        { (char *)"new_Tossim", _wrap_new_Tossim, METH_VARARGS, NULL},
+        { (char *)"delete_Tossim", _wrap_delete_Tossim, METH_VARARGS, NULL},
+        { (char *)"Tossim_init", _wrap_Tossim_init, METH_VARARGS, NULL},
+        { (char *)"Tossim_time", _wrap_Tossim_time, METH_VARARGS, NULL},
+        { (char *)"Tossim_ticksPerSecond", _wrap_Tossim_ticksPerSecond, METH_VARARGS, NULL},
+        { (char *)"Tossim_setTime", _wrap_Tossim_setTime, METH_VARARGS, NULL},
+        { (char *)"Tossim_timeStr", _wrap_Tossim_timeStr, METH_VARARGS, NULL},
+        { (char *)"Tossim_currentNode", _wrap_Tossim_currentNode, METH_VARARGS, NULL},
+        { (char *)"Tossim_getNode", _wrap_Tossim_getNode, METH_VARARGS, NULL},
+        { (char *)"Tossim_setCurrentNode", _wrap_Tossim_setCurrentNode, METH_VARARGS, NULL},
+        { (char *)"Tossim_addChannel", _wrap_Tossim_addChannel, METH_VARARGS, NULL},
+        { (char *)"Tossim_removeChannel", _wrap_Tossim_removeChannel, METH_VARARGS, NULL},
+        { (char *)"Tossim_randomSeed", _wrap_Tossim_randomSeed, METH_VARARGS, NULL},
+        { (char *)"Tossim_runNextEvent", _wrap_Tossim_runNextEvent, METH_VARARGS, NULL},
+        { (char *)"Tossim_mac", _wrap_Tossim_mac, METH_VARARGS, NULL},
+        { (char *)"Tossim_radio", _wrap_Tossim_radio, METH_VARARGS, NULL},
+        { (char *)"Tossim_newPacket", _wrap_Tossim_newPacket, METH_VARARGS, NULL},
+        { (char *)"Tossim_swigregister", Tossim_swigregister, METH_VARARGS, NULL},
+        { NULL, NULL, 0, NULL }
 };
 
 
 /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */
 
-static swig_type_info _swigt__p_Radio[] = {{"_p_Radio", 0, "Radio *", 0},{"_p_Radio"},{0}};
-static swig_type_info _swigt__p_nesc_app_t[] = {{"_p_nesc_app_t", 0, "nesc_app_t *", 0},{"_p_nesc_app_t"},{0}};
-static swig_type_info _swigt__p_FILE[] = {{"_p_FILE", 0, "FILE *", 0},{"_p_FILE"},{0}};
-static swig_type_info _swigt__p_MAC[] = {{"_p_MAC", 0, "MAC *", 0},{"_p_MAC"},{0}};
-static swig_type_info _swigt__p_Packet[] = {{"_p_Packet", 0, "Packet *", 0},{"_p_Packet"},{0}};
-static swig_type_info _swigt__p_Variable[] = {{"_p_Variable", 0, "Variable *", 0},{"_p_Variable"},{0}};
-static swig_type_info _swigt__p_Tossim[] = {{"_p_Tossim", 0, "Tossim *", 0},{"_p_Tossim"},{0}};
-static swig_type_info _swigt__p_variable_string_t[] = {{"_p_variable_string_t", 0, "variable_string_t *", 0},{"_p_variable_string_t"},{0}};
-static swig_type_info _swigt__p_Mote[] = {{"_p_Mote", 0, "Mote *", 0},{"_p_Mote"},{0}};
-static swig_type_info _swigt__p_p_char[] = {{"_p_p_char", 0, "char **", 0},{"_p_p_char"},{0}};
-static swig_type_info _swigt__p_int[] = {{"_p_int", 0, "int *", 0},{"_p_int"},{0}};
-
-static swig_type_info *swig_types_initial[] = {
-_swigt__p_Radio, 
-_swigt__p_nesc_app_t, 
-_swigt__p_FILE, 
-_swigt__p_MAC, 
-_swigt__p_Packet, 
-_swigt__p_Variable, 
-_swigt__p_Tossim, 
-_swigt__p_variable_string_t, 
-_swigt__p_Mote, 
-_swigt__p_p_char, 
-_swigt__p_int, 
-0
+static swig_type_info _swigt__p_FILE = {"_p_FILE", "FILE *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_MAC = {"_p_MAC", "MAC *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_Mote = {"_p_Mote", "Mote *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_Packet = {"_p_Packet", "Packet *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_Radio = {"_p_Radio", "Radio *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_Tossim = {"_p_Tossim", "Tossim *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_Variable = {"_p_Variable", "Variable *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_char = {"_p_char", "char *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_int = {"_p_int", "int *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_nesc_app = {"_p_nesc_app", "nesc_app *|nesc_app_t *", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_p_char = {"_p_p_char", "char **", 0, 0, (void*)0, 0};
+static swig_type_info _swigt__p_var_string = {"_p_var_string", "var_string *|variable_string_t *", 0, 0, (void*)0, 0};
+
+static swig_type_info *swig_type_initial[] = {
+  &_swigt__p_FILE,
+  &_swigt__p_MAC,
+  &_swigt__p_Mote,
+  &_swigt__p_Packet,
+  &_swigt__p_Radio,
+  &_swigt__p_Tossim,
+  &_swigt__p_Variable,
+  &_swigt__p_char,
+  &_swigt__p_int,
+  &_swigt__p_nesc_app,
+  &_swigt__p_p_char,
+  &_swigt__p_var_string,
+};
+
+static swig_cast_info _swigc__p_FILE[] = {  {&_swigt__p_FILE, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_MAC[] = {  {&_swigt__p_MAC, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_Mote[] = {  {&_swigt__p_Mote, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_Packet[] = {  {&_swigt__p_Packet, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_Radio[] = {  {&_swigt__p_Radio, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_Tossim[] = {  {&_swigt__p_Tossim, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_Variable[] = {  {&_swigt__p_Variable, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_char[] = {  {&_swigt__p_char, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_int[] = {  {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_nesc_app[] = {  {&_swigt__p_nesc_app, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_p_char[] = {  {&_swigt__p_p_char, 0, 0, 0},{0, 0, 0, 0}};
+static swig_cast_info _swigc__p_var_string[] = {  {&_swigt__p_var_string, 0, 0, 0},{0, 0, 0, 0}};
+
+static swig_cast_info *swig_cast_initial[] = {
+  _swigc__p_FILE,
+  _swigc__p_MAC,
+  _swigc__p_Mote,
+  _swigc__p_Packet,
+  _swigc__p_Radio,
+  _swigc__p_Tossim,
+  _swigc__p_Variable,
+  _swigc__p_char,
+  _swigc__p_int,
+  _swigc__p_nesc_app,
+  _swigc__p_p_char,
+  _swigc__p_var_string,
 };
 
 
 /* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */
 
 static swig_const_info swig_const_table[] = {
-{0}};
+{0, 0, 0, 0.0, 0, 0}};
 
 #ifdef __cplusplus
 }
 #endif
+/* -----------------------------------------------------------------------------
+ * Type initialization:
+ * This problem is tough by the requirement that no dynamic 
+ * memory is used. Also, since swig_type_info structures store pointers to 
+ * swig_cast_info structures and swig_cast_info structures store pointers back
+ * to swig_type_info structures, we need some lookup code at initialization. 
+ * The idea is that swig generates all the structures that are needed. 
+ * The runtime then collects these partially filled structures. 
+ * The SWIG_InitializeModule function takes these initial arrays out of 
+ * swig_module, and does all the lookup, filling in the swig_module.types
+ * array with the correct data and linking the correct swig_cast_info
+ * structures together.
+ *
+ * The generated swig_type_info structures are assigned staticly to an initial 
+ * array. We just loop through that array, and handle each type individually.
+ * First we lookup if this type has been already loaded, and if so, use the
+ * loaded structure instead of the generated one. Then we have to fill in the
+ * cast linked list. The cast data is initially stored in something like a
+ * two-dimensional array. Each row corresponds to a type (there are the same
+ * number of rows as there are in the swig_type_initial array). Each entry in
+ * a column is one of the swig_cast_info structures for that type.
+ * The cast_initial array is actually an array of arrays, because each row has
+ * a variable number of columns. So to actually build the cast linked list,
+ * we find the array of casts associated with the type, and loop through it 
+ * adding the casts to the list. The one last trick we need to do is making
+ * sure the type pointer in the swig_cast_info struct is correct.
+ *
+ * First off, we lookup the cast->type name to see if it is already loaded. 
+ * There are three cases to handle:
+ *  1) If the cast->type has already been loaded AND the type we are adding
+ *     casting info to has not been loaded (it is in this module), THEN we
+ *     replace the cast->type pointer with the type pointer that has already
+ *     been loaded.
+ *  2) If BOTH types (the one we are adding casting info to, and the 
+ *     cast->type) are loaded, THEN the cast info has already been loaded by
+ *     the previous module so we just ignore it.
+ *  3) Finally, if cast->type has not already been loaded, then we add that
+ *     swig_cast_info to the linked list (because the cast->type) pointer will
+ *     be correct.
+ * ----------------------------------------------------------------------------- */
 
 #ifdef __cplusplus
-extern "C"
+extern "C" {
+#if 0
+} /* c-mode */
+#endif
+#endif
+
+#if 0
+#define SWIGRUNTIME_DEBUG
+#endif
+
+
+SWIGRUNTIME void
+SWIG_InitializeModule(void *clientdata) {
+  size_t i;
+  swig_module_info *module_head, *iter;
+  int found;
+  
+  clientdata = clientdata;
+  
+  /* check to see if the circular list has been setup, if not, set it up */
+  if (swig_module.next==0) {
+    /* Initialize the swig_module */
+    swig_module.type_initial = swig_type_initial;
+    swig_module.cast_initial = swig_cast_initial;
+    swig_module.next = &swig_module;
+  }
+  
+  /* Try and load any already created modules */
+  module_head = SWIG_GetModule(clientdata);
+  if (!module_head) {
+    /* This is the first module loaded for this interpreter */
+    /* so set the swig module into the interpreter */
+    SWIG_SetModule(clientdata, &swig_module);
+    module_head = &swig_module;
+  } else {
+    /* the interpreter has loaded a SWIG module, but has it loaded this one? */
+    found=0;
+    iter=module_head;
+    do {
+      if (iter==&swig_module) {
+        found=1;
+        break;
+      }
+      iter=iter->next;
+    } while (iter!= module_head);
+    
+    /* if the is found in the list, then all is done and we may leave */
+    if (found) return;
+    /* otherwise we must add out module into the list */
+    swig_module.next = module_head->next;
+    module_head->next = &swig_module;
+  }
+  
+  /* Now work on filling in swig_module.types */
+#ifdef SWIGRUNTIME_DEBUG
+  printf("SWIG_InitializeModule: size %d\n", swig_module.size);
 #endif
-SWIGEXPORT(void) SWIG_init(void) {
-    static PyObject *SWIG_globals = 0; 
-    static int       typeinit = 0;
-    PyObject *m, *d;
-    int       i;
-    if (!SWIG_globals) SWIG_globals = SWIG_newvarlink();
-    m = Py_InitModule((char *) SWIG_name, SwigMethods);
-    d = PyModule_GetDict(m);
+  for (i = 0; i < swig_module.size; ++i) {
+    swig_type_info *type = 0;
+    swig_type_info *ret;
+    swig_cast_info *cast;
     
-    if (!typeinit) {
-        for (i = 0; swig_types_initial[i]; i++) {
-            swig_types[i] = SWIG_TypeRegister(swig_types_initial[i]);
-        }
-        typeinit = 1;
+#ifdef SWIGRUNTIME_DEBUG
+    printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name);
+#endif
+    
+    /* if there is another module already loaded */
+    if (swig_module.next != &swig_module) {
+      type = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, swig_module.type_initial[i]->name);
+    }
+    if (type) {
+      /* Overwrite clientdata field */
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: found type %s\n", type->name);
+#endif
+      if (swig_module.type_initial[i]->clientdata) {
+        type->clientdata = swig_module.type_initial[i]->clientdata;
+#ifdef SWIGRUNTIME_DEBUG
+        printf("SWIG_InitializeModule: found and overwrite type %s \n", type->name);
+#endif
+      }
+    } else {
+      type = swig_module.type_initial[i];
     }
-    SWIG_InstallConstants(d,swig_const_table);
     
+    /* Insert casting types */
+    cast = swig_module.cast_initial[i];
+    while (cast->type) {
+      /* Don't need to add information already in the list */
+      ret = 0;
+#ifdef SWIGRUNTIME_DEBUG
+      printf("SWIG_InitializeModule: look cast %s\n", cast->type->name);
+#endif
+      if (swig_module.next != &swig_module) {
+        ret = SWIG_MangledTypeQueryModule(swig_module.next, &swig_module, cast->type->name);
+#ifdef SWIGRUNTIME_DEBUG
+        if (ret) printf("SWIG_InitializeModule: found cast %s\n", ret->name);
+#endif
+      }
+      if (ret) {
+        if (type == swig_module.type_initial[i]) {
+#ifdef SWIGRUNTIME_DEBUG
+          printf("SWIG_InitializeModule: skip old type %s\n", ret->name);
+#endif
+          cast->type = ret;
+          ret = 0;
+        } else {
+          /* Check for casting already in the list */
+          swig_cast_info *ocast = SWIG_TypeCheck(ret->name, type);
+#ifdef SWIGRUNTIME_DEBUG
+          if (ocast) printf("SWIG_InitializeModule: skip old cast %s\n", ret->name);
+#endif
+          if (!ocast) ret = 0;
+        }
+      }
+      
+      if (!ret) {
+#ifdef SWIGRUNTIME_DEBUG
+        printf("SWIG_InitializeModule: adding cast %s\n", cast->type->name);
+#endif
+        if (type->cast) {
+          type->cast->prev = cast;
+          cast->next = type->cast;
+        }
+        type->cast = cast;
+      }
+      cast++;
+    }
+    /* Set entry in modules->types array equal to the type */
+    swig_module.types[i] = type;
+  }
+  swig_module.types[i] = 0;
+  
+#ifdef SWIGRUNTIME_DEBUG
+  printf("**** SWIG_InitializeModule: Cast List ******\n");
+  for (i = 0; i < swig_module.size; ++i) {
+    int j = 0;
+    swig_cast_info *cast = swig_module.cast_initial[i];
+    printf("SWIG_InitializeModule: type %d %s\n", i, swig_module.type_initial[i]->name);
+    while (cast->type) {
+      printf("SWIG_InitializeModule: cast type %s\n", cast->type->name);
+      cast++;
+      ++j;
+    }
+    printf("---- Total casts: %d\n",j);
+  }
+  printf("**** SWIG_InitializeModule: Cast List ******\n");
+#endif
+}
+
+/* This function will propagate the clientdata field of type to
+* any new swig_type_info structures that have been added into the list
+* of equivalent types.  It is like calling
+* SWIG_TypeClientData(type, clientdata) a second time.
+*/
+SWIGRUNTIME void
+SWIG_PropagateClientData(void) {
+  size_t i;
+  swig_cast_info *equiv;
+  static int init_run = 0;
+  
+  if (init_run) return;
+  init_run = 1;
+  
+  for (i = 0; i < swig_module.size; i++) {
+    if (swig_module.types[i]->clientdata) {
+      equiv = swig_module.types[i]->cast;
+      while (equiv) {
+        if (!equiv->converter) {
+          if (equiv->type && !equiv->type->clientdata)
+          SWIG_TypeClientData(equiv->type, swig_module.types[i]->clientdata);
+        }
+        equiv = equiv->next;
+      }
+    }
+  }
+}
+
+#ifdef __cplusplus
+#if 0
+{
+  /* c-mode */
+#endif
+}
+#endif
+
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+  
+  /* Python-specific SWIG API */
+#define SWIG_newvarlink()                             SWIG_Python_newvarlink()
+#define SWIG_addvarlink(p, name, get_attr, set_attr)  SWIG_Python_addvarlink(p, name, get_attr, set_attr)
+#define SWIG_InstallConstants(d, constants)           SWIG_Python_InstallConstants(d, constants)
+  
+  /* -----------------------------------------------------------------------------
+   * global variable support code.
+   * ----------------------------------------------------------------------------- */
+  
+  typedef struct swig_globalvar {
+    char       *name;                  /* Name of global variable */
+    PyObject *(*get_attr)(void);       /* Return the current value */
+    int       (*set_attr)(PyObject *); /* Set the value */
+    struct swig_globalvar *next;
+  } swig_globalvar;
+  
+  typedef struct swig_varlinkobject {
+    PyObject_HEAD
+    swig_globalvar *vars;
+  } swig_varlinkobject;
+  
+  SWIGINTERN PyObject *
+  swig_varlink_repr(swig_varlinkobject *SWIGUNUSEDPARM(v)) {
+    return PyString_FromString("<Swig global variables>");
+  }
+  
+  SWIGINTERN PyObject *
+  swig_varlink_str(swig_varlinkobject *v) {
+    PyObject *str = PyString_FromString("(");
+    swig_globalvar  *var;
+    for (var = v->vars; var; var=var->next) {
+      PyString_ConcatAndDel(&str,PyString_FromString(var->name));
+      if (var->next) PyString_ConcatAndDel(&str,PyString_FromString(", "));
+    }
+    PyString_ConcatAndDel(&str,PyString_FromString(")"));
+    return str;
+  }
+  
+  SWIGINTERN int
+  swig_varlink_print(swig_varlinkobject *v, FILE *fp, int SWIGUNUSEDPARM(flags)) {
+    PyObject *str = swig_varlink_str(v);
+    fprintf(fp,"Swig global variables ");
+    fprintf(fp,"%s\n", PyString_AsString(str));
+    Py_DECREF(str);
+    return 0;
+  }
+  
+  SWIGINTERN void
+  swig_varlink_dealloc(swig_varlinkobject *v) {
+    swig_globalvar *var = v->vars;
+    while (var) {
+      swig_globalvar *n = var->next;
+      free(var->name);
+      free(var);
+      var = n;
+    }
+  }
+  
+  SWIGINTERN PyObject *
+  swig_varlink_getattr(swig_varlinkobject *v, char *n) {
+    PyObject *res = NULL;
+    swig_globalvar *var = v->vars;
+    while (var) {
+      if (strcmp(var->name,n) == 0) {
+        res = (*var->get_attr)();
+        break;
+      }
+      var = var->next;
+    }
+    if (res == NULL && !PyErr_Occurred()) {
+      PyErr_SetString(PyExc_NameError,"Unknown C global variable");
+    }
+    return res;
+  }
+  
+  SWIGINTERN int
+  swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) {
+    int res = 1;
+    swig_globalvar *var = v->vars;
+    while (var) {
+      if (strcmp(var->name,n) == 0) {
+        res = (*var->set_attr)(p);
+        break;
+      }
+      var = var->next;
+    }
+    if (res == 1 && !PyErr_Occurred()) {
+      PyErr_SetString(PyExc_NameError,"Unknown C global variable");
+    }
+    return res;
+  }
+  
+  SWIGINTERN PyTypeObject*
+  swig_varlink_type(void) {
+    static char varlink__doc__[] = "Swig var link object";
+    static PyTypeObject varlink_type;
+    static int type_init = 0;  
+    if (!type_init) {
+      const PyTypeObject tmp
+      = {
+        PyObject_HEAD_INIT(NULL)
+        0,                                  /* Number of items in variable part (ob_size) */
+        (char *)"swigvarlink",              /* Type name (tp_name) */
+        sizeof(swig_varlinkobject),         /* Basic size (tp_basicsize) */
+        0,                                  /* Itemsize (tp_itemsize) */
+        (destructor) swig_varlink_dealloc,   /* Deallocator (tp_dealloc) */ 
+        (printfunc) swig_varlink_print,     /* Print (tp_print) */
+        (getattrfunc) swig_varlink_getattr, /* get attr (tp_getattr) */
+        (setattrfunc) swig_varlink_setattr, /* Set attr (tp_setattr) */
+        0,                                  /* tp_compare */
+        (reprfunc) swig_varlink_repr,       /* tp_repr */
+        0,                                  /* tp_as_number */
+        0,                                  /* tp_as_sequence */
+        0,                                  /* tp_as_mapping */
+        0,                                  /* tp_hash */
+        0,                                  /* tp_call */
+        (reprfunc)swig_varlink_str,        /* tp_str */
+        0,                                  /* tp_getattro */
+        0,                                  /* tp_setattro */
+        0,                                  /* tp_as_buffer */
+        0,                                  /* tp_flags */
+        varlink__doc__,                     /* tp_doc */
+        0,                                  /* tp_traverse */
+        0,                                  /* tp_clear */
+        0,                                  /* tp_richcompare */
+        0,                                  /* tp_weaklistoffset */
+#if PY_VERSION_HEX >= 0x02020000
+        0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, /* tp_iter -> tp_weaklist */
+#endif
+#if PY_VERSION_HEX >= 0x02030000
+        0,                                  /* tp_del */
+#endif
+#ifdef COUNT_ALLOCS
+        0,0,0,0                             /* tp_alloc -> tp_next */
+#endif
+      };
+      varlink_type = tmp;
+      varlink_type.ob_type = &PyType_Type;
+      type_init = 1;
+    }
+    return &varlink_type;
+  }
+  
+  /* Create a variable linking object for use later */
+  SWIGINTERN PyObject *
+  SWIG_Python_newvarlink(void) {
+    swig_varlinkobject *result = PyObject_NEW(swig_varlinkobject, swig_varlink_type());
+    if (result) {
+      result->vars = 0;
+    }
+    return ((PyObject*) result);
+  }
+  
+  SWIGINTERN void 
+  SWIG_Python_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) {
+    swig_varlinkobject *v = (swig_varlinkobject *) p;
+    swig_globalvar *gv = (swig_globalvar *) malloc(sizeof(swig_globalvar));
+    if (gv) {
+      size_t size = strlen(name)+1;
+      gv->name = (char *)malloc(size);
+      if (gv->name) {
+        strncpy(gv->name,name,size);
+        gv->get_attr = get_attr;
+        gv->set_attr = set_attr;
+        gv->next = v->vars;
+      }
+    }
+    v->vars = gv;
+  }
+  
+  SWIGINTERN PyObject *
+  SWIG_globals(void) {
+    static PyObject *_SWIG_globals = 0; 
+    if (!_SWIG_globals) _SWIG_globals = SWIG_newvarlink();  
+    return _SWIG_globals;
+  }
+  
+  /* -----------------------------------------------------------------------------
+   * constants/methods manipulation
+   * ----------------------------------------------------------------------------- */
+  
+  /* Install Constants */
+  SWIGINTERN void
+  SWIG_Python_InstallConstants(PyObject *d, swig_const_info constants[]) {
+    PyObject *obj = 0;
+    size_t i;
+    for (i = 0; constants[i].type; ++i) {
+      switch(constants[i].type) {
+      case SWIG_PY_POINTER:
+        obj = SWIG_NewPointerObj(constants[i].pvalue, *(constants[i]).ptype,0);
+        break;
+      case SWIG_PY_BINARY:
+        obj = SWIG_NewPackedObj(constants[i].pvalue, constants[i].lvalue, *(constants[i].ptype));
+        break;
+      default:
+        obj = 0;
+        break;
+      }
+      if (obj) {
+        PyDict_SetItemString(d, constants[i].name, obj);
+        Py_DECREF(obj);
+      }
+    }
+  }
+  
+  /* -----------------------------------------------------------------------------*/
+  /* Fix SwigMethods to carry the callback ptrs when needed */
+  /* -----------------------------------------------------------------------------*/
+  
+  SWIGINTERN void
+  SWIG_Python_FixMethods(PyMethodDef *methods,
+    swig_const_info *const_table,
+    swig_type_info **types,
+    swig_type_info **types_initial) {
+    size_t i;
+    for (i = 0; methods[i].ml_name; ++i) {
+      const char *c = methods[i].ml_doc;
+      if (c && (c = strstr(c, "swig_ptr: "))) {
+        int j;
+        swig_const_info *ci = 0;
+        const char *name = c + 10;
+        for (j = 0; const_table[j].type; ++j) {
+          if (strncmp(const_table[j].name, name, 
+              strlen(const_table[j].name)) == 0) {
+            ci = &(const_table[j]);
+            break;
+          }
+        }
+        if (ci) {
+          size_t shift = (ci->ptype) - types;
+          swig_type_info *ty = types_initial[shift];
+          size_t ldoc = (c - methods[i].ml_doc);
+          size_t lptr = strlen(ty->name)+2*sizeof(void*)+2;
+          char *ndoc = (char*)malloc(ldoc + lptr + 10);
+          if (ndoc) {
+            char *buff = ndoc;
+            void *ptr = (ci->type == SWIG_PY_POINTER) ? ci->pvalue : 0;
+            if (ptr) {
+              strncpy(buff, methods[i].ml_doc, ldoc);
+              buff += ldoc;
+              strncpy(buff, "swig_ptr: ", 10);
+              buff += 10;
+              SWIG_PackVoidPtr(buff, ptr, ty->name, lptr);
+              methods[i].ml_doc = ndoc;
+            }
+          }
+        }
+      }
+    }
+  } 
+  
+#ifdef __cplusplus
+}
+#endif
+
+/* -----------------------------------------------------------------------------*
+ *  Partial Init method
+ * -----------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+extern "C"
+#endif
+SWIGEXPORT void SWIG_init(void) {
+  PyObject *m, *d;
+  
+  /* Fix SwigMethods to carry the callback ptrs when needed */
+  SWIG_Python_FixMethods(SwigMethods, swig_const_table, swig_types, swig_type_initial);
+  
+  m = Py_InitModule((char *) SWIG_name, SwigMethods);
+  d = PyModule_GetDict(m);
+  
+  SWIG_InitializeModule(0);
+  SWIG_InstallConstants(d,swig_const_table);
+  
+  
 }
 
index ccbccfb11862eaba6c6203a52f9e7836ed6c911d..1c45d6bca349b07058e14eca1867591f7113ffd9 100644 (file)
 
 #include "CC2420.h"
 #include "AM.h"
+#include "Ieee154.h"
+
+#ifdef IEEE154FRAMES_ENABLED
+#error "CC2420 AM layer cannot work when IEEE 802.15.4 frames only are used"
+#endif
 
 configuration CC2420ActiveMessageC {
   provides {
@@ -57,29 +62,18 @@ configuration CC2420ActiveMessageC {
   }
 }
 implementation {
+  enum {
+    CC2420_AM_SEND_ID     = unique(IEEE154_SEND_CLIENT),
+  };
 
+  components CC2420RadioC as Radio;
   components CC2420ActiveMessageP as AM;
-  components CC2420CsmaC as CsmaC;
   components ActiveMessageAddressC;
-  components UniqueSendC;
-  components UniqueReceiveC;
-  components CC2420TinyosNetworkC;
-  components CC2420PacketC;
+  components CC2420CsmaC as CsmaC;
   components CC2420ControlC;
+  components CC2420PacketC;
   
-#if defined(LOW_POWER_LISTENING) || defined(ACK_LOW_POWER_LISTENING)
-  components DefaultLplC as LplC;
-#else
-  components DummyLplC as LplC;
-#endif
-
-#if defined(PACKET_LINK)
-  components PacketLinkC as LinkC;
-#else
-  components PacketLinkDummyC as LinkC;
-#endif
-
-  
+  SplitControl = Radio;
   RadioBackoff = AM;
   Packet = AM;
   AMSend = AM;
@@ -89,28 +83,16 @@ implementation {
   Snoop = AM.Snoop;
   SnoopDefault = AM.SnoopDefault;
   AMPacket = AM;
-  PacketLink = LinkC;
-  LowPowerListening = LplC;
-  CC2420Packet = CC2420PacketC;
-  PacketAcknowledgements = CC2420PacketC;
-  LinkPacketMetadata = CC2420PacketC;
-  
-  // SplitControl Layers
-  SplitControl = LplC;
-  LplC.SubControl -> CsmaC;
-  
-  // Send Layers
-  AM.SubSend -> UniqueSendC;
-  UniqueSendC.SubSend -> LinkC;
-  LinkC.SubSend -> LplC.Send;
-  LplC.SubSend -> CC2420TinyosNetworkC.Send;
-  CC2420TinyosNetworkC.SubSend -> CsmaC;
+  PacketLink = Radio;
+  LowPowerListening = Radio;
+  CC2420Packet = Radio;
+  PacketAcknowledgements = Radio;
+  LinkPacketMetadata = Radio;
   
-  // Receive Layers
-  AM.SubReceive -> LplC;
-  LplC.SubReceive -> UniqueReceiveC.Receive;
-  UniqueReceiveC.SubReceive -> CC2420TinyosNetworkC.Receive;
-  CC2420TinyosNetworkC.SubReceive -> CsmaC;
+  // Radio resource for the AM layer
+  AM.RadioResource -> Radio.Resource[CC2420_AM_SEND_ID];
+  AM.SubSend -> Radio.ActiveSend;
+  AM.SubReceive -> Radio.ActiveReceive;
 
   AM.ActiveMessageAddress -> ActiveMessageAddressC;
   AM.CC2420Packet -> CC2420PacketC;
@@ -118,5 +100,9 @@ implementation {
   AM.CC2420Config -> CC2420ControlC;
   
   AM.SubBackoff -> CsmaC;
-  
+
+  components LedsC;
+  AM.Leds -> LedsC;
 }
+
+
index 89ca391e9ea7172ebf6d80ff8cc17cc5f11aa72e..36ee724f2d9bfb9cdb206e2bfc4e1309257e52ca 100644 (file)
@@ -55,23 +55,57 @@ module CC2420ActiveMessageP @safe() {
     interface CC2420Config;
     interface ActiveMessageAddress;
     interface RadioBackoff as SubBackoff;
+
+    interface Resource as RadioResource;
+    interface Leds;
   }
 }
 implementation {
+  uint16_t pending_length;
+  message_t *pending_message = NULL;
+  /***************** Resource event  ****************/
+  event void RadioResource.granted() {
+    uint8_t rc;
+    cc2420_header_t* header = call CC2420PacketBody.getHeader( pending_message );
+
+    signal SendNotifier.aboutToSend[header->type](header->dest, pending_message);
+    rc = call SubSend.send( pending_message, pending_length );
+    if (rc != SUCCESS) {
+      call RadioResource.release();
+      signal AMSend.sendDone[header->type]( pending_message, rc );
+    }
+  }
 
   /***************** AMSend Commands ****************/
   command error_t AMSend.send[am_id_t id](am_addr_t addr,
                                          message_t* msg,
                                          uint8_t len) {
     cc2420_header_t* header = call CC2420PacketBody.getHeader( msg );
+    
+    if (len > call Packet.maxPayloadLength()) {
+      return ESIZE;
+    }
+    
     header->type = id;
     header->dest = addr;
     header->destpan = call CC2420Config.getPanAddr();
     header->src = call AMPacket.address();
     
-    signal SendNotifier.aboutToSend[id](addr, msg);
-    
-    return call SubSend.send( msg, len );
+    if (call RadioResource.immediateRequest() == SUCCESS) {
+      error_t rc;
+      signal SendNotifier.aboutToSend[id](addr, msg);
+      
+      rc = call SubSend.send( msg, len );
+      if (rc != SUCCESS) {
+        call RadioResource.release();
+      }
+
+      return rc;
+    } else {
+      pending_length  = len;
+      pending_message = msg;
+      return call RadioResource.request();
+    }
   }
 
   command error_t AMSend.cancel[am_id_t id](message_t* msg) {
@@ -155,7 +189,7 @@ implementation {
   }
   
   command uint8_t Packet.maxPayloadLength() {
-    return TOSH_DATA_LENGTH;
+    return call SubSend.maxPayloadLength();
   }
   
   command void* Packet.getPayload(message_t* msg, uint8_t len) {
@@ -165,6 +199,7 @@ implementation {
   
   /***************** SubSend Events ****************/
   event void SubSend.sendDone(message_t* msg, error_t result) {
+    call RadioResource.release();
     signal AMSend.sendDone[call AMPacket.type(msg)](msg, result);
   }
 
@@ -172,10 +207,6 @@ implementation {
   /***************** SubReceive Events ****************/
   event message_t* SubReceive.receive(message_t* msg, void* payload, uint8_t len) {
     
-    if(!(call CC2420PacketBody.getMetadata(msg))->crc) {
-      return msg;
-    }
-    
     if (call AMPacket.isForMe(msg)) {
       return signal Receive.receive[call AMPacket.type(msg)](msg, payload, len);
     }
@@ -232,8 +263,6 @@ implementation {
   async command void RadioBackoff.setCca[am_id_t amId](bool useCca) {
     call SubBackoff.setCca(useCca);
   }
-
-
   
   /***************** Defaults ****************/
   default event message_t* Receive.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
@@ -251,13 +280,13 @@ implementation {
   default event message_t* SnoopDefault.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
     return msg;
   }
-  
+
   default event void AMSend.sendDone[uint8_t id](message_t* msg, error_t err) {
+    call RadioResource.release();
   }
 
   default event void SendNotifier.aboutToSend[am_id_t amId](am_addr_t addr, message_t *msg) {
   }
-  
   default async event void RadioBackoff.requestInitialBackoff[am_id_t id](
       message_t *msg) {
   }
diff --git a/tos/lib/tosthreads/chips/msp430/sensors/BlockingMsp430InternalTemperatureC.nc b/tos/lib/tosthreads/chips/msp430/sensors/BlockingMsp430InternalTemperatureC.nc
new file mode 100644 (file)
index 0000000..305f9b7
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Msp430InternalTemperatureC is the temperature sensor available on
+ * the msp430-based platforms.
+ *
+ * To convert from ADC counts to temperature, convert to voltage by
+ * dividing by 4096 and multiplying by Vref (1.5V). Then subtract
+ * 0.986 from voltage and divide by 0.00355 to get degrees C.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$ $Date$
+ */
+/**
+ * Port to Tosthreads
+ *
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+generic configuration BlockingMsp430InternalTemperatureC() {
+  provides {
+    interface BlockingRead<uint16_t>;
+    interface BlockingReadStream<uint16_t>;
+  }
+}
+
+implementation {
+  components new BlockingAdcReadClientC();
+  BlockingRead = BlockingAdcReadClientC;
+
+  components new BlockingAdcReadStreamClientC();
+  BlockingReadStream = BlockingAdcReadStreamClientC;
+
+  components Msp430InternalTemperatureP;
+  BlockingAdcReadClientC.AdcConfigure -> Msp430InternalTemperatureP;
+  BlockingAdcReadStreamClientC.AdcConfigure -> Msp430InternalTemperatureP;
+}
diff --git a/tos/lib/tosthreads/chips/msp430/sensors/BlockingMsp430InternalVoltageC.nc b/tos/lib/tosthreads/chips/msp430/sensors/BlockingMsp430InternalVoltageC.nc
new file mode 100644 (file)
index 0000000..7b4ee6e
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Msp430InternalVoltageC is the voltage sensor available on the
+ * msp430-based platforms.
+ *
+ * To convert from ADC counts to actual voltage, divide by 4096 and
+ * multiply by 3.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$ $Date$
+ */
+
+/**
+ * Port to Tosthreads
+ *
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+generic configuration BlockingMsp430InternalVoltageC() {
+  provides {
+    interface BlockingRead<uint16_t>;
+    interface BlockingReadStream<uint16_t>;
+  }
+}
+
+implementation {
+  components new BlockingAdcReadClientC();
+  BlockingRead = BlockingAdcReadClientC;
+
+  components new BlockingAdcReadStreamClientC();
+  BlockingReadStream = BlockingAdcReadStreamClientC;
+
+  components Msp430InternalVoltageP;
+  BlockingAdcReadClientC.AdcConfigure -> Msp430InternalVoltageP;
+  BlockingAdcReadStreamClientC.AdcConfigure -> Msp430InternalVoltageP;
+}
index d7af862259cf92d043c70e0cc3f9478a26e8ed63..b16884a59f249ca452e6c8ef7c8eaca81f44efcc 100644 (file)
@@ -1,17 +1,17 @@
 /*
- * Copyright (c) 2007, Vanderbilt University
+ * Copyright (c) 2009, Vanderbilt University
  * All rights reserved.
  *
  * Permission to use, copy, modify, and distribute this software and its
  * documentation for any purpose, without fee, and without written agreement is
  * hereby granted, provided that the above copyright notice, the following
  * two paragraphs and the author appear in all copies of this software.
- *
+ * 
  * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
  * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
  * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
+ * 
  * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  * Author: Miklos Maroti
  */
 
-module ActiveMessageLayerC
+/*
+ * Make active message TOSThreads-compatible by exposing default interfaces
+ *
+ * Author: Chieh-Jan Mike Liang
+ */
+
+configuration ActiveMessageLayerC
 {
        provides
        {
+               interface AMPacket;
+               interface Packet;
                interface AMSend[am_id_t id];
-    interface Receive[am_id_t id];
+               interface Receive[am_id_t id];
     interface Receive as ReceiveDefault[am_id_t id];
     interface Receive as Snoop[am_id_t id];
     interface Receive as SnoopDefault[am_id_t id];
+               interface SendNotifier[am_id_t id];
        }
+
        uses
        {
-               interface Send as SubSend;
-               interface Receive as SubReceive;
-               interface AMPacket;
+               interface RadioPacket as SubPacket;
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
                interface ActiveMessageConfig as Config;
        }
 }
 
 implementation
 {
-/*----------------- Send -----------------*/
-
-       command error_t AMSend.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len)
-       {
-               error_t error;
-
-               error = call Config.checkPacket(msg);
-               if( error != SUCCESS )
-                       return error;
-
-               call AMPacket.setSource(msg, call AMPacket.address());
-               call AMPacket.setGroup(msg, call AMPacket.localGroup());
-               call AMPacket.setType(msg, id);
-               call AMPacket.setDestination(msg, addr);
-
-               return call SubSend.send(msg, len);
-       }
-
-       inline event void SubSend.sendDone(message_t* msg, error_t error)
-       {
-               signal AMSend.sendDone[call AMPacket.type(msg)](msg, error);
-       }
-
-       inline command error_t AMSend.cancel[am_id_t id](message_t* msg)
-       {
-               return call SubSend.cancel(msg);
-       }
-
-       default event void AMSend.sendDone[am_id_t id](message_t* msg, error_t error)
-       {
-       }
-
-       inline command uint8_t AMSend.maxPayloadLength[am_id_t id]()
-       {
-               return call SubSend.maxPayloadLength();
-       }
-
-       inline command void* AMSend.getPayload[am_id_t id](message_t* msg, uint8_t len)
-       {
-               return call SubSend.getPayload(msg, len);
-       }
-
-/*----------------- Receive -----------------*/
-
-       event message_t* SubReceive.receive(message_t* msg, void* payload, uint8_t len)
-       {
-               am_id_t type = call AMPacket.type(msg);
-
-               msg = call AMPacket.isForMe(msg)
-                       ? signal Receive.receive[type](msg, payload, len)
-                       : signal Snoop.receive[type](msg, payload, len);
-
-               return msg;
-       }
-
-  default event message_t* Receive.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
-    return signal ReceiveDefault.receive[id](msg, payload, len);
-  }
-
-  default event message_t* ReceiveDefault.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
-    return msg;
-  }
-
-  default event message_t* Snoop.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
-    return signal SnoopDefault.receive[id](msg, payload, len);
-  }
-
-  default event message_t* SnoopDefault.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
-    return msg;
-  }
+       components ActiveMessageLayerP, ActiveMessageAddressC;
+       ActiveMessageLayerP.ActiveMessageAddress -> ActiveMessageAddressC;
+
+       AMPacket = ActiveMessageLayerP;
+       Packet = ActiveMessageLayerP;
+       AMSend = ActiveMessageLayerP;
+       Receive = ActiveMessageLayerP.Receive;
+       ReceiveDefault = ActiveMessageLayerP.ReceiveDefault;
+       Snoop = ActiveMessageLayerP.Snoop;
+       SnoopDefault = ActiveMessageLayerP.SnoopDefault;
+       SendNotifier = ActiveMessageLayerP;
+       
+       SubPacket = ActiveMessageLayerP;
+       SubSend = ActiveMessageLayerP;
+       SubReceive = ActiveMessageLayerP;
+       Config = ActiveMessageLayerP;
 }
diff --git a/tos/lib/tosthreads/chips/rf230/ActiveMessageLayerP.nc b/tos/lib/tosthreads/chips/rf230/ActiveMessageLayerP.nc
new file mode 100644 (file)
index 0000000..8718b92
--- /dev/null
@@ -0,0 +1,272 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+/*
+ * Make active message TOSThreads-compatible by exposing default interfaces
+ *
+ * Author: Chieh-Jan Mike Liang
+ */
+
+#include <ActiveMessageLayer.h>
+
+module ActiveMessageLayerP
+{
+       provides
+       {
+               interface RadioPacket;
+               interface AMPacket;
+               interface Packet;
+               interface AMSend[am_id_t id];
+               interface Receive[am_id_t id];
+    interface Receive as ReceiveDefault[am_id_t id];
+               interface Receive as Snoop[uint8_t id];
+    interface Receive as SnoopDefault[am_id_t id];
+               interface SendNotifier[am_id_t id];
+       }
+
+       uses
+       {
+               interface RadioPacket as SubPacket;
+               interface BareSend as SubSend;
+               interface BareReceive as SubReceive;
+               interface ActiveMessageConfig as Config;
+               interface ActiveMessageAddress;
+       }
+}
+
+implementation
+{
+       activemessage_header_t* getHeader(message_t* msg)
+       {
+               return ((void*)msg) + call SubPacket.headerLength(msg);
+       }
+
+       void* getPayload(message_t* msg)
+       {
+               return ((void*)msg) + call RadioPacket.headerLength(msg);
+       }
+
+/*----------------- Send -----------------*/
+
+       command error_t AMSend.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len)
+       {
+               if( len > call Packet.maxPayloadLength() )
+                       return EINVAL;
+
+               if( call Config.checkFrame(msg) != SUCCESS )
+                       return FAIL;
+
+               call Packet.setPayloadLength(msg, len);
+               call AMPacket.setSource(msg, call AMPacket.address());
+               call AMPacket.setGroup(msg, call AMPacket.localGroup());
+               call AMPacket.setType(msg, id);
+               call AMPacket.setDestination(msg, addr);
+
+               signal SendNotifier.aboutToSend[id](addr, msg);
+
+               return call SubSend.send(msg);
+       }
+
+       inline event void SubSend.sendDone(message_t* msg, error_t error)
+       {
+               signal AMSend.sendDone[call AMPacket.type(msg)](msg, error);
+       }
+
+       inline command error_t AMSend.cancel[am_id_t id](message_t* msg)
+       {
+               return call SubSend.cancel(msg);
+       }
+
+       default event void AMSend.sendDone[am_id_t id](message_t* msg, error_t error)
+       {
+       }
+
+       inline command uint8_t AMSend.maxPayloadLength[am_id_t id]()
+       {
+               return call Packet.maxPayloadLength();
+       }
+
+       inline command void* AMSend.getPayload[am_id_t id](message_t* msg, uint8_t len)
+       {
+               return call Packet.getPayload(msg, len);
+       }
+
+       default event void SendNotifier.aboutToSend[am_id_t id](am_addr_t addr, message_t* msg)
+       {
+       }
+
+/*----------------- Receive -----------------*/
+
+       event message_t* SubReceive.receive(message_t* msg)
+       {
+               am_id_t id = call AMPacket.type(msg);
+               void* payload = getPayload(msg);
+               uint8_t len = call Packet.payloadLength(msg);
+
+               msg = call AMPacket.isForMe(msg) 
+                       ? signal Receive.receive[id](msg, payload, len)
+                       : signal Snoop.receive[id](msg, payload, len);
+
+               return msg;
+       }
+
+  default event message_t* Receive.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
+    return signal ReceiveDefault.receive[id](msg, payload, len);
+  }
+
+  default event message_t* ReceiveDefault.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
+    return msg;
+  }
+
+  default event message_t* Snoop.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
+    return signal SnoopDefault.receive[id](msg, payload, len);
+  }
+
+  default event message_t* SnoopDefault.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
+    return msg;
+  }
+
+/*----------------- AMPacket -----------------*/
+
+       inline command am_addr_t AMPacket.address()
+       {
+               return call ActiveMessageAddress.amAddress();
+       }
+       inline command am_group_t AMPacket.localGroup()
+       {
+               return call ActiveMessageAddress.amGroup();
+       }
+
+       inline command bool AMPacket.isForMe(message_t* msg)
+       {
+               am_addr_t addr = call AMPacket.destination(msg);
+               return addr == call AMPacket.address() || addr == AM_BROADCAST_ADDR;
+       }
+
+       inline command am_addr_t AMPacket.destination(message_t* msg)
+       {
+               return call Config.destination(msg);
+       }
+       inline command void AMPacket.setDestination(message_t* msg, am_addr_t addr)
+       {
+               call Config.setDestination(msg, addr);
+       }
+
+       inline command am_addr_t AMPacket.source(message_t* msg)
+       {
+               return call Config.source(msg);
+       }
+
+       inline command void AMPacket.setSource(message_t* msg, am_addr_t addr)
+       {
+               call Config.setSource(msg, addr);
+       }
+
+       inline command am_id_t AMPacket.type(message_t* msg)
+       {
+               return getHeader(msg)->type;
+       }
+
+       inline command void AMPacket.setType(message_t* msg, am_id_t type)
+       {
+               getHeader(msg)->type = type;
+       }
+  
+       inline command am_group_t AMPacket.group(message_t* msg) 
+       {
+               return call Config.group(msg);
+       }
+
+       inline command void AMPacket.setGroup(message_t* msg, am_group_t grp)
+       {
+               call Config.setGroup(msg, grp);
+       }
+
+       inline async event void ActiveMessageAddress.changed()
+       {
+       }
+
+/*----------------- RadioPacket -----------------*/
+
+       async command uint8_t RadioPacket.headerLength(message_t* msg)
+       {
+               return call SubPacket.headerLength(msg) + sizeof(activemessage_header_t);
+       }
+
+       async command uint8_t RadioPacket.payloadLength(message_t* msg)
+       {
+               return call SubPacket.payloadLength(msg) - sizeof(activemessage_header_t);
+       }
+
+       async command void RadioPacket.setPayloadLength(message_t* msg, uint8_t length)
+       {
+               call SubPacket.setPayloadLength(msg, length + sizeof(activemessage_header_t));
+       }
+
+       async command uint8_t RadioPacket.maxPayloadLength()
+       {
+               return call SubPacket.maxPayloadLength() - sizeof(activemessage_header_t);
+       }
+
+       async command uint8_t RadioPacket.metadataLength(message_t* msg)
+       {
+               return call SubPacket.metadataLength(msg);
+       }
+
+       async command void RadioPacket.clear(message_t* msg)
+       {
+               call SubPacket.clear(msg);
+       }
+
+/*----------------- Packet -----------------*/
+
+       command void Packet.clear(message_t* msg)
+       {
+               call RadioPacket.clear(msg);
+       }
+
+       command uint8_t Packet.payloadLength(message_t* msg)
+       {
+               return call RadioPacket.payloadLength(msg);
+       }
+
+       command void Packet.setPayloadLength(message_t* msg, uint8_t len)
+       {
+               call RadioPacket.setPayloadLength(msg, len);
+       }
+
+       command uint8_t Packet.maxPayloadLength()
+       {
+               return call RadioPacket.maxPayloadLength();
+       }
+
+       command void* Packet.getPayload(message_t* msg, uint8_t len)
+       {
+               if( len > call RadioPacket.maxPayloadLength() )
+                       return NULL;
+
+               return ((void*)msg) + call RadioPacket.headerLength(msg);
+       }
+}
index e30af9ceb39a0bed24ac8da35c07c88cfb774299..72324eec0ffe4b0fd1558ed883c3402175616989 100644 (file)
@@ -6,12 +6,12 @@
  * documentation for any purpose, without fee, and without written agreement is
  * hereby granted, provided that the above copyright notice, the following
  * two paragraphs and the author appear in all copies of this software.
- *
+ * 
  * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
  * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
  * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
+ * 
  * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  * Author: Miklos Maroti
  */
 
-#include <HplRF230.h>
+/*
+ * Make active message TOSThreads-compatible by exposing default interfaces
+ *
+ * Author: Chieh-Jan Mike Liang
+ */
+
+#include <RadioConfig.h>
+
+#ifdef IEEE154FRAMES_ENABLED
+#error "You cannot use ActiveMessageC with IEEE154FRAMES_ENABLED defined"
+#endif
 
 configuration RF230ActiveMessageC
 {
-       provides
+       provides 
        {
                interface SplitControl;
 
                interface AMSend[am_id_t id];
-    interface Receive[am_id_t id];
+               interface Receive[am_id_t id];
     interface Receive as ReceiveDefault[am_id_t id];
     interface Receive as Snoop[am_id_t id];
     interface Receive as SnoopDefault[am_id_t id];
+               interface SendNotifier[am_id_t id];
 
                interface Packet;
                interface AMPacket;
+
                interface PacketAcknowledgements;
                interface LowPowerListening;
+#ifdef PACKET_LINK
+               interface PacketLink;
+#endif
+
+               interface RadioChannel;
 
                interface PacketField<uint8_t> as PacketLinkQuality;
                interface PacketField<uint8_t> as PacketTransmitPower;
                interface PacketField<uint8_t> as PacketRSSI;
 
-               interface PacketTimeStamp<TRF230, uint32_t> as PacketTimeStampRadio;
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
                interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
        }
 }
 
 implementation
 {
-       components RF230ActiveMessageP, RF230PacketC, IEEE154PacketC, RadioAlarmC;
+       components RF230RadioC;
 
-#ifdef RF230_DEBUG
-       components AssertC;
-#endif
+       SplitControl = RF230RadioC;
 
-       RF230ActiveMessageP.IEEE154Packet -> IEEE154PacketC;
-       RF230ActiveMessageP.Packet -> RF230PacketC;
-       RF230ActiveMessageP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
-
-       Packet = RF230PacketC;
-       AMPacket = RF230PacketC;
-       PacketAcknowledgements = RF230PacketC;
-       PacketLinkQuality = RF230PacketC.PacketLinkQuality;
-       PacketTransmitPower = RF230PacketC.PacketTransmitPower;
-       PacketRSSI = RF230PacketC.PacketRSSI;
-       PacketTimeStampRadio = RF230PacketC;
-       PacketTimeStampMilli = RF230PacketC;
-       LowPowerListening = LowPowerListeningLayerC;
-
-       components ActiveMessageLayerC;
-#ifdef TFRAMES_ENABLED
-       components new DummyLayerC() as IEEE154NetworkLayerC;
-#else
-       components IEEE154NetworkLayerC;
-#endif
-#ifdef LOW_POWER_LISTENING
-       components LowPowerListeningLayerC;
-#else
-       components new DummyLayerC() as LowPowerListeningLayerC;
-#endif
-       components MessageBufferLayerC;
-       components UniqueLayerC;
-       components TrafficMonitorLayerC;
-#ifdef RF230_SLOTTED_MAC
-       components SlottedCollisionLayerC as CollisionAvoidanceLayerC;
-#else
-       components RandomCollisionLayerC as CollisionAvoidanceLayerC;
-#endif
-       components SoftwareAckLayerC;
-       components new DummyLayerC() as CsmaLayerC;
-       components RF230LayerC;
-
-       SplitControl = LowPowerListeningLayerC;
-       AMSend = ActiveMessageLayerC;
-  Receive = ActiveMessageLayerC.Receive;
-  ReceiveDefault = ActiveMessageLayerC.ReceiveDefault;
-  Snoop = ActiveMessageLayerC.Snoop;
-  SnoopDefault = ActiveMessageLayerC.SnoopDefault;
-
-       ActiveMessageLayerC.Config -> RF230ActiveMessageP;
-       ActiveMessageLayerC.AMPacket -> IEEE154PacketC;
-       ActiveMessageLayerC.SubSend -> IEEE154NetworkLayerC;
-       ActiveMessageLayerC.SubReceive -> IEEE154NetworkLayerC;
-
-       IEEE154NetworkLayerC.SubSend -> UniqueLayerC;
-       IEEE154NetworkLayerC.SubReceive -> LowPowerListeningLayerC;
-
-       // the UniqueLayer is wired at two points
-       UniqueLayerC.Config -> RF230ActiveMessageP;
-       UniqueLayerC.SubSend -> LowPowerListeningLayerC;
-
-       LowPowerListeningLayerC.SubControl -> MessageBufferLayerC;
-       LowPowerListeningLayerC.SubSend -> MessageBufferLayerC;
-       LowPowerListeningLayerC.SubReceive -> MessageBufferLayerC;
-#ifdef LOW_POWER_LISTENING
-       LowPowerListeningLayerC.PacketSleepInterval -> RF230PacketC;
-       LowPowerListeningLayerC.IEEE154Packet -> IEEE154PacketC;
-       LowPowerListeningLayerC.PacketAcknowledgements -> RF230PacketC;
-#endif
-
-       MessageBufferLayerC.Packet -> RF230PacketC;
-       MessageBufferLayerC.RadioSend -> TrafficMonitorLayerC;
-       MessageBufferLayerC.RadioReceive -> UniqueLayerC;
-       MessageBufferLayerC.RadioState -> TrafficMonitorLayerC;
+       AMSend = RF230RadioC;
+       Receive = RF230RadioC.Receive;
+  ReceiveDefault = RF230RadioC.ReceiveDefault;
+  Snoop = RF230RadioC.Snoop;
+  SnoopDefault = RF230RadioC.SnoopDefault;
+       SendNotifier = RF230RadioC;
 
-       UniqueLayerC.SubReceive -> TrafficMonitorLayerC;
+       Packet = RF230RadioC.PacketForActiveMessage;
+       AMPacket = RF230RadioC;
 
-       TrafficMonitorLayerC.Config -> RF230ActiveMessageP;
-       TrafficMonitorLayerC.SubSend -> CollisionAvoidanceLayerC;
-       TrafficMonitorLayerC.SubReceive -> CollisionAvoidanceLayerC;
-       TrafficMonitorLayerC.SubState -> RF230LayerC;
-
-       CollisionAvoidanceLayerC.Config -> RF230ActiveMessageP;
-       CollisionAvoidanceLayerC.SubSend -> SoftwareAckLayerC;
-       CollisionAvoidanceLayerC.SubReceive -> SoftwareAckLayerC;
+       PacketAcknowledgements = RF230RadioC;
+       LowPowerListening = RF230RadioC;
+#ifdef PACKET_LINK
+       PacketLink = RF230RadioC;
+#endif
 
-       SoftwareAckLayerC.Config -> RF230ActiveMessageP;
-       SoftwareAckLayerC.SubSend -> CsmaLayerC;
-       SoftwareAckLayerC.SubReceive -> RF230LayerC;
+       RadioChannel = RF230RadioC;
 
-       CsmaLayerC.Config -> RF230ActiveMessageP;
-       CsmaLayerC -> RF230LayerC.RadioSend;
-       CsmaLayerC -> RF230LayerC.RadioCCA;
+       PacketLinkQuality = RF230RadioC.PacketLinkQuality;
+       PacketTransmitPower = RF230RadioC.PacketTransmitPower;
+       PacketRSSI = RF230RadioC.PacketRSSI;
 
-       RF230LayerC.RF230Config -> RF230ActiveMessageP;
+       LocalTimeRadio = RF230RadioC;
+       PacketTimeStampMilli = RF230RadioC;
+       PacketTimeStampRadio = RF230RadioC;
 }
diff --git a/tos/lib/tosthreads/chips/rf230/RF230RadioC.nc b/tos/lib/tosthreads/chips/rf230/RF230RadioC.nc
new file mode 100644 (file)
index 0000000..4bf85d1
--- /dev/null
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+/*
+ * Make active message TOSThreads-compatible by exposing default interfaces
+ *
+ * Author: Chieh-Jan Mike Liang
+ */
+
+#include <RadioConfig.h>
+
+configuration RF230RadioC
+{
+       provides 
+       {
+               interface SplitControl;
+
+#ifndef IEEE154FRAMES_ENABLED
+               interface AMSend[am_id_t id];
+               interface Receive[am_id_t id];
+               interface Receive as ReceiveDefault[am_id_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface Receive as SnoopDefault[am_id_t id];
+               interface SendNotifier[am_id_t id];
+
+               interface AMPacket;
+               interface Packet as PacketForActiveMessage;
+#endif
+
+#ifndef TFRAMES_ENABLED
+               interface Ieee154Send;
+               interface Receive as Ieee154Receive;
+               interface SendNotifier as Ieee154Notifier;
+
+               interface Resource as SendResource[uint8_t clint];
+
+               interface Ieee154Packet;
+               interface Packet as PacketForIeee154Message;
+#endif
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+
+#ifdef PACKET_LINK
+               interface PacketLink;
+#endif
+
+               interface RadioChannel;
+
+               interface PacketField<uint8_t> as PacketLinkQuality;
+               interface PacketField<uint8_t> as PacketTransmitPower;
+               interface PacketField<uint8_t> as PacketRSSI;
+
+               interface LocalTime<TRadio> as LocalTimeRadio;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF230RadioP, RadioAlarmC;
+
+#ifdef RADIO_DEBUG
+       components AssertC;
+#endif
+
+       RF230RadioP.Ieee154PacketLayer -> Ieee154PacketLayerC;
+       RF230RadioP.RadioAlarm -> RadioAlarmC.RadioAlarm[unique("RadioAlarm")];
+       RF230RadioP.PacketTimeStamp -> TimeStampingLayerC;
+       RF230RadioP.RF230Packet -> RF230DriverLayerC;
+
+// -------- Active Message
+
+#ifndef IEEE154FRAMES_ENABLED
+       components ActiveMessageLayerC;
+       ActiveMessageLayerC.Config -> RF230RadioP;
+       ActiveMessageLayerC.SubSend -> AutoResourceAcquireLayerC;
+       ActiveMessageLayerC.SubReceive -> TinyosNetworkLayerC.TinyosReceive;
+       ActiveMessageLayerC.SubPacket -> TinyosNetworkLayerC.TinyosPacket;
+
+       AMSend = ActiveMessageLayerC;
+       Receive = ActiveMessageLayerC.Receive;
+       ReceiveDefault = ActiveMessageLayerC.ReceiveDefault;
+       Snoop = ActiveMessageLayerC.Snoop;
+       SnoopDefault = ActiveMessageLayerC.SnoopDefault;
+       SendNotifier = ActiveMessageLayerC;
+       AMPacket = ActiveMessageLayerC;
+       PacketForActiveMessage = ActiveMessageLayerC;
+#endif
+
+// -------- Automatic RadioSend Resource
+
+#ifndef IEEE154FRAMES_ENABLED
+#ifndef TFRAMES_ENABLED
+       components new AutoResourceAcquireLayerC();
+       AutoResourceAcquireLayerC.Resource -> SendResourceC.Resource[unique(RADIO_SEND_RESOURCE)];
+#else
+       components new DummyLayerC() as AutoResourceAcquireLayerC;
+#endif
+       AutoResourceAcquireLayerC.SubSend -> TinyosNetworkLayerC.TinyosSend;
+#endif
+
+// -------- RadioSend Resource
+
+#ifndef TFRAMES_ENABLED
+       components new SimpleFcfsArbiterC(RADIO_SEND_RESOURCE) as SendResourceC;
+       SendResource = SendResourceC;
+
+// -------- Ieee154 Message
+
+       components Ieee154MessageLayerC;
+       Ieee154MessageLayerC.Ieee154PacketLayer -> Ieee154PacketLayerC;
+       Ieee154MessageLayerC.Ieee154Packet -> Ieee154PacketLayerC;
+       Ieee154MessageLayerC.SubSend -> TinyosNetworkLayerC.Ieee154Send;
+       Ieee154MessageLayerC.SubReceive -> TinyosNetworkLayerC.Ieee154Receive;
+       Ieee154MessageLayerC.RadioPacket -> TinyosNetworkLayerC.Ieee154Packet;
+
+       Ieee154Send = Ieee154MessageLayerC;
+       Ieee154Receive = Ieee154MessageLayerC;
+       Ieee154Notifier = Ieee154MessageLayerC;
+       Ieee154Packet = Ieee154PacketLayerC;
+       PacketForIeee154Message = Ieee154MessageLayerC;
+#endif
+
+// -------- Tinyos Network
+
+       components TinyosNetworkLayerC;
+
+       TinyosNetworkLayerC.SubSend -> UniqueLayerC;
+       TinyosNetworkLayerC.SubReceive -> LowPowerListeningLayerC;
+       TinyosNetworkLayerC.SubPacket -> Ieee154PacketLayerC;
+
+// -------- IEEE 802.15.4 Packet
+
+       components Ieee154PacketLayerC;
+       Ieee154PacketLayerC.SubPacket -> LowPowerListeningLayerC;
+
+// -------- UniqueLayer Send part (wired twice)
+
+       components UniqueLayerC;
+       UniqueLayerC.Config -> RF230RadioP;
+       UniqueLayerC.SubSend -> LowPowerListeningLayerC;
+
+// -------- Low Power Listening 
+
+#ifdef LOW_POWER_LISTENING
+       #warning "*** USING LOW POWER LISTENING LAYER"
+       components LowPowerListeningLayerC;
+       LowPowerListeningLayerC.Config -> RF230RadioP;
+       LowPowerListeningLayerC.PacketAcknowledgements -> SoftwareAckLayerC;
+#else  
+       components LowPowerListeningDummyC as LowPowerListeningLayerC;
+#endif
+       LowPowerListeningLayerC.SubControl -> MessageBufferLayerC;
+       LowPowerListeningLayerC.SubSend -> PacketLinkLayerC;
+       LowPowerListeningLayerC.SubReceive -> MessageBufferLayerC;
+       LowPowerListeningLayerC.SubPacket -> PacketLinkLayerC;
+       SplitControl = LowPowerListeningLayerC;
+       LowPowerListening = LowPowerListeningLayerC;
+
+// -------- Packet Link
+
+#ifdef PACKET_LINK
+       components PacketLinkLayerC;
+       PacketLink = PacketLinkLayerC;
+       PacketLinkLayerC.PacketAcknowledgements -> SoftwareAckLayerC;
+#else
+       components new DummyLayerC() as PacketLinkLayerC;
+#endif
+       PacketLinkLayerC.SubSend -> MessageBufferLayerC;
+       PacketLinkLayerC.SubPacket -> TimeStampingLayerC;
+
+// -------- MessageBuffer
+
+       components MessageBufferLayerC;
+       MessageBufferLayerC.RadioSend -> TrafficMonitorLayerC;
+       MessageBufferLayerC.RadioReceive -> UniqueLayerC;
+       MessageBufferLayerC.RadioState -> TrafficMonitorLayerC;
+       RadioChannel = MessageBufferLayerC;
+
+// -------- UniqueLayer receive part (wired twice)
+
+       UniqueLayerC.SubReceive -> TrafficMonitorLayerC;
+
+// -------- Traffic Monitor
+
+#ifdef TRAFFIC_MONITOR
+       components TrafficMonitorLayerC;
+#else
+       components new DummyLayerC() as TrafficMonitorLayerC;
+#endif
+       TrafficMonitorLayerC.Config -> RF230RadioP;
+       TrafficMonitorLayerC -> CollisionAvoidanceLayerC.RadioSend;
+       TrafficMonitorLayerC -> CollisionAvoidanceLayerC.RadioReceive;
+       TrafficMonitorLayerC -> RF230DriverLayerC.RadioState;
+
+// -------- CollisionAvoidance
+
+#ifdef SLOTTED_MAC
+       components SlottedCollisionLayerC as CollisionAvoidanceLayerC;
+#else
+       components RandomCollisionLayerC as CollisionAvoidanceLayerC;
+#endif
+       CollisionAvoidanceLayerC.Config -> RF230RadioP;
+       CollisionAvoidanceLayerC.SubSend -> SoftwareAckLayerC;
+       CollisionAvoidanceLayerC.SubReceive -> SoftwareAckLayerC;
+
+// -------- SoftwareAcknowledgement
+
+       components SoftwareAckLayerC;
+       SoftwareAckLayerC.Config -> RF230RadioP;
+       SoftwareAckLayerC.SubSend -> CsmaLayerC;
+       SoftwareAckLayerC.SubReceive -> RF230DriverLayerC;
+       PacketAcknowledgements = SoftwareAckLayerC;
+
+// -------- Carrier Sense
+
+       components new DummyLayerC() as CsmaLayerC;
+       CsmaLayerC.Config -> RF230RadioP;
+       CsmaLayerC -> RF230DriverLayerC.RadioSend;
+       CsmaLayerC -> RF230DriverLayerC.RadioCCA;
+
+// -------- TimeStamping
+
+       components TimeStampingLayerC;
+       TimeStampingLayerC.LocalTimeRadio -> RF230DriverLayerC;
+       TimeStampingLayerC.SubPacket -> MetadataFlagsLayerC;
+       PacketTimeStampRadio = TimeStampingLayerC;
+       PacketTimeStampMilli = TimeStampingLayerC;
+
+// -------- MetadataFlags
+
+       components MetadataFlagsLayerC;
+       MetadataFlagsLayerC.SubPacket -> RF230DriverLayerC;
+
+// -------- RF230 Driver
+
+       components RF230DriverLayerC;
+       RF230DriverLayerC.Config -> RF230RadioP;
+       RF230DriverLayerC.PacketTimeStamp -> TimeStampingLayerC;
+       PacketTransmitPower = RF230DriverLayerC.PacketTransmitPower;
+       PacketLinkQuality = RF230DriverLayerC.PacketLinkQuality;
+       PacketRSSI = RF230DriverLayerC.PacketRSSI;
+       LocalTimeRadio = RF230DriverLayerC;
+}
index 8cb7f658d6480e310c9f4d4a513f3a81f0f9df7c..a066c05f251e32ccf53c19a6ae1535f902800dbc 100644 (file)
@@ -30,7 +30,6 @@ configuration CAMRadioC {}
 
 implementation {
   components CAMRadioP as CAMP;
-  components ActiveMessageC;
   components BlockingActiveMessageC as AM;
   
   CAMP.BlockingStdControl -> AM;
@@ -42,8 +41,4 @@ implementation {
   CAMP.Packet -> AM;
   CAMP.AMPacket -> AM;
   CAMP.PacketAcknowledgements -> AM;
-  
-  AM.Receive -> ActiveMessageC.ReceiveDefault;
-  AM.Snoop -> ActiveMessageC.SnoopDefault;
-  AM.AMSend -> ActiveMessageC;
 }
index f9d12e12b669b26798c0091edad5db1ce5c276f0..bfe3efe05acf7f4fc011ab530837ce95b0eec845 100644 (file)
@@ -38,82 +38,82 @@ module CAMRadioP {
   }
 }
 implementation {
-  error_t amRadioStart() @C() @spontaneous() { 
+  error_t amRadioStart() @C() AT_SPONTANEOUS { 
     return call BlockingStdControl.start();
   }
-  error_t amRadioStop() @C() @spontaneous() { 
+  error_t amRadioStop() @C() AT_SPONTANEOUS { 
     return call BlockingStdControl.stop();
   }
-  error_t amRadioReceive(message_t* m, uint32_t timeout, am_id_t amId) @C() @spontaneous() {
+  error_t amRadioReceive(message_t* m, uint32_t timeout, am_id_t amId) @C() AT_SPONTANEOUS {
     if(amId == AM_RECEIVE_FROM_ANY)
       return call BlockingReceiveAny.receive(m, timeout);
     else 
       return call BlockingReceive.receive[amId](m, timeout);
   }
-  error_t amRadioSnoop(message_t* m, uint32_t timeout, am_id_t amId) @C() @spontaneous() {
+  error_t amRadioSnoop(message_t* m, uint32_t timeout, am_id_t amId) @C() AT_SPONTANEOUS {
     if(amId == AM_RECEIVE_FROM_ANY)
       return call BlockingSnoopAny.receive(m, timeout);
     else 
       return call BlockingSnoop.receive[amId](m, timeout);
   }
-  error_t amRadioSend(am_addr_t addr, message_t* msg, uint8_t len, am_id_t amId) @C() @spontaneous() {
+  error_t amRadioSend(am_addr_t addr, message_t* msg, uint8_t len, am_id_t amId) @C() AT_SPONTANEOUS {
     return call Send.send[amId](addr, msg, len);
   }
-  am_addr_t amRadioGetLocalAddress() @C() @spontaneous() {
+  am_addr_t amRadioGetLocalAddress() @C() AT_SPONTANEOUS {
     return call AMPacket.address();
   }
-  am_group_t amRadioGetLocalGroup() @C() @spontaneous() {
+  am_group_t amRadioGetLocalGroup() @C() AT_SPONTANEOUS {
     return call AMPacket.localGroup();
   }
-  am_addr_t amRadioGetDestination(message_t* amsg) @C() @spontaneous() {
+  am_addr_t amRadioGetDestination(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.destination(amsg);
   }
-  am_addr_t amRadioGetSource(message_t* amsg) @C() @spontaneous() {
+  am_addr_t amRadioGetSource(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.source(amsg);
   }
-  void amRadioSetDestination(message_t* amsg, am_addr_t addr) @C() @spontaneous() {
+  void amRadioSetDestination(message_t* amsg, am_addr_t addr) @C() AT_SPONTANEOUS {
     call AMPacket.setDestination(amsg, addr);
   }
-  void amRadioSetSource(message_t* amsg, am_addr_t addr) @C() @spontaneous() {
+  void amRadioSetSource(message_t* amsg, am_addr_t addr) @C() AT_SPONTANEOUS {
     call AMPacket.setSource(amsg, addr);
   }
-  bool amRadioIsForMe(message_t* amsg) @C() @spontaneous() {
+  bool amRadioIsForMe(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.isForMe(amsg);
   }
-  am_id_t amRadioGetType(message_t* amsg) @C() @spontaneous() {
+  am_id_t amRadioGetType(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.type(amsg);
   }
-  void amRadioSetType(message_t* amsg, am_id_t t) @C() @spontaneous() {
+  void amRadioSetType(message_t* amsg, am_id_t t) @C() AT_SPONTANEOUS {
     call AMPacket.setType(amsg, t);
   }
-  am_group_t amRadioGetGroup(message_t* amsg) @C() @spontaneous() {
+  am_group_t amRadioGetGroup(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.group(amsg);
   }
-  void amRadioSetGroup(message_t* amsg, am_group_t grp) @C() @spontaneous() {
+  void amRadioSetGroup(message_t* amsg, am_group_t grp) @C() AT_SPONTANEOUS {
     call AMPacket.setGroup(amsg, grp);
   }
-  void radioClear(message_t* msg) @C() @spontaneous() {
+  void radioClear(message_t* msg) @C() AT_SPONTANEOUS {
     call Packet.clear(msg);
   }
-  uint8_t radioGetPayloadLength(message_t* msg) @C() @spontaneous() {
+  uint8_t radioGetPayloadLength(message_t* msg) @C() AT_SPONTANEOUS {
     return call Packet.payloadLength(msg);
   }
-  void  radioSetPayloadLength(message_t* msg, uint8_t len) @C() @spontaneous() {
+  void  radioSetPayloadLength(message_t* msg, uint8_t len) @C() AT_SPONTANEOUS {
     call Packet.setPayloadLength(msg, len);
   }
-  uint8_t radioMaxPayloadLength() @C() @spontaneous() {
+  uint8_t radioMaxPayloadLength() @C() AT_SPONTANEOUS {
     return call Packet.maxPayloadLength();
   }
-  void* radioGetPayload(message_t* msg, uint8_t len) @C() @spontaneous() {
+  void* radioGetPayload(message_t* msg, uint8_t len) @C() AT_SPONTANEOUS {
     return call Packet.getPayload(msg, len);
   }
-  error_t radioRequestAck( message_t* msg ) @C() @spontaneous() {
+  error_t radioRequestAck( message_t* msg ) @C() AT_SPONTANEOUS {
     return call PacketAcknowledgements.requestAck(msg);
   }
-  error_t radioNoAck( message_t* msg ) @C() @spontaneous() {
+  error_t radioNoAck( message_t* msg ) @C() AT_SPONTANEOUS {
     return call PacketAcknowledgements.noAck(msg);
   }
-  bool radioWasAcked(message_t* msg) @C() @spontaneous() {
+  bool radioWasAcked(message_t* msg) @C() AT_SPONTANEOUS {
     return call PacketAcknowledgements.wasAcked(msg);
   }
 }
index ec6b299bf2c975df85cae8c66128471383ee3db4..ac776aa46797753b969a33e9fc506e066efc3b61 100644 (file)
@@ -30,7 +30,6 @@ configuration CAMSerialC {}
 
 implementation {
   components CAMSerialP as CAMP;
-  components SerialActiveMessageC;
   components BlockingSerialActiveMessageC as AM;
   
   CAMP.BlockingStdControl -> AM;
@@ -40,7 +39,4 @@ implementation {
   CAMP.Packet -> AM;
   CAMP.AMPacket -> AM;
   CAMP.PacketAcknowledgements -> AM;
-  
-  AM.Receive -> SerialActiveMessageC.Receive;
-  AM.AMSend -> SerialActiveMessageC.AMSend;
 }
index c0a7bba94b1f3951b80c614c1bacfff5c4d6b750..dee9b384cc3e8a7b59bd1723d44c3505b11c2f3c 100644 (file)
@@ -36,76 +36,76 @@ module CAMSerialP {
   }
 }
 implementation {
-  error_t amSerialStart() @C() @spontaneous() { 
+  error_t amSerialStart() @C() AT_SPONTANEOUS { 
     return call BlockingStdControl.start();
   }
-  error_t amSerialStop() @C() @spontaneous() { 
+  error_t amSerialStop() @C() AT_SPONTANEOUS { 
     return call BlockingStdControl.stop();
   }
-  error_t amSerialReceive(message_t* m, uint32_t timeout, am_id_t amId) @C() @spontaneous() {
+  error_t amSerialReceive(message_t* m, uint32_t timeout, am_id_t amId) @C() AT_SPONTANEOUS {
     if(amId == AM_RECEIVE_FROM_ANY)
       return call BlockingReceiveAny.receive(m, timeout);
     else 
       return call BlockingReceive.receive[amId](m, timeout);
   }
-  error_t amSerialSend(am_addr_t addr, message_t* msg, uint8_t len, am_id_t amId) @C() @spontaneous() {
+  error_t amSerialSend(am_addr_t addr, message_t* msg, uint8_t len, am_id_t amId) @C() AT_SPONTANEOUS {
     return call Send.send[amId](addr, msg, len);
   }
-  am_addr_t amSerialLocalAddress() @C() @spontaneous() {
+  am_addr_t amSerialLocalAddress() @C() AT_SPONTANEOUS {
     return call AMPacket.address();
   }
-  am_group_t amSerialGetLocalGroup() @C() @spontaneous() {
+  am_group_t amSerialGetLocalGroup() @C() AT_SPONTANEOUS {
     return call AMPacket.localGroup();
   }
-  am_addr_t amSerialGetDestination(message_t* amsg) @C() @spontaneous() {
+  am_addr_t amSerialGetDestination(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.destination(amsg);
   }
-  am_addr_t amSerialGetSource(message_t* amsg) @C() @spontaneous() {
+  am_addr_t amSerialGetSource(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.source(amsg);
   }
-  void amSerialSetDestination(message_t* amsg, am_addr_t addr) @C() @spontaneous() {
+  void amSerialSetDestination(message_t* amsg, am_addr_t addr) @C() AT_SPONTANEOUS {
     call AMPacket.setDestination(amsg, addr);
   }
-  void amSerialSetSource(message_t* amsg, am_addr_t addr) @C() @spontaneous() {
+  void amSerialSetSource(message_t* amsg, am_addr_t addr) @C() AT_SPONTANEOUS {
     call AMPacket.setSource(amsg, addr);
   }
-  bool amSerialIsForMe(message_t* amsg) @C() @spontaneous() {
+  bool amSerialIsForMe(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.isForMe(amsg);
   }
-  am_id_t amSerialGetType(message_t* amsg) @C() @spontaneous() {
+  am_id_t amSerialGetType(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.type(amsg);
   }
-  void amSerialSetType(message_t* amsg, am_id_t t) @C() @spontaneous() {
+  void amSerialSetType(message_t* amsg, am_id_t t) @C() AT_SPONTANEOUS {
     call AMPacket.setType(amsg, t);
   }
-  am_group_t amSerialGetGroup(message_t* amsg) @C() @spontaneous() {
+  am_group_t amSerialGetGroup(message_t* amsg) @C() AT_SPONTANEOUS {
     return call AMPacket.group(amsg);
   }
-  void amSerialSetGroup(message_t* amsg, am_group_t grp) @C() @spontaneous() {
+  void amSerialSetGroup(message_t* amsg, am_group_t grp) @C() AT_SPONTANEOUS {
     call AMPacket.setGroup(amsg, grp);
   }
-  void serialClear(message_t* msg) @C() @spontaneous() {
+  void serialClear(message_t* msg) @C() AT_SPONTANEOUS {
     call Packet.clear(msg);
   }
-  uint8_t serialGetPayloadLength(message_t* msg) @C() @spontaneous() {
+  uint8_t serialGetPayloadLength(message_t* msg) @C() AT_SPONTANEOUS {
     return call Packet.payloadLength(msg);
   }
-  void  serialSetPayloadLength(message_t* msg, uint8_t len) @C() @spontaneous() {
+  void  serialSetPayloadLength(message_t* msg, uint8_t len) @C() AT_SPONTANEOUS {
     call Packet.setPayloadLength(msg, len);
   }
-  uint8_t serialMaxPayloadLength() @C() @spontaneous() {
+  uint8_t serialMaxPayloadLength() @C() AT_SPONTANEOUS {
     return call Packet.maxPayloadLength();
   }
-  void* serialGetPayload(message_t* msg, uint8_t len) @C() @spontaneous() {
+  void* serialGetPayload(message_t* msg, uint8_t len) @C() AT_SPONTANEOUS {
     return call Packet.getPayload(msg, len);
   }
-  error_t serialRequestAck( message_t* msg ) @C() @spontaneous() {
+  error_t serialRequestAck( message_t* msg ) @C() AT_SPONTANEOUS {
     return call PacketAcknowledgements.requestAck(msg);
   }
-  error_t serialNoAck( message_t* msg ) @C() @spontaneous() {
+  error_t serialNoAck( message_t* msg ) @C() AT_SPONTANEOUS {
     return call PacketAcknowledgements.noAck(msg);
   }
-  bool serialWasAcked(message_t* msg) @C() @spontaneous() {
+  bool serialWasAcked(message_t* msg) @C() AT_SPONTANEOUS {
     return call PacketAcknowledgements.wasAcked(msg);
   }
 }
index 82817dcbcce1662101c5b86bc4071a7ea1bc6950..1c3a4bb6db9752e17790710b36f05bbb6d2efb87 100644 (file)
@@ -31,27 +31,27 @@ module CBlockStorageP {
 }
 
 implementation {
-  error_t volumeBlockRead(uint8_t volumeId, storage_addr_t addr, void* buf, storage_len_t* len) @C() @spontaneous()
+  error_t volumeBlockRead(uint8_t volumeId, storage_addr_t addr, void* buf, storage_len_t* len) @C() AT_SPONTANEOUS
   {
     return call BlockingBlock.read[volumeId](addr, buf, len);
   }
   
-  error_t volumeBlockWrite(uint8_t volumeId, storage_addr_t addr, void* buf, storage_len_t* len)  @C() @spontaneous()
+  error_t volumeBlockWrite(uint8_t volumeId, storage_addr_t addr, void* buf, storage_len_t* len)  @C() AT_SPONTANEOUS
   {
     return call BlockingBlock.write[volumeId](addr, buf, len);
   }
   
-  error_t volumeBlockCrc(uint8_t volumeId, storage_addr_t addr, storage_len_t* len, uint16_t crc, uint16_t *finalCrc) @C() @spontaneous()
+  error_t volumeBlockCrc(uint8_t volumeId, storage_addr_t addr, storage_len_t* len, uint16_t crc, uint16_t *finalCrc) @C() AT_SPONTANEOUS
   {
     return call BlockingBlock.computeCrc[volumeId](addr, len, crc, finalCrc);
   }
   
-  error_t volumeBlockErase(uint8_t volumeId) @C() @spontaneous()
+  error_t volumeBlockErase(uint8_t volumeId) @C() AT_SPONTANEOUS
   {
     return call BlockingBlock.erase[volumeId]();
   }
   
-  error_t volumeBlockSync(uint8_t volumeId) @C() @spontaneous()
+  error_t volumeBlockSync(uint8_t volumeId) @C() AT_SPONTANEOUS
   {
     return call BlockingBlock.sync[volumeId]();
   }
diff --git a/tos/lib/tosthreads/csystem/CConfigStorageC.nc b/tos/lib/tosthreads/csystem/CConfigStorageC.nc
new file mode 100644 (file)
index 0000000..c21c3dd
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2009 RWTH Aachen University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author J\97 Ã§gila Bitsch Link <jo.bitsch@cs.rwth-aachen.de>
+ */
+
+configuration CConfigStorageC {}
+
+implementation {
+  components CConfigStorageP,
+             BlockingConfigStorageP,
+             VolumeMapC;
+
+  CConfigStorageP.BlockingConfig -> BlockingConfigStorageP;
+  CConfigStorageP.BlockingMount -> BlockingConfigStorageP;
+
+  BlockingConfigStorageP.ConfigMount -> VolumeMapC.Mount;
+  BlockingConfigStorageP.ConfigStorage -> VolumeMapC.ConfigStorage;
+}
diff --git a/tos/lib/tosthreads/csystem/CConfigStorageP.nc b/tos/lib/tosthreads/csystem/CConfigStorageP.nc
new file mode 100644 (file)
index 0000000..bb67f9c
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2009 RWTH Aachen University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author J\97 Ã§gila Bitsch Link <jo.bitsch@cs.rwth-aachen.de>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+module CConfigStorageP {
+  uses {
+    interface BlockingConfig[uint8_t volume_id];
+    interface BlockingMount[uint8_t volume_id];
+  }
+}
+
+implementation {
+  error_t volumeConfigMount(uint8_t volumeId) @C() AT_SPONTANEOUS {
+    return call BlockingMount.mount[volumeId]();
+  }
+  
+  error_t volumeConfigRead(uint8_t volumeId, storage_addr_t addr, void* buf, storage_len_t* len) @C() AT_SPONTANEOUS {
+    return call BlockingConfig.read[volumeId](addr, buf, len);
+  }
+  
+  error_t volumeConfigWrite(uint8_t volumeId, storage_addr_t addr, void* buf, storage_len_t* len) @C() AT_SPONTANEOUS {
+    return call BlockingConfig.write[volumeId](addr, buf, len);
+  }
+  
+  error_t volumeConfigCommit(uint8_t volumeId) @C() AT_SPONTANEOUS {
+    return call BlockingConfig.commit[volumeId]();
+  }
+  
+  storage_len_t volumeConfigGetSize(uint8_t volumeId) @C() AT_SPONTANEOUS {
+    return call BlockingConfig.getSize[volumeId]();
+  }
+  
+  bool volumeConfigValid(uint8_t volumeId) @C() AT_SPONTANEOUS {
+    return call BlockingConfig.valid[volumeId]();
+  }
+}
index cf1944eb792746529c4c8afbf581772045289701..63fa4773eff764e29927858bfc39ebfec5006365 100644 (file)
@@ -39,40 +39,40 @@ module CLedsP {
   }
 }
 implementation {
-  void led0On() @C() @spontaneous(){
+  void led0On() @C() AT_SPONTANEOUS {
     call Leds.led0On();
   }
-  void led0Off() @C() @spontaneous(){
+  void led0Off() @C() AT_SPONTANEOUS {
     call Leds.led0Off();
   }
-  void led0Toggle() @C() @spontaneous(){
+  void led0Toggle() @C() AT_SPONTANEOUS{
     call Leds.led0Toggle();
   }
 
-  void led1On() @C() @spontaneous(){
+  void led1On() @C() AT_SPONTANEOUS{
     call Leds.led1On();
   }
-  void led1Off() @C() @spontaneous(){
+  void led1Off() @C() AT_SPONTANEOUS{
     call Leds.led1Off();
   }
-  void led1Toggle() @C() @spontaneous(){
+  void led1Toggle() @C() AT_SPONTANEOUS{
     call Leds.led1Toggle();
   }
   
-  void led2On() @C() @spontaneous(){
+  void led2On() @C() AT_SPONTANEOUS{
     call Leds.led2On();
   }
-  void led2Off() @C() @spontaneous(){
+  void led2Off() @C() AT_SPONTANEOUS{
     call Leds.led2Off();
   }
-  void led2Toggle() @C() @spontaneous(){
+  void led2Toggle() @C() AT_SPONTANEOUS{
     call Leds.led2Toggle();
   }
 
-  uint8_t getLeds() @C() @spontaneous(){
+  uint8_t getLeds() @C() AT_SPONTANEOUS{
     return call Leds.get();
   }
-  void setLeds(uint8_t val) @C() @spontaneous(){
+  void setLeds(uint8_t val) @C() AT_SPONTANEOUS{
     call Leds.set(val);
   }
 }
index 33d1cf7a7236d44c709bdcd3cb66ad63eda49d93..ec15e4e756def6e6f521db0153a29f29077dc7c3 100644 (file)
@@ -38,64 +38,64 @@ module CLinkedListP {
   uses interface LinkedList;
 }
 implementation { 
-  void linked_list_init(linked_list_t* l) @C() @spontaneous() {  
+  void linked_list_init(linked_list_t* l) @C() AT_SPONTANEOUS {  
     call LinkedList.init(l);
   }
-  void linked_list_clear(linked_list_t* l) @C() @spontaneous() { 
+  void linked_list_clear(linked_list_t* l) @C() AT_SPONTANEOUS { 
     call LinkedList.clear(l);
   }
-  uint8_t linked_list_size(linked_list_t* l) @C() @spontaneous() { 
+  uint8_t linked_list_size(linked_list_t* l) @C() AT_SPONTANEOUS { 
     return call LinkedList.size(l);
   }
-  error_t linked_list_addFirst(linked_list_t* l, list_element_t* e) @C() @spontaneous() { 
+  error_t linked_list_addFirst(linked_list_t* l, list_element_t* e) @C() AT_SPONTANEOUS { 
     return call LinkedList.addFirst(l, e);
   }
-  list_element_t* linked_list_getFirst(linked_list_t* l) @C() @spontaneous() { 
+  list_element_t* linked_list_getFirst(linked_list_t* l) @C() AT_SPONTANEOUS { 
     return call LinkedList.getFirst(l);
   }
-  list_element_t* linked_list_removeFirst(linked_list_t* l) @C() @spontaneous() { 
+  list_element_t* linked_list_removeFirst(linked_list_t* l) @C() AT_SPONTANEOUS { 
     return call LinkedList.removeFirst(l);
   }
-  error_t linked_list_addLast(linked_list_t* l, list_element_t* e) @C() @spontaneous() { 
+  error_t linked_list_addLast(linked_list_t* l, list_element_t* e) @C() AT_SPONTANEOUS { 
     return call LinkedList.addLast(l, e);
   }
-  list_element_t* linked_list_getLast(linked_list_t* l) @C() @spontaneous() { 
+  list_element_t* linked_list_getLast(linked_list_t* l) @C() AT_SPONTANEOUS { 
     return call LinkedList.getLast(l);
   }
-  list_element_t* linked_list_removeLast(linked_list_t* l) @C() @spontaneous() { 
+  list_element_t* linked_list_removeLast(linked_list_t* l) @C() AT_SPONTANEOUS { 
     return call LinkedList.removeLast(l);
   }
-  error_t linked_list_addAt(linked_list_t* l, list_element_t* e, uint8_t i) @C() @spontaneous() { 
+  error_t linked_list_addAt(linked_list_t* l, list_element_t* e, uint8_t i) @C() AT_SPONTANEOUS { 
     return call LinkedList.addAt(l, e, i);
   }
-  list_element_t* linked_list_getAt(linked_list_t* l, uint8_t i) @C() @spontaneous() { 
+  list_element_t* linked_list_getAt(linked_list_t* l, uint8_t i) @C() AT_SPONTANEOUS { 
     return call LinkedList.getAt(l, i);
   }
-  list_element_t* linked_list_removeAt(linked_list_t* l, uint8_t i) @C() @spontaneous() { 
+  list_element_t* linked_list_removeAt(linked_list_t* l, uint8_t i) @C() AT_SPONTANEOUS { 
     return call LinkedList.removeAt(l, i);
   }  
-  error_t linked_list_addAfter(linked_list_t* l, list_element_t* first, list_element_t* second) @C() @spontaneous() { 
+  error_t linked_list_addAfter(linked_list_t* l, list_element_t* first, list_element_t* second) @C() AT_SPONTANEOUS { 
     return call LinkedList.addAfter(l, first, second);
   }
-  error_t linked_list_addBefore(linked_list_t* l, list_element_t* first, list_element_t* e) @C() @spontaneous() { 
+  error_t linked_list_addBefore(linked_list_t* l, list_element_t* first, list_element_t* e) @C() AT_SPONTANEOUS { 
     return call LinkedList.addBefore(l, first, e);
   }
-  list_element_t* linked_list_getAfter(linked_list_t* l, list_element_t* e) @C() @spontaneous() { 
+  list_element_t* linked_list_getAfter(linked_list_t* l, list_element_t* e) @C() AT_SPONTANEOUS { 
     return call LinkedList.getAfter(l, e);
   }  
-  list_element_t* linked_list_getBefore(linked_list_t* l, list_element_t* e) @C() @spontaneous() { 
+  list_element_t* linked_list_getBefore(linked_list_t* l, list_element_t* e) @C() AT_SPONTANEOUS { 
     return call LinkedList.getBefore(l, e);
   }
-  list_element_t* linked_list_remove(linked_list_t* l, list_element_t* e) @C() @spontaneous() { 
+  list_element_t* linked_list_remove(linked_list_t* l, list_element_t* e) @C() AT_SPONTANEOUS { 
     return call LinkedList.remove(l, e);
   }  
-  list_element_t* linked_list_removeBefore(linked_list_t* l, list_element_t* e) @C() @spontaneous() { 
+  list_element_t* linked_list_removeBefore(linked_list_t* l, list_element_t* e) @C() AT_SPONTANEOUS { 
     return call LinkedList.removeBefore(l, e);
   }  
-  list_element_t* linked_list_removeAfter(linked_list_t* l, list_element_t* e) @C() @spontaneous() { 
+  list_element_t* linked_list_removeAfter(linked_list_t* l, list_element_t* e) @C() AT_SPONTANEOUS { 
     return call LinkedList.removeAfter(l, e);
   }  
-  uint8_t linked_list_indexOf(linked_list_t* l, list_element_t* e) @C() @spontaneous() { 
+  uint8_t linked_list_indexOf(linked_list_t* l, list_element_t* e) @C() AT_SPONTANEOUS { 
     return call LinkedList.indexOf(l, e);
   }
 }
index 04f0db59898ec0ebc1307afc280b3d7747442bb8..92638a7d5bc72663438950fbe2d872ccda6d70c5 100644 (file)
@@ -39,28 +39,28 @@ module CLogStorageP {
   }
 }
 implementation {
-  error_t volumeLogRead(uint8_t volumeId, void *buf, storage_len_t *len) @C() @spontaneous() {
+  error_t volumeLogRead(uint8_t volumeId, void *buf, storage_len_t *len) @C() AT_SPONTANEOUS {
     return call BlockingLog.read[volumeId](buf, len);
   }
-  storage_cookie_t volumeLogCurrentReadOffset(uint8_t volumeId) @C() @spontaneous() {
+  storage_cookie_t volumeLogCurrentReadOffset(uint8_t volumeId) @C() AT_SPONTANEOUS {
     return call BlockingLog.currentReadOffset[volumeId]();
   }
-  error_t volumeLogSeek(uint8_t volumeId, storage_cookie_t offset) @C() @spontaneous() {
+  error_t volumeLogSeek(uint8_t volumeId, storage_cookie_t offset) @C() AT_SPONTANEOUS {
     return call BlockingLog.seek[volumeId](offset);
   }
-  storage_len_t volumeLogGetSize(uint8_t volumeId) @C() @spontaneous() {
+  storage_len_t volumeLogGetSize(uint8_t volumeId) @C() AT_SPONTANEOUS {
     return call BlockingLog.getSize[volumeId]();
   }  
-  error_t volumeLogAppend(uint8_t volumeId, void* buf, storage_len_t *len, bool *recordsLost) @C() @spontaneous() {
+  error_t volumeLogAppend(uint8_t volumeId, void* buf, storage_len_t *len, bool *recordsLost) @C() AT_SPONTANEOUS {
     return call BlockingLog.append[volumeId](buf, len, recordsLost);
   }
-  storage_cookie_t volumeLogCurrentWriteOffset(uint8_t volumeId) @C() @spontaneous() {
+  storage_cookie_t volumeLogCurrentWriteOffset(uint8_t volumeId) @C() AT_SPONTANEOUS {
     return call BlockingLog.currentWriteOffset[volumeId]();
   }
-  error_t volumeLogErase(uint8_t volumeId) @C() @spontaneous() {
+  error_t volumeLogErase(uint8_t volumeId) @C() AT_SPONTANEOUS {
     return call BlockingLog.erase[volumeId]();
   }
-  error_t volumeLogSync(uint8_t volumeId) @C() @spontaneous() {
+  error_t volumeLogSync(uint8_t volumeId) @C() AT_SPONTANEOUS {
     return call BlockingLog.sync[volumeId]();
   }
 }
index 267c1c6dee6d62b052359496b0d74e710dcbc491..6d958cbdc1d78423831fa77d00f5c18d0363fa58 100644 (file)
 
 module CQueueC {}
 implementation { 
-  void queue_init(queue_t* q) @C() @spontaneous() {  
+  void queue_init(queue_t* q) @C() AT_SPONTANEOUS {  
     linked_list_init( &(q->l) );
   }
-  void queue_clear(queue_t* q) @C() @spontaneous() { 
+  void queue_clear(queue_t* q) @C() AT_SPONTANEOUS { 
     linked_list_clear( &(q->l) );
   }
-  error_t queue_enqueue(queue_t* q, queue_element_t* e) @C() @spontaneous() { 
+  error_t queue_enqueue(queue_t* q, queue_element_t* e) @C() AT_SPONTANEOUS { 
     return linked_list_addLast(&(q->l), (list_element_t*)e);
   }
-  queue_element_t* queue_dequeue(queue_t* q) @C() @spontaneous() { 
+  queue_element_t* queue_dequeue(queue_t* q) @C() AT_SPONTANEOUS { 
     return (queue_element_t*)linked_list_removeFirst( &(q->l) );
   }
-  queue_element_t* queue_remove(queue_t* q, queue_element_t* e) @C() @spontaneous() { 
+  queue_element_t* queue_remove(queue_t* q, queue_element_t* e) @C() AT_SPONTANEOUS { 
     return (queue_element_t*)linked_list_remove(&(q->l), (list_element_t*)e);
   }
-  uint8_t queue_size(queue_t* q) @C() @spontaneous() { 
+  uint8_t queue_size(queue_t* q) @C() AT_SPONTANEOUS { 
     return linked_list_size( &(q->l) );
   }
-  bool queue_is_empty(queue_t* q) @C() @spontaneous() { 
+  bool queue_is_empty(queue_t* q) @C() AT_SPONTANEOUS { 
     return (linked_list_size( &(q->l) ) == 0);
   }
 }
diff --git a/tos/lib/tosthreads/csystem/CRandomC.nc b/tos/lib/tosthreads/csystem/CRandomC.nc
new file mode 100644 (file)
index 0000000..15b2bcb
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2009 RWTH Aachen University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author J\97 Ã§gila Bitsch Link <jo.bitsch@cs.rwth-aachen.de>
+ */
+configuration CRandomC {}
+
+implementation {
+  components CRandomP,
+             RandomC;
+
+  CRandomP.Random -> RandomC;
+  CRandomP.SeedInit -> RandomC;
+}
diff --git a/tos/lib/tosthreads/csystem/CRandomP.nc b/tos/lib/tosthreads/csystem/CRandomP.nc
new file mode 100644 (file)
index 0000000..348836c
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2009 RWTH Aachen University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author J\97 Ã§gila Bitsch Link <jo.bitsch@cs.rwth-aachen.de>
+ */
+
+module CRandomP {
+  uses {
+    interface ParameterInit<uint16_t> as SeedInit;
+    interface Random;
+  }
+}
+
+implementation {
+  error_t randSeed(uint16_t seed) @C() AT_SPONTANEOUS {
+    return call SeedInit.init(seed);
+  }
+  
+  uint16_t rand16() @C() AT_SPONTANEOUS {
+    return call Random.rand16();
+  }
+  
+  uint32_t rand32() @C() AT_SPONTANEOUS {
+    return call Random.rand32();
+  }
+}
index 52f160131a4dd1a4df8bcb477e8b19cfc21912a2..18026f17f6faf6d6e461b2f2e402262253824082 100644 (file)
@@ -42,19 +42,22 @@ module CThreadP {
 }
 implementation {
 
-  error_t tosthread_create(tosthread_t* t, void (*start_routine)(void*), void* arg, uint16_t stack_size) @C() @spontaneous() {
+  error_t tosthread_create(tosthread_t* t, void (*start_routine)(void*), void* arg, uint16_t stack_size) @C() AT_SPONTANEOUS {
     return call DynamicThread.create(t, start_routine, arg, stack_size);
   }
-  error_t tosthread_destroy(tosthread_t* t) @C() @spontaneous() {
+  error_t tosthread_destroy(tosthread_t* t) @C() AT_SPONTANEOUS {
     return call DynamicThread.destroy(t);
   }
-  error_t tosthread_pause(tosthread_t* t) @C() @spontaneous() {
+  error_t tosthread_pause(tosthread_t* t) @C() AT_SPONTANEOUS {
     return call DynamicThread.pause(t);
   }
-  error_t tosthread_resume(tosthread_t* t) @C() @spontaneous() {
+  error_t tosthread_resume(tosthread_t* t) @C() AT_SPONTANEOUS {
     return call DynamicThread.resume(t);
   }
-  error_t tosthread_sleep(uint32_t milli) @C() @spontaneous() {
+  error_t tosthread_sleep(uint32_t milli) @C() AT_SPONTANEOUS {
     return call DynamicThread.sleep(milli);
   }
+  error_t tosthread_join(tosthread_t* t) @C() AT_SPONTANEOUS {
+    return call DynamicThread.join(t);
+  }
 }
index 952c48d1027831cbc86e4568c9f113abcce696ab..a82b9e0e3dab431001ce031a7719116de43a6b9f 100644 (file)
@@ -44,69 +44,69 @@ module CThreadSynchronizationP {
 }
 implementation {
   /******************** Mutex ***************************/
-  void mutex_init(mutex_t* m) @C() @spontaneous() {
+  void mutex_init(mutex_t* m) @C() AT_SPONTANEOUS {
     call Mutex.init(m);
   }
-  error_t mutex_lock(mutex_t* m) @C() @spontaneous() {
+  error_t mutex_lock(mutex_t* m) @C() AT_SPONTANEOUS {
     return call Mutex.lock(m);
   }
-  error_t mutex_unlock(mutex_t* m) @C() @spontaneous() {
+  error_t mutex_unlock(mutex_t* m) @C() AT_SPONTANEOUS {
     return call Mutex.unlock(m);
   }
   
   /******************** Semaphore ***************************/
-  void semaphore_reset(semaphore_t* s, uint8_t v) @C() @spontaneous() {
+  void semaphore_reset(semaphore_t* s, uint8_t v) @C() AT_SPONTANEOUS {
     call Semaphore.reset(s, v);
   }
-  error_t semaphore_acquire(semaphore_t* s) @C() @spontaneous() {
+  error_t semaphore_acquire(semaphore_t* s) @C() AT_SPONTANEOUS {
     return call Semaphore.acquire(s);
   }
-  error_t semaphore_release(semaphore_t* s) @C() @spontaneous() {
+  error_t semaphore_release(semaphore_t* s) @C() AT_SPONTANEOUS {
     return call Semaphore.release(s);
   }
   
   /******************** Barrier ***************************/
-  void barrier_reset(barrier_t* b, uint8_t count) @C() @spontaneous() {
+  void barrier_reset(barrier_t* b, uint8_t count) @C() AT_SPONTANEOUS {
     call Barrier.reset(b, count);
   }
-  void barrier_block(barrier_t* b) @C() @spontaneous() {
+  void barrier_block(barrier_t* b) @C() AT_SPONTANEOUS {
     call Barrier.block(b);
   }
-  bool barrier_isBlocking(barrier_t* b) @C() @spontaneous() {
+  bool barrier_isBlocking(barrier_t* b) @C() AT_SPONTANEOUS {
     return call Barrier.isBlocking(b);
   }
-  void condvar_init(condvar_t* c) @C() @spontaneous() {
+  void condvar_init(condvar_t* c) @C() AT_SPONTANEOUS {
     call ConditionVariable.init(c);
   }
   
   /******************** Condition Variable ***************************/
-  void condvar_wait(condvar_t* c, mutex_t* m) @C() @spontaneous() {
+  void condvar_wait(condvar_t* c, mutex_t* m) @C() AT_SPONTANEOUS {
     call ConditionVariable.wait(c, m);
   }
-  void condvar_signalNext(condvar_t* c) @C() @spontaneous() {
+  void condvar_signalNext(condvar_t* c) @C() AT_SPONTANEOUS {
     call ConditionVariable.signalNext(c);
   }
-  void condvar_signalAll(condvar_t* c) @C() @spontaneous() {
+  void condvar_signalAll(condvar_t* c) @C() AT_SPONTANEOUS {
     call ConditionVariable.signalAll(c);
   }
-  bool condvar_isBlocking(condvar_t* c) @C() @spontaneous() {
+  bool condvar_isBlocking(condvar_t* c) @C() AT_SPONTANEOUS {
     return call ConditionVariable.isBlocking(c);
   }
   
   /******************** Reference Counter ***************************/
-  void refcounter_init(refcounter_t* r) @C() @spontaneous() {
+  void refcounter_init(refcounter_t* r) @C() AT_SPONTANEOUS {
     call ReferenceCounter.init(r);
   }
-  void refcounter_increment(refcounter_t* r) @C() @spontaneous() {
+  void refcounter_increment(refcounter_t* r) @C() AT_SPONTANEOUS {
     call ReferenceCounter.increment(r);
   }
-  void refcounter_decrement(refcounter_t* r) @C() @spontaneous() {
+  void refcounter_decrement(refcounter_t* r) @C() AT_SPONTANEOUS {
     call ReferenceCounter.decrement(r);
   }
-  void refcounter_waitOnValue(refcounter_t* r, uint8_t count) @C() @spontaneous() {
+  void refcounter_waitOnValue(refcounter_t* r, uint8_t count) @C() AT_SPONTANEOUS {
     call ReferenceCounter.waitOnValue(r, count);
   }
-  uint8_t refcounter_count(refcounter_t* r) @C() @spontaneous() {
+  uint8_t refcounter_count(refcounter_t* r) @C() AT_SPONTANEOUS {
     return call ReferenceCounter.count(r);
   }
 }
index 17803b991fb259260e88fab706196e93d9103267..da04a860bb1ddf6c8e87fe10fb0009a9d15bd26e 100644 (file)
@@ -31,6 +31,7 @@
  
 /**
  * @author Kevin Klues <klueska@cs.stanford.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
  
 #include "tosthread.h"
@@ -67,6 +68,9 @@ implementation {
   #if defined(TOSTHREAD_LOGSTORAGE_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
     components CLogStorageC;
   #endif 
+  #if defined(TOSTHREAD_CONFIGSTORAGE_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CConfigStorageC;
+  #endif
   #if defined(TOSTHREAD_COLLECTION_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
     components CCollectionC;
   #endif 
index 2821a08c31e847662496d09fec1f5d10f3304fd9..ee2126fdffbabec327b12b39be9e9043f3416e4f 100644 (file)
@@ -22,6 +22,7 @@
 
 /**
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author J\97 Ã§gila Bitsch Link <jo.bitsch@cs.rwth-aachen.de>
  */
 
 configuration VolumeMapC { 
@@ -30,6 +31,8 @@ configuration VolumeMapC {
     interface BlockWrite[uint8_t volume_id];
     interface LogRead[uint8_t volume_id];
     interface LogWrite[uint8_t volume_id];
+    interface ConfigStorage[uint8_t volume_id];
+    interface Mount[uint8_t volume_id];
   }
 } 
 
@@ -40,4 +43,7 @@ implementation {
   BlockWrite = VolumeMapP;
   LogRead = VolumeMapP;
   LogWrite = VolumeMapP;
+  
+  ConfigStorage = VolumeMapP;
+  Mount = VolumeMapP;
 } 
index 5c810ddab21c5bf5e124c6394db0572b48174f91..2896fa19d5dc109f5da43e67b0f13aefa6871cb8 100644 (file)
@@ -22,6 +22,7 @@
 
 /**
  * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author J\97 Ã§gila Bitsch Link <jo.bitsch@cs.rwth-aachen.de>
  */
 
 module VolumeMapP {
@@ -30,6 +31,8 @@ module VolumeMapP {
     interface BlockWrite[uint8_t volume_id];
     interface LogRead[uint8_t volume_id];
     interface LogWrite[uint8_t volume_id];
+    interface ConfigStorage[uint8_t volume_id];
+    interface Mount[uint8_t volume_id];
   }
   
   uses { 
@@ -37,6 +40,8 @@ module VolumeMapP {
     interface BlockWrite as SubBlockWrite[uint8_t volume_id]; 
     interface LogRead as SubLogRead[uint8_t volume_id];
     interface LogWrite as SubLogWrite[uint8_t volume_id];
+    interface ConfigStorage as SubConfigStorage[uint8_t volume_id];
+    interface Mount as SubMount[uint8_t volume_id];
   }
 }
 
@@ -204,4 +209,73 @@ implementation {
   default event void LogWrite.appendDone[uint8_t volume_id](void* buf, storage_len_t len, bool recordsLost, error_t error) {}
   default event void LogWrite.eraseDone[uint8_t volume_id](error_t error) {}
   default event void LogWrite.syncDone[uint8_t volume_id](error_t error) {}
+  
+  command error_t ConfigStorage.read[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len) {
+    return call SubConfigStorage.read[volume_id](addr, buf, len);
+  }
+  
+  event void SubConfigStorage.readDone[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {
+    signal ConfigStorage.readDone[volume_id](addr, buf, len, error);
+  }
+  
+  command error_t ConfigStorage.write[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len) {
+    return call SubConfigStorage.write[volume_id](addr, buf, len);
+  }
+  
+  event void SubConfigStorage.writeDone[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {
+    signal ConfigStorage.writeDone[volume_id](addr, buf, len, error);
+  }
+  
+  command error_t ConfigStorage.commit[uint8_t volume_id]() {
+    return call SubConfigStorage.commit[volume_id]();
+  }
+  
+  event void SubConfigStorage.commitDone[uint8_t volume_id](error_t error) {
+    signal ConfigStorage.commitDone[volume_id](error);
+  }
+
+  command storage_len_t ConfigStorage.getSize[uint8_t volume_id]() {
+    return call SubConfigStorage.getSize[volume_id]();
+  }
+  
+  command bool ConfigStorage.valid[uint8_t volume_id]() {
+    return call SubConfigStorage.valid[volume_id]();
+  }
+  
+  command error_t Mount.mount[uint8_t volume_id]() {
+    return call SubMount.mount[volume_id]();
+  }
+  
+  event void SubMount.mountDone[uint8_t volume_id](error_t error) {
+    signal Mount.mountDone[volume_id](error);
+  }
+  
+  default command error_t SubConfigStorage.read[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len) {
+    return FAIL;
+  }
+
+  default command error_t SubConfigStorage.write[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len) {
+    return FAIL;
+  }
+  
+  default command error_t SubConfigStorage.commit[uint8_t volume_id]() {
+    return FAIL;
+  }
+
+  default command storage_len_t SubConfigStorage.getSize[uint8_t volume_id]() {
+    return FAIL;
+  }
+  
+  default command bool SubConfigStorage.valid[uint8_t volume_id]() {
+    return FAIL;
+  }
+  
+  default command error_t SubMount.mount[uint8_t volume_id]() {
+    return FAIL;
+  }
+
+  default event void ConfigStorage.commitDone[uint8_t volume_id](error_t error) {}
+  default event void ConfigStorage.writeDone[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {}  
+  default event void ConfigStorage.readDone[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {}
+  default event void Mount.mountDone[uint8_t volume_id](error_t error) {}
 }
index b032ad54599529f75a99d85c13117e5ca098cdce..3c1551c904391f560f8cefcb9fa94fca121940d3 100644 (file)
@@ -120,4 +120,17 @@ extern error_t tosthread_resume(tosthread_t* t);
  */
 extern error_t tosthread_sleep(uint32_t milli);
 
+/**
+ *  tosthread_join(tosthread_t* t)
+ *
+ *  This function bocks until the thread passed as a parameter has completed
+ *  
+ *  @param id                  The handle to the thread to block on
+ *  @return                            An error code indicating whether the thread could be waited on or not
+ *                                                     SUCCESS         -       The thread has been waited on and is now completed
+ *                                                     EALREADY        -       The thread we are trying to wait on has already completed
+ *                                                     FAIL            -       The thread could not waited on
+ */
+extern error_t tosthread_join(tosthread_t* id);
+
 #endif //TOSTHREAD_H_INCLUDED
diff --git a/tos/lib/tosthreads/csystem/tosthread_configstorage.h b/tos/lib/tosthreads/csystem/tosthread_configstorage.h
new file mode 100644 (file)
index 0000000..51d5d30
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2009 RWTH Aachen University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author J\97 Ã§gila Bitsch Link <jo.bitsch@cs.rwth-aachen.de>
+ */
+
+#ifndef TOSTHREAD_CONFIGSTORAGE_H
+#define TOSTHREAD_CONFIGSTORAGE_H
+
+#include "Storage.h"
+
+extern error_t volumeConfigMount(uint8_t volumeId);
+extern error_t volumeConfigRead(uint8_t volumeId, storage_addr_t addr, void* buf, storage_len_t* len);
+extern error_t volumeConfigWrite(uint8_t volumeId, storage_addr_t addr, void* buf, storage_len_t* len);
+extern error_t volumeConfigCommit(uint8_t volumeId);
+extern storage_len_t volumeConfigGetSize(uint8_t volumeId);
+extern bool volumeConfigValid(uint8_t volumeId);
+
+#endif   // TOSTHREAD_CONFIGSTORAGE_H
diff --git a/tos/lib/tosthreads/csystem/tosthread_random.h b/tos/lib/tosthreads/csystem/tosthread_random.h
new file mode 100644 (file)
index 0000000..fb8e54d
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2009 RWTH Aachen University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author J\97 Ã§gila Bitsch Link <jo.bitsch@cs.rwth-aachen.de>
+ */
+
+#ifndef TOSTHREAD_RANDOM_H
+#define TOSTHREAD_RANDOM_H
+
+#include "TinyError.h"
+
+extern error_t randSeed(uint16_t seed);
+extern uint16_t rand16();
+extern uint32_t rand32();
+
+#endif //TOSTHREAD_RANDOM_H
diff --git a/tos/lib/tosthreads/csystem/tosthread_tenet.h b/tos/lib/tosthreads/csystem/tosthread_tenet.h
deleted file mode 100644 (file)
index a2d5fd9..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-
-/**
- * @author Jeongyeup Paek (jpaek@enl.usc.edu)
- **/
-#ifndef TOSTHREAD_TENET_H
-#define TOSTHREAD_TENET_H
-
-extern error_t tenet_send(uint8_t len, uint8_t *data);
-extern error_t tenet_sendto(uint16_t tid, uint16_t dst, uint8_t len, uint8_t *data);
-
-extern uint16_t tenet_get_tid();
-extern uint16_t tenet_get_src();
-extern uint8_t tenet_get_numtasks();
-
-extern void reboot();
-
-extern uint16_t get_nodeid();
-extern uint16_t get_nexthop();
-extern uint32_t get_globaltime();
-extern uint32_t get_localtime();
-extern uint16_t get_rfpower();
-extern uint16_t get_istimesync();
-extern uint32_t get_globaltimems();
-extern uint32_t get_localtimems();
-extern uint16_t get_clockfreq();
-extern uint16_t get_platform();
-extern uint16_t get_hopcount();
-extern uint16_t get_rfchannel();
-
-extern uint16_t read_voltage();
-extern uint16_t read_internal_temperature();
-extern uint16_t read_tsr_sensor();
-extern uint16_t read_par_sensor();
-extern uint16_t read_temperature();
-extern uint16_t read_humidity();
-
-#endif //TOSTHREAD_TENET_H
-
diff --git a/tos/lib/tosthreads/interfaces/BlockingBlockWrite.nc b/tos/lib/tosthreads/interfaces/BlockingBlockWrite.nc
deleted file mode 100644 (file)
index 83f79c4..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2008 Johns Hopkins University.
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written
- * agreement is hereby granted, provided that the above copyright
- * notice, the (updated) modification history and the author appear in
- * all copies of this source code.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
- * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-/**
- * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
- */
-interface BlockingBlockWrite { 
-  command error_t write(storage_addr_t addr, void* buf, storage_len_t len);
-  command error_t erase();
-  command error_t sync();
-}
diff --git a/tos/lib/tosthreads/interfaces/BlockingConfig.nc b/tos/lib/tosthreads/interfaces/BlockingConfig.nc
new file mode 100644 (file)
index 0000000..9ffd647
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2009 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "Storage.h"
+
+interface BlockingConfig
+{
+  command error_t read(storage_addr_t addr, void* buf, storage_len_t* len);
+  command error_t write(storage_addr_t addr, void* buf, storage_len_t* len);
+  command error_t commit();
+  command storage_len_t getSize();
+  command bool valid();
+}
diff --git a/tos/lib/tosthreads/interfaces/BlockingMount.nc b/tos/lib/tosthreads/interfaces/BlockingMount.nc
new file mode 100644 (file)
index 0000000..b459c69
--- /dev/null
@@ -0,0 +1,52 @@
+/* Copyright (c) 2002-2006 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ * Mount a volume.
+ *
+ * @author David Gay
+ * @version $Revision$ $Date$
+ */
+
+/*
+ * Copyright (c) 2009 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+interface BlockingMount {
+  /**
+   * Mount a particular volume. This must be done before the volume's
+   * first use. <code>mountDone</code> will be signaled if SUCCESS is
+   * returned.
+   * @return SUCCESS if mount request is accepted, FAIL if mount has
+   *   already been attempted.
+   */
+  command error_t mount();
+}
index aea023c905a347d44c58c60a73ab56528a7bd5f7..d3d26264632bb95606fb1f2503cd3632f8bab8c8 100644 (file)
@@ -102,4 +102,17 @@ interface DynamicThread {
    *                                                   FAIL            -       The thread could not be put to sleep
    */
   command error_t sleep(uint32_t milli);
+  
+  /**
+   *  join(tosthread_t* t)
+   *
+   *  This function bocks until the thread passed as a parameter has completed
+   *  
+   *  @param id                        The handle to the thread to block on
+   *  @return                          An error code indicating whether the thread could be waited on or not
+   *                                                   SUCCESS         -       The thread has been waited on and is now completed
+   *                                                   EALREADY        -       The thread we are trying to wait on has already completed
+   *                                                   FAIL            -       The thread could not waited on
+   */
+  command error_t join(tosthread_t* id);
 }  
index 15b93f6c1257740a52f8107adb8ee64507ff9b7b..0fc2f4602fbd70a187d791c6abc1874ee6059bfc 100644 (file)
@@ -40,4 +40,5 @@ interface Thread {
   command error_t resume();
   command error_t sleep(uint32_t milli);
   event void run(void* arg);
+  command error_t join();
 }  
index d98379fc05a5ea7586d92afc7e7f5f0f995dea11..df244c1c4a00e558c90245cb81a5b3167b7358b9 100644 (file)
@@ -36,5 +36,6 @@
 #include "thread.h"
 
 interface ThreadInfo {
+  async command error_t reset();
   async command thread_t* get();
 }  
index 089460807addda6779380e342e5103894cef971e..c682d28a3a0b5c68e7cdef9a0559c57e2a1d2283 100644 (file)
@@ -48,4 +48,5 @@ interface ThreadScheduler {
   async command error_t interruptCurrentThread();
 
   async command error_t wakeupThread(thread_id_t id);
+  async command error_t joinThread(thread_id_t id);
 }
index e7b2182260dc26d879d8e06400ed53aeb809fb7a..4a775542d70e067c5e9bd0c4bb139e16a21fb9c2 100644 (file)
@@ -32,11 +32,15 @@ configuration BlockingCollectionControlC {
 }
 
 implementation {
-  components BlockingCollectionControlP,
-             CollectionC as Collector;
+  components CollectionC as Collector,
+             SystemCallC,
+             MutexC,
+             BlockingCollectionControlP;
   
   RoutingControl = BlockingCollectionControlP.BlockingStdControl;
   RootControl = Collector;
   
   BlockingCollectionControlP.RoutingControl -> Collector.StdControl;
+  BlockingCollectionControlP.SystemCall -> SystemCallC;
+  BlockingCollectionControlP.Mutex -> MutexC;
 }
index b2d920af885872a2b0cd6f5c3d248abe90f9ccd8..1bb62b19fe4d89e9570613f3da4141515c561539 100644 (file)
 
 module BlockingCollectionControlP {
   provides {
-    interface BlockingStdControl; 
+    interface BlockingStdControl;
+    interface Init;
   }
   
   uses {
     interface StdControl as RoutingControl;
+    interface SystemCall;
+    interface Mutex;
   }
 }
 
 implementation {
-  command error_t BlockingStdControl.start()
+  typedef struct params {
+    error_t error;
+  } params_t;
+
+  syscall_t* start_call = NULL;
+  mutex_t my_mutex;
+  
+  command error_t Init.init()
   {
-    return call RoutingControl.start();
+    call Mutex.init(&my_mutex);
+    return SUCCESS;
   }
   
-  command error_t BlockingStdControl.stop()
+  void startTask(syscall_t* s)
   {
+    params_t* p = s->params;
+    p->error = call RoutingControl.start();
+    call SystemCall.finish(s);
+  }
+
+  command error_t BlockingStdControl.start()
+  {
+    syscall_t s;
+    params_t p;
+    
+    call Mutex.lock(&my_mutex);
+      if (start_call == NULL) {
+        start_call = &s;
+        call SystemCall.start(&startTask, &s, INVALID_ID, &p);
+        start_call = NULL;
+      } else {
+        p.error = EBUSY;
+      }
+        
+    atomic {
+      call Mutex.unlock(&my_mutex);
+      return p.error;
+    }
+  }
+  
+  command error_t BlockingStdControl.stop() {
     return call RoutingControl.stop();
   }
 }
diff --git a/tos/lib/tosthreads/lib/net/BlockingCollectionSenderImplP.nc b/tos/lib/tosthreads/lib/net/BlockingCollectionSenderImplP.nc
deleted file mode 100644 (file)
index 3b32158..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (c) 2008 Johns Hopkins University.
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written
- * agreement is hereby granted, provided that the above copyright
- * notice, the (updated) modification history and the author appear in
- * all copies of this source code.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
- * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-/*
- * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
- */
-module BlockingCollectionSenderImplP {
-  provides {
-    interface BlockingSend[uint8_t client];
-    interface Init;
-  }
-  
-  uses {
-    interface Send[uint8_t client];
-    interface SystemCall;
-    interface Mutex;
-    interface Packet;
-    interface Leds;
-  }
-}
-
-implementation {
-  typedef struct params {
-    message_t *msg;
-    uint8_t len;
-    error_t error;
-  } params_t;
-  
-  syscall_t* send_call;
-  mutex_t my_mutex;
-  
-  command error_t Init.init()
-  {
-    call Mutex.init(&my_mutex);
-    return SUCCESS;
-  }
-
-  void sendTask(syscall_t *s)
-  {
-    params_t* p = s->params;
-    
-    p->error = call Send.send[s->id](p->msg, p->len);
-    if(p->error != SUCCESS) {
-      call SystemCall.finish(s);
-    }
-  }
-
-  command error_t BlockingSend.send[uint8_t client](message_t *msg, uint8_t len)
-  {
-    syscall_t s;
-    params_t p;
-    call Mutex.lock(&my_mutex);
-    send_call = &s;
-    
-    p.msg = msg;
-    p.len = len;
-    
-    call SystemCall.start(&sendTask, &s, client, &p);
-    
-    atomic {
-      call Mutex.unlock(&my_mutex);
-      return p.error;
-    }
-  }
-  
-  event void Send.sendDone[uint8_t client](message_t* m, error_t error)
-  {
-    if (client == send_call->id) {
-      params_t* p;
-      
-      p = send_call->params;
-      p->error = error;
-      call SystemCall.finish(send_call);
-    }
-  }
-  
-  command error_t BlockingSend.cancel[uint8_t client](message_t* msg)
-  {
-    return call Send.cancel[client](msg);
-  }
-  
-  command uint8_t BlockingSend.maxPayloadLength[uint8_t client]()
-  {
-    return call Send.maxPayloadLength[client]();
-  }
-  
-  command void* BlockingSend.getPayload[uint8_t client](message_t* msg, uint8_t len)
-  {
-    return call Send.getPayload[client](msg, len);
-  }
-}
diff --git a/tos/lib/tosthreads/lib/net/BlockingCollectionSenderP.nc b/tos/lib/tosthreads/lib/net/BlockingCollectionSenderP.nc
deleted file mode 100644 (file)
index e2ba37e..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2008 Johns Hopkins University.
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written
- * agreement is hereby granted, provided that the above copyright
- * notice, the (updated) modification history and the author appear in
- * all copies of this source code.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
- * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-/*
- * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
- * @author Kevin Klues <klueska@cs.stanford.edu>
- */
-
-configuration BlockingCollectionSenderP {
-  provides {
-    interface BlockingSend[uint8_t id];
-  }
-}
-
-implementation {
-  components BlockingCollectionSenderImplP,
-             CollectionC as Collector,
-             MutexC,
-             SystemCallC,
-             MainC,
-             LedsC;
-  
-  MainC.SoftwareInit -> BlockingCollectionSenderImplP;
-  BlockingSend = BlockingCollectionSenderImplP.BlockingSend;
-  
-  BlockingCollectionSenderImplP.Mutex -> MutexC;
-  BlockingCollectionSenderImplP.SystemCall -> SystemCallC;
-  BlockingCollectionSenderImplP.Send -> Collector;
-  BlockingCollectionSenderImplP.Packet -> Collector;
-  BlockingCollectionSenderImplP.Leds -> LedsC;
-}
-
diff --git a/tos/lib/tosthreads/lib/net/CCollectionId.nc b/tos/lib/tosthreads/lib/net/CCollectionId.nc
new file mode 100644 (file)
index 0000000..7e13b6a
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+interface CCollectionId {
+  command collection_id_t fetch(uint8_t clientid);
+  command error_t set(uint8_t clientid, collection_id_t collectionid);
+}
diff --git a/tos/lib/tosthreads/lib/net/CCollectionP.nc b/tos/lib/tosthreads/lib/net/CCollectionP.nc
deleted file mode 100644 (file)
index 52878a5..0000000
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (c) 2008 Stanford University.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * - Redistributions of source code must retain the above copyright
- *   notice, this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright
- *   notice, this list of conditions and the following disclaimer in the
- *   documentation and/or other materials provided with the
- *   distribution.
- * - Neither the name of the Stanford University nor the names of
- *   its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
- * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/**
- * @author Kevin Klues <klueska@cs.stanford.edu>
- */
-
-module CCollectionP {
-  uses {
-    interface BlockingStdControl as RoutingControl;
-    interface BlockingReceive[collection_id_t id];
-    interface BlockingReceive as BlockingSnoop[collection_id_t id];
-    interface BlockingSend[am_id_t id];
-    interface Packet;
-    interface CollectionPacket;
-    interface RootControl;
-  }
-  provides {
-    interface CollectionId[uint8_t client];
-  }
-}
-implementation {
-  command collection_id_t CollectionId.fetch[uint8_t id]() {
-    return id;
-  }
-  
-  error_t collectionRoutingStart() @C() @spontaneous() {
-    return call RoutingControl.start();
-  }
-  error_t collectionRoutingStop() @C() @spontaneous() {
-    return call RoutingControl.stop();
-  }
-
-  error_t collectionReceive(message_t* m, uint32_t timeout, collection_id_t id) @C() @spontaneous() {
-    return call BlockingReceive.receive[id](m, timeout);
-  }
-  error_t collectionSnoop(message_t* m, uint32_t timeout, collection_id_t id) @C() @spontaneous() {
-    return call BlockingSnoop.receive[id](m, timeout);
-  }
-  error_t collectionSend(message_t* msg, uint8_t len, collection_id_t id) @C() @spontaneous() {
-    return call BlockingSend.send[id](msg, len);
-  }
-  void collectionClear(message_t* msg) @C() @spontaneous() {
-    call Packet.clear(msg);
-  }
-  uint8_t collectionGetPayloadLength(message_t* msg) @C() @spontaneous() {
-    return call Packet.payloadLength(msg);
-  }
-  void collectionSetPayloadLength(message_t* msg, uint8_t len) @C() @spontaneous() {
-    call Packet.setPayloadLength(msg, len);
-  }
-  uint8_t collectionMaxPayloadLength() @C() @spontaneous() {
-    return call Packet.maxPayloadLength();
-  }
-  void* collectionGetPayload(message_t* msg, uint8_t len) @C() @spontaneous() {
-    return call Packet.getPayload(msg, len);
-  }
-
-  am_addr_t collectionGetOrigin(message_t* msg) @C() @spontaneous() {
-    return call CollectionPacket.getOrigin(msg);
-  }
-  void collectionSetOrigin(message_t* msg, am_addr_t addr) @C() @spontaneous() {
-    call CollectionPacket.setOrigin(msg, addr);
-  }
-  collection_id_t collectionGetType(message_t* msg) @C() @spontaneous() {
-    return call CollectionPacket.getType(msg);
-  }
-  void collectionSetType(message_t* msg, collection_id_t id) @C() @spontaneous() {
-    call CollectionPacket.setType(msg, id);
-  }
-  uint8_t collectionGetSequenceNumber(message_t* msg) @C() @spontaneous() {
-    return call CollectionPacket.getSequenceNumber(msg);
-  }
-  void collectionSetSequenceNumber(message_t* msg, uint8_t seqno) @C() @spontaneous() {
-    call CollectionPacket.setSequenceNumber(msg, seqno);
-  }
-
-  error_t collectionSetRoot() @C() @spontaneous() {
-    return call RootControl.setRoot();
-  }
-  error_t collectionUnsetRoot() @C() @spontaneous() {
-    return call RootControl.unsetRoot();
-  }
-  bool collectionIsRoot() @C() @spontaneous() {
-    return call RootControl.isRoot();
-  }
-}
-
diff --git a/tos/lib/tosthreads/lib/net/ctp/BlockingCollectionSenderImplP.nc b/tos/lib/tosthreads/lib/net/ctp/BlockingCollectionSenderImplP.nc
new file mode 100644 (file)
index 0000000..3b32158
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+module BlockingCollectionSenderImplP {
+  provides {
+    interface BlockingSend[uint8_t client];
+    interface Init;
+  }
+  
+  uses {
+    interface Send[uint8_t client];
+    interface SystemCall;
+    interface Mutex;
+    interface Packet;
+    interface Leds;
+  }
+}
+
+implementation {
+  typedef struct params {
+    message_t *msg;
+    uint8_t len;
+    error_t error;
+  } params_t;
+  
+  syscall_t* send_call;
+  mutex_t my_mutex;
+  
+  command error_t Init.init()
+  {
+    call Mutex.init(&my_mutex);
+    return SUCCESS;
+  }
+
+  void sendTask(syscall_t *s)
+  {
+    params_t* p = s->params;
+    
+    p->error = call Send.send[s->id](p->msg, p->len);
+    if(p->error != SUCCESS) {
+      call SystemCall.finish(s);
+    }
+  }
+
+  command error_t BlockingSend.send[uint8_t client](message_t *msg, uint8_t len)
+  {
+    syscall_t s;
+    params_t p;
+    call Mutex.lock(&my_mutex);
+    send_call = &s;
+    
+    p.msg = msg;
+    p.len = len;
+    
+    call SystemCall.start(&sendTask, &s, client, &p);
+    
+    atomic {
+      call Mutex.unlock(&my_mutex);
+      return p.error;
+    }
+  }
+  
+  event void Send.sendDone[uint8_t client](message_t* m, error_t error)
+  {
+    if (client == send_call->id) {
+      params_t* p;
+      
+      p = send_call->params;
+      p->error = error;
+      call SystemCall.finish(send_call);
+    }
+  }
+  
+  command error_t BlockingSend.cancel[uint8_t client](message_t* msg)
+  {
+    return call Send.cancel[client](msg);
+  }
+  
+  command uint8_t BlockingSend.maxPayloadLength[uint8_t client]()
+  {
+    return call Send.maxPayloadLength[client]();
+  }
+  
+  command void* BlockingSend.getPayload[uint8_t client](message_t* msg, uint8_t len)
+  {
+    return call Send.getPayload[client](msg, len);
+  }
+}
diff --git a/tos/lib/tosthreads/lib/net/ctp/BlockingCollectionSenderP.nc b/tos/lib/tosthreads/lib/net/ctp/BlockingCollectionSenderP.nc
new file mode 100644 (file)
index 0000000..e2ba37e
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Kevin Klues <klueska@cs.stanford.edu>
+ */
+
+configuration BlockingCollectionSenderP {
+  provides {
+    interface BlockingSend[uint8_t id];
+  }
+}
+
+implementation {
+  components BlockingCollectionSenderImplP,
+             CollectionC as Collector,
+             MutexC,
+             SystemCallC,
+             MainC,
+             LedsC;
+  
+  MainC.SoftwareInit -> BlockingCollectionSenderImplP;
+  BlockingSend = BlockingCollectionSenderImplP.BlockingSend;
+  
+  BlockingCollectionSenderImplP.Mutex -> MutexC;
+  BlockingCollectionSenderImplP.SystemCall -> SystemCallC;
+  BlockingCollectionSenderImplP.Send -> Collector;
+  BlockingCollectionSenderImplP.Packet -> Collector;
+  BlockingCollectionSenderImplP.Leds -> LedsC;
+}
+
index 7508b706aa88e0deae73ce1443a59ccf64a58b65..5bee546cca05782d29a429fac32f2acfa8d95370 100644 (file)
@@ -44,21 +44,13 @@ implementation {
   components BlockingCollectionSnooperP;
   components BlockingCollectionSenderP;
   components BlockingCollectionControlC;
-  
-  //Allocate enough room in the message queue for all message types.
-  //This number needs to be 255-1-12 because 
-  //(1) The max number that can be provided to the Queue underneath for its size is 255
-  //(2) uniqueN() will give you values from 0..N constituting N+1 unique numbers
-  //(3) there are 12 spaces reserved in the send queue in CtpP for forwarding messages.
-  //I don't like this implementation, but it will do for now....
-  enum {
-   FIRST_CLIENT = uniqueN(UQ_CTP_CLIENT, 255-1-12),
-  };
+  components CCollectionIdP;
   
   CCP.BlockingReceive -> BlockingCollectionReceiverP;
   CCP.BlockingSnoop -> BlockingCollectionSnooperP;
   CCP.BlockingSend -> BlockingCollectionSenderP;
   CCP.RoutingControl -> BlockingCollectionControlC;
+  CCP.CCollectionId -> CCollectionIdP;
   
   components CollectionC;
   CCP.Packet -> CollectionC;
diff --git a/tos/lib/tosthreads/lib/net/ctp/CCollectionIdP.nc b/tos/lib/tosthreads/lib/net/ctp/CCollectionIdP.nc
new file mode 100644 (file)
index 0000000..93cabca
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+module CCollectionIdP
+{
+  provides {
+    interface CCollectionId;
+  }
+}
+
+implementation {
+  collection_id_t clientCollectionIds[uniqueCount(UQ_CTP_CLIENT)];
+  
+  command collection_id_t CCollectionId.fetch(uint8_t clientid)
+  {
+    return clientCollectionIds[clientid];
+  }
+  
+  command error_t CCollectionId.set(uint8_t clientid, collection_id_t collectionid)
+  {
+    if (clientid < uniqueCount(UQ_CTP_CLIENT)) {
+      clientCollectionIds[clientid] = collectionid;
+      
+      return SUCCESS;
+    }
+    
+    return FAIL;
+  }
+}
diff --git a/tos/lib/tosthreads/lib/net/ctp/CCollectionP.nc b/tos/lib/tosthreads/lib/net/ctp/CCollectionP.nc
new file mode 100644 (file)
index 0000000..5b7ee8a
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @author Kevin Klues <klueska@cs.stanford.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+module CCollectionP {
+  uses {
+    interface BlockingStdControl as RoutingControl;
+    interface BlockingReceive[collection_id_t id];
+    interface BlockingReceive as BlockingSnoop[collection_id_t id];
+    interface BlockingSend[uint8_t id];
+    interface Packet;
+    interface CollectionPacket;
+    interface RootControl;
+    interface CCollectionId;
+  }
+  provides {
+    interface CollectionId[uint8_t client];
+  }
+}
+implementation {
+  command collection_id_t CollectionId.fetch[uint8_t id]() {
+    return call CCollectionId.fetch(id);
+  }
+
+  error_t collectionSetCollectionId(uint8_t clientid, collection_id_t collectionid) @C() AT_SPONTANEOUS {
+    return call CCollectionId.set(clientid, collectionid);
+  }
+  
+  error_t collectionRoutingStart() @C() AT_SPONTANEOUS {
+    return call RoutingControl.start();
+  }
+  error_t collectionRoutingStop() @C() AT_SPONTANEOUS {
+    return call RoutingControl.stop();
+  }
+
+  error_t collectionReceive(message_t* m, uint32_t timeout, collection_id_t id) @C() AT_SPONTANEOUS {
+    return call BlockingReceive.receive[id](m, timeout);
+  }
+  error_t collectionSnoop(message_t* m, uint32_t timeout, collection_id_t id) @C() AT_SPONTANEOUS {
+    return call BlockingSnoop.receive[id](m, timeout);
+  }
+  error_t collectionSend(message_t* msg, uint8_t len, uint8_t id) @C() AT_SPONTANEOUS {
+    return call BlockingSend.send[id](msg, len);
+  }
+  void collectionClear(message_t* msg) @C() AT_SPONTANEOUS {
+    call Packet.clear(msg);
+  }
+  uint8_t collectionGetPayloadLength(message_t* msg) @C() AT_SPONTANEOUS {
+    return call Packet.payloadLength(msg);
+  }
+  void collectionSetPayloadLength(message_t* msg, uint8_t len) @C() AT_SPONTANEOUS {
+    call Packet.setPayloadLength(msg, len);
+  }
+  uint8_t collectionMaxPayloadLength() @C() AT_SPONTANEOUS {
+    return call Packet.maxPayloadLength();
+  }
+  void* collectionGetPayload(message_t* msg, uint8_t len) @C() AT_SPONTANEOUS {
+    return call Packet.getPayload(msg, len);
+  }
+
+  am_addr_t collectionGetOrigin(message_t* msg) @C() AT_SPONTANEOUS {
+    return call CollectionPacket.getOrigin(msg);
+  }
+  void collectionSetOrigin(message_t* msg, am_addr_t addr) @C() AT_SPONTANEOUS {
+    call CollectionPacket.setOrigin(msg, addr);
+  }
+  collection_id_t collectionGetType(message_t* msg) @C() AT_SPONTANEOUS {
+    return call CollectionPacket.getType(msg);
+  }
+  void collectionSetType(message_t* msg, collection_id_t id) @C() AT_SPONTANEOUS {
+    call CollectionPacket.setType(msg, id);
+  }
+  uint8_t collectionGetSequenceNumber(message_t* msg) @C() AT_SPONTANEOUS {
+    return call CollectionPacket.getSequenceNumber(msg);
+  }
+  void collectionSetSequenceNumber(message_t* msg, uint8_t seqno) @C() AT_SPONTANEOUS {
+    call CollectionPacket.setSequenceNumber(msg, seqno);
+  }
+
+  error_t collectionSetRoot() @C() AT_SPONTANEOUS {
+    return call RootControl.setRoot();
+  }
+  error_t collectionUnsetRoot() @C() AT_SPONTANEOUS {
+    return call RootControl.unsetRoot();
+  }
+  bool collectionIsRoot() @C() AT_SPONTANEOUS {
+    return call RootControl.isRoot();
+  }
+}
+
diff --git a/tos/lib/tosthreads/lib/net/ctp/ccollection.h b/tos/lib/tosthreads/lib/net/ctp/ccollection.h
new file mode 100644 (file)
index 0000000..6ef74d0
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @author Kevin Klues <klueska@cs.stanford.edu>
+ */
+#ifndef CCOLLECTION_H
+#define CCOLLECTION_H
+
+#include "message.h"
+#include "TinyError.h"
+#include "Collection.h"
+#include "Ctp.h"
+
+#define  NEW_COLLECTION_CLIENT_ID() ((uint8_t)unique(UQ_CTP_CLIENT))
+
+#endif //CCOLLECTION_H
index e65b69540dda2486ef66400238b56a602bec1fdb..eedf6c93c1fa9a5ea1c6c927c128b129a6a345b5 100644 (file)
@@ -46,5 +46,5 @@ implementation {
   BlockingSend = BlockingCollectionSenderP.BlockingSend[CLIENT_ID];
   Packet = Collector;
   
-  Collector.CollectionId[CLIENT_ID] -> CollectionIdP;
+  BlockingCollectionSenderP.CollectionId[CLIENT_ID] -> CollectionIdP;
 }
diff --git a/tos/lib/tosthreads/lib/net/lqi/BlockingCollectionSenderImplP.nc b/tos/lib/tosthreads/lib/net/lqi/BlockingCollectionSenderImplP.nc
new file mode 100644 (file)
index 0000000..1f886f4
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+module BlockingCollectionSenderImplP {
+  provides {
+    interface BlockingSend[uint8_t client];
+    interface Init;
+  }
+  
+  uses {
+    interface Send[uint8_t client];
+    interface SystemCall;
+    interface Mutex;
+    interface Packet;
+    interface Leds;
+    interface CollectionPacket;
+    interface CollectionId[uint8_t client];
+  }
+}
+
+implementation {
+  typedef struct params {
+    message_t *msg;
+    uint8_t len;
+    error_t error;
+  } params_t;
+  
+  syscall_t* send_call;
+  mutex_t my_mutex;
+  
+  command error_t Init.init()
+  {
+    call Mutex.init(&my_mutex);
+    return SUCCESS;
+  }
+
+  void sendTask(syscall_t *s)
+  {
+    params_t* p = s->params;
+    
+    call CollectionPacket.setType(p->msg, call CollectionId.fetch[s->id]());
+    p->error = call Send.send[s->id](p->msg, p->len);
+    if(p->error != SUCCESS) {
+      call SystemCall.finish(s);
+    }
+  }
+
+  command error_t BlockingSend.send[uint8_t client](message_t *msg, uint8_t len)
+  {
+    syscall_t s;
+    params_t p;
+    call Mutex.lock(&my_mutex);
+    send_call = &s;
+    
+    p.msg = msg;
+    p.len = len;
+    
+    call SystemCall.start(&sendTask, &s, client, &p);
+    
+    atomic {
+      call Mutex.unlock(&my_mutex);
+      return p.error;
+    }
+  }
+  
+  event void Send.sendDone[uint8_t client](message_t* m, error_t error)
+  {
+    if (client == send_call->id) {
+      params_t* p;
+      
+      p = send_call->params;
+      p->error = error;
+      call SystemCall.finish(send_call);
+    }
+  }
+  
+  command error_t BlockingSend.cancel[uint8_t client](message_t* msg)
+  {
+    return call Send.cancel[client](msg);
+  }
+  
+  command uint8_t BlockingSend.maxPayloadLength[uint8_t client]()
+  {
+    return call Send.maxPayloadLength[client]();
+  }
+  
+  command void* BlockingSend.getPayload[uint8_t client](message_t* msg, uint8_t len)
+  {
+    return call Send.getPayload[client](msg, len);
+  }
+  
+  default command collection_id_t CollectionId.fetch[uint8_t id]() { return 0; }
+}
diff --git a/tos/lib/tosthreads/lib/net/lqi/BlockingCollectionSenderP.nc b/tos/lib/tosthreads/lib/net/lqi/BlockingCollectionSenderP.nc
new file mode 100644 (file)
index 0000000..fd2b301
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Kevin Klues <klueska@cs.stanford.edu>
+ */
+
+configuration BlockingCollectionSenderP {
+  provides {
+    interface BlockingSend[uint8_t id];
+  }
+  
+  uses {
+    interface CollectionId[uint8_t id];
+  }
+}
+
+implementation {
+  components BlockingCollectionSenderImplP,
+             CollectionC as Collector,
+             MutexC,
+             SystemCallC,
+             MainC,
+             LedsC;
+  
+  MainC.SoftwareInit -> BlockingCollectionSenderImplP;
+  BlockingSend = BlockingCollectionSenderImplP.BlockingSend;
+  CollectionId = BlockingCollectionSenderImplP;
+  
+  BlockingCollectionSenderImplP.Mutex -> MutexC;
+  BlockingCollectionSenderImplP.SystemCall -> SystemCallC;
+  BlockingCollectionSenderImplP.Send -> Collector;
+  BlockingCollectionSenderImplP.Packet -> Collector;
+  BlockingCollectionSenderImplP.Leds -> LedsC;
+  BlockingCollectionSenderImplP.CollectionPacket -> Collector;
+}
+
index ecbb4a65449caa2bbdc485e5908531b36ebf53d4..527d7a629e6c9e37d4f4d76fd39e0d81679d5f94 100644 (file)
@@ -44,25 +44,16 @@ implementation {
   components BlockingCollectionSnooperP;
   components BlockingCollectionSenderP;
   components BlockingCollectionControlC;
-  
-  //Allocate enough room in the message queue for all message types.
-  //This number needs to be 255-1-12 because 
-  //(1) The max number that can be provided to the Queue underneath for its size is 255
-  //(2) uniqueN() will give you values from 0..N constituting N+1 unique numbers
-  //(3) there are 12 spaces reserved in the send queue in CtpP for forwarding messages.
-  //I don't like this implementation, but it will do for now....
-  enum {
-   FIRST_CLIENT = uniqueN(UQ_LQI_CLIENT, 255-1-12),
-  };
+  components CCollectionIdP;
   
   CCP.BlockingReceive -> BlockingCollectionReceiverP;
   CCP.BlockingSnoop -> BlockingCollectionSnooperP;
   CCP.BlockingSend -> BlockingCollectionSenderP;
   CCP.RoutingControl -> BlockingCollectionControlC;
+  CCP.CCollectionId -> CCollectionIdP;
   
   components CollectionC;
   CCP.Packet -> CollectionC;
   CCP.CollectionPacket -> CollectionC;
   CCP.RootControl -> CollectionC;
-  CollectionC.CollectionId -> CCP;
 }
diff --git a/tos/lib/tosthreads/lib/net/lqi/CCollectionIdP.nc b/tos/lib/tosthreads/lib/net/lqi/CCollectionIdP.nc
new file mode 100644 (file)
index 0000000..bc8a9e7
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+module CCollectionIdP
+{
+  provides {
+    interface CCollectionId;
+  }
+}
+
+implementation {
+  collection_id_t clientCollectionIds[uniqueCount(UQ_LQI_CLIENT)];
+  
+  command collection_id_t CCollectionId.fetch(uint8_t clientid)
+  {
+    return clientCollectionIds[clientid];
+  }
+  
+  command error_t CCollectionId.set(uint8_t clientid, collection_id_t collectionid)
+  {
+    if (clientid < uniqueCount(UQ_LQI_CLIENT)) {
+      clientCollectionIds[clientid] = collectionid;
+      
+      return SUCCESS;
+    }
+    
+    return FAIL;
+  }
+}
diff --git a/tos/lib/tosthreads/lib/net/lqi/CCollectionP.nc b/tos/lib/tosthreads/lib/net/lqi/CCollectionP.nc
new file mode 100644 (file)
index 0000000..8d2b3d5
--- /dev/null
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @author Kevin Klues <klueska@cs.stanford.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+module CCollectionP {
+  uses {
+    interface BlockingStdControl as RoutingControl;
+    interface BlockingReceive[collection_id_t id];
+    interface BlockingReceive as BlockingSnoop[collection_id_t id];
+    interface BlockingSend[uint8_t id];
+    interface Packet;
+    interface CollectionPacket;
+    interface RootControl;
+    interface CCollectionId;
+  }
+  provides {
+    interface CollectionId[uint8_t client];
+  }
+}
+implementation {
+  command collection_id_t CollectionId.fetch[uint8_t id]() {
+    return call CCollectionId.fetch(id);
+  }
+
+  error_t collectionSetCollectionId(uint8_t clientid, collection_id_t collectionid) @C() AT_SPONTANEOUS {
+    return call CCollectionId.set(clientid, collectionid);
+  }
+  
+  error_t collectionRoutingStart() @C() AT_SPONTANEOUS {
+    return call RoutingControl.start();
+  }
+  error_t collectionRoutingStop() @C() AT_SPONTANEOUS {
+    return call RoutingControl.stop();
+  }
+
+  error_t collectionReceive(message_t* m, uint32_t timeout, collection_id_t id) @C() AT_SPONTANEOUS {
+    return call BlockingReceive.receive[id](m, timeout);
+  }
+  error_t collectionSnoop(message_t* m, uint32_t timeout, collection_id_t id) @C() AT_SPONTANEOUS {
+    return call BlockingSnoop.receive[id](m, timeout);
+  }
+  error_t collectionSend(message_t* msg, uint8_t len, uint8_t id) @C() AT_SPONTANEOUS {
+    call CollectionPacket.setType(msg, call CCollectionId.fetch(id));
+    return call BlockingSend.send[id](msg, len);
+  }
+  void collectionClear(message_t* msg) @C() AT_SPONTANEOUS {
+    call Packet.clear(msg);
+  }
+  uint8_t collectionGetPayloadLength(message_t* msg) @C() AT_SPONTANEOUS {
+    return call Packet.payloadLength(msg);
+  }
+  void collectionSetPayloadLength(message_t* msg, uint8_t len) @C() AT_SPONTANEOUS {
+    call Packet.setPayloadLength(msg, len);
+  }
+  uint8_t collectionMaxPayloadLength() @C() AT_SPONTANEOUS {
+    return call Packet.maxPayloadLength();
+  }
+  void* collectionGetPayload(message_t* msg, uint8_t len) @C() AT_SPONTANEOUS {
+    return call Packet.getPayload(msg, len);
+  }
+
+  am_addr_t collectionGetOrigin(message_t* msg) @C() AT_SPONTANEOUS {
+    return call CollectionPacket.getOrigin(msg);
+  }
+  void collectionSetOrigin(message_t* msg, am_addr_t addr) @C() AT_SPONTANEOUS {
+    call CollectionPacket.setOrigin(msg, addr);
+  }
+  collection_id_t collectionGetType(message_t* msg) @C() AT_SPONTANEOUS {
+    return call CollectionPacket.getType(msg);
+  }
+  void collectionSetType(message_t* msg, collection_id_t id) @C() AT_SPONTANEOUS {
+    call CollectionPacket.setType(msg, id);
+  }
+  uint8_t collectionGetSequenceNumber(message_t* msg) @C() AT_SPONTANEOUS {
+    return call CollectionPacket.getSequenceNumber(msg);
+  }
+  void collectionSetSequenceNumber(message_t* msg, uint8_t seqno) @C() AT_SPONTANEOUS {
+    call CollectionPacket.setSequenceNumber(msg, seqno);
+  }
+
+  error_t collectionSetRoot() @C() AT_SPONTANEOUS {
+    return call RootControl.setRoot();
+  }
+  error_t collectionUnsetRoot() @C() AT_SPONTANEOUS {
+    return call RootControl.unsetRoot();
+  }
+  bool collectionIsRoot() @C() AT_SPONTANEOUS {
+    return call RootControl.isRoot();
+  }
+}
+
diff --git a/tos/lib/tosthreads/lib/net/lqi/ccollection.h b/tos/lib/tosthreads/lib/net/lqi/ccollection.h
new file mode 100644 (file)
index 0000000..e0937ec
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @author Kevin Klues <klueska@cs.stanford.edu>
+ */
+#ifndef CCOLLECTION_H
+#define CCOLLECTION_H
+
+#include "message.h"
+#include "TinyError.h"
+#include "Collection.h"
+#include "MultiHopLqi.h"
+
+#define  NEW_COLLECTION_CLIENT_ID() ((uint8_t)unique(UQ_LQI_CLIENT))
+
+#endif //CCOLLECTION_H
index 4bdfb30e5f1aee5102c5232e6194baa99b193c5d..b3967c4e02cc99e9a042c408aaab36a5fe67f909 100644 (file)
 
 /**
  * @author Kevin Klues <klueska@cs.stanford.edu>
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
  
 #ifndef TOSTHREAD_COLLECTION_H
 #define TOSTHREAD_COLLECTION_H
 
-#include "message.h"
-#include "TinyError.h"
-#include "Collection.h"
+#include "ccollection.h"
 
 extern error_t collectionRoutingStart();
 extern error_t collectionRoutingStop();
 
+extern error_t collectionSetCollectionId(uint8_t clientid, collection_id_t collectionid);
+
 extern error_t collectionReceive(message_t* m, uint32_t timeout, collection_id_t id);
 extern error_t collectionSnoop(message_t* m, uint32_t timeout, collection_id_t id);
 extern error_t collectionSend(message_t* msg, uint8_t len, collection_id_t id);
diff --git a/tos/lib/tosthreads/lib/serial/SerialActiveMessageC.nc b/tos/lib/tosthreads/lib/serial/SerialActiveMessageC.nc
new file mode 100644 (file)
index 0000000..3c88aff
--- /dev/null
@@ -0,0 +1,64 @@
+//$Id$
+
+/* "Copyright (c) 2000-2005 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * Sending active messages over the serial port.
+ *
+ * @author Philip Levis
+ * @author Ben Greenstein
+ * @date August 7 2005
+ *
+ */
+
+#include "Serial.h"
+configuration SerialActiveMessageC {
+  provides {
+    interface SplitControl;
+    interface AMSend[am_id_t id];
+    interface Receive as ReceiveDefault[am_id_t id];
+    interface Receive[am_id_t id];
+    interface Packet;
+    interface AMPacket;
+    interface PacketAcknowledgements;
+  }
+  uses interface Leds;
+}
+implementation {
+  components new SerialActiveMessageP() as AM, SerialDispatcherC;
+  components SerialPacketInfoActiveMessageP as Info, MainC;
+
+  MainC.SoftwareInit -> SerialDispatcherC;
+  Leds = SerialDispatcherC;
+  SplitControl = SerialDispatcherC;
+  
+  AMSend = AM;
+  Receive = AM.Receive;
+  ReceiveDefault = AM.ReceiveDefault;
+  Packet = AM;
+  AMPacket = AM;
+  PacketAcknowledgements = AM;
+  
+  AM.SubSend -> SerialDispatcherC.Send[TOS_SERIAL_ACTIVE_MESSAGE_ID];
+  AM.SubReceive -> SerialDispatcherC.Receive[TOS_SERIAL_ACTIVE_MESSAGE_ID];
+  
+  SerialDispatcherC.SerialPacketInfo[TOS_SERIAL_ACTIVE_MESSAGE_ID] -> Info;
+}
diff --git a/tos/lib/tosthreads/lib/serial/SerialActiveMessageP.nc b/tos/lib/tosthreads/lib/serial/SerialActiveMessageP.nc
new file mode 100644 (file)
index 0000000..e2f8caa
--- /dev/null
@@ -0,0 +1,197 @@
+//$Id$
+
+/* "Copyright (c) 2000-2005 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * Sending active messages over the serial port.
+ *
+ * @author Philip Levis
+ * @author Ben Greenstein
+ * @date August 7 2005
+ *
+ */
+
+#include <Serial.h>
+
+generic module SerialActiveMessageP () {
+  provides {
+    interface AMSend[am_id_t id];
+    interface Receive[am_id_t id];
+    interface Receive as ReceiveDefault[am_id_t id];
+    interface AMPacket;
+    interface Packet;
+    interface PacketAcknowledgements;
+  }
+  uses {
+    interface Send as SubSend;
+    interface Receive as SubReceive;
+  }
+}
+implementation {
+
+  serial_header_t* ONE getHeader(message_t* ONE msg) {
+    return TCAST(serial_header_t* ONE, (uint8_t*)msg + offsetof(message_t, data) - sizeof(serial_header_t));
+  }
+
+  serial_metadata_t* getMetadata(message_t* msg) {
+    return (serial_metadata_t*)(msg->metadata);
+  }
+  
+  command error_t AMSend.send[am_id_t id](am_addr_t dest,
+                                         message_t* msg,
+                                         uint8_t len) {
+    serial_header_t* header = getHeader(msg);
+    header->dest = dest;
+    // Do not set the source address or group, as doing so
+    // prevents transparent bridging. Need a better long-term
+    // solution for this.
+    //header->src = call AMPacket.address();
+    //header->group = TOS_AM_GROUP;
+    header->type = id;
+    header->length = len;
+
+    return call SubSend.send(msg, len);
+  }
+
+  command error_t AMSend.cancel[am_id_t id](message_t* msg) {
+    return call SubSend.cancel(msg);
+  }
+
+  command uint8_t AMSend.maxPayloadLength[am_id_t id]() {
+    return call Packet.maxPayloadLength();
+  }
+
+  command void* AMSend.getPayload[am_id_t id](message_t* m, uint8_t len) {
+    return call Packet.getPayload(m, len);
+  }
+  
+  event void SubSend.sendDone(message_t* msg, error_t result) {
+    signal AMSend.sendDone[call AMPacket.type(msg)](msg, result);
+  }
+
+  default event void AMSend.sendDone[uint8_t id](message_t* msg, error_t result) {
+    return;
+  }
+  
+  default event message_t* Receive.receive[uint8_t id](message_t* msg, void* payload, uint8_t len) {
+    return signal ReceiveDefault.receive[id](msg, payload, len);
+  }
+  default event message_t* ReceiveDefault.receive[am_id_t id](message_t* msg, void* payload, uint8_t len) {
+    return msg;
+  }
+  event message_t* SubReceive.receive(message_t* msg, void* payload, uint8_t len) {
+    return signal Receive.receive[call AMPacket.type(msg)](msg, msg->data, len);
+  }
+
+  command void Packet.clear(message_t* msg) {
+    memset(getHeader(msg), 0, sizeof(serial_header_t));
+    return;
+  }
+
+  command uint8_t Packet.payloadLength(message_t* msg) {
+    serial_header_t* header = getHeader(msg);    
+    return header->length;
+  }
+
+  command void Packet.setPayloadLength(message_t* msg, uint8_t len) {
+    getHeader(msg)->length  = len;
+  }
+  
+  command uint8_t Packet.maxPayloadLength() {
+    return TOSH_DATA_LENGTH;
+  }
+  
+  command void* Packet.getPayload(message_t* msg, uint8_t len) {
+    if (len > call Packet.maxPayloadLength()) {
+      return NULL;
+    }
+    else {
+      return (void * COUNT_NOK(len))msg->data;
+    }
+  }
+
+  command am_addr_t AMPacket.address() {
+    return 0;
+  }
+
+  command am_addr_t AMPacket.destination(message_t* amsg) {
+    serial_header_t* header = getHeader(amsg);
+    return header->dest;
+  }
+
+  command am_addr_t AMPacket.source(message_t* amsg) {
+    serial_header_t* header = getHeader(amsg);
+    return header->src;
+  }
+
+  command void AMPacket.setDestination(message_t* amsg, am_addr_t addr) {
+    serial_header_t* header = getHeader(amsg);
+    header->dest = addr;
+  }
+
+  command void AMPacket.setSource(message_t* amsg, am_addr_t addr) {
+    serial_header_t* header = getHeader(amsg);
+    header->src = addr;
+  }
+  
+  command bool AMPacket.isForMe(message_t* amsg) {
+    return TRUE;
+  }
+
+  command am_id_t AMPacket.type(message_t* amsg) {
+    serial_header_t* header = getHeader(amsg);
+    return header->type;
+  }
+
+  command void AMPacket.setType(message_t* amsg, am_id_t type) {
+    serial_header_t* header = getHeader(amsg);
+    header->type = type;
+  }
+
+  async command error_t PacketAcknowledgements.requestAck( message_t* msg ) {
+    return FAIL;
+  }
+  async command error_t PacketAcknowledgements.noAck( message_t* msg ) {
+    return SUCCESS;
+  }
+  
+  command void AMPacket.setGroup(message_t* msg, am_group_t group) {
+    serial_header_t* header = getHeader(msg);
+    header->group = group;
+  }
+
+  command am_group_t AMPacket.group(message_t* msg) {
+    serial_header_t* header = getHeader(msg);
+    return header->group;
+  }
+
+  command am_group_t AMPacket.localGroup() {
+    return TOS_AM_GROUP;
+  }
+
+  async command bool PacketAcknowledgements.wasAcked(message_t* msg) {
+    return FALSE;
+  }
+
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/BigCrc.nc b/tos/lib/tosthreads/lib/tinyld/BigCrc.nc
new file mode 100644 (file)
index 0000000..248ef1a
--- /dev/null
@@ -0,0 +1,4 @@
+interface BigCrc {
+  command error_t computeCrc(void* buf, uint16_t len);
+  event void computeCrcDone(void* buf, uint16_t len, uint16_t crc, error_t error);
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/BigCrcC.nc b/tos/lib/tosthreads/lib/tinyld/BigCrcC.nc
new file mode 100644 (file)
index 0000000..ed90bfa
--- /dev/null
@@ -0,0 +1,12 @@
+configuration BigCrcC {
+  provides interface BigCrc;
+}
+
+implementation {
+  components CrcC,
+             BigCrcP;
+  
+  BigCrc = BigCrcP;
+  
+  BigCrcP.Crc -> CrcC;
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/BigCrcP.nc b/tos/lib/tosthreads/lib/tinyld/BigCrcP.nc
new file mode 100644 (file)
index 0000000..6565bd4
--- /dev/null
@@ -0,0 +1,44 @@
+module BigCrcP {
+  provides interface BigCrc;
+  uses interface Crc;
+}
+
+implementation {
+  bool isBusy = FALSE;
+  void* inbuf;
+  uint16_t inlen;
+  uint16_t pos;
+  uint16_t computedCrc;
+
+  task void computeCrc()
+  {
+    uint8_t len = 0xFF;
+    if (inlen < 0xFF) {
+      len = inlen;
+    }
+    computedCrc = call Crc.seededCrc16(computedCrc, inbuf + pos, len);
+    inlen -= len;
+    pos += len;
+    
+    if (inlen > 0) {
+      post computeCrc();
+    } else {
+      isBusy = FALSE;
+      signal BigCrc.computeCrcDone(inbuf, pos + 1, computedCrc, SUCCESS);
+    }
+  }
+
+  command error_t BigCrc.computeCrc(void* buf, uint16_t len)
+  {
+    if (isBusy == TRUE) {
+      return EBUSY;
+    }
+    
+    inbuf = buf;
+    inlen = len;
+    computedCrc = pos = 0;
+    post computeCrc();
+    
+    return SUCCESS;
+  }
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/DynamicLoader.h b/tos/lib/tosthreads/lib/tinyld/DynamicLoader.h
new file mode 100755 (executable)
index 0000000..469a36d
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#ifndef DYNAMICLOADER_H
+#define DYNAMICLOADER_H
+
+//#defines for setting up which set of apis the dynamic loader 
+//should recognize.  This should eventually move into a file that 
+//gets #included in here, but for now we set the defaults here.
+
+#ifdef TOSTHREAD_TENET
+#define ApiForDynamicLoaderC TosThreadTenetApiC
+#define SLCS_TYPES_FILE      "tosthread_tenet_slcs_types.h"
+#else
+#define ApiForDynamicLoaderC TosThreadApiC
+#define SLCS_TYPES_FILE      "tosthread_slcs_types.h"
+#endif
+
+#define TOSTHREAD_DYNAMIC_LOADER
+
+#ifndef DISABLE_LOADER_FLASH
+#include "StorageVolumes.h"
+#endif
+
+enum {
+  READSOURCE_MEMORY = 0xFF,
+};
+
+#endif
diff --git a/tos/lib/tosthreads/lib/tinyld/DynamicLoader.nc b/tos/lib/tosthreads/lib/tinyld/DynamicLoader.nc
new file mode 100755 (executable)
index 0000000..102b8c3
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "thread.h"
+
+interface DynamicLoader
+{
+  command error_t loadFromFlash(uint8_t volumeId);
+  event void loadFromFlashDone(uint8_t volumeId, tosthread_t id, error_t error);
+  command error_t loadFromMemory(void *addr);
+  event void loadFromMemoryDone(void *addr, tosthread_t id, error_t error);
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/DynamicLoaderC.nc b/tos/lib/tosthreads/lib/tinyld/DynamicLoaderC.nc
new file mode 100755 (executable)
index 0000000..9adcdc8
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ */
+#include "DynamicLoader.h"
+
+configuration DynamicLoaderC
+{
+  provides interface DynamicLoader;
+}
+
+implementation
+{
+  components MainC, 
+             DynamicLoaderP,
+             LedsC, NoLedsC,
+             LoadSourceMapC,
+             DynamicThreadC,
+             ReferenceCounterC,
+             TinyThreadSchedulerC;
+
+  DynamicLoader = DynamicLoaderP;
+
+  DynamicLoaderP <- MainC.SoftwareInit;
+  DynamicLoaderP.Leds -> LedsC;
+  DynamicLoaderP.ImageRead -> LoadSourceMapC;
+  DynamicLoaderP.DynamicThread -> DynamicThreadC;
+  DynamicLoaderP.ReferenceCounter -> ReferenceCounterC;
+  DynamicLoaderP.ThreadNotification -> DynamicThreadC;
+  DynamicLoaderP.ThreadScheduler -> TinyThreadSchedulerC;
+  
+  components ApiForDynamicLoaderC;
+  components PMManagerC;
+  DynamicLoaderP.PMManager -> PMManagerC;
+
+#ifndef DISABLE_LOADER_USERBUTTON
+  components UserButtonC;
+  DynamicLoaderP.UserButton -> UserButtonC;
+#endif
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/DynamicLoaderP.nc b/tos/lib/tosthreads/lib/tinyld/DynamicLoaderP.nc
new file mode 100755 (executable)
index 0000000..37095b2
--- /dev/null
@@ -0,0 +1,471 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ * @author Razvan Musaloiu-E. <razvanm@cs.jhu.edu>
+ */
+#include SLCS_TYPES_FILE
+#include "thread.h"
+
+module DynamicLoaderP
+{
+  provides {
+    interface Init;
+    interface DynamicLoader;
+  }
+  
+  uses {
+    interface Leds;
+    interface BlockRead as ImageRead[uint8_t id];
+    interface DynamicThread;
+    interface ThreadNotification[uint8_t id];
+    interface ThreadScheduler;
+    interface ReferenceCounter;
+    interface PMManager;
+#ifndef DISABLE_LOADER_USERBUTTON
+    interface UserButton;
+#endif
+  }
+}
+
+implementation
+{ 
+  uint8_t *code;   // Points to first byte of the program code in the internal flash
+  uint8_t *tablesMemory;
+  void *gVarMemory;
+  struct prog_desc prog_desc;
+  init_block_t *proc;
+  
+  uint16_t codePtr;   // Records what code has been copied to the internal flash
+  uint16_t nextAddr;
+  uint8_t *nextTask_chain;   // Used to update the next patching address in a chain
+  
+  uint8_t readSource;   // Loads from flash or memory
+  uint16_t readSourceOffset;   // If loading from memory, then this is effectively the passed-in memory address  
+  error_t retError = FAIL;
+  tosthread_t handler;
+  uint16_t threadCodeSizes[TOSTHREAD_MAX_NUM_THREADS];
+  uint16_t codeFirstAddrs[TOSTHREAD_MAX_NUM_THREADS];
+  
+  async event void ThreadNotification.justCreated[uint8_t id]()
+  {
+    thread_t *t = call ThreadScheduler.threadInfo(id);
+    if(t->init_block != NULL) {
+      call ReferenceCounter.increment(&(t->init_block->thread_counter));
+    }
+  }
+  
+  async event void ThreadNotification.aboutToDestroy[uint8_t id]()
+  {
+    thread_t *t = call ThreadScheduler.threadInfo(id);
+    if(t->init_block != NULL) {
+      call ReferenceCounter.decrement(&(t->init_block->thread_counter));
+    }
+  }
+
+  task void loadDoneTask()
+  {
+    if (retError != SUCCESS)
+      handler = TOSTHREAD_INVALID_THREAD_ID;
+
+    if (readSource == READSOURCE_MEMORY) {
+      signal DynamicLoader.loadFromMemoryDone(((void *)readSourceOffset), handler, retError);
+    } else {
+      signal DynamicLoader.loadFromFlashDone(readSource, handler, retError);
+    }
+  }
+    
+  void initProgDesc()
+  {
+    prog_desc.main_addr = 0;
+    prog_desc.alloc_count = 0;
+    prog_desc.g_reloc_count = 0;
+    prog_desc.l_reloc_count = 0;
+    prog_desc.code_count = 0;
+    prog_desc.patch_table_count = 0;
+
+    prog_desc.loading_stage = 0;
+    codePtr = 0;
+  }
+
+  void errorHandler()
+  {
+    call Leds.set(7);
+    
+    if (tablesMemory != NULL) { free(tablesMemory); tablesMemory = NULL; }
+    if (gVarMemory != NULL) { free(gVarMemory); gVarMemory = NULL; }
+    if (proc != NULL) { free(proc); proc = NULL; }
+    initProgDesc();
+    
+    retError = FAIL;
+    post loadDoneTask();
+  }
+
+  void run_proc(void *arg)
+  {
+    init_block_t* curProc = arg;
+    thread_t* t = call ThreadScheduler.currentThreadInfo();
+    t->init_block = curProc;
+    
+    (*(curProc->init_ptr))(curProc->init_arg);
+    call ReferenceCounter.waitOnValue(&(curProc->thread_counter), 0);
+    
+    call PMManager.release(codeFirstAddrs[t->id], threadCodeSizes[t->id]);
+    codeFirstAddrs[t->id] = 0;
+    threadCodeSizes[t->id] = 0;
+    if (curProc->globals != NULL) {
+      free(curProc->globals);
+    }
+    free(curProc);
+  }
+
+  task void start_prog()
+  {
+    free(tablesMemory);
+    proc = malloc(sizeof(init_block_t));
+    proc->globals = gVarMemory;
+    proc->init_ptr = (void *)((uint16_t)code + prog_desc.main_addr);
+    proc->init_arg = NULL;
+    call ReferenceCounter.init( &(proc->thread_counter) );
+    
+    if (call DynamicThread.create(&handler, run_proc, proc, 200) == SUCCESS) {  
+      codeFirstAddrs[handler] = (uint16_t)code;
+      threadCodeSizes[handler] = prog_desc.code_count;
+      retError = SUCCESS;
+      post loadDoneTask();
+    } else {
+      retError = FAIL;
+      post loadDoneTask();
+      if (proc->globals != NULL) {
+        free(proc->globals);
+      }
+      free(proc);
+    }
+    
+    initProgDesc();
+  }
+
+  // Gets write access to the internal flash
+  void eeprom_w()
+  {
+    FCTL2 = FWKEY + FSSEL1 + FN2;   // selects SMCLK and divides it by 4
+    FCTL3 = FWKEY;   // enables the writing/erasing by clearing the LOCK bit
+    FCTL1 = FWKEY + WRT;   // enables the writing
+  }
+
+  // Gets read-only access to the internal flash
+  void eeprom_r()
+  {
+    FCTL1 = FWKEY;   // Clear WRT bit
+    FCTL3 = FWKEY + LOCK;   // disabling the writing/erasing
+  }
+
+  // Calculates where should the code be placed in the internal flash
+  /*
+  uint16_t eeprom_code_addr()
+  {
+    uint16_t addr;
+    
+    addr = (((prog_desc.code_count - 1) / 512) + 1) * 512;   // Spaces needed for the code
+    addr = 0xFFFF - 512 - addr + 1;   // The 1 is to align the code
+    
+    return addr; 
+  }
+  */
+
+  // Loads program image meta data
+  void loader_metaData()
+  {
+    prog_desc.patch_table_count = prog_desc.alloc_count +
+                                  prog_desc.g_reloc_count +
+                                  prog_desc.l_reloc_count;
+    prog_desc.code_offset = sizeof(prog_desc.main_addr) +
+                            sizeof(prog_desc.alloc_count) +
+                            sizeof(prog_desc.alloc_size) +
+                            sizeof(prog_desc.g_reloc_count) +
+                            sizeof(prog_desc.l_reloc_count) +
+                            sizeof(prog_desc.datasec_count) +
+                            sizeof(prog_desc.code_count) +
+                            (prog_desc.patch_table_count * 4) +
+                            (prog_desc.datasec_count * 6);
+    
+    if (prog_desc.patch_table_count > 0 || prog_desc.datasec_count > 0) {
+      if ((prog_desc.patch_table_count * 4) > (prog_desc.datasec_count * 6)) {
+        tablesMemory = malloc(prog_desc.patch_table_count * 4);
+      } else {
+        tablesMemory = malloc(prog_desc.datasec_count * 6);
+      }
+    } else {
+      tablesMemory = NULL;
+    }
+  }
+
+  // Prepares the patch table before patching addresses in the binary code
+  void loader_patch_table()
+  {
+    uint16_t i, tempUInt16 = 0;
+    
+    // Find out the total space global variables need, and malloc
+    /*
+    for (i = 0; i < (prog_desc.alloc_count * 4); i+=4) {
+      tempUInt16 += *((uint16_t *)&tablesMemory[i]);
+      *((uint16_t *)&tablesMemory[i]) = tempUInt16 - *((uint16_t *)&tablesMemory[i]);
+    }
+    */
+    if (prog_desc.alloc_size > 0) {
+      gVarMemory = malloc(prog_desc.alloc_size);
+      memset(gVarMemory, 0, prog_desc.alloc_size);
+    } else {
+      gVarMemory = NULL;
+    }
+    
+    // Some "real" addresses need offsets added. For example, local relocation table entries need
+    // the starting code address
+    for (i = 0; i < (prog_desc.patch_table_count * 4); i+=4) {
+      if (i < (prog_desc.alloc_count * 4)) {
+        tempUInt16 = (uint16_t)gVarMemory;   // Allocation table needs memory's offset
+      } else if (i < ((prog_desc.alloc_count + prog_desc.g_reloc_count) * 4)) {
+        tempUInt16 = 0;   // Global relocation table doesn't need anything
+      } else {
+        tempUInt16 = (uint16_t)code;   // Local relocation table needs code's offset
+      }
+      *((uint16_t *)&(tablesMemory[i])) = *((uint16_t *)&(tablesMemory[i])) + tempUInt16;   // Writes the real address
+    }
+    
+    // Converts function IDs in global relocation table to real addresses
+    for (i = (prog_desc.alloc_count * 4); i < ((prog_desc.alloc_count + prog_desc.g_reloc_count) * 4); i+=4) {
+      tempUInt16 = *((uint16_t *)&tablesMemory[i]);   // Gets function ID
+      tempUInt16 = (uint16_t)fun[tempUInt16].addr;   // Gets the real address of the function ID
+      *((uint16_t *)&tablesMemory[i]) = tempUInt16;   // Writes the real address
+    }
+  }
+  
+  void loader_addr_1()
+  {
+    uint16_t i, laddr = 0, raddr = 0;
+    
+    // Resets before start
+    nextTask_chain = 0x0;
+    nextAddr = 0;
+    
+    // Gets the next task by searching for the lowest next patching address
+    raddr = 0xFFFF;   // Temp variable to store the minimum patching address so far
+    laddr = 0;   // Temp variable to store the current patching address
+    for (i = 0; i < (prog_desc.patch_table_count * 4); i+=4) {
+      laddr = *((uint16_t *)&tablesMemory[i + 2]);
+      
+      if (((uint16_t)nextTask_chain == 0x0 && laddr != 0xFFFF) || 
+           raddr > laddr) {
+        nextTask_chain = &(tablesMemory[i]);
+        raddr = laddr;
+      }
+    }
+    
+    if (nextTask_chain != 0x0) {
+      // Gets the next patching address in the chain from the flash
+      raddr = *((uint16_t *)&nextTask_chain[2]);
+      call ImageRead.read[readSource](readSourceOffset + prog_desc.code_offset + raddr, 
+                                      &nextAddr, 
+                                      2);
+    } else {
+      // Copies the rest of the binary code
+      call ImageRead.read[readSource](readSourceOffset + prog_desc.code_offset + codePtr, 
+                                      &(code[codePtr]), 
+                                      prog_desc.code_count - codePtr);
+      prog_desc.loading_stage++;
+    }
+  }
+  
+  // Patches the part of binary code that needs "real" addresses
+  void loader_addr_2()
+  {
+    uint16_t laddr;
+    
+    laddr = *((uint16_t *)&nextTask_chain[2]);   // Gets the current patching address
+    
+    // Updates the chain with the next patching address
+    if (nextAddr == 0x0000) {
+      nextAddr = 0xFFFF;   // End of chain, marks it with a big number
+    }
+    *((uint16_t *)&nextTask_chain[2]) = nextAddr;
+    
+    // Patches address in the binary code
+    *((uint16_t *)&code[laddr]) = *((uint16_t *)&nextTask_chain[0]);
+    
+    // Copies the binary code between the last patching address and the current patching address
+    call ImageRead.read[readSource](readSourceOffset + prog_desc.code_offset + codePtr, 
+                                    &(code[codePtr]), 
+                                    laddr - codePtr);
+    codePtr = laddr + 2;   // Notes up to what location in the binary code we have copied
+  }
+  
+  void loader_datasec()
+  {
+    uint16_t i, j;
+    
+    for (i = 0; i < (prog_desc.datasec_count * 6); i+=6) {
+      uint16_t destAddr = *((uint16_t *)&(tablesMemory[i])) + (uint16_t)gVarMemory;   // Writes the real address
+      uint16_t srcAddr = *((uint16_t *)&(tablesMemory[i + 2])) + (uint16_t)code;   // Writes the real address
+      uint16_t size = *((uint16_t *)&(tablesMemory[i + 4]));
+      
+      for (j = 0; j < size; j++) {
+        ((uint8_t *)((void *)(destAddr + j)))[0] = ((uint8_t *)((void *)(srcAddr + j)))[0];
+        //*((uint8_t *)&code[destAddr + j]) = *((uint8_t *)&code[srcAddr + j]);
+      }
+    }
+  }
+  
+  void loadProgram()
+  {
+    error_t error = SUCCESS;
+    switch (prog_desc.loading_stage) {
+      case 0:
+        // Loads meta data to memory array
+        error = call ImageRead.read[readSource](readSourceOffset + 0, 
+                                                &prog_desc, 
+                                                7 * 2);
+        if (error == SUCCESS) {
+          prog_desc.loading_stage++;   // Moves to next loading phase
+        } else {
+          errorHandler();
+        }
+        break;
+      
+      case 1:
+        loader_metaData();   // Gets meta data
+        code = (void *) call PMManager.request(prog_desc.code_count);   // Gets the location of where the code will be copied to
+        
+        if ((uint16_t)code != 0xFFFF) {
+          // Loads patch table to memory array
+          error = call ImageRead.read[readSource](readSourceOffset + 7 * 2, 
+                                                  tablesMemory, 
+                                                  prog_desc.patch_table_count * 4);
+          if (error == SUCCESS) {
+            prog_desc.loading_stage++;   // Moves to next loading phase
+          } else {
+            errorHandler();
+          }
+        } else {
+          errorHandler();
+        }
+        
+        break;
+      
+      case 2:
+        loader_patch_table();
+        
+        eeprom_w();   // Gets write-access to internal flash
+        prog_desc.loading_stage++;   // Moves to next loading phase
+      
+      case 3:
+        loader_addr_1();
+        break;
+      
+      case 4:
+        eeprom_r();   // Locks the internal flash back
+        
+        error = call ImageRead.read[readSource](readSourceOffset + 7 * 2 + prog_desc.patch_table_count * 4, 
+                                                tablesMemory, 
+                                                prog_desc.datasec_count * 6);
+        if (error == SUCCESS) {
+          prog_desc.loading_stage++;   // Moves to next loading phase
+        } else {
+          errorHandler();
+        }
+        
+        break;
+      case 5:
+        loader_datasec();
+        prog_desc.loading_stage++;
+        
+      case 6:
+        post start_prog();
+        break;
+    }
+  }
+  
+  command error_t Init.init()
+  {
+    int i;
+    for (i = 0; i < TOSTHREAD_MAX_NUM_THREADS; i++) {
+      threadCodeSizes[i] = 0;
+      codeFirstAddrs[i] = 0;
+    }
+    initProgDesc();
+    return SUCCESS;
+  }
+  
+  task void taskLoadProgram()
+  {
+    loadProgram();
+  }
+  
+  error_t start_load(uint8_t in_readSource, uint16_t in_readSourceOffset)
+  {
+    if (prog_desc.loading_stage == 0) {
+      uint16_t i;
+      call Leds.set(7);
+      for (i = 0; i < 2000; i++) { }
+      call Leds.set(0);
+      
+      readSource = in_readSource;
+      readSourceOffset = in_readSourceOffset;
+      post taskLoadProgram();   // Start Loading
+      
+      return SUCCESS;
+    }
+    
+    return EBUSY;
+  }
+  
+  command error_t DynamicLoader.loadFromFlash(uint8_t volumeId) { return start_load(volumeId, 0); }
+  
+  command error_t DynamicLoader.loadFromMemory(void *addr) { return start_load(READSOURCE_MEMORY, (uint16_t)addr); }
+  
+  event void ImageRead.readDone[uint8_t id](storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    if (error == SUCCESS) {
+      if (buf == &nextAddr) {
+        loader_addr_2();
+      } else {
+        post taskLoadProgram();
+      }
+    } else {
+      errorHandler();
+    }
+  }
+
+#ifndef DISABLE_LOADER_USERBUTTON
+  event void UserButton.fired()
+  {
+     call DynamicLoader.loadFromFlash(VOLUME_MICROEXEIMAGE);
+  }
+#endif
+  
+  event void ImageRead.computeCrcDone[uint8_t id](storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error) {}
+  
+  default command error_t ImageRead.read[uint8_t id](storage_addr_t addr, void *buf, storage_len_t len) { return FAIL; }
+  default event void DynamicLoader.loadFromFlashDone(uint8_t volumeId, tosthread_t id, error_t error) {}
+  default event void DynamicLoader.loadFromMemoryDone(void *addr, tosthread_t id, error_t error) {}
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/LoadSourceMapC.nc b/tos/lib/tosthreads/lib/tinyld/LoadSourceMapC.nc
new file mode 100755 (executable)
index 0000000..8ccd4bb
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+configuration LoadSourceMapC
+{
+  provides interface BlockRead[uint8_t id];
+}
+
+implementation
+{
+  components LoadSourceMapP,
+        #ifdef DISABLE_LOADER_FLASH
+             NullVolumeMapC as VolumeMapC,
+        #else
+             VolumeMapC,
+        #endif
+             MemoryStorageC;
+  
+  BlockRead = LoadSourceMapP;
+  
+  LoadSourceMapP.SubBlockRead -> VolumeMapC;
+  LoadSourceMapP.SubMemoryRead -> MemoryStorageC;
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/LoadSourceMapP.nc b/tos/lib/tosthreads/lib/tinyld/LoadSourceMapP.nc
new file mode 100755 (executable)
index 0000000..ca55766
--- /dev/null
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "DynamicLoader.h"
+
+module LoadSourceMapP
+{
+  provides interface BlockRead[uint8_t id];
+  
+  uses {
+    interface BlockRead as SubBlockRead[uint8_t id];
+    interface BlockRead as SubMemoryRead;
+  }
+}
+
+implementation
+{
+  event void SubMemoryRead.readDone(storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    signal BlockRead.readDone[READSOURCE_MEMORY](addr, buf, len, error);
+  }
+  
+  event void SubBlockRead.readDone[uint8_t id](storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    signal BlockRead.readDone[id](addr, buf, len, error);
+  }
+                          
+  command error_t BlockRead.read[uint8_t id](storage_addr_t addr, void* buf, storage_len_t len)
+  {
+    error_t error = FAIL;
+    
+    if (id == READSOURCE_MEMORY) {
+      error = call SubMemoryRead.read(addr, buf, len);
+    } else {
+      error = call SubBlockRead.read[id](addr, buf, len);
+    }
+    
+    return error;
+  }
+
+  event void SubMemoryRead.computeCrcDone(storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error)
+  {
+    signal BlockRead.computeCrcDone[READSOURCE_MEMORY](addr, len, crc, error);
+  }
+
+  event void SubBlockRead.computeCrcDone[uint8_t id](storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error)
+  {
+    signal BlockRead.computeCrcDone[id](addr, len, crc, error);
+  }
+  
+  command error_t BlockRead.computeCrc[uint8_t id](storage_addr_t addr, storage_len_t len, uint16_t crc)
+  {
+    error_t error = FAIL;
+    
+    if (id == READSOURCE_MEMORY) {
+      error = call SubMemoryRead.computeCrc(addr, len, crc);
+    } else {
+      error = call SubBlockRead.computeCrc[id](addr, len, crc);
+    }
+    
+    return error;
+  }
+  
+  command storage_len_t BlockRead.getSize[uint8_t id]()
+  {
+    storage_len_t len;
+    
+    if (id == READSOURCE_MEMORY) {
+      len = call SubMemoryRead.getSize();
+    } else {
+      len = call SubBlockRead.getSize[id]();
+    }
+    
+    return len;
+  }
+  
+  default command error_t SubBlockRead.read[uint8_t id](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t SubBlockRead.computeCrc[uint8_t id](storage_addr_t addr, storage_len_t len, uint16_t crc) { return FAIL; }
+  default command storage_len_t SubBlockRead.getSize[uint8_t id]() { return 0; }
+  default event void BlockRead.readDone[uint8_t id](storage_addr_t addr, void* buf, storage_len_t len, error_t error) {}
+  default event void BlockRead.computeCrcDone[uint8_t id](storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error) {}
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/MemoryStorageC.nc b/tos/lib/tosthreads/lib/tinyld/MemoryStorageC.nc
new file mode 100755 (executable)
index 0000000..8134e53
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+configuration MemoryStorageC
+{
+  provides interface BlockRead;
+}
+
+implementation
+{
+  components MemoryStorageP,
+             CrcC;
+  
+  BlockRead = MemoryStorageP;
+  
+  MemoryStorageP.Crc -> CrcC;
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/MemoryStorageP.nc b/tos/lib/tosthreads/lib/tinyld/MemoryStorageP.nc
new file mode 100755 (executable)
index 0000000..2782cc7
--- /dev/null
@@ -0,0 +1,56 @@
+module MemoryStorageP
+{
+  provides interface BlockRead;
+  uses interface Crc;
+}
+
+implementation
+{
+  storage_addr_t retAddr;
+  void *retBuf;
+  storage_len_t retLen;
+  uint16_t retCrc;
+
+  task void taskReadDone()
+  {
+    signal BlockRead.readDone(retAddr, retBuf, retLen, SUCCESS);
+  }
+
+  command error_t BlockRead.read(storage_addr_t addr, void* buf, storage_len_t len)
+  {
+    storage_len_t i;
+    uint8_t *from = (uint8_t *)((void *)((uint16_t)addr));
+    
+    for (i = 0; i < len; i++) {
+      ((uint8_t *)buf)[i] = from[i];
+    }
+    
+    retAddr = addr;
+    retBuf = buf;
+    retLen = len;
+    post taskReadDone();
+    return SUCCESS;
+  }
+  
+  task void taskCrcDone()
+  {
+    signal BlockRead.computeCrcDone(retAddr, retLen, retCrc, SUCCESS);
+  }
+  
+  command error_t BlockRead.computeCrc(storage_addr_t addr, storage_len_t len, uint16_t crc)
+  {
+    retCrc = call Crc.seededCrc16(crc, (void *)addr, len);
+    retAddr = addr;
+    retLen = len;
+    post taskCrcDone();
+    return SUCCESS;
+  }
+  
+  command storage_len_t BlockRead.getSize()
+  {
+    return 0;   // Not sure what to do
+  }
+  
+  default event void BlockRead.readDone(storage_addr_t addr, void* buf, storage_len_t len, error_t error) {}
+  default event void BlockRead.computeCrcDone(storage_addr_t addr, storage_len_t len, uint16_t crc, error_t error) {}
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/NullVolumeMapC.nc b/tos/lib/tosthreads/lib/tinyld/NullVolumeMapC.nc
new file mode 100755 (executable)
index 0000000..0c0084f
--- /dev/null
@@ -0,0 +1,18 @@
+
+/**
+ * @author Jeongyeup Paek <jpaek@enl.usc.edu>
+ */
+
+#include "DynamicLoader.h"
+
+module NullVolumeMapC
+{
+  provides interface BlockRead[uint8_t id];
+}
+
+implementation
+{
+  command error_t BlockRead.read[uint8_t id](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  command error_t BlockRead.computeCrc[uint8_t id](storage_addr_t addr, storage_len_t len, uint16_t crc) { return FAIL; }
+  command storage_len_t BlockRead.getSize[uint8_t id]() { return 0; }
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/PMManager.nc b/tos/lib/tosthreads/lib/tinyld/PMManager.nc
new file mode 100644 (file)
index 0000000..01b44f1
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+interface PMManager
+{
+  command uint16_t request(uint16_t size);
+  command void release(uint16_t startingAddr, uint16_t size);
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/PMManagerC.nc b/tos/lib/tosthreads/lib/tinyld/PMManagerC.nc
new file mode 100644 (file)
index 0000000..ab7988b
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+configuration PMManagerC
+{
+  provides interface PMManager;
+}
+
+implementation
+{
+  components MainC,
+             PMManagerP,
+             LedsC,
+             BitArrayUtilsC;
+  
+  PMManager = PMManagerP;
+  
+  MainC.SoftwareInit -> PMManagerP;
+  PMManagerP.BitArrayUtils -> BitArrayUtilsC;
+  PMManagerP.Leds -> LedsC;
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/PMManagerP.nc b/tos/lib/tosthreads/lib/tinyld/PMManagerP.nc
new file mode 100644 (file)
index 0000000..35558e5
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+module PMManagerP {
+  provides {
+    interface Init;
+    interface PMManager;
+  }
+  
+  uses {
+    interface BitArrayUtils;
+    interface Leds;
+  }
+}
+
+implementation {
+  uint16_t HOST_ROM_SIZE = 0;   // Set by tos-set-symbol
+  uint16_t SEGMENT_SIZE = 512;   // For telosb, the internal flash segment size is 512 bytes
+  uint16_t FLASH_ROM_START_ADDR = 0x4000;   // For telosb, the program memory starts at 0x4000
+  uint16_t FLASH_ROM_END_ADDR = 0xFDFF;   // Last free byte (the last segment is used for interrupt vector)
+  
+  uint16_t numFreeSegments = 0;
+  uint8_t *segmentBitArray;
+  
+  command error_t Init.init()
+  {
+    uint16_t numBytes;
+    
+    // Adjust FLASH_ROM_START_ADDR to account for the code loaded with PMManager
+    if (HOST_ROM_SIZE == 0) {
+      // Should not be here at all
+      // return FAIL;
+    } else {
+      FLASH_ROM_START_ADDR += (((HOST_ROM_SIZE - 1) / SEGMENT_SIZE) + 1) * SEGMENT_SIZE;
+    }
+    
+    // Calculates the number of available segments
+    numFreeSegments = FLASH_ROM_END_ADDR - FLASH_ROM_START_ADDR + 1;
+    numFreeSegments = ((numFreeSegments - 1) / SEGMENT_SIZE) + 1;
+    
+    // Initializes an bit array to track the status of available segments
+    numBytes = ((numFreeSegments - 1) / 8) + 1;
+    segmentBitArray = malloc(numBytes);
+    call BitArrayUtils.clrArray(segmentBitArray, numBytes);
+    
+    return SUCCESS;
+  }
+  
+  uint16_t bitIndexToAddress(uint16_t bitIndex)
+  {
+    return FLASH_ROM_START_ADDR + (bitIndex * SEGMENT_SIZE);
+  }
+
+  void eraseSegment(void* addr)
+  {
+    FCTL2 = FWKEY + FSSEL1 + FN2;
+    FCTL3 = FWKEY;
+    FCTL1 = FWKEY + ERASE;
+    *((uint16_t *)addr) = 0;
+    FCTL1 = FWKEY;
+    FCTL3 = FWKEY + LOCK;
+  }
+
+  command uint16_t PMManager.request(uint16_t size)
+  {    
+    if (size > 0) {
+      uint8_t numSegments = ((size - 1) / SEGMENT_SIZE) + 1;   // Number of segments needed to cover size
+      int i;
+      
+      for (i = (numFreeSegments - 1); i >= 0; i--) {
+        if (call BitArrayUtils.getBit(segmentBitArray, i) == FALSE) {
+          int j, tempNumSegments = numSegments - 1;
+          
+          for (j = (i - 1); j >= 0 && tempNumSegments > 0; ) {
+            // Checks if there are enough consecutive free segments
+            if (call BitArrayUtils.getBit(segmentBitArray, j) == TRUE) {
+              break;
+            } else {
+              j--;
+              tempNumSegments--;
+            }
+          }
+          j++;
+          if ((i - j + 1) >= numSegments) {
+            // There are enough consecutive free segments (starting segment index (j + 1))
+            int k;
+            for (k = j; k <= i; k++) {
+              eraseSegment((void *)bitIndexToAddress(k));   // Erase segment content
+              call BitArrayUtils.setBit(segmentBitArray, k);   // Mark segment as occupied
+            }
+            
+            return bitIndexToAddress(j);
+          } else {
+            i = j;
+          }
+        }
+      }
+    }
+    
+    return 0xFFFF;
+  }
+  
+  command void PMManager.release(uint16_t startingAddr, uint16_t size)
+  {
+    if ((startingAddr >= FLASH_ROM_START_ADDR && startingAddr <= FLASH_ROM_END_ADDR) &&
+        size > 0) {
+      uint8_t numSegments = ((size - 1) / SEGMENT_SIZE) + 1;   // Number of segments needed to cover size
+      uint8_t startingSegment = (startingAddr - FLASH_ROM_START_ADDR) / SEGMENT_SIZE;
+      int i;
+      
+      for (i = 0; i < numSegments && (i + startingSegment) < numFreeSegments; i++) {
+        call BitArrayUtils.clrBit(segmentBitArray, i + startingSegment);   // Mark the segment as free
+      }
+    }
+  }
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/TosThreadApiC.nc b/tos/lib/tosthreads/lib/tinyld/TosThreadApiC.nc
new file mode 100644 (file)
index 0000000..41128da
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2008 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * @author Kevin Klues <klueska@cs.stanford.edu>
+ */
+#include "tosthread.h"
+
+configuration TosThreadApiC {
+}
+implementation {
+  //Here are all the components that implement the Tosthread API calls
+  components CThreadC;
+  #if defined(PRINTF_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components PrintfC;
+  #endif
+  #if defined(TOSTHREAD_QUEUE_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CQueueC;
+  #endif
+  #if defined(TOSTHREAD_LINKED_LIST_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CLinkedListC;
+  #endif
+  #if defined(TOSTHREAD_THREADSYNC_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CThreadSynchronizationC;
+  #endif
+  #if defined(TOSTHREAD_LEDS_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CLedsC;
+  #endif
+  #if defined(TOSTHREAD_AMRADIO_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CAMRadioC;
+  #endif
+  #if defined(TOSTHREAD_AMSERIAL_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CAMSerialC;
+  #endif
+  #if defined(TOSTHREAD_BLOCKSTORAGE_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CBlockStorageC;
+  #endif 
+  #if defined(TOSTHREAD_BLOCKSTORAGE_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CConfigStorageC;
+  #endif 
+  #if defined(TOSTHREAD_LOGSTORAGE_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CLogStorageC;
+  #endif 
+  #if defined(TOSTHREAD_COLLECTION_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+  //  components CCollectionC;
+  #endif 
+  
+  //Telosb sensorboard specific.
+  #if defined(TOSTHREAD_HAMAMATSUS1087_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CHamamatsuS1087ParC;
+  #endif
+  #if defined(TOSTHREAD_HAMAMATSUS10871_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CHamamatsuS10871TsrC;
+  #endif
+  #if defined(TOSTHREAD_SENSIRIONSHT11_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+    components CSensirionSht11C;
+  #endif
+  
+  //Universal sensorboard specific
+  #if defined(TOSTHREAD_SINESENSOR_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+  //  components CSineSensorC;
+  #endif
+  
+  //Basicsb sensorboard specific
+  #if defined(TOSTHREAD_PHOTO_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+  //  components CPhotoC;
+  #endif
+  #if defined(TOSTHREAD_TEMP_H) || defined(TOSTHREAD_DYNAMIC_LOADER)
+  //  components CTempC;
+  #endif
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/UserButton.nc b/tos/lib/tosthreads/lib/tinyld/UserButton.nc
new file mode 100755 (executable)
index 0000000..8b10c14
--- /dev/null
@@ -0,0 +1,4 @@
+interface UserButton
+{
+  event void fired();
+}
diff --git a/tos/lib/tosthreads/lib/tinyld/UserButtonC.nc b/tos/lib/tosthreads/lib/tinyld/UserButtonC.nc
new file mode 100755 (executable)
index 0000000..29ac64e
--- /dev/null
@@ -0,0 +1,48 @@
+/* "Copyright (c) 2000-2003 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * Init/start/stop the user button with StdControl and get interrupt events
+ * when the button is released with MSP430Event.
+ *
+ * @author Cory Sharp <cssharp@eecs.berkeley.edu>
+ * @author Andrew Redfern <aredfern@kingkong.me.berkeley.edu>
+ */
+
+configuration UserButtonC
+{
+  provides interface UserButton;
+}
+
+implementation
+{
+  components MainC, new TimerMilliC(),
+    HplMsp430GeneralIOC, HplMsp430InterruptC,
+    UserButtonP;
+
+  UserButton = UserButtonP;
+
+  MainC.SoftwareInit -> UserButtonP;
+
+  UserButtonP -> HplMsp430GeneralIOC.Port27;
+  UserButtonP -> HplMsp430InterruptC.Port27;
+  UserButtonP.Timer -> TimerMilliC;
+}
+
diff --git a/tos/lib/tosthreads/lib/tinyld/UserButtonP.nc b/tos/lib/tosthreads/lib/tinyld/UserButtonP.nc
new file mode 100755 (executable)
index 0000000..7f91314
--- /dev/null
@@ -0,0 +1,77 @@
+/* "Copyright (c) 2000-2003 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * Andew's timer debouce logic used from the CountInput application.
+ *
+ * @author Cory Sharp <cssharp@eecs.berkeley.edu>
+ * @author Andrew Redfern <aredfern@kingkong.me.berkeley.edu>
+ */
+
+module UserButtonP
+{
+  provides {
+    interface Init;
+    interface UserButton;
+  }
+  uses {
+    interface HplMsp430GeneralIO;
+    interface HplMsp430Interrupt;
+    interface Timer<TMilli>;
+  }
+}
+implementation
+{
+  command error_t Init.init()
+  {
+    atomic {
+      call HplMsp430Interrupt.disable();
+      call HplMsp430GeneralIO.makeInput();
+      call HplMsp430GeneralIO.selectIOFunc();
+      call HplMsp430Interrupt.edge(TRUE);
+      call HplMsp430Interrupt.clear();
+      call HplMsp430Interrupt.enable();
+    }
+    return SUCCESS;
+  }
+
+  event void Timer.fired()
+  {
+    atomic {
+      call HplMsp430Interrupt.clear();
+      call HplMsp430Interrupt.enable();
+    }
+  }
+
+  task void debounce()
+  {
+    call Timer.startOneShot(100);
+    signal UserButton.fired();
+  }
+
+  async event void HplMsp430Interrupt.fired()
+  {
+    atomic {
+      call HplMsp430Interrupt.disable();
+      post debounce();
+    }
+  }
+}
+
diff --git a/tos/lib/tosthreads/lib/tinyld/slcs_types.h b/tos/lib/tosthreads/lib/tinyld/slcs_types.h
new file mode 100755 (executable)
index 0000000..15e4338
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#ifndef _SLCS_TYPES_H
+#define _SLCS_TYPES_H
+
+#include "tosthread.h"
+#include "tosthread_leds.h"
+#include "tosthread_amradio.h"
+#include "tosthread_blockstorage.h"
+#include "tosthread_logstorage.h"
+#include "tosthread_configstorage.h"
+#include "tosthread_threadsync.h"
+#include "tosthread_amserial.h"
+#include "tosthread_queue.h"
+
+#include "tosthread_sensirionSht11.h"
+#include "tosthread_hamamatsuS10871.h"
+#include "tosthread_hamamatsuS1087.h"
+
+struct value_addr_pair {
+  uint16_t value;
+  void *addr;
+};
+
+struct addr {
+  void *addr;
+};
+
+struct prog_desc {
+  uint16_t main_addr;   // Loadable program's main function (or tosthread_main() in our case)
+  uint16_t alloc_count;
+  uint16_t alloc_size;
+  uint16_t g_reloc_count;
+  uint16_t l_reloc_count;
+  uint16_t datasec_count;
+  uint16_t code_count;
+  
+  uint16_t patch_table_count;   // alloc_count + g_reloc_count + l_reloc_count;
+  uint16_t code_offset;   // sizeof(main_addr) +
+                          // sizeof(alloc_count) +
+                          // sizeof(alloc_size) +
+                          // sizeof(g_reloc_count) +
+                          // sizeof(l_reloc_count) +
+                          // sizeof(datasec_count) +
+                          // sizeof(code_count) +
+                          // (g_sym_count + patch_table_count) * 4
+  
+  uint16_t loading_stage;
+};
+
+#endif
diff --git a/tos/lib/tosthreads/lib/tinyld/tosthread_slcs_types.h b/tos/lib/tosthreads/lib/tinyld/tosthread_slcs_types.h
new file mode 100755 (executable)
index 0000000..f17e325
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#ifndef _TOSTHREAD_SLCS_TYPES_H
+#define _TOSTHREAD_SLCS_TYPES_H
+
+#include "slcs_types.h"
+
+struct addr fun[] = {
+  
+  {tosthread_sleep}, {tosthread_create},
+    
+  {led0On}, {led1On}, {led2On},
+  {led0Off}, {led1Off}, {led2Off},
+  {led0Toggle}, {led1Toggle}, {led2Toggle},
+  
+  {amSerialStart}, {amSerialStop}, {amSerialReceive},
+  {amSerialSend}, {amSerialLocalAddress}, {amSerialGetLocalGroup},
+  {amSerialGetDestination}, {amSerialGetSource}, {amSerialSetDestination},
+  {amSerialSetSource}, {amSerialIsForMe}, {amSerialGetType},
+  {amSerialSetType}, {amSerialGetGroup}, {amSerialSetGroup},
+  {serialClear}, {serialGetPayloadLength}, {serialSetPayloadLength},
+  {serialMaxPayloadLength}, {serialGetPayload}, {serialRequestAck},
+  {serialNoAck}, {serialWasAcked},
+  
+  {amRadioStart}, {amRadioStop}, {amRadioReceive},
+  {amRadioSend}, {amRadioGetLocalAddress}, {amRadioGetLocalGroup},
+  {amRadioGetDestination}, {amRadioGetSource}, {amRadioSetDestination},
+  {amRadioSetSource}, {amRadioIsForMe}, {amRadioGetType},
+  {amRadioSetType}, {amRadioGetGroup}, {amRadioSetGroup},
+  {radioClear}, {radioGetPayloadLength}, {radioSetPayloadLength},
+  {radioMaxPayloadLength}, {radioGetPayload}, {radioRequestAck},
+  {radioNoAck}, {radioWasAcked},
+    
+  {semaphore_reset}, {semaphore_acquire}, {semaphore_release},
+
+  {barrier_reset}, {barrier_block}, {barrier_isBlocking},
+
+  {condvar_init}, {condvar_wait}, {condvar_signalNext},
+  {condvar_signalAll}, {condvar_isBlocking},
+
+  {mutex_init}, {mutex_lock}, {mutex_unlock},
+
+  {volumeBlockRead}, {volumeBlockWrite}, {volumeBlockCrc},
+  {volumeBlockErase}, {volumeBlockSync},
+
+  {refcounter_init}, {refcounter_increment}, {refcounter_decrement},
+  {refcounter_waitOnValue}, {refcounter_count},
+  
+  {amRadioSnoop},
+
+  {queue_init}, {queue_clear}, {queue_enqueue},
+  {queue_dequeue}, {queue_remove}, {queue_size},
+  {queue_is_empty},
+
+  {sensirionSht11_humidity_read}, {sensirionSht11_humidity_getNumBits}, {sensirionSht11_temperature_read},
+  {sensirionSht11_temperature_getNumBits},
+  
+  {hamamatsuS10871_tsr_read}, {hamamatsuS10871_tsr_readStream}, {hamamatsuS10871_tsr_getNumBits},
+  
+  {hamamatsuS1087_par_read}, {hamamatsuS1087_par_readStream}, {hamamatsuS1087_par_getNumBits},
+  
+  {volumeLogRead}, {volumeLogCurrentReadOffset}, {volumeLogSeek},
+  {volumeLogGetSize},
+  
+  {volumeLogAppend}, {volumeLogCurrentWriteOffset}, {volumeLogErase},
+  {volumeLogSync},
+  
+  {getLeds}, {setLeds},
+
+  {div},
+  
+  {tosthread_join},
+  
+  {volumeConfigMount}, {volumeConfigRead}, {volumeConfigWrite},
+  {volumeConfigCommit}, {volumeConfigGetSize}, {volumeConfigValid}
+};
+
+#endif
diff --git a/tos/lib/tosthreads/platforms/epic/ActiveMessageC.nc b/tos/lib/tosthreads/platforms/epic/ActiveMessageC.nc
new file mode 100644 (file)
index 0000000..816f8b6
--- /dev/null
@@ -0,0 +1,82 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2004-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2004-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+/*
+ *
+ * Authors:            Philip Levis
+ * Date last modified:  $Id$
+ *
+ */
+
+/**
+ *
+ * The Active Message layer on the Telos platform. This is a naming wrapper
+ * around the CC2420 Active Message layer.
+ *
+ * @author Philip Levis
+ * @version $Revision$ $Date$
+ */
+#include "Timer.h"
+
+configuration ActiveMessageC {
+  provides {
+    interface SplitControl;
+
+    interface AMSend[am_id_t id];
+    interface Receive[am_id_t id];
+    interface Receive as ReceiveDefault[am_id_t id];
+    interface Receive as Snoop[am_id_t id];
+    interface Receive as SnoopDefault[am_id_t id];
+
+    interface Packet;
+    interface AMPacket;
+    interface PacketAcknowledgements;
+    interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
+    interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+  }
+}
+implementation {
+  components CC2420ActiveMessageC as AM;
+
+  SplitControl = AM;
+  
+  AMSend       = AM;
+  Receive      = AM.Receive;
+  ReceiveDefault = AM.ReceiveDefault;
+  Snoop        = AM.Snoop;
+  SnoopDefault = AM.SnoopDefault;
+  Packet       = AM;
+  AMPacket     = AM;
+  PacketAcknowledgements = AM;
+
+  components CC2420PacketC;
+  PacketTimeStamp32khz = CC2420PacketC;
+  PacketTimeStampMilli = CC2420PacketC;
+}
diff --git a/tos/lib/tosthreads/platforms/epic/TelosSerialP.nc b/tos/lib/tosthreads/platforms/epic/TelosSerialP.nc
new file mode 100644 (file)
index 0000000..fcfc91d
--- /dev/null
@@ -0,0 +1,23 @@
+module TelosSerialP {
+  provides interface StdControl;
+  provides interface Msp430UartConfigure;
+  uses interface Resource;
+}
+implementation {
+  
+  msp430_uart_union_config_t msp430_uart_telos_config = { {ubr: UBR_1MHZ_57600, umctl: UMCTL_1MHZ_57600, ssel: 0x02, pena: 0, pev: 0, spb: 0, clen: 1, listen: 0, mm: 0, ckpl: 0, urxse: 0, urxeie: 1, urxwie: 0, utxe : 1, urxe : 1} };
+
+  command error_t StdControl.start(){
+    return call Resource.immediateRequest();
+  }
+  command error_t StdControl.stop(){
+    call Resource.release();
+    return SUCCESS;
+  }
+  event void Resource.granted(){}
+
+  async command msp430_uart_union_config_t* Msp430UartConfigure.getConfig() {
+    return &msp430_uart_telos_config;
+  }
+  
+}
index de7d75589fed9c40b06ab3fe7a64605d5c098b47..6b1a009693e45ef4c0a181f9c8576b2d85010089 100644 (file)
@@ -6,12 +6,12 @@
  * documentation for any purpose, without fee, and without written agreement is
  * hereby granted, provided that the above copyright notice, the following
  * two paragraphs and the author appear in all copies of this software.
- *
+ * 
  * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
  * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
  * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
+ * 
  * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  * Author: Miklos Maroti
  */
 
+/*
+ * Make active message TOSThreads-compatible by exposing default interfaces
+ *
+ * Author: Chieh-Jan Mike Liang
+ */
+
+#include <RadioConfig.h>
+
 configuration ActiveMessageC
 {
        provides
@@ -32,11 +40,16 @@ configuration ActiveMessageC
     interface Receive as ReceiveDefault[am_id_t id];
                interface Receive as Snoop[uint8_t id];
     interface Receive as SnoopDefault[am_id_t id];
+               interface SendNotifier[am_id_t id];
+
                interface Packet;
                interface AMPacket;
 
                interface PacketAcknowledgements;
                interface LowPowerListening;
+#ifdef PACKET_LINK
+               interface PacketLink;
+#endif
 
                interface PacketTimeStamp<TMicro, uint32_t> as PacketTimeStampMicro;
                interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
@@ -45,19 +58,26 @@ configuration ActiveMessageC
 
 implementation
 {
-       components RF230ActiveMessageC as MAC;
-
-       SplitControl = MAC;
-       AMSend       = MAC;
-  Receive      = MAC.Receive;
-  ReceiveDefault = MAC.ReceiveDefault;
-  Snoop        = MAC.Snoop;
-  SnoopDefault = MAC.SnoopDefault;
-       Packet       = MAC;
-       AMPacket     = MAC;
-
-       PacketAcknowledgements  = MAC;
-       LowPowerListening               = MAC;
-       PacketTimeStampMilli    = MAC;
-       PacketTimeStampMicro    = MAC;
+       components RF230ActiveMessageC as MessageC;
+
+       SplitControl = MessageC;
+
+       AMSend = MessageC;
+       Receive = MessageC.Receive;
+  ReceiveDefault = MessageC.ReceiveDefault;
+  Snoop        = MessageC.Snoop;
+  SnoopDefault = MessageC.SnoopDefault;
+       SendNotifier = MessageC;
+
+       Packet = MessageC;
+       AMPacket = MessageC;
+
+       PacketAcknowledgements = MessageC;
+       LowPowerListening = MessageC;
+#ifdef PACKET_LINK
+       PacketLink = MessageC;
+#endif
+
+       PacketTimeStampMilli = MessageC;
+       PacketTimeStampMicro = MessageC;
 }
index 51aeeff320bcd97b9153f63708e6dffa827456c9..f1baf8e7998cc552f74d48000bfff138e7322b8c 100644 (file)
@@ -40,10 +40,10 @@ module CPhotoP {
   }
 }
 implementation {
-  error_t photo_read(uint16_t* val) @C() @spontaneous() {
+  error_t photo_read(uint16_t* val) @C() AT_SPONTANEOUS {
     return call BlockingRead.read(val);
   }
-  error_t photo_readStream(uint32_t* usPeriod, uint16_t* buf, uint16_t count) @C() @spontaneous() {
+  error_t photo_readStream(uint32_t* usPeriod, uint16_t* buf, uint16_t count) @C() AT_SPONTANEOUS {
     return call BlockingReadStream.read(usPeriod, buf, count);
   }
 }
index 1bcc8d9eb26944bededb2362eeeecb90ceceb655..a9efc9c2163a3f51dfa808ea4693696ae971c966 100644 (file)
@@ -40,10 +40,10 @@ module CTempP {
   }
 }
 implementation {
-  error_t temp_read(uint16_t* val) @C() @spontaneous() {
+  error_t temp_read(uint16_t* val) @C() AT_SPONTANEOUS {
     return call BlockingRead.read(val);
   }
-  error_t temp_readStream(uint32_t* usPeriod, uint16_t* buf, uint16_t count) @C() @spontaneous() {
+  error_t temp_readStream(uint32_t* usPeriod, uint16_t* buf, uint16_t count) @C() AT_SPONTANEOUS {
     return call BlockingReadStream.read(usPeriod, buf, count);
   }
 }
index e90f0e591300e96434c8b0b1c2bf6f3feea5b84c..1c75d720cb69b0a94f06a3a39befb4309d9d4e2c 100644 (file)
 configuration CHamamatsuS10871TsrC {}
 implementation {
   components CHamamatsuS10871TsrP;
+#ifdef PLATFORM_TELOSB
   components new BlockingHamamatsuS10871TsrC();
              
   CHamamatsuS10871TsrP.DeviceMetadata -> BlockingHamamatsuS10871TsrC.DeviceMetadata;
   CHamamatsuS10871TsrP.Read -> BlockingHamamatsuS10871TsrC.Read;
   CHamamatsuS10871TsrP.ReadStream -> BlockingHamamatsuS10871TsrC.ReadStream;
+#endif
 }
index 8346ee8d82137d368370b6d58c539b5db84ca01f..da4bfa9f4d552470cf083f6a9a08f04bbb663bea 100644 (file)
@@ -41,13 +41,25 @@ module CHamamatsuS10871TsrP {
   }
 }
 implementation {
-  error_t hamamatsuS10871_tsr_read(uint16_t* val) @C() @spontaneous() {
+  error_t hamamatsuS10871_tsr_read(uint16_t* val) @C() AT_SPONTANEOUS {
     return call Read.read(val);
   }
-  error_t hamamatsuS10871_tsr_readStream(uint32_t* usPeriod, uint16_t* buf, uint16_t count) @C() @spontaneous() {
+  error_t hamamatsuS10871_tsr_readStream(uint32_t* usPeriod, uint16_t* buf, uint16_t count) @C() AT_SPONTANEOUS {
     return call ReadStream.read(usPeriod, buf, count);                                           
   }                                            
-  uint8_t hamamatsuS10871_tsr_getNumBits() @C() @spontaneous() {
+  uint8_t hamamatsuS10871_tsr_getNumBits() @C() AT_SPONTANEOUS {
     return call DeviceMetadata.getSignificantBits();
   }
+  
+  default command error_t Read.read(uint16_t* val) {
+    return FAIL;
+  }
+  
+  default command error_t ReadStream.read(uint32_t* usPeriod, uint16_t* buf, uint16_t count) {
+    return FAIL;
+  }
+  
+  default command uint8_t DeviceMetadata.getSignificantBits() {
+    return 0;
+  }
 }
index 8466647d5c9d52a3b88155960b1155a27e135371..a4a020d13ec294fd4ae56c589403098679bf791d 100644 (file)
 configuration CHamamatsuS1087ParC {}
 implementation {
   components CHamamatsuS1087ParP;
+#ifdef PLATFORM_TELOSB
   components new BlockingHamamatsuS1087ParC();
              
   CHamamatsuS1087ParP.DeviceMetadata -> BlockingHamamatsuS1087ParC.DeviceMetadata;
   CHamamatsuS1087ParP.Read -> BlockingHamamatsuS1087ParC.Read;
   CHamamatsuS1087ParP.ReadStream -> BlockingHamamatsuS1087ParC.ReadStream;
+#endif
 }
index 683b606cf3dc67753d7503772a9a525e722e6a15..bd45a932614a2184151c4b7590e12592009b2bb0 100644 (file)
@@ -42,13 +42,25 @@ module CHamamatsuS1087ParP {
 }
 implementation {
 
-  error_t hamamatsuS1087_par_read(uint16_t* val) @C() @spontaneous() {
+  error_t hamamatsuS1087_par_read(uint16_t* val) @C() AT_SPONTANEOUS {
     return call Read.read(val);
   }
-  error_t hamamatsuS1087_par_readStream(uint32_t* usPeriod, uint16_t* buf, uint16_t count) @C() @spontaneous() {
+  error_t hamamatsuS1087_par_readStream(uint32_t* usPeriod, uint16_t* buf, uint16_t count) @C() AT_SPONTANEOUS {
     return call ReadStream.read(usPeriod, buf, count);                                           
   }                                           
-  uint8_t hamamatsuS1087_par_getNumBits() @C() @spontaneous() {
+  uint8_t hamamatsuS1087_par_getNumBits() @C() AT_SPONTANEOUS {
     return call DeviceMetadata.getSignificantBits();
   }
+  
+  default command error_t Read.read(uint16_t* val) {
+    return FAIL;
+  }
+  
+  default command error_t ReadStream.read(uint32_t* usPeriod, uint16_t* buf, uint16_t count) {
+    return FAIL;
+  }
+  
+  default command uint8_t DeviceMetadata.getSignificantBits() {
+    return 0;
+  }
 }
index b30196e2a7b79fcebd6324f47a24aab86b67884e..52d9623bbdc92fabeb3714e7bc4a89970a63748e 100644 (file)
 configuration CSensirionSht11C {}
 implementation {
   components CSensirionSht11P;
+#ifdef PLATFORM_TELOSB
   components new BlockingSensirionSht11C();
              
   CSensirionSht11P.Temperature -> BlockingSensirionSht11C.Temperature;
   CSensirionSht11P.TemperatureMetadata -> BlockingSensirionSht11C.TemperatureMetadata;
   CSensirionSht11P.Humidity -> BlockingSensirionSht11C.Humidity;
   CSensirionSht11P.HumidityMetadata -> BlockingSensirionSht11C.HumidityMetadata;
+#endif
 }
index 38ba3e80f6bf2cb29f710c12e3d8ac10e66dbf42..448d668150c326c3cec3506d5277d5ae2af9adeb 100644 (file)
@@ -42,16 +42,32 @@ module CSensirionSht11P {
   }
 }
 implementation {
-  error_t sensirionSht11_humidity_read(uint16_t* val) @C() @spontaneous() {
+  error_t sensirionSht11_humidity_read(uint16_t* val) @C() AT_SPONTANEOUS {
     return call Humidity.read(val);
   }
-  uint8_t sensirionSht11_humidity_getNumBits() @C() @spontaneous() {
+  uint8_t sensirionSht11_humidity_getNumBits() @C() AT_SPONTANEOUS {
     return call HumidityMetadata.getSignificantBits();
   }
-  error_t sensirionSht11_temperature_read(uint16_t* val) @C() @spontaneous() {
+  error_t sensirionSht11_temperature_read(uint16_t* val) @C() AT_SPONTANEOUS {
     return call Temperature.read(val);
   }
-  uint8_t sensirionSht11_temperature_getNumBits() @C() @spontaneous() {
+  uint8_t sensirionSht11_temperature_getNumBits() @C() AT_SPONTANEOUS {
     return call TemperatureMetadata.getSignificantBits();
   }
+  
+  default command error_t Humidity.read(uint16_t* val) {
+    return FAIL;
+  }
+
+  default command uint8_t HumidityMetadata.getSignificantBits() {
+    return 0;
+  }
+  
+  default command error_t Temperature.read(uint16_t* val) {
+    return FAIL;
+  }
+
+  default command uint8_t TemperatureMetadata.getSignificantBits() {
+    return 0;
+  }
 }
index 63f197d557882a07133b2497f2e8fdde4fac6390..770362a97fba96b27efd1cc627fca722e29c07f7 100644 (file)
@@ -39,7 +39,7 @@ module CSineSensorP {
   }
 }
 implementation {
-  error_t sinesensor_read(uint16_t* val) @C() @spontaneous() {
+  error_t sinesensor_read(uint16_t* val) @C() AT_SPONTANEOUS {
     return call BlockingRead.read(val);
   }
 }
index 0bbd0b7f159ddd211282420fd553ae82defa85c1..f36760101ac6601cf95b18a586ca1eaf66706abd 100644 (file)
@@ -44,10 +44,8 @@ generic configuration BlockingAMReceiverC(am_id_t amId) {
   }
 }
 implementation {
-  components ActiveMessageC;
   components BlockingActiveMessageC as AM;
   BlockingReceive = AM.BlockingReceive[amId];
-  AM.Receive[amId] -> ActiveMessageC.ReceiveDefault[amId];
   
   Packet = AM;
   AMPacket = AM;
index c2c7fa4ae8a8b9db15bea63bff7456224f7e7eca..e9b6b4ed3743edbc5609dea78aeb9712f79a00e4 100644 (file)
@@ -52,8 +52,8 @@ generic module BlockingAMReceiverImplP() {
 implementation {
   
   typedef struct params {
-    message_t* msg;
     uint32_t*  timeout;
+    message_t* msg;
     error_t    error;
   } params_t;
 
index 142a8d7ee56e465a98d6c212dcfd19bee19280e0..4d70b1e0670d586590dd3ef2b125f2398b45f666 100644 (file)
@@ -45,10 +45,8 @@ generic configuration BlockingAMSenderC(am_id_t AMId) {
 }
 
 implementation {
-  components ActiveMessageC;
   components BlockingActiveMessageC as AM;
   BlockingAMSend = AM.BlockingAMSend[AMId];
-  AM.AMSend[AMId] -> ActiveMessageC.AMSend[AMId];
   
   Packet = AM;
   AMPacket = AM;
index 539e074813fd0915428ba034b8db3142859ac64d..c519e64cf9d58e44f305de12c607602e02cd5fea 100644 (file)
@@ -31,6 +31,7 @@
  
 /**
  * @author Kevin Klues (klueska@cs.stanford.edu)
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
  */
 
 generic module BlockingAMSenderImplP() {
@@ -55,7 +56,7 @@ implementation {
     error_t    error;
   } params_t;
   
-  syscall_t* send_call;
+  syscall_t* send_call = NULL;
   mutex_t my_mutex;
   
   void sendTask(syscall_t* s) {
@@ -74,13 +75,18 @@ implementation {
     syscall_t s;
     params_t p;
     call Mutex.lock(&my_mutex);
-      send_call = &s;
-    
-      p.addr = addr;
-      p.msg = msg;
-      p.len = len;
-    
-      call SystemCall.start(&sendTask, &s, am_id, &p);
+      if (send_call == NULL) {
+        send_call = &s;
+      
+        p.addr = addr;
+        p.msg = msg;
+        p.len = len;
+      
+        call SystemCall.start(&sendTask, &s, am_id, &p);
+        send_call = NULL;
+      } else {
+        p.error = EBUSY;
+      }
     
     atomic {
       call Mutex.unlock(&my_mutex);
@@ -96,13 +102,17 @@ implementation {
   }
   
   event void AMSend.sendDone[am_id_t am_id](message_t* m, error_t error) {
-    params_t* p;
-    p = send_call->params;
-    p->error = error;
-    call SystemCall.finish(send_call);
+    if (send_call != NULL) {
+      if (send_call->id == am_id) {
+        params_t* p;
+        p = send_call->params;
+        p->error = error;
+        call SystemCall.finish(send_call);
+      }
+    }
   }
   default command error_t AMSend.send[am_id_t id](am_addr_t addr, message_t* msg, uint8_t len) {
-    return SUCCESS;
+    return FAIL;
   }
 }
 
index 5564b534e01a07f1772760e5837eceb7642e7b88..3f90b911fc396137e6870dfdd3744a4ee0426be6 100644 (file)
@@ -44,10 +44,8 @@ generic configuration BlockingAMSnooperC(am_id_t amId) {
   }
 }
 implementation {
-  components ActiveMessageC;
   components BlockingActiveMessageC as AM;
   BlockingReceive = AM.BlockingSnoop[amId];
-  AM.Snoop[amId] -> ActiveMessageC.SnoopDefault[amId];
   
   Packet = AM;
   AMPacket = AM;
index f749e1c9401f0129328d0a01077ba07d0db3fb97..26b29ffce28164885301d6d192c70a8f0570d368 100644 (file)
@@ -46,11 +46,6 @@ configuration BlockingActiveMessageC {
     interface AMPacket;
     interface PacketAcknowledgements;
   }
-  uses {
-    interface Receive as Receive[uint8_t id];
-    interface Receive as Snoop[uint8_t id];
-    interface AMSend as AMSend[uint8_t id];
-  }
 }
 implementation {
   components ActiveMessageC as AM;
@@ -66,9 +61,9 @@ implementation {
   BlockingAMSend = AMSenderP;
   
   BlockingStdControlC.SplitControl -> AM;
-  Receive = AMReceiverP.Receive;
-  Snoop = AMSnooperP.Snoop;
-  AMSend = AMSenderP.AMSend;
+  AMReceiverP.Receive -> AM.ReceiveDefault;
+  AMSnooperP.Snoop -> AM.SnoopDefault;
+  AMSenderP.AMSend -> AM.AMSend;
     
   Packet       = AM;
   AMPacket     = AM;
diff --git a/tos/lib/tosthreads/system/BlockingConfigStorageC.nc b/tos/lib/tosthreads/system/BlockingConfigStorageC.nc
new file mode 100644 (file)
index 0000000..9656445
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#define UQ_BLOCKING_CONFIG_STORAGE_VOLUME "Blocking.Config.Storage.Volume"
+
+generic configuration BlockingConfigStorageC(volume_id_t volume_id) {
+  provides {
+    interface BlockingConfig;
+    interface BlockingMount;
+  }
+}
+
+implementation {
+  enum {
+    VOLUME_ID = unique(UQ_BLOCKING_CONFIG_STORAGE_VOLUME),
+  };
+
+  components new ConfigStorageC(volume_id),
+             BlockingConfigStorageP;
+  
+  BlockingConfig = BlockingConfigStorageP.BlockingConfig[VOLUME_ID];
+  BlockingMount = BlockingConfigStorageP.BlockingMount[VOLUME_ID];
+  
+  BlockingConfigStorageP.ConfigStorage[VOLUME_ID] -> ConfigStorageC;
+  BlockingConfigStorageP.ConfigMount[VOLUME_ID] -> ConfigStorageC;
+}
diff --git a/tos/lib/tosthreads/system/BlockingConfigStorageImplP.nc b/tos/lib/tosthreads/system/BlockingConfigStorageImplP.nc
new file mode 100644 (file)
index 0000000..1287783
--- /dev/null
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2009 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+module BlockingConfigStorageImplP {
+  provides {
+    interface Init;
+    interface BlockingConfig[uint8_t volume_id];
+    interface BlockingMount[uint8_t volume_id];
+  }
+  
+  uses {
+    interface ConfigStorage[uint8_t volume_id];
+    interface Mount as ConfigMount[uint8_t volume_id];
+    interface SystemCall;
+    interface SystemCallQueue;
+  }
+}
+
+implementation {
+  typedef struct read_write_params {
+    storage_addr_t addr;
+    void*          buf;
+    storage_len_t* len;
+    error_t        error;
+  } read_write_params_t;
+    
+  typedef struct commit_mount_params {
+    error_t error;
+  } commit_mount_params_t;
+
+  syscall_queue_t vol_queue;
+
+  command error_t Init.init()
+  {
+    call SystemCallQueue.init(&vol_queue);
+    return SUCCESS;
+  }
+
+  command storage_len_t BlockingConfig.getSize[uint8_t volume_id]() {
+    return call ConfigStorage.getSize[volume_id]();
+  }
+  
+  command bool BlockingConfig.valid[uint8_t volume_id]() {
+    return call ConfigStorage.valid[volume_id]();
+  }
+  
+  /**************************** Reading ********************************/
+  void readTask(syscall_t* s)
+  {
+    read_write_params_t* p = s->params;
+    p->error = call ConfigStorage.read[s->id](p->addr, p->buf, *(p->len));
+    if(p->error != SUCCESS) {
+      call SystemCall.finish(s);
+    }
+  }
+  
+  command error_t BlockingConfig.read[uint8_t volume_id](storage_addr_t addr, void *buf, storage_len_t* len)
+  {
+    syscall_t s;
+    read_write_params_t p;
+    atomic {
+      if(call SystemCallQueue.find(&vol_queue, volume_id) != NULL) {
+        return EBUSY;
+      }
+      call SystemCallQueue.enqueue(&vol_queue, &s);
+    }
+    
+    p.addr = addr;
+    p.buf = buf;
+    p.len = len;
+    call SystemCall.start(&readTask, &s, volume_id, &p);
+    
+    atomic {
+      call SystemCallQueue.remove(&vol_queue, &s);
+      return p.error;
+    }
+  }
+
+  event void ConfigStorage.readDone[uint8_t volume_id](storage_addr_t addr, void *buf, storage_len_t len, error_t error)
+  {
+    syscall_t* s = call SystemCallQueue.find(&vol_queue, volume_id);
+    read_write_params_t* p = s->params;
+    p->error = error;
+    *(p->len) = len;
+    call SystemCall.finish(s);
+  }
+
+  
+  /**************************** Writing ********************************/
+  void writeTask(syscall_t* s)
+  {
+    read_write_params_t* p = s->params;
+    p->error = call ConfigStorage.write[s->id](p->addr, p->buf, *(p->len));
+    if(p->error != SUCCESS) {
+      call SystemCall.finish(s);
+    }
+  }
+  
+  command error_t BlockingConfig.write[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t* len)
+  {
+    syscall_t s;
+    read_write_params_t p;
+    atomic {
+      if(call SystemCallQueue.find(&vol_queue, volume_id) != NULL) {
+        return EBUSY;
+      }
+      call SystemCallQueue.enqueue(&vol_queue, &s);
+    }
+    
+    p.addr = addr;
+    p.buf = buf;
+    p.len = len;
+    call SystemCall.start(&writeTask, &s, volume_id, &p);
+
+    atomic {
+      call SystemCallQueue.remove(&vol_queue, &s);
+      return p.error;
+    }
+  }
+  
+  event void ConfigStorage.writeDone[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len, error_t error)
+  {
+    syscall_t* s = call SystemCallQueue.find(&vol_queue, volume_id);
+    read_write_params_t* p = s->params;
+    *(p->len) = len;
+    p->error = error;
+    call SystemCall.finish(s);
+  }
+
+  /**************************** Committing ********************************/
+  void commitTask(syscall_t* s)
+  {
+    commit_mount_params_t* p = s->params;
+    p->error = call ConfigStorage.commit[s->id]();
+    if(p->error != SUCCESS) {
+      call SystemCall.finish(s);
+    }
+  }
+  
+  command error_t BlockingConfig.commit[uint8_t volume_id]()
+  {
+    syscall_t s;
+    commit_mount_params_t p;
+    atomic {
+      if(call SystemCallQueue.find(&vol_queue, volume_id) != NULL) {
+        return EBUSY;
+      }
+      call SystemCallQueue.enqueue(&vol_queue, &s);
+    }
+    
+    call SystemCall.start(&commitTask, &s, volume_id, &p);
+    
+    atomic {
+      call SystemCallQueue.remove(&vol_queue, &s);
+      return p.error;
+    }
+  }
+
+  event void ConfigStorage.commitDone[uint8_t volume_id](error_t error)
+  {
+    syscall_t* s = call SystemCallQueue.find(&vol_queue, volume_id);
+    commit_mount_params_t* p = s->params;
+    p->error = error;
+    call SystemCall.finish(s);
+  }
+  
+  /**************************** Mounting ********************************/
+  void mountTask(syscall_t* s)
+  {
+    commit_mount_params_t* p = s->params;
+    p->error = call ConfigMount.mount[s->id]();
+    if(p->error != SUCCESS) {
+      call SystemCall.finish(s);
+    }
+  }
+  
+  command error_t BlockingMount.mount[uint8_t volume_id]()
+  {
+    syscall_t s;
+    commit_mount_params_t p;
+    atomic {
+      if(call SystemCallQueue.find(&vol_queue, volume_id) != NULL) {
+        return EBUSY;
+      }
+      call SystemCallQueue.enqueue(&vol_queue, &s);
+    }
+    
+    call SystemCall.start(&mountTask, &s, volume_id, &p);
+    
+    atomic {
+      call SystemCallQueue.remove(&vol_queue, &s);
+      return p.error;
+    }
+  }
+
+  event void ConfigMount.mountDone[uint8_t volume_id](error_t error)
+  {
+    syscall_t* s = call SystemCallQueue.find(&vol_queue, volume_id);
+    commit_mount_params_t* p = s->params;
+    p->error = error;
+    call SystemCall.finish(s);
+  }  
+  
+  default command error_t ConfigStorage.read[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t ConfigStorage.write[uint8_t volume_id](storage_addr_t addr, void* buf, storage_len_t len) { return FAIL; }
+  default command error_t ConfigStorage.commit[uint8_t volume_id]() { return FAIL; }
+  default command storage_len_t ConfigStorage.getSize[uint8_t volume_id]() { return 0; }
+  default command bool ConfigStorage.valid[uint8_t volume_id]() { return FALSE; }
+  default command error_t ConfigMount.mount[uint8_t volume_id]() { return FAIL; }
+}
diff --git a/tos/lib/tosthreads/system/BlockingConfigStorageP.nc b/tos/lib/tosthreads/system/BlockingConfigStorageP.nc
new file mode 100644 (file)
index 0000000..8c6060d
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2009 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+configuration BlockingConfigStorageP {
+  provides {
+    interface BlockingConfig[uint8_t id];
+    interface BlockingMount[uint8_t id];
+  }
+  
+  uses {
+    interface ConfigStorage[uint8_t id];
+    interface Mount as ConfigMount[uint8_t id];
+  }
+}
+
+implementation {
+  components MainC,
+             SystemCallC,
+             SystemCallQueueC,
+             BlockingConfigStorageImplP;
+             
+  MainC.SoftwareInit -> BlockingConfigStorageImplP;
+  
+  BlockingConfig = BlockingConfigStorageImplP;
+  BlockingMount = BlockingConfigStorageImplP;
+  ConfigStorage = BlockingConfigStorageImplP;
+  ConfigMount = BlockingConfigStorageImplP;
+  
+  BlockingConfigStorageImplP.SystemCall -> SystemCallC;
+  BlockingConfigStorageImplP.SystemCallQueue -> SystemCallQueueC;
+}
index 4de3b921aa149addc25f919d0b0a10fbeeed5cc1..aca77acff417e9822cfa5fc5fc1a804e446a1554 100644 (file)
@@ -266,4 +266,14 @@ implementation {
   command storage_cookie_t BlockingLog.currentWriteOffset[uint8_t volume_id]() { return call LogWrite.currentOffset[volume_id](); }
   command storage_cookie_t BlockingLog.currentReadOffset[uint8_t volume_id]() { return call LogRead.currentOffset[volume_id](); }
   command storage_len_t BlockingLog.getSize[uint8_t volume_id]() { return call LogRead.getSize[volume_id](); }
+  
+  default command error_t LogRead.read[uint8_t volume_id](void* buf, storage_len_t len) { return FAIL; }
+  default command storage_cookie_t LogRead.currentOffset[uint8_t volume_id]() { return SEEK_BEGINNING; }
+  default command error_t LogRead.seek[uint8_t volume_id](storage_cookie_t offset) { return FAIL; }
+  default command storage_len_t LogRead.getSize[uint8_t volume_id]() { return 0; }
+  
+  default command error_t LogWrite.append[uint8_t volume_id](void* buf, storage_len_t len) { return FAIL; }
+  default command storage_cookie_t LogWrite.currentOffset[uint8_t volume_id]() { return SEEK_BEGINNING; }
+  default command error_t LogWrite.erase[uint8_t volume_id]() { return FAIL; }
+  default command error_t LogWrite.sync[uint8_t volume_id]() { return FAIL; }
 }
index fc14b25393e56697debf506cc25ddffe2792468d..e7a4532eb3e92840b1ed4373358ca54482ca2153 100644 (file)
@@ -47,8 +47,8 @@ implementation {
   BlockingResource = BlockingResourceP;
   Resource = BlockingResourceP;
   
-  components ThreadTimersC;
-  BlockingResourceP.Timer -> ThreadTimersC;
+  components ThreadSleepC;
+  BlockingResourceP.ThreadSleep -> ThreadSleepC;
   
   components SystemCallC;
   components TinyThreadSchedulerC;
index b3e69a7298503168f4a2674857b6a044b64d7958..2821185e6c727b6add787ecadf556b5a0b8b0be3 100644 (file)
@@ -41,12 +41,11 @@ generic module BlockingResourceP() {
     interface SystemCall;
     interface ThreadScheduler;
     interface Resource;
-    interface Timer<TMilli>[uint8_t id];
+    interface ThreadSleep;
   }
 }
 implementation {
   typedef struct params {
-    uint32_t* milli;
     error_t   error;
   } params_t;
   
@@ -108,11 +107,6 @@ implementation {
   }
   
   /************************* Timed Release *****************************/
-  void timerTask(syscall_t* s) {
-    params_t* p = s->params;
-    call Timer.startOneShot[s->thread->id](*(p->milli));
-  }    
-  
   command error_t BlockingResource.timedRelease(uint32_t milli) {
     syscall_t s;
     params_t p;
@@ -122,15 +116,12 @@ implementation {
       resource_call = &s;
     }
     
-    if(milli != 0) {
-      p.milli = &milli;
-      call SystemCall.start(timerTask, &s, INVALID_ID, &p);
-    }
-    else {
-      call SystemCall.start(releaseTask, &s, INVALID_ID, &p); 
-      if(p.error == SUCCESS)
-        call SystemCall.start(requestTask, &s, INVALID_ID, &p); 
-    }
+    if(milli != 0)
+      call ThreadSleep.sleep(milli);
+
+    call SystemCall.start(releaseTask, &s, INVALID_ID, &p); 
+    if(p.error == SUCCESS)
+      call SystemCall.start(requestTask, &s, INVALID_ID, &p); 
     
     atomic {
       resource_call = NULL;
@@ -138,16 +129,6 @@ implementation {
     }  
   }
   
-  event void Timer.fired[uint8_t id]() {
-    thread_t* t = call ThreadScheduler.threadInfo(id);
-    syscall_t* s = t->syscall;
-    params_t* p = t->syscall->params;
-    call SystemCall.start(releaseTask, s, INVALID_ID, p); 
-    if(p->error == SUCCESS)
-      call SystemCall.start(requestTask, s, INVALID_ID, p);   
-    else call SystemCall.finish(s); 
-  }
-  
   /************************* isOwner pass through *****************************/
   command error_t BlockingResource.isOwner() {
     return call Resource.isOwner();
diff --git a/tos/lib/tosthreads/system/BlockingSendC.nc b/tos/lib/tosthreads/system/BlockingSendC.nc
new file mode 100644 (file)
index 0000000..7b70284
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#define UQ_BLOCKING_SEND "Blocking.Send"
+
+generic configuration BlockingSendC() {
+  provides {
+    interface BlockingSend;
+  }
+  uses {
+    interface Send;
+  }
+}
+
+implementation {
+  enum {
+    CLIENT_ID = unique(UQ_BLOCKING_SEND),
+  };
+
+  components BlockingSendP;
+  
+  BlockingSend = BlockingSendP.BlockingSend[CLIENT_ID];
+  Send = BlockingSendP.Send[CLIENT_ID];
+}
diff --git a/tos/lib/tosthreads/system/BlockingSendImplP.nc b/tos/lib/tosthreads/system/BlockingSendImplP.nc
new file mode 100644 (file)
index 0000000..e0738cb
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+#include "message.h"
+
+module BlockingSendImplP {
+  provides {
+    interface Init;
+    interface BlockingSend[uint8_t id];
+  }
+  uses {
+    interface Send[uint8_t id];
+    interface SystemCall;
+    interface SystemCallQueue;
+  }
+}
+
+implementation {
+
+  typedef struct params {
+    message_t* msg;
+    uint8_t len;
+    error_t error;
+  } params_t;
+
+  syscall_queue_t send_queue;
+  command error_t Init.init() {
+    call SystemCallQueue.init(&send_queue);
+    return SUCCESS;
+  }
+  
+  void sendTask(syscall_t* s) {
+    params_t* p = s->params;
+    p->error = call Send.send[s->id](p->msg, p->len);
+    if(p->error != SUCCESS)
+      call SystemCall.finish(s);
+  }  
+  
+  command error_t BlockingSend.send[uint8_t id](message_t* msg, uint8_t len) {
+    syscall_t s;
+    params_t p;
+    atomic {
+      if(call SystemCallQueue.find(&send_queue, id) != NULL)
+        return EBUSY;
+      call SystemCallQueue.enqueue(&send_queue, &s);
+    }
+    
+    p.msg = msg;
+    p.len = len;
+    call SystemCall.start(&sendTask, &s, id, &p);
+    
+    atomic {
+      call SystemCallQueue.remove(&send_queue, &s);
+      return p.error;
+    }
+  }
+  
+  event void Send.sendDone[uint8_t id](message_t* msg, error_t error) {
+    syscall_t* s = call SystemCallQueue.find(&send_queue, id);
+    params_t* p = s->params;    
+    p->error = error;
+    call SystemCall.finish(s);
+  }
+  
+  command uint8_t BlockingSend.maxPayloadLength[uint8_t id]() {
+    return call Send.maxPayloadLength[id]();
+  }
+  
+  command void* BlockingSend.getPayload[uint8_t id](message_t* msg, uint8_t len) {
+    return call Send.getPayload[id](msg, len);
+  }
+  
+  default command error_t Send.send[uint8_t id](message_t* msg, uint8_t len) { return FAIL; }
+  default command uint8_t Send.maxPayloadLength[uint8_t id]() { return 0; }
+  default command void* Send.getPayload[uint8_t id](message_t* msg, uint8_t len) { return NULL; }
+}
diff --git a/tos/lib/tosthreads/system/BlockingSendP.nc b/tos/lib/tosthreads/system/BlockingSendP.nc
new file mode 100644 (file)
index 0000000..1c8b06f
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2008 Johns Hopkins University.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the (updated) modification history and the author appear in
+ * all copies of this source code.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
+ * OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/**
+ * @author Chieh-Jan Mike Liang <cliang4@cs.jhu.edu>
+ */
+
+configuration BlockingSendP {
+  provides {
+    interface BlockingSend[uint8_t id];
+  }
+  uses {
+    interface Send[uint8_t id];
+  }
+}
+
+implementation {
+  components MainC,
+             SystemCallC,
+             SystemCallQueueC,
+             BlockingSendImplP;
+  
+  MainC.SoftwareInit -> BlockingSendImplP;
+
+  BlockingSend = BlockingSendImplP;
+  Send = BlockingSendImplP;
+  
+  BlockingSendImplP.SystemCallQueue -> SystemCallQueueC;
+  BlockingSendImplP.SystemCall -> SystemCallC;
+}
index bbd8938010b2900b85dd7c0506e020d0943e282c..7ec4d389e90bbe05092c548e59141ad0238b80a9 100644 (file)
@@ -43,10 +43,8 @@ generic configuration BlockingSerialAMReceiverC(am_id_t amId) {
   }
 }
 implementation {
-  components SerialActiveMessageC;
   components BlockingSerialActiveMessageC as AM;
   BlockingReceive = AM.BlockingReceive[amId];
-  AM.Receive[amId] -> SerialActiveMessageC.Receive[amId];
   
   Packet = AM;
   AMPacket = AM;
index 66c9262c716e4cea9ab467d696f131ed2a8cb5a2..b866dea1f413632f3cf48499ceaf196943562bc1 100644 (file)
@@ -45,10 +45,8 @@ generic configuration BlockingSerialAMSenderC(am_id_t AMId) {
 }
 
 implementation {
-  components SerialActiveMessageC;
   components BlockingSerialActiveMessageC as AM;
   BlockingAMSend = AM.BlockingAMSend[AMId];
-  AM.AMSend[AMId] -> SerialActiveMessageC.AMSend[AMId];
   
   Packet = AM;
   AMPacket = AM;
index f9b9ed3d75fd70e18f6d13a7ab4beab0b1666cbd..69c12ec77ead8051d57367e40ee8563c3aecacb6 100644 (file)
@@ -44,24 +44,21 @@ configuration BlockingSerialActiveMessageC {
     interface AMPacket;
     interface PacketAcknowledgements;
   }
-  uses {
-    interface Receive as Receive[uint8_t id];
-    interface AMSend as AMSend[uint8_t id];
-  }
 }
 implementation {
   components SerialActiveMessageC as AM;
   components new BlockingStdControlC();
   components BlockingSerialAMReceiverP as AMReceiverP;
   components BlockingSerialAMSenderP as AMSenderP;
+  
   BlockingStdControl = BlockingStdControlC;
   BlockingReceive = AMReceiverP;
   BlockingReceiveAny = AMReceiverP;
   BlockingAMSend = AMSenderP;
   
   BlockingStdControlC.SplitControl -> AM;
-  Receive = AMReceiverP.Receive;
-  AMSend = AMSenderP.AMSend;
+  AMReceiverP.Receive -> AM.ReceiveDefault;
+  AMSenderP.AMSend -> AM.AMSend;
     
   Packet       = AM;
   AMPacket     = AM;
index 4866a5c0944ef17a51bfe861a3701411212656bc..e19fb9e7fee62efc8978bddb443d38fe1c34c8d2 100644 (file)
@@ -122,8 +122,8 @@ implementation {
     p->error = error;
     call SystemCall.finish(s);
   }
-  default command error_t SplitControl.start[uint8_t id]() { return SUCCESS; }
-  default command error_t SplitControl.stop[uint8_t id]() { return SUCCESS; }
+  default command error_t SplitControl.start[uint8_t id]() { return FAIL; }
+  default command error_t SplitControl.stop[uint8_t id]() { return FAIL; }
 }
 
 
index cb4cd804a62745c524e9563aae2ddaa724df2ba1..de03f20dda0c6c04ebb1c1c96405fa3d549cd4be 100644 (file)
@@ -137,11 +137,18 @@ happy:
   command error_t DynamicThread.sleep(uint32_t milli) {
     return call ThreadSleep.sleep(milli);
   }
+  command error_t DynamicThread.join(tosthread_t* t) {
+    return call ThreadScheduler.joinThread(*t);
+  }
   
   async command thread_t* ThreadInfo.get[uint8_t id]() {
     atomic return thread_info[id - TOSTHREAD_NUM_STATIC_THREADS];
   }
   
+  async command error_t ThreadInfo.reset[uint8_t id]() {
+    return FAIL;
+  }
+  
   async event void ThreadCleanup.cleanup[uint8_t id]() {
     signal ThreadNotification.aboutToDestroy[id]();
     atomic {
index 64947ac4af9b2037905cd03cfe94cc53c7cadea3..710d281c019fb5216cc27fbeeada4ea4eff108d8 100644 (file)
@@ -54,6 +54,10 @@ implementation {
   components TinyThreadSchedulerC;
   components StaticThreadC;
     
+#ifdef SAFE_TINYOS
+  components SafeFailureHandlerC;
+#endif
+
   // Export the SoftwareInit and Boot for applications
   SoftwareInit = TinyOSMainP.SoftwareInit;
   Boot = TinyOSMainP;
index ace29d103769c7027c0a6d757d4f422c56cebe39..f4e1e92c07ebf6495907604f93c9be085880915f 100644 (file)
@@ -50,11 +50,14 @@ module StaticThreadP {
 implementation {
 
   error_t init(uint8_t id, void* arg) {
+    error_t r1, r2;
     thread_t* thread_info = call ThreadInfo.get[id]();
     thread_info->start_arg_ptr = arg; 
     thread_info->mutex_count = 0;
     thread_info->next_thread = NULL;
-    return call ThreadScheduler.initThread(id);
+    r1 = call ThreadInfo.reset[id]();
+    r2 = call ThreadScheduler.initThread(id);
+    return ecombine(r1, r2);
   }
   
   command error_t Thread.start[uint8_t id](void* arg) {
@@ -87,6 +90,10 @@ implementation {
     return call ThreadSleep.sleep(milli);
   }
   
+  command error_t Thread.join[uint8_t id]() {
+    return call ThreadScheduler.joinThread(id);
+  }
+  
   event void ThreadFunction.signalThreadRun[uint8_t id](void *arg) {
     signal Thread.run[id](arg);
   }
@@ -97,6 +104,7 @@ implementation {
   
   default event void Thread.run[uint8_t id](void* arg) {}
   default async command thread_t* ThreadInfo.get[uint8_t id]() {return NULL;}
+  default async command error_t ThreadInfo.reset[uint8_t id]() {return FAIL;}
   default async event void ThreadNotification.justCreated[uint8_t id]() {}
   default async event void ThreadNotification.aboutToDestroy[uint8_t id]() {}
 
index b971299a73332db7e94787892c94f5c39836b38b..c9cd980eab70638c69309d76275ae674f9323d40 100644 (file)
@@ -51,7 +51,7 @@ implementation {
     signal ThreadFunction.signalThreadRun(arg);
   }
   
-  command error_t Init.init() {
+  error_t init() {
     thread_info.next_thread = NULL;
     thread_info.id = thread_id;
     thread_info.init_block = NULL;
@@ -64,6 +64,14 @@ implementation {
     return SUCCESS;
   }
   
+  command error_t Init.init() {
+    return init();
+  }
+  
+  async command error_t ThreadInfo.reset() {
+    return init();
+  }
+  
   async command thread_t* ThreadInfo.get() {
     return &thread_info;
   }
index 9b4861a9dfc52f2cdfcc9472e93209fa132c9445..805260516e696aa4b5231d83e33442c3a2eaf1da 100644 (file)
@@ -50,12 +50,21 @@ implementation {
   async command thread_t* ThreadInfo.get[uint8_t id]() {
     return call StaticThreadInfo.get[id]();
   }
+  async command error_t ThreadInfo.reset[uint8_t id]() {
+    return call StaticThreadInfo.reset[id]();
+  }
   default async command thread_t* StaticThreadInfo.get[uint8_t id]() {
     return call DynamicThreadInfo.get[id]();
   }
+  default async command error_t StaticThreadInfo.reset[uint8_t id]() {
+    return call DynamicThreadInfo.reset[id]();
+  }
   default async command thread_t* DynamicThreadInfo.get[uint8_t id]() {
     return call StaticThreadInfo.get[id]();
   }
+  default async command error_t DynamicThreadInfo.reset[uint8_t id]() {
+    return call StaticThreadInfo.reset[id]();
+  }
   async event void ThreadCleanup.cleanup[uint8_t id]() {
     signal StaticThreadCleanup.cleanup[id]();
   }
index 65554cf0298b61291e3572adfd156570afcce5fe..d78212d99aa729b7ee10410a1a3dbb60a288ef05 100644 (file)
@@ -62,8 +62,20 @@ implementation {
     return SUCCESS;
   }
   
+  //Need to add a cancel command so that components like
+  //BlockingAMReceiverImplP can use the ThreadSleep interface
+  //directly instead of reusing the underlying ThreadTimerC 
+  //component.  The current implementation does things this way
+  //and causes us to be defensive in here since the same 
+  //TimerMilli.fired() event is sent to that component as well.
+  //Basically its just broken....  cancel() would get rid of this.
+  
+  //Also need some sort of a sleepWithSyscall command
+  //Need to think about this one a little more
+  
   event void TimerMilli.fired[uint8_t id]() {
     thread_t* t = call ThreadScheduler.threadInfo(id);
-    call SystemCall.finish(t->syscall);
+    if(t->syscall->syscall_ptr == sleepTask)
+           call SystemCall.finish(t->syscall);
   }
 }
index 2df6d5df357c351c65ae1888f61641f73e5fb65a..8c8e44238099fa329c6f88969180f33d3a2afc44 100644 (file)
  * @author Kevin Klues <klueska@cs.stanford.edu> 
  */
 
+#ifdef DYNTHREADS 
+  #define AT_SPONTANEOUS       @spontaneous()
+#else
+  #define AT_SPONTANEOUS
+#endif
+
 module TinyOSMainP {
   provides {
     interface Boot;
@@ -93,6 +99,10 @@ implementation {
     call TaskScheduler.taskLoop();
     
   }
+  
+  async command error_t ThreadInfo.reset() {
+    return FAIL;
+  }
 
   async command thread_t* ThreadInfo.get() {
     return &thread_info;
index cf5c283daed1a9e29ffb9099ced62b9360b774fc..0d4d60362e21fff87b805af5340610b808e1c943 100644 (file)
@@ -57,6 +57,9 @@ implementation {
   ThreadScheduler = Sched;
   Sched.McuSleep -> Sleep;
   
+  components BitArrayUtilsC;
+  Sched.BitArrayUtils -> BitArrayUtilsC;
+  
   components ThreadQueueC;
   Sched.ThreadQueue -> ThreadQueueC;
   
index 1ae67708558488bad103d2c6760a5a5d2dd75864..8466a9821513ef86e4987f450682b956b9b1322d 100644 (file)
@@ -32,7 +32,7 @@
 /**
  * @author Kevin Klues <klueska@cs.stanford.edu>
  */
+  
 module TinyThreadSchedulerP {
   provides {
     interface ThreadScheduler;
@@ -43,6 +43,7 @@ module TinyThreadSchedulerP {
     interface Boot as ThreadSchedulerBoot;
     interface ThreadInfo[uint8_t id];
     interface ThreadQueue;
+    interface BitArrayUtils;
     interface McuSleep;
     interface Leds;
     interface Timer<TMilli> as PreemptionAlarm;
@@ -56,10 +57,19 @@ implementation {
   //Pointer to yielding thread
   thread_t* yielding_thread;
   //Number of threads started, and currently capable of running if given the chance
-  uint8_t num_started_threads;
+  uint8_t num_runnable_threads;
   //Thread queue for keeping track of threads waiting to run
   thread_queue_t ready_queue;
   
+  void task alarmTask() {
+    uint8_t temp;
+    atomic temp = num_runnable_threads;
+    if(temp <= 1)
+      call PreemptionAlarm.stop();
+    else if(temp > 1)
+      call PreemptionAlarm.startOneShot(TOSTHREAD_PREEMPTION_PERIOD);
+  }
+  
   /* switch_threads()
    * This routine swaps the stack and allows a thread to run.
    * Needs to be in a separate function like this so that the 
@@ -88,7 +98,7 @@ implementation {
     while(TRUE) {
       bool mt;
       atomic mt = (call ThreadQueue.isEmpty(&ready_queue) == TRUE);
-      if(!mt) break;
+      if(!mt || tos_thread->state == TOSTHREAD_STATE_READY) break;
       call McuSleep.sleep();
     }
   }
@@ -100,7 +110,7 @@ implementation {
    */
   void scheduleNextThread() {
     if(tos_thread->state == TOSTHREAD_STATE_READY)
-      current_thread = call ThreadQueue.remove(&ready_queue, tos_thread);
+      current_thread = tos_thread;
     else
       current_thread = call ThreadQueue.dequeue(&ready_queue);
 
@@ -128,22 +138,48 @@ implementation {
   void suspend(thread_t* thread) {
     //if there are no active threads, put the MCU to sleep
     //Then wakeup the TinyOS thread whenever the MCU wakes up again
+    #ifdef TOSTHREADS_TIMER_OPTIMIZATION
+      num_runnable_threads--;
+         post alarmTask();    
+       #endif
     sleepWhileIdle();
     interrupt(thread);
   }
   
+  void wakeupJoined(thread_t* t) {
+    int i,j,k;
+    k = 0;
+    for(i=0; i<sizeof(t->joinedOnMe); i++) {
+      if(t->joinedOnMe[i] == 0) {
+        k+=8;
+        continue;
+      }
+      for(j=0; j<8; j++) {
+        if(t->joinedOnMe[i] & 0x1)
+          call ThreadScheduler.wakeupThread(k);
+        t->joinedOnMe[i] >>= 1;
+        k++;
+      }
+    }
+  }
+  
   /* stop
    * This routine stops a thread by putting it into the inactive state
    * and decrementing any necessary variables used to keep track of
    * threads by the thread scheduler.
    */
-   void stop(thread_t* t) {
-     t->state = TOSTHREAD_STATE_INACTIVE;
-     num_started_threads--;
-     if(num_started_threads == 1)
-       call PreemptionAlarm.stop();
-     signal ThreadCleanup.cleanup[t->id]();
-   }
+  void stop(thread_t* t) {
+    t->state = TOSTHREAD_STATE_INACTIVE;
+    num_runnable_threads--;
+    wakeupJoined(t);
+    #ifdef TOSTHREADS_TIMER_OPTIMIZATION
+         post alarmTask();    
+       #else
+      if(num_runnable_threads == 1)
+        call PreemptionAlarm.stop();
+    #endif
+    signal ThreadCleanup.cleanup[t->id]();
+  }
   
   /* This executes and cleans up a thread
    */
@@ -163,7 +199,7 @@ implementation {
   } 
   
   event void ThreadSchedulerBoot.booted() {
-    num_started_threads = 0;
+    num_runnable_threads = 0;
     tos_thread = call ThreadInfo.get[TOSTHREAD_TOS_THREAD_ID]();
     tos_thread->id = TOSTHREAD_TOS_THREAD_ID;
     call ThreadQueue.init(&ready_queue);
@@ -178,6 +214,7 @@ implementation {
     thread_t* t = (call ThreadInfo.get[id]());
     t->state = TOSTHREAD_STATE_INACTIVE;
     t->init_block = current_thread->init_block;
+    call BitArrayUtils.clrArray(t->joinedOnMe, sizeof(t->joinedOnMe));
     PREPARE_THREAD(t, threadWrapper);
     return SUCCESS;
   }
@@ -186,9 +223,13 @@ implementation {
     atomic {
       thread_t* t = (call ThreadInfo.get[id]());
       if(t->state == TOSTHREAD_STATE_INACTIVE) {
-        num_started_threads++;
-        if(num_started_threads == 2)
-          call PreemptionAlarm.startOneShot(TOSTHREAD_PREEMPTION_PERIOD);
+        num_runnable_threads++;
+        #ifdef TOSTHREADS_TIMER_OPTIMIZATION
+          post alarmTask();
+        #else 
+          if(num_runnable_threads == 2)
+            call PreemptionAlarm.startOneShot(TOSTHREAD_PREEMPTION_PERIOD);
+        #endif
         t->state = TOSTHREAD_STATE_READY;
         call ThreadQueue.enqueue(&ready_queue, t);
         return SUCCESS;
@@ -224,7 +265,8 @@ implementation {
     atomic {
       if(current_thread->state == TOSTHREAD_STATE_ACTIVE) {
         current_thread->state = TOSTHREAD_STATE_READY;
-        call ThreadQueue.enqueue(&ready_queue, current_thread);
+        if(current_thread != tos_thread)
+          call ThreadQueue.enqueue(&ready_queue, current_thread);
         interrupt(current_thread);
         return SUCCESS;
       }
@@ -232,11 +274,31 @@ implementation {
     }
   }
   
+  async command error_t ThreadScheduler.joinThread(thread_id_t id) { 
+    thread_t* t = call ThreadInfo.get[id]();
+    atomic {
+      if(current_thread == tos_thread)
+        return FAIL;
+      if (t->state != TOSTHREAD_STATE_INACTIVE) {
+        call BitArrayUtils.setBit(t->joinedOnMe, current_thread->id);
+        call ThreadScheduler.suspendCurrentThread();
+        return SUCCESS;
+      }
+    }
+    return EALREADY;
+  }
+  
   async command error_t ThreadScheduler.wakeupThread(uint8_t id) {
     thread_t* t = call ThreadInfo.get[id]();
     if((t->state) == TOSTHREAD_STATE_SUSPENDED) {
       t->state = TOSTHREAD_STATE_READY;
-      call ThreadQueue.enqueue(&ready_queue, call ThreadInfo.get[id]());
+      if(t != tos_thread) {
+        call ThreadQueue.enqueue(&ready_queue, call ThreadInfo.get[id]());
+        #ifdef TOSTHREADS_TIMER_OPTIMIZATION
+          atomic num_runnable_threads++;
+          post alarmTask();
+        #endif
+      }
       return SUCCESS;
     }
     return FAIL;
@@ -267,4 +329,3 @@ implementation {
     return NULL;
   }
 }
-
index 7f811e2b212834bde22dc2f01a9372f03d72b9ba..8de2ba39feee80323f7482b146256357ac543fc4 100644 (file)
@@ -52,7 +52,7 @@ implementation {
 
   size_t malloc_heap[MALLOC_HEAP_SIZE];
 
-  void *tos_malloc (size_t size) @C() @spontaneous()
+  void *tos_malloc (size_t size) @C() AT_SPONTANEOUS
   {
     static char once = 0;
     size_t * heap_bottom = &(malloc_heap[MALLOC_HEAP_SIZE]);
@@ -103,7 +103,7 @@ implementation {
     return NULL;
   }
 
-  void tos_free (void *p) @C() @spontaneous()
+  void tos_free (void *p) @C() AT_SPONTANEOUS
   {
     size_t *t = (size_t*)p - 1;
     MARK_FREE (t);
index c86d9f744c902ac49988ea913a26cff81c92d7cf..87df6121e3ca55813ed9d38eb75581b7f1fbd5a2 100644 (file)
@@ -94,7 +94,6 @@ struct syscall {
 };
 
 //This is a thread data structure
-//This structure is 43 bytes long...
 struct thread {
   //***** next_thread must be at first position in struct for casting purposes *******
   volatile struct thread* next_thread;  //Pointer to next thread for use in queues when blocked
@@ -103,6 +102,7 @@ struct thread {
   stack_ptr_t stack_ptr;                //Pointer to this threads stack
   volatile uint8_t state;               //Current state the thread is in
   volatile uint8_t mutex_count;         //A reference count of the number of mutexes held by this thread
+  uint8_t joinedOnMe[(TOSTHREAD_MAX_NUM_THREADS - 1) / 8 + 1]; //Bitmask of threads waiting for me to finish
   void (*start_ptr)(void*);             //Pointer to the start function of this thread
   void* start_arg_ptr;                  //Pointer to the argument passed as a parameter to the start function of this thread
   syscall_t* syscall;                   //Pointer to an instance of a system call
index 14103ceb921d295abda66c0ccb37d741b6f712db..99484b8ba2b8407f120c40b713961185a807283e 100644 (file)
 #include <Atm128Adc.h>
 #include <MicaTimer.h>
 
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = ATM128_POWER_IDLE,
+};
+
 // A/D constants (channels, etc)
 enum {
   CHANNEL_RSSI       = ATM128_ADC_SNGL_ADC2,
diff --git a/tos/platforms/epic/.platform b/tos/platforms/epic/.platform
new file mode 100644 (file)
index 0000000..49ae205
--- /dev/null
@@ -0,0 +1,80 @@
+
+# Perl snippets that are interpreted by ncc.
+
+# Directories to add to the include path for all Epic applications.
+# Includes that should take precedence must come first.  Platforms
+# come before chips because they may override files.  These must be
+# specified as @includes instead of -I's to @opts, otherwise the %T
+# won't be processed by ncc.
+
+push( @includes, qw(
+
+  %T/platforms/epic
+  %T/platforms/epic/chips/at45db
+  %T/platforms/epic/chips/ds2411
+  %T/platforms/telosa
+  %T/platforms/telosa/chips/cc2420
+  %T/chips/cc2420
+  %T/chips/cc2420/alarm
+  %T/chips/cc2420/control
+  %T/chips/cc2420/csma
+  %T/chips/cc2420/interfaces
+  %T/chips/cc2420/link
+  %T/chips/cc2420/lowpan
+  %T/chips/cc2420/lpl
+  %T/chips/cc2420/packet
+  %T/chips/cc2420/receive
+  %T/chips/cc2420/spi
+  %T/chips/cc2420/transmit
+  %T/chips/cc2420/unique
+  %T/chips/cc2420/security
+  %T/chips/msp430
+  %T/chips/msp430/adc12
+  %T/chips/msp430/dma
+  %T/chips/msp430/pins
+  %T/chips/msp430/timer
+  %T/chips/msp430/usart
+  %T/chips/msp430/sensors
+  %T/chips/at45db
+  %T/chips/ds2401
+  %T/lib/timer
+  %T/lib/serial
+  %T/lib/adc
+  %T/lib/power
+) );
+
+# The @opts list contains parameters that are passed to ncc.
+@opts = qw(
+  -gcc=msp430-gcc
+  -mmcu=msp430x1611
+  -fnesc-target=msp430
+  -fnesc-no-debug
+);
+
+push @opts, "-fnesc-scheduler=TinySchedulerC,TinySchedulerC.TaskBasic,TaskBasic,TaskBasic,runTask,postTask" if !$with_scheduler_flag;
+push @opts, "-mingw-gcc" if $cygwin;
+
+$ENV{'CIL_MACHINE'} =
+    "version_major=3 " .
+    "version_minor=2 " .
+    "version=msp430-3.2.3 " .
+    "short=2,2 " .
+    "int=2,2 " .
+    "long=4,2 " .
+    "long_long=8,2 " .
+    "pointer=2,2 " .
+    "enum=2,2 " .
+    "float=4,2 " .
+    "double=4,2 " .
+    "long_double=4,2 " .
+    "void=1,1 " .
+    "fun=1,2 " .
+    "wchar_size_size=2,2 " .
+    "alignof_string=1 " .
+    "max_alignment=1 " .
+    "char_wchar_signed=true,true " .
+    "const_string_literals=true " .
+    "big_endian=false " .
+    "underscore_name=false " .
+    "__builtin_va_list=true " .
+    "__thread_is_keyword=true";
diff --git a/tos/platforms/epic/DemoSensorC.nc b/tos/platforms/epic/DemoSensorC.nc
new file mode 100644 (file)
index 0000000..154a36b
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/** 
+ * DemoSensorC is a generic sensor device that provides a 16-bit
+ * value. The platform author chooses which sensor actually sits
+ * behind DemoSensorC, and though it's probably Voltage, Light, or
+ * Temperature, there are no guarantees.
+ *
+ * This particular DemoSensorC on the telosb platform provides a
+ * voltage reading, using VoltageC. 
+ *
+ * To convert from ADC counts to actual voltage, divide this reading
+ * by 4096 and multiply by 3.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$ $Date$
+ * 
+ */
+
+generic configuration DemoSensorC()
+{
+  provides interface Read<uint16_t>;
+}
+implementation
+{
+  components new VoltageC() as DemoSensor;
+  Read = DemoSensor;
+}
diff --git a/tos/platforms/epic/DemoSensorNowC.nc b/tos/platforms/epic/DemoSensorNowC.nc
new file mode 100644 (file)
index 0000000..b361595
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/** 
+ * DemoSensorNowC is a generic sensor device that provides a 16-bit
+ * value that can be read from async context. The platform author
+ * chooses which sensor actually sits behind DemoSensorNowC, and
+ * though it's probably Voltage, Light, or Temperature, there are no
+ * guarantees.
+ *
+ * This particular DemoSensorNowC on the telosb platform provides a
+ * voltage reading, using VoltageC.
+ *
+ * To convert from ADC counts to actual voltage, divide this reading
+ * by 4096 and multiply by 3.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$ $Date$
+ * 
+ */
+
+generic configuration DemoSensorNowC()
+{
+  provides interface Resource;
+  provides interface ReadNow<uint16_t>;
+}
+implementation
+{
+  components new Msp430InternalVoltageC() as DemoSensorNow;
+
+  Resource = DemoSensorNow;
+  ReadNow = DemoSensorNow;
+}
diff --git a/tos/platforms/epic/DemoSensorStreamC.nc b/tos/platforms/epic/DemoSensorStreamC.nc
new file mode 100644 (file)
index 0000000..d94e5ee
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/** 
+ * DemoSensorStreamC is a generic sensor device that provides a 16-bit
+ * value. The platform author chooses which sensor actually sits
+ * behind DemoSensorStreamC, and though it's probably Voltage, Light, or
+ * Temperature, there are no guarantees.
+ *
+ * This particular DemoSensorStreamC on the telosb platform provides a
+ * voltage reading, using VoltageStreamC. 
+ *
+ * To convert from ADC counts to actual voltage, divide this reading
+ * by 4096 and multiply by 3.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$ $Date$
+ * 
+ */
+
+generic configuration DemoSensorStreamC()
+{
+  provides interface ReadStream<uint16_t>;
+}
+implementation
+{
+  components new VoltageStreamC() as DemoSensor;
+  ReadStream = DemoSensor;
+}
diff --git a/tos/platforms/epic/HplUserButtonC.nc b/tos/platforms/epic/HplUserButtonC.nc
new file mode 100644 (file)
index 0000000..706d79a
--- /dev/null
@@ -0,0 +1,54 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telos platform
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ */
+
+configuration HplUserButtonC {
+  provides interface GeneralIO;
+  provides interface GpioInterrupt;
+}
+implementation {
+  components HplMsp430GeneralIOC as GeneralIOC;
+  components HplMsp430InterruptC as InterruptC;
+
+  components new Msp430GpioC() as UserButtonC;
+  UserButtonC -> GeneralIOC.Port27;
+  GeneralIO = UserButtonC;
+
+  components new Msp430InterruptC() as InterruptUserButtonC;
+  InterruptUserButtonC.HplInterrupt -> InterruptC.Port27;
+  GpioInterrupt = InterruptUserButtonC.Interrupt;
+}
diff --git a/tos/platforms/epic/Ieee154MessageC.nc b/tos/platforms/epic/Ieee154MessageC.nc
new file mode 100644 (file)
index 0000000..2099d1b
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+
+/**
+ *
+ * @author Stephen Dawson-Haggerty
+ */
+configuration Ieee154MessageC  {
+  provides {
+    interface SplitControl;
+
+    interface Resource as SendResource[uint8_t clientId];
+    interface Ieee154Send;
+    interface Receive as Ieee154Receive;
+
+    interface Ieee154Packet;
+    interface Packet;
+
+    interface PacketAcknowledgements;
+    interface LinkPacketMetadata;
+    interface LowPowerListening;
+    interface PacketLink;
+  }
+
+} implementation {
+  components CC2420Ieee154MessageC as Msg;
+
+  SplitControl = Msg;
+  SendResource = Msg;
+  Ieee154Send  = Msg;
+  Ieee154Receive = Msg;
+  Ieee154Packet = Msg;
+  Packet = Msg;
+  
+  PacketAcknowledgements = Msg;
+  LinkPacketMetadata = Msg;
+  LowPowerListening = Msg;
+  PacketLink = Msg;
+}
diff --git a/tos/platforms/epic/MoteClockC.nc b/tos/platforms/epic/MoteClockC.nc
new file mode 100644 (file)
index 0000000..4fe3391
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2007, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universität Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * $Id$
+ *
+ */
+ /**
+ * @author Vlado Handziski <handzisk@tkn.tu-berlind.de>
+ */
+configuration MoteClockC
+{
+  provides interface Init as MoteClockInit;
+}
+implementation
+
+{
+  components Msp430ClockC, MoteClockP;
+  
+  MoteClockInit = Msp430ClockC.Init;
+  //MoteClockP.Msp430ClockInit -> Msp430ClockC;
+}
diff --git a/tos/platforms/epic/MoteClockP.nc b/tos/platforms/epic/MoteClockP.nc
new file mode 100644 (file)
index 0000000..bd3cfdc
--- /dev/null
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2007, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universität Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * $Id$
+ *
+ */
+  /**
+ * @author Vlado Handziski <handzisk@tkn.tu-berlind.de>
+ * @author Cory Sharp <cssharp@eecs.berkeley.edu>
+ */
+module MoteClockP {
+  uses interface Msp430ClockInit;
+}
+
+implementation {
+
+  event void Msp430ClockInit.setupDcoCalibrate()
+  {
+  
+    // --- setup ---
+
+    TACTL = TASSEL1 | MC1; // source SMCLK, continuous mode, everything else 0
+    TBCTL = TBSSEL0 | MC1;
+    BCSCTL1 = XT2OFF | RSEL2;
+    BCSCTL2 = DCOR; // enable DCOR
+    TBCCTL0 = CM0;
+   }
+    
+  event void Msp430ClockInit.initClocks()
+  {
+    // BCSCTL1
+    // .XT2OFF = 1; disable the external oscillator for SCLK and MCLK
+    // .XTS = 0; set low frequency mode for LXFT1
+    // .DIVA = 0; set the divisor on ACLK to 1
+    // .RSEL, do not modify
+    BCSCTL1 = XT2OFF | (BCSCTL1 & (RSEL2|RSEL1|RSEL0));
+
+    // BCSCTL2
+    // .SELM = 0; select DCOCLK as source for MCLK
+    // .DIVM = 0; set the divisor of MCLK to 1
+    // .SELS = 0; select DCOCLK as source for SCLK
+    // .DIVS = 2; set the divisor of SCLK to 4
+    // .DCOR = 1; select internal resistor for DCO
+    BCSCTL2 = DIVS1 | DCOR;
+
+    // IE1.OFIE = 0; no interrupt for oscillator fault
+    CLR_FLAG( IE1, OFIE );
+  }
+
+  event void Msp430ClockInit.initTimerA()
+  {
+    TAR = 0;
+
+    // TACTL
+    // .TACLGRP = 0; each TACL group latched independently
+    // .CNTL = 0; 16-bit counter
+    // .TASSEL = 2; source SMCLK = DCO/4
+    // .ID = 0; input divisor of 1
+    // .MC = 0; initially disabled
+    // .TACLR = 0; reset timer A
+    // .TAIE = 1; enable timer A interrupts
+    TACTL = TASSEL1 | TAIE;
+  }
+
+  event void Msp430ClockInit.initTimerB()
+  {
+    TBR = 0;
+
+    // TBCTL
+    // .TBCLGRP = 0; each TBCL group latched independently
+    // .CNTL = 0; 16-bit counter
+    // .TBSSEL = 1; source ACLK
+    // .ID = 0; input divisor of 1
+    // .MC = 0; initially disabled
+    // .TBCLR = 0; reset timer B
+    // .TBIE = 1; enable timer B interrupts
+    TBCTL = TBSSEL0 | TBIE;
+  }
+}
diff --git a/tos/platforms/epic/MotePlatformC.nc b/tos/platforms/epic/MotePlatformC.nc
new file mode 100644 (file)
index 0000000..43ea3fb
--- /dev/null
@@ -0,0 +1,48 @@
+module MotePlatformC @safe() {
+  provides interface Init;
+  uses interface Init as SubInit;
+}
+implementation {
+
+  command error_t Init.init() {
+    // reset all of the ports to be input and using i/o functionality
+    atomic
+      {
+       P1SEL = 0;
+       P2SEL = 0;
+       P3SEL = 0;
+       P4SEL = 0;
+       P5SEL = 0;
+       P6SEL = 0;
+
+       P1OUT = 0x00;
+       P1DIR = 0xe0;
+       P2OUT = 0x30;
+       P2DIR = 0x7b;
+
+       P3OUT = 0x00;
+       P3DIR = 0xf1;
+
+       P4OUT = 0xdd;
+       P4DIR = 0xfd;
+
+       P5OUT = 0xff;
+       P5DIR = 0xff;
+
+       P6OUT = 0x00;
+       P6DIR = 0xff;
+
+       P1IE = 0;
+       P2IE = 0;
+
+       // the commands above take care of the pin directions
+       // there is no longer a need for explicit set pin
+       // directions using the TOSH_SET/CLR macros
+
+      }//atomic
+    return call SubInit.init();
+  }
+
+ default command error_t SubInit.init() { return SUCCESS; }
+}
diff --git a/tos/platforms/epic/PlatformC.nc b/tos/platforms/epic/PlatformC.nc
new file mode 100644 (file)
index 0000000..b36f1f3
--- /dev/null
@@ -0,0 +1,48 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2004-2008 The Regents of the University of
+ * California.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY
+ * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
+ * DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
+ * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
+ * UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * Initialization code responsible for booting Epic to a usable state.
+ *
+ * @author Prabal Dutta <prabal@cs.berkeley.edu>
+ */
+#include "hardware.h"
+
+configuration PlatformC {
+  provides {
+    interface Init;
+  }
+}
+implementation {
+  components PlatformP;
+  components MoteClockC;
+  components MotePlatformC;
+
+  Init = PlatformP;
+  PlatformP.MoteClockInit -> MoteClockC;
+  PlatformP.MoteInit -> MotePlatformC;
+}
diff --git a/tos/platforms/epic/PlatformLedsC.nc b/tos/platforms/epic/PlatformLedsC.nc
new file mode 100644 (file)
index 0000000..47340ea
--- /dev/null
@@ -0,0 +1,30 @@
+#include "hardware.h"
+
+configuration PlatformLedsC {
+  provides {
+    interface GeneralIO as Led0;
+    interface GeneralIO as Led1;
+    interface GeneralIO as Led2;
+  }
+  uses {
+    interface Init;
+  }
+}
+implementation {
+  components HplMsp430GeneralIOC as GeneralIOC;
+  components new Msp430GpioC() as Led0Impl;
+  components new Msp430GpioC() as Led1Impl;
+  components new Msp430GpioC() as Led2Impl;
+  components PlatformP;
+
+  Init = PlatformP.LedsInit;
+
+  Led0 = Led0Impl;
+  Led0Impl -> GeneralIOC.Port40;
+
+  Led1 = Led1Impl;
+  Led1Impl -> GeneralIOC.Port43;
+
+  Led2 = Led2Impl;
+  Led2Impl -> GeneralIOC.Port47;
+}
diff --git a/tos/platforms/epic/PlatformP.nc b/tos/platforms/epic/PlatformP.nc
new file mode 100644 (file)
index 0000000..acb3afb
--- /dev/null
@@ -0,0 +1,56 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2004-2008 The Regents of the University of
+ * California.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY
+ * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
+ * DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
+ * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
+ * UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ * Initialization code responsible for booting Epic to a usable state.
+ *
+ * @author Prabal Dutta <prabal@cs.berkeley.edu>
+ */
+#include "hardware.h"
+
+module PlatformP {
+  provides {
+    interface Init;
+  }
+  uses {
+    interface Init as MoteClockInit;
+    interface Init as MoteInit;
+    interface Init as LedsInit;
+  }
+}
+implementation {
+  command error_t Init.init() {
+    call MoteClockInit.init();
+    call MoteInit.init();
+    call LedsInit.init();
+    return SUCCESS;
+  }
+
+  default command error_t LedsInit.init() {
+    return SUCCESS;
+  }
+}
diff --git a/tos/platforms/epic/UserButton.h b/tos/platforms/epic/UserButton.h
new file mode 100644 (file)
index 0000000..d020741
--- /dev/null
@@ -0,0 +1,44 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telosb platform
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ */
+
+#ifndef USERBUTTON_H
+#define USERBUTTON_H
+
+typedef enum { BUTTON_RELEASED = 0, BUTTON_PRESSED = 1 } button_state_t;
+
+#endif
diff --git a/tos/platforms/epic/UserButtonC.nc b/tos/platforms/epic/UserButtonC.nc
new file mode 100644 (file)
index 0000000..e44b2af
--- /dev/null
@@ -0,0 +1,63 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telosb platform. Get
+ * returns the current state of the button by reading the pin,
+ * regardless of whether enable() or disable() has been called on the
+ * Interface. Notify.enable() and Notify.disable() modify the
+ * underlying interrupt state of the pin, and have the effect of
+ * enabling or disabling notifications that the button has changed
+ * state.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ */
+
+#include <UserButton.h>
+
+configuration UserButtonC {
+  provides interface Get<button_state_t>;
+  provides interface Notify<button_state_t>;
+}
+implementation {
+  components HplUserButtonC;
+  components new SwitchToggleC();
+  SwitchToggleC.GpioInterrupt -> HplUserButtonC.GpioInterrupt;
+  SwitchToggleC.GeneralIO -> HplUserButtonC.GeneralIO;
+
+  components UserButtonP;
+  Get = UserButtonP;
+  Notify = UserButtonP;
+
+  UserButtonP.GetLower -> SwitchToggleC.Get;
+  UserButtonP.NotifyLower -> SwitchToggleC.Notify;
+}
diff --git a/tos/platforms/epic/UserButtonP.nc b/tos/platforms/epic/UserButtonP.nc
new file mode 100644 (file)
index 0000000..7a34fe0
--- /dev/null
@@ -0,0 +1,75 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telosb platform
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ */
+
+#include <UserButton.h>
+
+module UserButtonP {
+  provides interface Get<button_state_t>;
+  provides interface Notify<button_state_t>;
+
+  uses interface Get<bool> as GetLower;
+  uses interface Notify<bool> as NotifyLower;
+}
+implementation {
+  
+  command button_state_t Get.get() { 
+    // telosb user button pin is high when released - invert state
+    if ( call GetLower.get() ) {
+      return BUTTON_RELEASED;
+    } else {
+      return BUTTON_PRESSED;
+    }
+  }
+
+  command error_t Notify.enable() {
+    return call NotifyLower.enable();
+  }
+
+  command error_t Notify.disable() {
+    return call NotifyLower.disable();
+  }
+
+  event void NotifyLower.notify( bool val ) {
+    // telosb user button pin is high when released - invert state
+    if ( val ) {
+      signal Notify.notify( BUTTON_RELEASED );
+    } else {
+      signal Notify.notify( BUTTON_PRESSED );
+    }
+  }
+}
diff --git a/tos/platforms/epic/VoltageC.nc b/tos/platforms/epic/VoltageC.nc
new file mode 100644 (file)
index 0000000..2da64b6
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * VoltageC is a common name for the Msp430InternalVoltageC voltage
+ * sensor available on the telosb platform.
+ *
+ * To convert from ADC counts to actual voltage, divide by 4096 and
+ * multiply by 3.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$ $Date$
+ */
+
+generic configuration VoltageC() {
+  provides interface Read<uint16_t>;
+}
+implementation {
+  components new Msp430InternalVoltageC();
+  Read = Msp430InternalVoltageC.Read;
+}
+
diff --git a/tos/platforms/epic/VoltageStreamC.nc b/tos/platforms/epic/VoltageStreamC.nc
new file mode 100644 (file)
index 0000000..2c27834
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * VoltageC is a common name for the Msp430InternalVoltageC voltage
+ * sensor available on the telosb platform.
+ *
+ * To convert from ADC counts to actual voltage, divide by 4096 and
+ * multiply by 3.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$ $Date$
+ */
+
+generic configuration VoltageStreamC() {
+  provides interface ReadStream<uint16_t>;
+}
+implementation {
+  components new Msp430InternalVoltageC();
+  ReadStream = Msp430InternalVoltageC.ReadStream;
+}
+
diff --git a/tos/platforms/epic/chips/at45db/HplAt45dbC.nc b/tos/platforms/epic/chips/at45db/HplAt45dbC.nc
new file mode 100644 (file)
index 0000000..ef992a8
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+* Copyright (c) 2006, Technische Universitat Berlin
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* - Redistributions of source code must retain the above copyright notice,
+*   this list of conditions and the following disclaimer.
+* - Redistributions in binary form must reproduce the above copyright
+*   notice, this list of conditions and the following disclaimer in the
+*   documentation and/or other materials provided with the distribution.
+* - Neither the name of the Technische Universitat Berlin nor the names
+*   of its contributors may be used to endorse or promote products derived
+*   from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+configuration HplAt45dbC {
+  provides interface HplAt45db;
+}
+implementation {
+
+  components new HplAt45dbByteC(10),
+       new Msp430Spi0C() as Spi,
+       HplAt45dbP,
+       HplMsp430GeneralIOC as MspGeneralIO,
+       new Msp430GpioC() as Select;
+
+  HplAt45db = HplAt45dbByteC;
+
+  HplAt45dbByteC.Resource -> Spi;
+  HplAt45dbByteC.FlashSpi -> Spi;
+  HplAt45dbByteC.HplAt45dbByte -> HplAt45dbP;
+
+  Select -> MspGeneralIO.Port44;
+  HplAt45dbP.Select -> Select;
+  HplAt45dbP.FlashSpi -> Spi;
+}
diff --git a/tos/platforms/epic/chips/at45db/HplAt45dbP.nc b/tos/platforms/epic/chips/at45db/HplAt45dbP.nc
new file mode 100644 (file)
index 0000000..b3be5b9
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+* Copyright (c) 2006, Technische Universitat Berlin
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* - Redistributions of source code must retain the above copyright notice,
+*   this list of conditions and the following disclaimer.
+* - Redistributions in binary form must reproduce the above copyright
+*   notice, this list of conditions and the following disclaimer in the
+*   documentation and/or other materials provided with the distribution.
+* - Neither the name of the Technische Universitat Berlin nor the names
+*   of its contributors may be used to endorse or promote products derived
+*   from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+
+module HplAt45dbP {
+  provides {
+    interface HplAt45dbByte;
+  }
+  uses {
+    interface SpiByte as FlashSpi;
+    interface GeneralIO as Select;
+  }
+}
+implementation
+{
+  command void HplAt45dbByte.select() {
+    call Select.clr();
+  }
+
+  command void HplAt45dbByte.deselect() {
+    call Select.set();
+  }
+
+  task void idleTask() {
+    uint8_t status;
+    status = call FlashSpi.write(0);
+    if (!(status & 0x80)) {
+      post idleTask();
+    } else {
+      //printf("idle: %d\n", status);
+      signal HplAt45dbByte.idle();
+    }
+  }
+
+  command void HplAt45dbByte.waitIdle() {
+    post idleTask();
+  }
+
+  command bool HplAt45dbByte.getCompareStatus() {
+    uint8_t status;
+    status = call FlashSpi.write(0);
+    //printf("s: %d\n", status);
+    return (!(status & 0x40));
+  }
+}
diff --git a/tos/platforms/epic/chips/at45db/HplAt45db_chip.h b/tos/platforms/epic/chips/at45db/HplAt45db_chip.h
new file mode 100644 (file)
index 0000000..303b351
--- /dev/null
@@ -0,0 +1,45 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2006 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+#ifndef HPLAT45DB_CHIP_H
+#define HPLAT45DB_CHIP_H
+
+// flash characteristics
+enum {
+  AT45_MAX_PAGES = 4096,
+  AT45_PAGE_SIZE = 528,
+  AT45_PAGE_SIZE_LOG2 = 9 // For those who want to ignore the last 8 bytes
+};
+
+typedef uint16_t at45page_t;
+typedef uint16_t at45pageoffset_t; /* must fit 0 to AT45_PAGE_SIZE - 1 */
+
+#endif
diff --git a/tos/platforms/epic/chips/ds2411/CachedIeeeEui64C.nc b/tos/platforms/epic/chips/ds2411/CachedIeeeEui64C.nc
new file mode 100644 (file)
index 0000000..0a61b1e
--- /dev/null
@@ -0,0 +1,40 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+/**
+ * Cache an EUI 64 at initialization time and return the cached value for
+ * subsequent queries.
+ */
+configuration CachedIeeeEui64C {
+  uses interface LocalIeeeEui64 as SubIeeeEui64;
+  provides interface LocalIeeeEui64;
+} implementation {
+  components CachedIeeeEui64P, MotePlatformC;
+
+  MotePlatformC.SubInit -> CachedIeeeEui64P.Init;
+
+  SubIeeeEui64 = CachedIeeeEui64P;
+  LocalIeeeEui64 = CachedIeeeEui64P;
+
+}
diff --git a/tos/platforms/epic/chips/ds2411/LocalIeeeEui64C.nc b/tos/platforms/epic/chips/ds2411/LocalIeeeEui64C.nc
new file mode 100644 (file)
index 0000000..cfee46f
--- /dev/null
@@ -0,0 +1,45 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ * Epic port by Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
+ */
+
+configuration LocalIeeeEui64C {
+  provides interface LocalIeeeEui64;
+} implementation {
+  components
+    OneWireMasterC as OneWireC,
+    HplDs2401C,
+    BusyWaitMicroC,
+    HplMsp430GeneralIOC, new Msp430GpioC(),
+    Ds2401ToIeeeEui64C,
+    CachedIeeeEui64C;
+
+  Msp430GpioC.HplGeneralIO -> HplMsp430GeneralIOC.Port24;
+  OneWireC.Pin -> Msp430GpioC;
+
+  OneWireC.BusyWaitMicro -> BusyWaitMicroC.BusyWait;
+  HplDs2401C.OneWire -> OneWireC;
+  Ds2401ToIeeeEui64C.Hpl -> HplDs2401C;
+  CachedIeeeEui64C.SubIeeeEui64 -> Ds2401ToIeeeEui64C;
+  LocalIeeeEui64 = CachedIeeeEui64C;
+}
diff --git a/tos/platforms/epic/chips/ds2411/PlatformIeeeEui64.h b/tos/platforms/epic/chips/ds2411/PlatformIeeeEui64.h
new file mode 100644 (file)
index 0000000..54f9849
--- /dev/null
@@ -0,0 +1,37 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ * <stevedh@eecs.berkeley.edu> changes for Epic
+ */
+
+#ifndef PLATFORMIEEEEUI64_H
+#define PLATFORMIEEEEUI64_H
+enum {
+  IEEE_EUI64_COMPANY_ID_0 = 'U',
+  IEEE_EUI64_COMPANY_ID_1 = 'C',
+  IEEE_EUI64_COMPANY_ID_2 = 'B',
+  IEEE_EUI64_SERIAL_ID_0 = 'E',
+  IEEE_EUI64_SERIAL_ID_1 = 'P',
+};
+
+#endif // PLATFORMIEEEEUI64_H
diff --git a/tos/platforms/epic/hardware.h b/tos/platforms/epic/hardware.h
new file mode 100644 (file)
index 0000000..e69eb74
--- /dev/null
@@ -0,0 +1,95 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2007-2008 The Regents of the University of
+ * California.  All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY
+ * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
+ * DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
+ * DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
+ * CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
+ * UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2004-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached
+ * INTEL-LICENSE file. If you do not find these files, copies can be
+ * found by writing to Intel Research Berkeley, 2150 Shattuck Avenue,
+ * Suite 1300, Berkeley, CA, 94704.  Attention: Intel License Inquiry.
+ */
+
+/**
+ * Hardware definition for the Epic platform.
+ *
+ * @author Prabal Dutta
+ */
+#ifndef _H_hardware_h
+#define _H_hardware_h
+
+#include "msp430hardware.h"
+
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = MSP430_POWER_ACTIVE,
+};
+
+// LEDS
+TOSH_ASSIGN_PIN(RED_LED, 4, 0);
+TOSH_ASSIGN_PIN(GREEN_LED, 4, 3);
+TOSH_ASSIGN_PIN(YELLOW_LED, 4, 7);
+
+// CC2420 RADIO
+TOSH_ASSIGN_PIN(RADIO_CSN, 4, 2);
+TOSH_ASSIGN_PIN(RADIO_VREF, 4, 5);
+TOSH_ASSIGN_PIN(RADIO_RESET, 4, 6);
+TOSH_ASSIGN_PIN(RADIO_FIFOP, 1, 0);
+TOSH_ASSIGN_PIN(RADIO_SFD, 4, 1);
+TOSH_ASSIGN_PIN(RADIO_GIO0, 1, 3);
+TOSH_ASSIGN_PIN(RADIO_FIFO, 1, 3);
+TOSH_ASSIGN_PIN(RADIO_GIO1, 1, 4);
+TOSH_ASSIGN_PIN(RADIO_CCA, 1, 4);
+
+TOSH_ASSIGN_PIN(CC_FIFOP, 1, 0);
+TOSH_ASSIGN_PIN(CC_FIFO, 1, 3);
+TOSH_ASSIGN_PIN(CC_SFD, 4, 1);
+TOSH_ASSIGN_PIN(CC_VREN, 4, 5);
+TOSH_ASSIGN_PIN(CC_RSTN, 4, 6);
+
+// USART0
+TOSH_ASSIGN_PIN(SIMO0, 3, 1);
+TOSH_ASSIGN_PIN(SOMI0, 3, 2);
+TOSH_ASSIGN_PIN(UCLK0, 3, 3);
+
+// USART1
+TOSH_ASSIGN_PIN(SIMO1, 5, 1);
+TOSH_ASSIGN_PIN(SOMI1, 5, 2);
+TOSH_ASSIGN_PIN(UCLK1, 5, 3);
+
+// UART1
+TOSH_ASSIGN_PIN(UTXD0, 3, 4);
+TOSH_ASSIGN_PIN(URXD0, 3, 5);
+TOSH_ASSIGN_PIN(UTXD1, 3, 6);
+TOSH_ASSIGN_PIN(URXD1, 3, 7);
+
+// 1-Wire
+TOSH_ASSIGN_PIN(ONEWIRE, 2, 4);
+
+// need to undef atomic inside header files or nesC ignores the directive
+#undef atomic
+
+#endif // _H_hardware_h
diff --git a/tos/platforms/epic/platform.h b/tos/platforms/epic/platform.h
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/tos/platforms/epic/platform_message.h b/tos/platforms/epic/platform_message.h
new file mode 100644 (file)
index 0000000..0c4b3b5
--- /dev/null
@@ -0,0 +1,58 @@
+/* $Id$
+ * "Copyright (c) 2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ * Defining the platform-independently named packet structures to be the
+ * chip-specific CC1000 packet structures.
+ *
+ * @author Philip Levis
+ * @version $Revision$ $Date$
+ */
+
+
+#ifndef PLATFORM_MESSAGE_H
+#define PLATFORM_MESSAGE_H
+
+#include <CC2420.h>
+#include <Serial.h>
+
+typedef union message_header {
+  cc2420_header_t cc2420;
+  serial_header_t serial;
+} message_header_t;
+
+typedef union TOSRadioFooter {
+  cc2420_footer_t cc2420;
+} message_footer_t;
+
+typedef union TOSRadioMetadata {
+  cc2420_metadata_t cc2420;
+} message_metadata_t;
+
+#endif
index eee306f511147347ca070eeb94b652e962452dc3..aa50a5ceec79760cf54e23484c9f2f781c36920c 100644 (file)
@@ -65,11 +65,8 @@ implementation
         LinkLayerC as Llc;                       //The Link Layer Control module to use
     
     //Don't change wirings below this point, just change which components
-    //They are compposed of in the list above             
+    //They are compposed of in the list above
     
-    components MainC;
-    MainC.SoftwareInit -> PacketSerializer;
-            
     SplitControl = Llc;
     Llc.MacSplitControl -> Mac.SplitControl;
     Llc.RadioSplitControl -> Radio.SplitControl;
@@ -95,7 +92,14 @@ implementation
     PacketSerializer.PhyPacketRx -> UartPhy.PhyPacketRx;
     
     UartPhy.RadioByteComm -> Radio.RadioByteComm;
+
 #ifndef RADIO_UART_VCO
     components SmclkManagerC;
 #endif
+
+#ifdef PACKETSERIALIZER_DEBUG
+    components new SerialDebugC() as SD;
+    PacketSerializer.SerialDebug -> SD;
+#endif
+
 }
diff --git a/tos/platforms/eyesIFX/WhiteBitAccessorC.nc b/tos/platforms/eyesIFX/WhiteBitAccessorC.nc
new file mode 100644 (file)
index 0000000..fdd9872
--- /dev/null
@@ -0,0 +1,49 @@
+/* -*- mode:c++; indent-tabs-mode:nil -*- 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Accessor module for link quality
+ *  
+ * @author Andreas Koepke <koepke@tkn.tu-berlin.de>
+ */
+
+#include "radiopacketfunctions.h"
+
+module WhiteBitAccessorC {
+    provides {          
+        interface LinkPacketMetadata;
+    }
+}
+implementation {
+    async command bool LinkPacketMetadata.highChannelQuality(message_t* msg) {
+        bool res = FALSE;
+        if(getMetadata(msg)->strength > 13) res = TRUE;
+        return res;
+    }
+}
index b1fd2097f10330fa7a4d2407c78ce2ed24fd1710..cf9d4ad11683c336e00924f6c19f9788d972bc67 100644 (file)
@@ -286,7 +286,7 @@ implementation
     task void UpdateNoiseFloorTask() {
         shellsort(rssisamples,NSAMPLES);
         atomic { 
-            noisefloor = (5*noisefloor + rssisamples[NSAMPLES/2])/6;
+            noisefloor = (5*noisefloor + rssisamples[NSAMPLES/2] + 3)/6;
             rssiindex = 0; 
         }
         sdDebug(60000U + noisefloor);
@@ -318,7 +318,7 @@ implementation
             } else { 
                 shellsort(rssisamples,NSAMPLES);
                 if(rssisamples[MINIMUM_POSITION] < noisefloor + THREE_SIGMA)  {
-                    noisefloor = (7*noisefloor + rssisamples[NSAMPLES/2])/8;
+                    noisefloor = (7*noisefloor + rssisamples[NSAMPLES/2] + 4)/8;
                     ++deadlockCounter;
                 }
                 else {
@@ -411,6 +411,6 @@ implementation
     async command uint16_t BatteryLevel.getLevel() {
         uint16_t l;
         atomic l = batteryLevel;
-        return (uint32_t)l*39>>5;
+        return (uint32_t)(l+3)*6/5;
     }
 }
index 8c1e786b9944335aa43c13e6f803ecc0d5c420bc..91c4f3066312eead85ce30784e4148376b9fb53f 100644 (file)
 
 #include "msp430hardware.h"
 
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = MSP430_POWER_ACTIVE,
+};
+
 // LED assignments
 TOSH_ASSIGN_PIN(RED_LED, 5, 0); // Compatibility with the mica2
 TOSH_ASSIGN_PIN(GREEN_LED, 5, 1);
index 212e4d8f27fdfaa2d0836c8a3865fa9b5f425da4..92b29b03e68118e9645e24f20e5cd7073a511a2d 100644 (file)
 
 #include "msp430hardware.h"
 
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = MSP430_POWER_ACTIVE,
+};
+
 // LED assignments
 TOSH_ASSIGN_PIN(RED_LED, 5, 0); // Compatibility with the mica2
 TOSH_ASSIGN_PIN(GREEN_LED, 5, 1);
diff --git a/tos/platforms/eyesIFX/net/lqi/CC2420ActiveMessageC.nc b/tos/platforms/eyesIFX/net/lqi/CC2420ActiveMessageC.nc
new file mode 100644 (file)
index 0000000..50121a5
--- /dev/null
@@ -0,0 +1,62 @@
+/* -*- mode:c++; indent-tabs-mode:nil -*- 
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Pseudo module to enable MultihopLqi on eyesIFX. The mapping of
+ * strength to LQI is based on the packet delivery ratio.  For CC2420
+ * the ratios were taken from: Kannan Srinivasan and Philip Levis:
+ * "RSSI is Under Appreciated" Third Workshop on Embedded Networked
+ * Sensors, EmNets 2006.
+ * 
+ * @author Andreas Köpke <koepke@tkn.tu-berlin.de>
+ */
+
+#include "radiopacketfunctions.h"
+
+module CC2420ActiveMessageC {
+    provides {
+        interface CC2420Packet;
+    }
+}
+implementation {
+    async command uint8_t CC2420Packet.getPower(message_t* p_msg ) {
+        return 31;
+    }
+    async command void CC2420Packet.setPower(message_t* p_msg, uint8_t power) {
+    }
+    async command int8_t CC2420Packet.getRssi(message_t* p_msg ) {
+        return (getMetadata(p_msg))->strength;
+    }
+    async command uint8_t CC2420Packet.getLqi( message_t* p_msg ) {
+        uint32_t s = (getMetadata(p_msg))->strength;
+        if(s > 60) s = 10;
+        if(s > 22) s = 22;
+        return (s*13/5 + 48);
+    }
+}
diff --git a/tos/platforms/eyesIFX/net/lqi/CC2420Packet.nc b/tos/platforms/eyesIFX/net/lqi/CC2420Packet.nc
new file mode 100644 (file)
index 0000000..b18df71
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * @author Jonathan Hui <jhui@archrock.com>
+ * @author David Moss
+ * @author Chad Metcalf
+ */
+
+#include "message.h"
+
+interface CC2420Packet {
+  
+  /**
+   * Get transmission power setting for current packet.
+   *
+   * @param the message
+   */
+  async command uint8_t getPower( message_t* p_msg );
+
+  /**
+   * Set transmission power for a given packet. Valid ranges are
+   * between 0 and 31.
+   *
+   * @param p_msg the message.
+   * @param power transmission power.
+   */
+  async command void setPower( message_t* p_msg, uint8_t power );
+  
+  /**
+   * Get rssi value for a given packet. For received packets, it is
+   * the received signal strength when receiving that packet. For sent
+   * packets, it is the received signal strength of the ack if an ack
+   * was received.
+   */
+  async command int8_t getRssi( message_t* p_msg );
+
+  /**
+   * Get lqi value for a given packet. For received packets, it is the
+   * link quality indicator value when receiving that packet. For sent
+   * packets, it is the link quality indicator value of the ack if an
+   * ack was received.
+   */
+  async command uint8_t getLqi( message_t* p_msg );
+  
+}
index 0ec827f7bd97f43386ab0357d39b03414462135c..efccf78a0ca4797ca910a1dd4bc6bca2b62b2099 100644 (file)
@@ -28,6 +28,7 @@ push ( @includes, qw(
   %T/chips/cc2420/spi
   %T/chips/cc2420/transmit
   %T/chips/cc2420/unique
+  %T/chips/cc2420/security
   %T/chips/pxa27x
   %T/chips/pxa27x/lib
   %T/chips/pxa27x/timer
index b6cb5d8baf4886577e7c35e22f6b9dd9778fa9e8..3ff83b7b96a38a131f632be55b48996b00ea6afa 100644 (file)
 #include "pxa27xhardware.h"
 //#include "AM.h"
 
+// enum so components can override power saving,
+// as per TEP 112.
+// Note that currently the pxa27x does not support
+// McuPowerOverride, so SLEEP_NONE is defined to
+// be 0.
+enum {
+  TOS_SLEEP_NONE = 0,
+};
+
 #define MIN(a,b) ((a) < (b) ? (a) : (b))
 
 /* Watchdog Prescaler
index c5693c265aaf4ad3b84e0cade7a70b83444d9db6..1f97d154fd5b4a99a9a189e2a8973045ea61974a 100644 (file)
@@ -13,12 +13,16 @@ push( @includes, qw(
   %T/platforms/micaz
   %T/platforms/mica
   %T/platforms/iris/chips/rf230
-  %T/chips/rf230
-  %T/chips/cc2420
+  %T/chips/rf2xx/rf230
+  %T/chips/rf2xx/layers
+  %T/chips/rf2xx/util
   %T/platforms/iris/chips/at45db
   %T/platforms/mica2/chips/at45db
   %T/platforms/mica/chips/at45db
   %T/chips/at45db
+  %T/platforms/iris/chips/ds2401
+  %T/platforms/mica2/chips/ds2401
+  %T/chips/ds2401
   %T/chips/atm1281
   %T/chips/atm1281/adc
   %T/chips/atm1281/timer
index ef6a2c3d22578b74706a3efe194378ce6ca85a6e..e95827470fe9e07816e2d056455c99cc34a3f8a9 100644 (file)
@@ -21,6 +21,8 @@
  * Author: Miklos Maroti
  */
 
+#include <RadioConfig.h>
+
 configuration ActiveMessageC
 {
        provides
@@ -30,11 +32,16 @@ configuration ActiveMessageC
                interface AMSend[uint8_t id];
                interface Receive[uint8_t id];
                interface Receive as Snoop[uint8_t id];
+               interface SendNotifier[am_id_t id];
+
                interface Packet;
                interface AMPacket;
 
                interface PacketAcknowledgements;
                interface LowPowerListening;
+#ifdef PACKET_LINK
+               interface PacketLink;
+#endif
 
                interface PacketTimeStamp<TMicro, uint32_t> as PacketTimeStampMicro;
                interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
@@ -43,17 +50,24 @@ configuration ActiveMessageC
 
 implementation
 {
-       components RF230ActiveMessageC as MAC;
-
-       SplitControl = MAC;
-       AMSend       = MAC;
-       Receive      = MAC.Receive;
-       Snoop        = MAC.Snoop;
-       Packet       = MAC;
-       AMPacket     = MAC;
-
-       PacketAcknowledgements  = MAC;
-       LowPowerListening               = MAC;
-       PacketTimeStampMilli    = MAC;
-       PacketTimeStampMicro    = MAC;
+       components RF230ActiveMessageC as MessageC;
+
+       SplitControl = MessageC;
+
+       AMSend = MessageC;
+       Receive = MessageC.Receive;
+       Snoop = MessageC.Snoop;
+       SendNotifier = MessageC;
+
+       Packet = MessageC;
+       AMPacket = MessageC;
+
+       PacketAcknowledgements = MessageC;
+       LowPowerListening = MessageC;
+#ifdef PACKET_LINK
+       PacketLink = MessageC;
+#endif
+
+       PacketTimeStampMilli = MessageC;
+       PacketTimeStampMicro = MessageC;
 }
diff --git a/tos/platforms/iris/Ieee154MessageC.nc b/tos/platforms/iris/Ieee154MessageC.nc
new file mode 100644 (file)
index 0000000..1c611f2
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration Ieee154MessageC
+{
+       provides
+       {
+               interface SplitControl;
+
+               interface Ieee154Send;
+               interface Receive as Ieee154Receive;
+               interface SendNotifier;
+
+               interface Packet;
+               interface Ieee154Packet;
+               interface Resource as SendResource[uint8_t clint];
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+               interface PacketLink;
+
+               interface PacketTimeStamp<TMicro, uint32_t> as PacketTimeStampMicro;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF230Ieee154MessageC as MessageC;
+
+       SplitControl = MessageC;
+
+       Ieee154Send = MessageC;
+       Ieee154Receive = MessageC;
+       SendNotifier = MessageC;
+
+       Packet = MessageC;
+       Ieee154Packet = MessageC;
+       SendResource = MessageC;
+
+       PacketAcknowledgements = MessageC;
+       LowPowerListening = MessageC;
+       PacketLink = MessageC;
+
+       PacketTimeStampMilli = MessageC;
+       PacketTimeStampMicro = MessageC;
+}
index aca670b3732831ec602436d809aa0132a77e9d08..6e955c0a8a1ccf81320a2bdd72815e9a10d0ca55 100644 (file)
@@ -21,7 +21,7 @@
  * Author: Miklos Maroti
  */
 
-#include <HplRF230.h>
+#include <RadioConfig.h>
 
 configuration TimeSyncMessageC
 {
@@ -34,9 +34,11 @@ configuration TimeSyncMessageC
                interface Packet;
                interface AMPacket;
 
-               interface TimeSyncAMSend<TRF230, uint32_t> as TimeSyncAMSendRadio[am_id_t id];
-               interface TimeSyncPacket<TRF230, uint32_t> as TimeSyncPacketRadio;
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface TimeSyncAMSend<TRadio, uint32_t> as TimeSyncAMSendRadio[am_id_t id];
+               interface TimeSyncPacket<TRadio, uint32_t> as TimeSyncPacketRadio;
 
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
                interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[am_id_t id];
                interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
        }
@@ -44,17 +46,19 @@ configuration TimeSyncMessageC
 
 implementation
 {
-       components RF230TimeSyncMessageC;
+       components RF230TimeSyncMessageC as MessageC;
   
-       SplitControl = RF230TimeSyncMessageC;
-  
-       Receive         = RF230TimeSyncMessageC.Receive;
-       Snoop           = RF230TimeSyncMessageC.Snoop;
-       Packet          = RF230TimeSyncMessageC;
-       AMPacket        = RF230TimeSyncMessageC;
-
-       TimeSyncAMSendRadio = RF230TimeSyncMessageC;
-       TimeSyncPacketRadio = RF230TimeSyncMessageC;
-       TimeSyncAMSendMilli = RF230TimeSyncMessageC;
-       TimeSyncPacketMilli = RF230TimeSyncMessageC;
+       SplitControl    = MessageC;
+       Receive         = MessageC.Receive;
+       Snoop           = MessageC.Snoop;
+       Packet          = MessageC;
+       AMPacket        = MessageC;
+
+       PacketTimeStampRadio    = MessageC;
+       TimeSyncAMSendRadio     = MessageC;
+       TimeSyncPacketRadio     = MessageC;
+
+       PacketTimeStampMilli    = MessageC;
+       TimeSyncAMSendMilli     = MessageC;
+       TimeSyncPacketMilli     = MessageC;
 }
diff --git a/tos/platforms/iris/chips/ds2401/PlatformIeeeEui64.h b/tos/platforms/iris/chips/ds2401/PlatformIeeeEui64.h
new file mode 100644 (file)
index 0000000..8290be9
--- /dev/null
@@ -0,0 +1,41 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+#ifndef PLATFORMIEEEEUI64_H
+#define PLATFORMIEEEEUI64_H
+
+/* For now, let us set the company ID to 'X' 'B' 'W', and the first two bytes
+ * of the serial ID to 'I' 'R'. The last three bytes of the serial ID are read
+ * from the DS2401 chip.
+ */
+enum {
+  IEEE_EUI64_COMPANY_ID_0 = 'X',
+  IEEE_EUI64_COMPANY_ID_1 = 'B',
+  IEEE_EUI64_COMPANY_ID_2 = 'W',
+  IEEE_EUI64_SERIAL_ID_0 = 'I',
+  IEEE_EUI64_SERIAL_ID_1 = 'R',
+};
+
+#endif // PLATFORMIEEEEUI64_H
diff --git a/tos/platforms/iris/chips/rf230/HplRF230.h b/tos/platforms/iris/chips/rf230/HplRF230.h
deleted file mode 100644 (file)
index 4418ffe..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-#ifndef __HPLRF230_H__
-#define __HPLRF230_H__
-
-#include <RF230.h>
-
-enum
-{
-       /**
-        * This is the value of the TRX_CTRL_0 register
-        * which configures the output pin currents and the CLKM clock
-        */
-       RF230_TRX_CTRL_0_VALUE = 0,
-
-       /**
-        * This is the default value of the CCA_MODE field in the PHY_CC_CCA register
-        * which is used to configure the default mode of the clear channel assesment
-        */
-       RF230_CCA_MODE_VALUE = RF230_CCA_MODE_3,
-
-       /**
-        * This is the value of the CCA_THRES register that controls the
-        * energy levels used for clear channel assesment
-        */
-       RF230_CCA_THRES_VALUE = 0xC7,
-};
-
-/**
- * This is the timer type of the RF230 alarm interface
- */
-typedef TOne TRF230;
-
-
-/**
- * The number of alarm ticks per one second (921600)
- */
-#define RF230_ALARM_SEC        ((7372800UL / MHZ / 32) * (1 << MICA_DIVIDE_ONE_FOR_32KHZ_LOG2))
-
-/**
- * The number of alarm ticks per one microsecond (0.9216)
- */
-#define RF230_ALARM_MICROSEC   (RF230_ALARM_SEC / 1000000.0)
-
-/* This is the default value of the TX_PWR field of the PHY_TX_PWR register. */
-#ifndef RF230_DEF_RFPOWER
-#define RF230_DEF_RFPOWER      0
-#endif
-
-/* This is the default value of the CHANNEL field of the PHY_CC_CCA register. */
-#ifndef RF230_DEF_CHANNEL
-#define RF230_DEF_CHANNEL      11
-#endif
-
-#endif//__HPLRF230_H__
diff --git a/tos/platforms/iris/chips/rf230/HplRF230.nc b/tos/platforms/iris/chips/rf230/HplRF230.nc
deleted file mode 100644 (file)
index 29faa76..0000000
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2007, Vanderbilt University
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
- * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- *
- * Author: Miklos Maroti
- */
-
-/**
- * There should be standard interfaces/commands for these
-*/
-interface HplRF230
-{
-       /**
-        * Calculates the crc. For some unknown reason the standard
-        * tinyos crcByte command swiches endianness.
-        */
-       async command uint16_t crcByte(uint16_t crc, uint8_t data);
-
-       /**
-        * Starts a split-phase SPI data transfer with the given data.
-        * A spiSplitRead command must follow this command even if the
-        * result is unimportant. The SpiByte interface should be 
-        * extended with this protocol.
-        */
-       async command void spiSplitWrite(uint8_t data);
-
-       /**
-        * Finishes the split-phase SPI data transfer by waiting till 
-        * the write command comletes and returning the received data.
-        */
-       async command uint8_t spiSplitRead();
-
-       /**
-        * This command first reads the SPI register and then writes
-        * there the new data, then returns
-        */
-       async command uint8_t spiSplitReadWrite(uint8_t data);
-
-       /**
-        * This is the standard SpiByte.write command but a little
-        * faster as we shuold not need to adjust the power state there.
-        */
-       async command uint8_t spiWrite(uint8_t data);
-}
index 91962f7ea93d366f6f3cc12b3033be748c73693c..dd4285a4dfcd6010b16dd48bf20bb7b989f1f624 100644 (file)
@@ -21,7 +21,7 @@
  * Author: Miklos Maroti
  */
 
-#include <HplRF230.h>
+#include <RadioConfig.h>
 
 configuration HplRF230C
 {
@@ -29,15 +29,14 @@ configuration HplRF230C
        {
                interface GeneralIO as SELN;
                interface Resource as SpiResource;
-               interface SpiByte;
+               interface FastSpiByte;
 
                interface GeneralIO as SLP_TR;
                interface GeneralIO as RSTN;
 
                interface GpioCapture as IRQ;
-               interface Alarm<TRF230, uint16_t> as Alarm;
-
-               interface HplRF230;
+               interface Alarm<TRadio, uint16_t> as Alarm;
+               interface LocalTime<TRadio> as LocalTimeRadio;
        }
 }
 
@@ -51,9 +50,7 @@ implementation
        
        components Atm128SpiC as SpiC;
        SpiResource = SpiC.Resource[unique("Atm128SpiC.Resource")];
-       SpiByte = SpiC;
-
-       HplRF230 = HplRF230P;
+       FastSpiByte = SpiC;
 
        components HplAtm128GeneralIOC as IO;
        SLP_TR = IO.PortB7;
@@ -68,4 +65,7 @@ implementation
 
        components RealMainP;
        RealMainP.PlatformInit -> HplRF230P.PlatformInit;
+
+       components LocalTimeMicroC;
+       LocalTimeRadio = LocalTimeMicroC;
 }
index cbe6c9487d5555bb986a60f7dab130fb3aa00362..761a2a96ba8c48d28173483541ebf987bcfab37e 100644 (file)
  * Author: Miklos Maroti
  */
 
-#include <util/crc16.h>
-#include "Atm128Spi.h"
-
 module HplRF230P
 {
        provides
        {
                interface GpioCapture as IRQ;
                interface Init as PlatformInit;
-
-               interface HplRF230;
        }
 
        uses
@@ -84,49 +79,4 @@ implementation
        {
                call Capture.stop();
        }
-
-       // TODO: Check why the default crcByte implementation is in a different endianness
-       inline async command uint16_t HplRF230.crcByte(uint16_t crc, uint8_t data)
-       {
-               return _crc_ccitt_update(crc, data);
-       }
-
-       inline async command void HplRF230.spiSplitWrite(uint8_t data)
-       {
-               // the SPI must have been started, so do not waste time here
-               // SET_BIT(SPCR, SPE);
-
-               SPDR = data;
-       }
-
-       inline async command uint8_t HplRF230.spiSplitRead()
-       {
-           while( !( SPSR & 0x80 ) )
-                       ;
-               return SPDR;
-       }
-
-       inline async command uint8_t HplRF230.spiSplitReadWrite(uint8_t data)
-       {
-               uint8_t b;
-
-           while( !( SPSR & 0x80 ) )
-                       ;
-               b = SPDR;
-               SPDR = data;
-
-               return b;
-       }
-
-       inline async command uint8_t HplRF230.spiWrite(uint8_t data)
-       {
-               // the SPI must have been started, so do not waste time here
-               // SET_BIT(SPCR, SPE);
-
-               SPDR = data;
-           while( !( SPSR & 0x80 ) )
-                       ;
-
-               return SPDR;
-       }
 }
diff --git a/tos/platforms/iris/chips/rf230/RadioConfig.h b/tos/platforms/iris/chips/rf230/RadioConfig.h
new file mode 100644 (file)
index 0000000..e73d354
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#ifndef __RADIOCONFIG_H__
+#define __RADIOCONFIG_H__
+
+#include <MicaTimer.h>
+#include <RF230DriverLayer.h>
+#include <util/crc16.h>
+
+enum
+{
+       /**
+        * This is the value of the TRX_CTRL_0 register
+        * which configures the output pin currents and the CLKM clock
+        */
+       RF230_TRX_CTRL_0_VALUE = 0,
+
+       /**
+        * This is the default value of the CCA_MODE field in the PHY_CC_CCA register
+        * which is used to configure the default mode of the clear channel assesment
+        */
+       RF230_CCA_MODE_VALUE = RF230_CCA_MODE_3,
+
+       /**
+        * This is the value of the CCA_THRES register that controls the
+        * energy levels used for clear channel assesment
+        */
+       RF230_CCA_THRES_VALUE = 0xC7,
+};
+
+/* This is the default value of the TX_PWR field of the PHY_TX_PWR register. */
+#ifndef RF230_DEF_RFPOWER
+#define RF230_DEF_RFPOWER      0
+#endif
+
+/* This is the default value of the CHANNEL field of the PHY_CC_CCA register. */
+#ifndef RF230_DEF_CHANNEL
+#define RF230_DEF_CHANNEL      11
+#endif
+
+/* The number of microseconds a sending IRIS mote will wait for an acknowledgement */
+#ifndef SOFTWAREACK_TIMEOUT
+#define SOFTWAREACK_TIMEOUT    800
+#endif
+
+/*
+ * This is the command used to calculate the CRC for the RF230 chip. 
+ * TODO: Check why the default crcByte implementation is in a different endianness
+ */
+inline uint16_t RF230_CRCBYTE_COMMAND(uint16_t crc, uint8_t data)
+{
+       return _crc_ccitt_update(crc, data);
+}
+
+/**
+ * This is the timer type of the radio alarm interface
+ */
+typedef TOne TRadio;
+
+/**
+ * The number of radio alarm ticks per one microsecond (0.9216). 
+ * We use integers and no parentheses just to make deputy happy.
+ * Ok, further hacks were required for deputy, I removed 00 from the
+ * beginning and end to ba able to handle longer wait periods.
+ */
+#define RADIO_ALARM_MICROSEC   (73728UL / MHZ / 32) * (1 << MICA_DIVIDE_ONE_FOR_32KHZ_LOG2) / 10000UL
+
+/**
+ * The base two logarithm of the number of radio alarm ticks per one millisecond
+ */
+#define RADIO_ALARM_MILLI_EXP  (5 + MICA_DIVIDE_ONE_FOR_32KHZ_LOG2)
+
+/**
+ * Make PACKET_LINK automaticaly enabled for Ieee154MessageC
+ */
+#if !defined(TFRAMES_ENABLED) && !defined(PACKET_LINK)
+#define PACKET_LINK
+#endif
+
+#endif//__RADIOCONFIG_H__
index 9bc04c4a8aff86d60dc44f1f3ee08457eeb41e9d..3b2ffb021e2a6226ac3065550c189304d42ba4ff 100644 (file)
@@ -1,32 +1,3 @@
-/* $Id$
- * "Copyright (c) 2005 The Regents of the University  of California.  
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice, the following
- * two paragraphs and the author appear in all copies of this software.
- * 
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
- *
- * Copyright (c) 2002-2005 Intel Corporation
- * All rights reserved.
- *
- * This file is distributed under the terms in the attached INTEL-LICENSE     
- * file. If you do not find these files, copies can be found by writing to
- * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
- * 94704.  Attention:  Intel License Inquiry.
- */
-
 /*
  * Copyright (c) 2007, Vanderbilt University
  * All rights reserved.
  *
  */
 
-/**
- * Defining the platform-independently named packet structures to be the
- * chip-specific CC1000 packet structures.
- *
- * @author Philip Levis
- * @date   May 16 2005
- * Revision:  $Revision$
- */
-
-
 #ifndef PLATFORM_MESSAGE_H
 #define PLATFORM_MESSAGE_H
 
-#include <RF230Packet.h>
+#include <RF230Radio.h>
 #include <Serial.h>
 
 typedef union message_header {
index e32f6c361b613ce08def3a43588126c92deef39b..3d3be2710fd89baddf6ac46b5d29df465eba9d21 100644 (file)
@@ -26,7 +26,7 @@ configuration Counter32khz32C
 implementation
 {
   components CounterOne16C as Counter16, 
-    new TransformCounterC(T32khz, uint32_t, T32khz, uint16_t,
+    new TransformCounterC(T32khz, uint32_t, TOne, uint16_t,
                          MICA_DIVIDE_ONE_FOR_32KHZ_LOG2,
                          counter_one_overflow_t) as Transform32;
 
index 531ccc75ed94904e9b9c8713f74f85a650bca198..9d034d6124381cb032e5bda4f60fed8e6125eb18 100644 (file)
@@ -54,6 +54,9 @@ configuration ActiveMessageC {
     interface Packet;
     interface AMPacket;
     interface PacketAcknowledgements;
+    interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli; 
+    interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz; 
+    interface LowPowerListening;
   }
 }
 implementation {
@@ -67,4 +70,7 @@ implementation {
   Packet       = AM;
   AMPacket     = AM;
   PacketAcknowledgements = AM;
+  PacketTimeStampMilli   = AM;
+  PacketTimeStamp32khz   = AM;
+  LowPowerListening     = AM;
 }
diff --git a/tos/platforms/mica2/TimeSyncMessageC.nc b/tos/platforms/mica2/TimeSyncMessageC.nc
new file mode 100644 (file)
index 0000000..fa22a77
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * "Copyright (c) 2004-2005 The Regents of the University  of California.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2004-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ *
+ * The Active Message layer on the mica2 platform. This is a naming wrapper
+ * around the CC1000 Active Message layer that implemets timesync interface (TEP 133).
+ *
+ * @author Philip Levis
+ * @author Brano Kusy
+ * @author Marco Langerwisch (Mica2 port)
+ */
+
+configuration TimeSyncMessageC {
+  provides
+  {
+    interface SplitControl;
+    interface Receive[am_id_t id];
+    interface Receive as Snoop[am_id_t id];
+    interface Packet;
+    interface AMPacket;
+
+    interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
+    interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+
+    interface TimeSyncAMSend<T32khz, uint32_t> as TimeSyncAMSend32khz[am_id_t id];
+    interface TimeSyncPacket<T32khz, uint32_t> as TimeSyncPacket32khz;
+
+    interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[am_id_t id];
+    interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
+  }
+}
+implementation {
+  components CC1000TimeSyncMessageC as AM;
+
+  SplitControl = AM;
+
+  Receive      = AM.Receive;
+  Snoop        = AM.Snoop;
+  Packet       = AM;
+  AMPacket     = AM;
+  TimeSyncAMSend32khz       = AM;
+  TimeSyncAMSendMilli       = AM;
+  TimeSyncPacket32khz       = AM;
+  TimeSyncPacketMilli       = AM;
+  PacketTimeStamp32khz      = AM;
+  PacketTimeStampMilli      = AM;
+}
diff --git a/tos/platforms/mica2/chips/ds2401/CachedIeeeEui64C.nc b/tos/platforms/mica2/chips/ds2401/CachedIeeeEui64C.nc
new file mode 100644 (file)
index 0000000..0a61b1e
--- /dev/null
@@ -0,0 +1,40 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+/**
+ * Cache an EUI 64 at initialization time and return the cached value for
+ * subsequent queries.
+ */
+configuration CachedIeeeEui64C {
+  uses interface LocalIeeeEui64 as SubIeeeEui64;
+  provides interface LocalIeeeEui64;
+} implementation {
+  components CachedIeeeEui64P, MotePlatformC;
+
+  MotePlatformC.SubInit -> CachedIeeeEui64P.Init;
+
+  SubIeeeEui64 = CachedIeeeEui64P;
+  LocalIeeeEui64 = CachedIeeeEui64P;
+
+}
diff --git a/tos/platforms/mica2/chips/ds2401/LocalIeeeEui64C.nc b/tos/platforms/mica2/chips/ds2401/LocalIeeeEui64C.nc
new file mode 100644 (file)
index 0000000..6189ee6
--- /dev/null
@@ -0,0 +1,48 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ */
+
+/**
+ * Mica2-specific wiring to access the DS2401 hardware ID chip through the
+ * LocalIeeeEui64 interface. The CachedIeeeEui64C component reads the ID
+ * during hardware initialization, caches it, and returns the cached value at
+ * subsequent calls to LocalIeeeEui64.getId().
+ */
+configuration LocalIeeeEui64C {
+  provides interface LocalIeeeEui64;
+} implementation {
+  components
+    OneWireMasterC as OneWireC,
+    HplDs2401C,
+    BusyWaitMicroC,
+    HplAtm128GeneralIOC,
+    Ds2401ToIeeeEui64C,
+    CachedIeeeEui64C;
+
+  OneWireC.Pin -> HplAtm128GeneralIOC.PortA4;
+  OneWireC.BusyWaitMicro -> BusyWaitMicroC.BusyWait;
+  HplDs2401C.OneWire -> OneWireC;
+  Ds2401ToIeeeEui64C.Hpl -> HplDs2401C;
+  CachedIeeeEui64C.SubIeeeEui64 -> Ds2401ToIeeeEui64C;
+  LocalIeeeEui64 = CachedIeeeEui64C;
+}
index c3dc7a9ac170b6758cc664c42df2d06b4fba7620..bfd66849ad90a99111b2ad9681323b46960560e7 100644 (file)
 #include <Atm128Adc.h>
 #include <MicaTimer.h>
 
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = ATM128_POWER_IDLE,
+};
+
 // A/D channels
 enum {
   CHANNEL_RSSI       = ATM128_ADC_SNGL_ADC0,
index fa5788516f6ba63fb5ba52112683a7f629626a3a..d59f5671c7a7146422c5677416cc986e7931d8ad 100644 (file)
 #include <Atm128Adc.h>
 #include <MicaTimer.h>
 
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = ATM128_POWER_IDLE,
+};
+
 // A/D channels
 enum {
   CHANNEL_RSSI       = ATM128_ADC_SNGL_ADC0,
index 33e6f51cd653c11bc3689364b8e266f18c2ce8cf..def15d339b413b945841313dd8c1c4641ef829dc 100644 (file)
@@ -25,6 +25,7 @@ push( @includes, qw(
   %T/chips/cc2420/spi
   %T/chips/cc2420/transmit
   %T/chips/cc2420/unique
+  %T/chips/cc2420/security
   %T/platforms/mica2/chips/at45db
   %T/platforms/mica/chips/at45db
   %T/chips/at45db
index b5d90c5a58c3c26dc2e0267c9baa7953c12c45cf..aaf2bfffcc34e4020c4e620057499ebb9c11a0ae 100644 (file)
 
 /**
  *
- * The Active Message layer on the micaZ platform. This is a naming wrapper
+ * The Active Message layer on the Telos platform. This is a naming wrapper
  * around the CC2420 Active Message layer.
  *
  * @author Philip Levis
- * @date June 19 2005
+ * @version $Revision$ $Date$
  */
 #include "Timer.h"
 
@@ -58,11 +58,12 @@ configuration ActiveMessageC {
     interface PacketAcknowledgements;
     interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
     interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+    interface LowPowerListening;
   }
 }
 implementation {
   components CC2420ActiveMessageC as AM;
-  
+
   SplitControl = AM;
   
   AMSend       = AM;
@@ -71,6 +72,7 @@ implementation {
   Packet       = AM;
   AMPacket     = AM;
   PacketAcknowledgements = AM;
+  LowPowerListening = AM;
 
   components CC2420PacketC;
   PacketTimeStamp32khz = CC2420PacketC;
diff --git a/tos/platforms/micaz/Ieee154MessageC.nc b/tos/platforms/micaz/Ieee154MessageC.nc
new file mode 100644 (file)
index 0000000..2099d1b
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+
+/**
+ *
+ * @author Stephen Dawson-Haggerty
+ */
+configuration Ieee154MessageC  {
+  provides {
+    interface SplitControl;
+
+    interface Resource as SendResource[uint8_t clientId];
+    interface Ieee154Send;
+    interface Receive as Ieee154Receive;
+
+    interface Ieee154Packet;
+    interface Packet;
+
+    interface PacketAcknowledgements;
+    interface LinkPacketMetadata;
+    interface LowPowerListening;
+    interface PacketLink;
+  }
+
+} implementation {
+  components CC2420Ieee154MessageC as Msg;
+
+  SplitControl = Msg;
+  SendResource = Msg;
+  Ieee154Send  = Msg;
+  Ieee154Receive = Msg;
+  Ieee154Packet = Msg;
+  Packet = Msg;
+  
+  PacketAcknowledgements = Msg;
+  LinkPacketMetadata = Msg;
+  LowPowerListening = Msg;
+  PacketLink = Msg;
+}
index eb4a801fc159a970ea1dddee592eb0a29b73752c..a81f723c27b0b7fea2c23570b127ee3aba0e552e 100644 (file)
@@ -47,6 +47,8 @@ configuration TimeSyncMessageC {
     interface Receive as Snoop[am_id_t id];
     interface Packet;
     interface AMPacket;
+    interface PacketAcknowledgements;
+    interface LowPowerListening;
 
     interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
     interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
@@ -67,6 +69,8 @@ implementation {
   Snoop        = AM.Snoop;
   Packet       = AM;
   AMPacket     = AM;
+  PacketAcknowledgements = AM;
+  LowPowerListening = AM;
   TimeSyncAMSend32khz       = AM;
   TimeSyncAMSendMilli       = AM;
   TimeSyncPacket32khz       = AM;
index c21554a0eb9d9bbf6b979a3bd5f2e01be50c2575..3276ed8901f6ead6474dbcfeabfb4e2126f64237 100644 (file)
 #include <Atm128Adc.h>
 #include <MicaTimer.h>
 
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = ATM128_POWER_IDLE,
+};
+
 // A/D channels
 enum {
   CHANNEL_THERMISTOR = ATM128_ADC_SNGL_ADC1    // normally unpopulated
diff --git a/tos/platforms/micaz/mac/tkn154/Makefile.include b/tos/platforms/micaz/mac/tkn154/Makefile.include
new file mode 100644 (file)
index 0000000..45a02db
--- /dev/null
@@ -0,0 +1,4 @@
+CFLAGS += -I$(TOSDIR)/platforms/micaz/mac/tkn154 \
+       -I$(TOSDIR)/platforms/telosb/mac/tkn154 \
+       -I$(TOSDIR)/platforms/telosb/mac/tkn154/timer \
+       -I$(TOSDIR)/chips/cc2420_tkn154
diff --git a/tos/platforms/micaz/mac/tkn154/README.txt b/tos/platforms/micaz/mac/tkn154/README.txt
new file mode 100644 (file)
index 0000000..8b51e01
--- /dev/null
@@ -0,0 +1,12 @@
+This directory contains the TKN15.4 "platform glue" code for the micaz
+platform. Like the telos platform, micaz uses the CC2420 radio and in order not
+to maintain identical configuration files, the micaz platform pulls in (uses) some
+files from the platform/telosb/mac/tkn154 directory. This includes the central
+MAC configurations "Ieee802154BeaconEnabledC" and "Ieee802154NonBeaconEnabledC",
+to which the next higher layer will wire to.
+The ./Makefile.include file defines in which order the directories are parsed and
+should be included by any micaz application. 
+
+More information on TKN15.4 can be found here:
+tinyos-2.x/tos/lib/mac/tkn154/README.txt
diff --git a/tos/platforms/micaz/mac/tkn154/TKN154TimingP.nc b/tos/platforms/micaz/mac/tkn154/TKN154TimingP.nc
new file mode 100644 (file)
index 0000000..fb947f9
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * extraification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+/** 
+ * In slotted CSMA-CA frames must be sent on backoff boundaries (slot width:
+ * 320 us). The MicaZ platform lacks a clock with sufficient precision and
+ * accuracy, i.e. for slotted CSMA-CA the timing is *not* standard compliant
+ * (this code is experimental)
+ */
+
+#include "TKN154_platform.h"
+module TKN154TimingP
+{
+  provides interface CaptureTime;
+  provides interface ReliableWait;
+  provides interface ReferenceTime;
+  uses interface TimeCalc;
+  uses interface GetNow<bool> as CCA;
+  uses interface Alarm<T62500hz,uint32_t> as SymbolAlarm;
+  uses interface Leds;
+}
+implementation
+{
+  enum {
+    S_WAIT_OFF,
+    S_WAIT_RX,
+    S_WAIT_TX,
+    S_WAIT_BACKOFF,
+  };
+  uint8_t m_state = S_WAIT_OFF;
+
+  async command error_t CaptureTime.convert(uint16_t time, ieee154_timestamp_t *localTime, int16_t offset)
+  {
+    // Timer1 is used for capturing, it is sourced by ACLK (32768Hz),
+    // we now need to convert the capture "time" into ieee154_timestamp_t.
+    // With the 32768Hz quartz we don't have enough precision anyway,
+    // so the code below generates a timestamp that is not accurate
+    
+    uint16_t tcnt1, delta;
+    uint32_t now;
+    atomic {
+      tcnt1 = TCNT1;
+      now = call SymbolAlarm.getNow(); 
+    }
+    if (time < tcnt1)
+      delta = tcnt1 - time;
+    else
+      delta = ~(time - tcnt1) + 1;
+    *localTime = now - delta * 2 + offset; // one tick of Timer1 ~ two symbols
+    
+    return SUCCESS;
+  }
+
+  async command bool ReliableWait.ccaOnBackoffBoundary(ieee154_timestamp_t *slot0)
+  {
+    // There is no point in trying
+    return (call CCA.getNow() ? 20: 0);
+  }
+
+  async command bool CaptureTime.isValidTimestamp(uint16_t risingSFDTime, uint16_t fallingSFDTime)
+  {
+    // smallest packet (ACK) takes 
+    // length field (1) + MPDU (5) = 6 byte => 12 * 16 us = 192 us 
+    return (fallingSFDTime - risingSFDTime) > 5;
+  }
+
+  async command void ReliableWait.waitRx(uint32_t t0, uint32_t dt)
+  {
+    if (m_state != S_WAIT_OFF){
+      ASSERT(0);
+      return;
+    }
+    m_state = S_WAIT_RX;
+    call SymbolAlarm.startAt(t0 - 16, dt); // subtract 12 symbols required for Rx calibration
+  }
+
+  async command void ReliableWait.waitTx(ieee154_timestamp_t *t0, uint32_t dt)
+  {
+    if (m_state != S_WAIT_OFF){
+      ASSERT(0);
+      return;
+    }
+    m_state = S_WAIT_TX;
+    call SymbolAlarm.startAt(*t0 - 16, dt); // subtract 12 symbols required for Tx calibration
+  }
+    
+  async command void ReliableWait.waitBackoff(uint32_t dt)
+  {
+    if (m_state != S_WAIT_OFF){
+      ASSERT(0);
+      return;
+    }
+    m_state = S_WAIT_BACKOFF;
+    call SymbolAlarm.start(dt);
+  }
+
+  async event void SymbolAlarm.fired() 
+  {
+    switch (m_state)
+    {
+      case S_WAIT_RX: m_state = S_WAIT_OFF; signal ReliableWait.waitRxDone(); break;
+      case S_WAIT_TX: m_state = S_WAIT_OFF; signal ReliableWait.waitTxDone(); break;
+      case S_WAIT_BACKOFF: m_state = S_WAIT_OFF; signal ReliableWait.waitBackoffDone(); break;
+      default: ASSERT(0); break;
+    }
+  }
+
+  async command void ReferenceTime.getNow(ieee154_timestamp_t* timestamp, uint16_t dt)
+  {
+    *timestamp = call SymbolAlarm.getNow() + dt;
+  }
+
+  async command uint32_t ReferenceTime.toLocalTime(const ieee154_timestamp_t* timestamp)
+  {
+    return *timestamp;
+  } 
+
+}
diff --git a/tos/platforms/micaz/mac/tkn154/TKN154_platform.h b/tos/platforms/micaz/mac/tkn154/TKN154_platform.h
new file mode 100644 (file)
index 0000000..c650996
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+#ifndef __TKN154_platform_H
+#define __TKN154_platform_H
+
+/**************************************************** 
+ * The following constants define guard times on MicaZ. 
+ * All values are in symbol time (1 symbol = 16 us)
+ */
+
+enum {
+  // the expected maximum time between calling a transmit() operation and
+  // the radio putting the first byte on the channel assuming no CSMA-CA
+  IEEE154_RADIO_TX_DELAY = 400,
+
+  // the expected maximum time between calling a receive() operation and the 
+  // the radio actually being put in receive mode
+  IEEE154_RADIO_RX_DELAY = 400,
+
+  // defines at what time the MAC payload for a beacon frame is assembled before
+  // the next scheduled beacon transmission time; the value must be smaller than 
+  // the beacon interval plus the time for preparing the Tx operation
+  BEACON_PAYLOAD_UPDATE_INTERVAL = 2500, 
+};
+
+typedef uint32_t ieee154_timestamp_t;
+
+#endif
+
diff --git a/tos/platforms/micaz/mac/tkn154/platform_message.h b/tos/platforms/micaz/mac/tkn154/platform_message.h
new file mode 100644 (file)
index 0000000..8aef751
--- /dev/null
@@ -0,0 +1,25 @@
+
+#ifndef PLATFORM_MESSAGE_H
+#define PLATFORM_MESSAGE_H
+
+#include <Serial.h>
+
+/* The following include pulls in the ieee154_header_t/ieee154_metadata_t definitions */
+#include <TKN154_MAC.h>
+
+/* TOSH_DATA_LENGTH should be the maximum length of the MAC payload */
+#define TOSH_DATA_LENGTH IEEE154_aMaxMACPayloadSize
+
+typedef union message_header {
+  ieee154_header_t ieee154;
+  serial_header_t serial;
+} message_header_t;
+
+typedef union TOSRadioFooter {
+} message_footer_t;
+
+typedef union TOSRadioMetadata {
+  ieee154_metadata_t ieee154;
+} message_metadata_t;
+
+#endif
index fe798618f5ee1467a35f8af9f385dac77d9c0ebf..e9de97234bbbd84406bd666c034f7eb06cf03f68 100644 (file)
@@ -28,11 +28,15 @@ push( @includes, qw(
 
 @opts = qw(
 
-  -gcc=gcc
   -fnesc-no-debug
   -fnesc-scheduler=TinySchedulerC,TinySchedulerC.TaskBasic,TaskBasic,TaskBasic,runTask,postTask
 
 );
 
+if (defined($ENV{"GCC"})) {
+  push @opts, "-gcc=$ENV{'GCC'}";
+} else {
+  push @opts, "-gcc=gcc";
+}
 push @opts, "-mingw-gcc" if $cygwin;
 
diff --git a/tos/platforms/mulle/.platform b/tos/platforms/mulle/.platform
new file mode 100755 (executable)
index 0000000..eb04440
--- /dev/null
@@ -0,0 +1,42 @@
+push( @includes, qw(
+  %T/platforms/mulle
+  %T/platforms/mulle/chips/rf230
+  %T/chips/rf2xx/rf230
+  %T/chips/rf2xx/layers
+  %T/chips/rf2xx/util
+  %T/chips/at45db
+  %T/platforms/mulle/button
+  %T/platforms/mulle/softwarei2c
+  %T/platforms/mulle/softwarespi
+  %T/platforms/mulle/chips/rv8564
+  %T/platforms/mulle/chips/at45db
+  %T/platforms/mulle/chips/m16c62p
+  %T/platforms/mulle/chips/mma7261qt
+  %T/platforms/mulle/chips/ds2782
+  %T/platforms/mulle/system
+  %T/platforms/mulle/timers
+  %T/platforms/mulle/timers/stop
+  %T/platforms/mulle/timers/wait
+  %T/platforms/mulle/timers/rf230
+  %T/chips/m16c62p
+  %T/chips/m16c62p/control
+  %T/chips/m16c62p/adc
+  %T/chips/m16c62p/dac
+  %T/chips/m16c62p/pins
+  %T/chips/m16c62p/timer
+  %T/chips/m16c62p/uart
+  %T/chips/m16c62p/printf
+  %T/chips/mma7261qt
+  %T/chips/ds2782
+  %T/lib/power
+  %T/lib/timer
+  %T/lib/serial
+  %T/lib/diagmsg
+  %T/lib/printf
+) );
+
+@opts = qw(
+  -gcc=m32c-elf-gcc
+  -mcpu=m16c
+);
+
diff --git a/tos/platforms/mulle/ActiveMessageC.nc b/tos/platforms/mulle/ActiveMessageC.nc
new file mode 100755 (executable)
index 0000000..2e5cdc4
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+configuration ActiveMessageC
+{
+       provides
+       {
+               interface SplitControl;
+
+               interface AMSend[uint8_t id];
+               interface Receive[uint8_t id];
+               interface Receive as Snoop[uint8_t id];
+               interface SendNotifier[am_id_t id];
+
+               interface Packet;
+               interface AMPacket;
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+#ifdef PACKET_LINK
+               interface PacketLink;
+#endif
+
+               interface PacketTimeStamp<TMicro, uint32_t> as PacketTimeStampMicro;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF230ActiveMessageC as MessageC,
+               RF230SplitControlP,
+               new SystemClockControlC();
+
+       RF230SplitControlP.SplitControlOrig -> MessageC;
+       RF230SplitControlP.SystemClockControl -> SystemClockControlC;
+
+       SplitControl = RF230SplitControlP.SplitControl;
+
+       AMSend = MessageC;
+       Receive = MessageC.Receive;
+       Snoop = MessageC.Snoop;
+       SendNotifier = MessageC;
+
+       Packet = MessageC;
+       AMPacket = MessageC;
+
+       PacketAcknowledgements = MessageC;
+       LowPowerListening = MessageC;
+#ifdef PACKET_LINK
+       PacketLink = MessageC;
+#endif
+
+       PacketTimeStampMilli = MessageC;
+       PacketTimeStampMicro = MessageC;
+}
diff --git a/tos/platforms/mulle/DemoSensorC.nc b/tos/platforms/mulle/DemoSensorC.nc
new file mode 100755 (executable)
index 0000000..3c88114
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Demo sensor that connects to the AN0 channel on the MCU. This can
+ * easily be used together with the potentiometer on the Mulle
+ * expansionboard.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+generic configuration DemoSensorC()
+{
+  provides interface Read<uint16_t>;
+}
+implementation
+{
+  components new AdcReadClientC(), DemoSensorP,
+             HplM16c62pGeneralIOC as IOs,
+             RealMainP;
+
+  DemoSensorP.Pin -> IOs.PortP100;
+  DemoSensorP.AVcc -> IOs.PortP76;
+
+  Read = AdcReadClientC;
+
+  AdcReadClientC.M16c62pAdcConfig -> DemoSensorP;
+
+  RealMainP.PlatformInit -> DemoSensorP;
+}
diff --git a/tos/platforms/mulle/DemoSensorNowC.nc b/tos/platforms/mulle/DemoSensorNowC.nc
new file mode 100644 (file)
index 0000000..22b60e3
--- /dev/null
@@ -0,0 +1,27 @@
+/**
+ * Demo sensor for the mica2 platform.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic configuration DemoSensorNowC()
+{
+  provides interface Resource;
+  provides interface ReadNow<uint16_t>;
+}
+implementation {
+  components new AdcReadNowClientC(),
+             DemoSensorP,
+             HplM16c62pGeneralIOC as IOs,
+             RealMainP;
+
+  DemoSensorP.Pin -> IOs.PortP100;
+  DemoSensorP.AVcc -> IOs.PortP76;
+
+  ReadNow = AdcReadNowClientC;
+  Resource = AdcReadNowClientC;
+
+  AdcReadNowClientC.M16c62pAdcConfig -> DemoSensorP;
+
+  RealMainP.PlatformInit -> DemoSensorP;
+}
diff --git a/tos/platforms/mulle/DemoSensorP.nc b/tos/platforms/mulle/DemoSensorP.nc
new file mode 100644 (file)
index 0000000..d3242d7
--- /dev/null
@@ -0,0 +1,36 @@
+module DemoSensorP
+{
+  provides interface M16c62pAdcConfig;
+  provides interface Init;
+
+  uses interface GeneralIO as Pin;
+  uses interface GeneralIO as AVcc;
+}
+implementation
+{
+  command error_t Init.init()
+  {
+    call Pin.makeInput();
+    // TODO(henrik) This Vref should be turned on in connection to the A/D
+    // converter code and not here.
+    // Turn on the Vref
+    call AVcc.makeOutput();
+    call AVcc.set();
+  }
+
+  async command uint8_t M16c62pAdcConfig.getChannel()
+  {
+    // select the AN0 = P10_0 to potentiometer on the expansion board.
+    return M16c62p_ADC_CHL_AN0;
+  }
+
+  async command uint8_t M16c62pAdcConfig.getPrecision()
+  {
+    return M16c62p_ADC_PRECISION_10BIT;
+  }
+
+  async command uint8_t M16c62pAdcConfig.getPrescaler()
+  {
+    return M16c62p_ADC_PRESCALE_4;
+  }
+}
diff --git a/tos/platforms/mulle/DemoSensorStreamC.nc b/tos/platforms/mulle/DemoSensorStreamC.nc
new file mode 100644 (file)
index 0000000..43c50ea
--- /dev/null
@@ -0,0 +1,34 @@
+/* $Id$
+ * Copyright (c) 2006 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+/**
+ * Demo sensor for the mica2 platform.
+ *
+ * @author David Gay
+ */
+
+generic configuration DemoSensorStreamC()
+{
+  provides interface ReadStream<uint16_t>;
+}
+implementation {
+  components new AdcReadStreamClientC(),
+             DemoSensorP,
+             HplM16c62pGeneralIOC as IOs,
+             RealMainP;
+
+  DemoSensorP.Pin -> IOs.PortP100;
+  DemoSensorP.AVcc -> IOs.PortP76;
+
+  ReadStream = AdcReadStreamClientC;
+
+  AdcReadStreamClientC.M16c62pAdcConfig -> DemoSensorP;
+
+  RealMainP.PlatformInit -> DemoSensorP;
+}
diff --git a/tos/platforms/mulle/Ieee154MessageC.nc b/tos/platforms/mulle/Ieee154MessageC.nc
new file mode 100644 (file)
index 0000000..1c611f2
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2009, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+configuration Ieee154MessageC
+{
+       provides
+       {
+               interface SplitControl;
+
+               interface Ieee154Send;
+               interface Receive as Ieee154Receive;
+               interface SendNotifier;
+
+               interface Packet;
+               interface Ieee154Packet;
+               interface Resource as SendResource[uint8_t clint];
+
+               interface PacketAcknowledgements;
+               interface LowPowerListening;
+               interface PacketLink;
+
+               interface PacketTimeStamp<TMicro, uint32_t> as PacketTimeStampMicro;
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+       }
+}
+
+implementation
+{
+       components RF230Ieee154MessageC as MessageC;
+
+       SplitControl = MessageC;
+
+       Ieee154Send = MessageC;
+       Ieee154Receive = MessageC;
+       SendNotifier = MessageC;
+
+       Packet = MessageC;
+       Ieee154Packet = MessageC;
+       SendResource = MessageC;
+
+       PacketAcknowledgements = MessageC;
+       LowPowerListening = MessageC;
+       PacketLink = MessageC;
+
+       PacketTimeStampMilli = MessageC;
+       PacketTimeStampMicro = MessageC;
+}
diff --git a/tos/platforms/mulle/PlatformC.nc b/tos/platforms/mulle/PlatformC.nc
new file mode 100755 (executable)
index 0000000..c236b9a
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * All the wiring of the Mulle platform components.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "hardware.h"
+#
+configuration PlatformC
+{
+  provides interface Init;
+
+  uses interface Init as SubInit;
+
+}
+implementation
+{
+  components
+    PlatformP,
+    LedsC,
+    M16c62pControlC,
+    new StopModeControlC();
+
+  Init = PlatformP;
+  SubInit = PlatformP.SubInit;
+  PlatformP.M16c62pControl -> M16c62pControlC;
+
+  PlatformP.StopModeControl -> StopModeControlC;
+
+#ifdef ENABLE_STOP_MODE
+  components RV8564C, DS2782InternalC, MainC;
+  PlatformP.Boot -> MainC;
+  PlatformP.RTC -> RV8564C;
+  PlatformP.HplDS2782 -> DS2782InternalC;
+  PlatformP.DS2782Control -> DS2782InternalC;
+#endif
+}
+
diff --git a/tos/platforms/mulle/PlatformLedsC.nc b/tos/platforms/mulle/PlatformLedsC.nc
new file mode 100755 (executable)
index 0000000..0dbf006
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Mulle platform-specific LED interface.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration PlatformLedsC
+{
+  provides interface GeneralIO as Led0;
+  provides interface GeneralIO as Led1;
+  provides interface GeneralIO as Led2;
+  uses interface Init;
+}
+implementation
+{
+  components HplM16c62pGeneralIOC as IO;
+  components PlatformP;
+
+  Init = PlatformP.SubInit;
+
+  Led0 = IO.PortP36;  // Pin P3_6 = Red LED
+  Led1 = IO.PortP37;  // Pin P3_7 = Green LED
+  Led2 = IO.PortP34;  // External LED, supplied by user.
+}
diff --git a/tos/platforms/mulle/PlatformP.nc b/tos/platforms/mulle/PlatformP.nc
new file mode 100755 (executable)
index 0000000..4722140
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Mulle platform initialization code.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "hardware.h"
+#include "rv8564.h"
+
+module PlatformP
+{
+  provides interface Init;
+  uses interface Init as SubInit;
+  uses interface M16c62pControl;
+  uses interface StopModeControl;
+#ifdef ENABLE_STOP_MODE
+  uses interface RV8564 as RTC;
+  uses interface HplDS2782;
+  uses interface StdControl as DS2782Control;
+  uses interface Boot;
+#endif
+}
+
+implementation
+{
+  command error_t Init.init()
+  {
+    error_t ok = SUCCESS;
+
+    ok = call M16c62pControl.init();
+
+    call StopModeControl.allowStopMode(false);
+
+    // Init the M16c/62p to run at 10MHz.
+    ok = ecombine (ok, call M16c62pControl.defaultSystemClock(MCU_SPEED_10MHz));
+
+    // Sub components initialization.
+    ok = ecombine(ok, call SubInit.init());
+
+    return SUCCESS;
+  }
+
+
+#ifdef ENABLE_STOP_MODE
+  task void stopDS2782()
+  {
+    call DS2782Control.stop();
+  }
+  // The Boot event is needed so we can be sure that all underlying components 
+  // have been initialized, for example the I2C resource.
+  event void Boot.booted()
+  {
+    call StopModeControl.allowStopMode(true);
+    // Activate the RTC and set it to output 1024 tics on the CLKOUT pin
+    call DS2782Control.start();
+    call HplDS2782.allowSleep(true);
+    call RTC.on();
+    call RTC.enableCLKOUT();
+    call RTC.writeRegister(RV8564_CLKF, 0x81);
+  }
+
+  async event void RTC.fired() {}
+  async event void RTC.readRegisterDone(uint8_t val, uint8_t reg) {}
+  async event void RTC.writeRegisterDone(uint8_t reg) {}
+
+  async event void HplDS2782.setConfigDone(error_t error) {return; }
+  async event void HplDS2782.allowSleepDone( error_t error ) { post stopDS2782(); }
+  async event void HplDS2782.measureTemperatureDone( error_t error, uint16_t val ){ return; }
+  async event void HplDS2782.measureVoltageDone( error_t error, uint16_t val ){ return; }
+  async event void HplDS2782.measureCurrentDone( error_t error, uint16_t val ){ return; }
+  async event void HplDS2782.measureAccCurrentDone( error_t error, uint16_t val ){ return; }
+  async event void HplDS2782.setOffsetBiasDone( error_t error ){ return; }
+  async event void HplDS2782.setAccOffsetBiasDone(error_t error){ return; }
+#endif
+}
diff --git a/tos/platforms/mulle/PlatformSerialC.nc b/tos/platforms/mulle/PlatformSerialC.nc
new file mode 100755 (executable)
index 0000000..2b3cf7c
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * The wiring of the Serial interface used to communicate with the Mulle
+ * platform.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration PlatformSerialC {
+  
+  provides interface StdControl;
+  provides interface UartStream;
+  provides interface UartByte;
+  
+}
+implementation {
+
+  components M16c62pUartC as Uart,
+      PlatformSerialP, CounterMicro16C;
+      
+  StdControl = PlatformSerialP;
+  PlatformSerialP -> Uart.Uart1Control;
+  UartStream = Uart.Uart1Stream;
+  UartByte = Uart.Uart1Byte;
+  
+  Uart.Counter -> CounterMicro16C;
+  
+  components MainC;
+  
+  MainC.SoftwareInit -> PlatformSerialP;
+  
+}
diff --git a/tos/platforms/mulle/PlatformSerialP.nc b/tos/platforms/mulle/PlatformSerialP.nc
new file mode 100644 (file)
index 0000000..81c8e11
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Initialization of the PlatformSerial uart and a StdControl implementation
+ * for it.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+module PlatformSerialP
+{
+  provides interface StdControl;
+  provides interface Init;
+  
+  uses interface UartControl;
+}
+implementation
+{
+  command error_t Init.init() {
+    call UartControl.setParity(TOS_UART_PARITY_NONE);
+    call UartControl.setNoStop();
+    call UartControl.setSpeed(TOS_UART_57600);
+    return SUCCESS;
+  }
+  
+  
+  command error_t StdControl.start()
+  {
+    call UartControl.setDuplexMode(TOS_UART_DUPLEX);
+    return SUCCESS;
+  }
+
+  command error_t StdControl.stop()
+  {
+    call UartControl.setDuplexMode(TOS_UART_OFF);
+    return SUCCESS;
+  }
+}
diff --git a/tos/platforms/mulle/TimeSyncMessageC.nc b/tos/platforms/mulle/TimeSyncMessageC.nc
new file mode 100755 (executable)
index 0000000..a08e9fa
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+#include <RadioConfig.h>
+
+configuration TimeSyncMessageC
+{
+       provides
+       {
+               interface SplitControl;
+
+               interface Receive[uint8_t id];
+               interface Receive as Snoop[am_id_t id];
+               interface Packet;
+               interface AMPacket;
+
+               interface PacketTimeStamp<TRadio, uint32_t> as PacketTimeStampRadio;
+               interface TimeSyncAMSend<TRadio, uint32_t> as TimeSyncAMSendRadio[am_id_t id];
+               interface TimeSyncPacket<TRadio, uint32_t> as TimeSyncPacketRadio;
+
+               interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+               interface TimeSyncAMSend<TMilli, uint32_t> as TimeSyncAMSendMilli[am_id_t id];
+               interface TimeSyncPacket<TMilli, uint32_t> as TimeSyncPacketMilli;
+       }
+}
+
+implementation
+{
+       components RF230TimeSyncMessageC as MessageC,
+               RF230SplitControlP,
+               new SystemClockControlC();
+  
+       RF230SplitControlP.SplitControlOrig -> MessageC;
+       RF230SplitControlP.SystemClockControl -> SystemClockControlC;
+  
+       SplitControl = RF230SplitControlP.SplitControl;
+
+       Receive         = MessageC.Receive;
+       Snoop           = MessageC.Snoop;
+       Packet          = MessageC;
+       AMPacket        = MessageC;
+
+       PacketTimeStampRadio    = MessageC;
+       TimeSyncAMSendRadio     = MessageC;
+       TimeSyncPacketRadio     = MessageC;
+
+       PacketTimeStampMilli    = MessageC;
+       TimeSyncAMSendMilli     = MessageC;
+       TimeSyncPacketMilli     = MessageC;
+}
diff --git a/tos/platforms/mulle/button/HplUserButtonC.nc b/tos/platforms/mulle/button/HplUserButtonC.nc
new file mode 100644 (file)
index 0000000..568cd63
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the Mulle platform extension board.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+configuration HplUserButtonC {
+  provides interface GeneralIO;
+  provides interface GpioInterrupt;
+}
+implementation {
+  components  HplM16c62pInterruptC as Irqs,
+              HplM16c62pGeneralIOC as IOs,
+           new M16c62pInterruptC() as Irq;
+  
+  Irq -> Irqs.Int4;
+  GpioInterrupt = Irq;
+  GeneralIO = IOs.PortP16;
+}
diff --git a/tos/platforms/mulle/button/UserButton.h b/tos/platforms/mulle/button/UserButton.h
new file mode 100644 (file)
index 0000000..aef5ecc
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ */
+
+/**
+ * Implementation of the user button for the Mulle platform
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#ifndef __USERBUTTON_H__
+#define __USERBUTTON_H__
+
+typedef enum { BUTTON_RELEASED = 0, BUTTON_PRESSED = 1 } button_state_t;
+
+#endif
diff --git a/tos/platforms/mulle/button/UserButtonC.nc b/tos/platforms/mulle/button/UserButtonC.nc
new file mode 100644 (file)
index 0000000..8a06909
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ */
+
+/**
+ * Implementation of the user button for the Mulle platform. Get
+ * returns the current state of the button by reading the pin,
+ * regardless of whether enable() or disable() has been called on the
+ * Interface. Notify.enable() and Notify.disable() modify the
+ * underlying interrupt state of the pin, and have the effect of
+ * enabling or disabling notifications that the button has changed
+ * state.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include <UserButton.h>
+
+configuration UserButtonC {
+  provides interface Get<button_state_t>;
+  provides interface Notify<button_state_t>;
+}
+implementation {
+  components HplUserButtonC;
+
+  components UserButtonP;
+  Get = UserButtonP;
+  Notify = UserButtonP;
+
+  UserButtonP.GeneralIO -> HplUserButtonC.GeneralIO;
+  UserButtonP.GpioInterrupt -> HplUserButtonC.GpioInterrupt;
+}
diff --git a/tos/platforms/mulle/button/UserButtonP.nc b/tos/platforms/mulle/button/UserButtonP.nc
new file mode 100644 (file)
index 0000000..042f3be
--- /dev/null
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ */
+
+/**
+ * Implementation of the user button for the Mulle platform extension board.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include <UserButton.h>
+
+module UserButtonP {
+  provides interface Get<button_state_t>;
+  provides interface Notify<button_state_t>;
+  
+  uses interface GeneralIO;
+  uses interface GpioInterrupt;
+}
+implementation {
+
+  task void notify()
+  {
+    signal Notify.notify(BUTTON_PRESSED);
+  }
+       
+  command button_state_t Get.get()
+  { 
+    if ( call GeneralIO.get() )
+    {
+      return BUTTON_PRESSED;
+    } 
+    else 
+    {
+      return BUTTON_RELEASED;
+    }
+  }
+
+  command error_t Notify.enable()
+  {
+    call GeneralIO.clr();
+    call GeneralIO.makeInput();
+    return call GpioInterrupt.enableRisingEdge();
+  }
+
+  command error_t Notify.disable()
+  {
+    call GpioInterrupt.disable();
+    call GeneralIO.makeOutput();
+    call GeneralIO.clr();
+    return SUCCESS;
+  }
+
+  async event void GpioInterrupt.fired()
+  {
+    post notify();
+  }
+}
diff --git a/tos/platforms/mulle/chips/at45db/At45dbSpi.h b/tos/platforms/mulle/chips/at45db/At45dbSpi.h
new file mode 100644 (file)
index 0000000..78b29ce
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Unique identifier for the SPI used to communicate with the AT45DB chip.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#ifndef __AT45DBSOFTSPI_H__
+#define __AT45DBSOFTSPI_H__
+
+#define UQ_MULLE_SOFTSPIAT45DB "SoftSPIAt45dbC.SoftSPIPacket"
+
+#endif // __AT45DBSOFTSPI_H__
diff --git a/tos/platforms/mulle/chips/at45db/HplAt45dbC.nc b/tos/platforms/mulle/chips/at45db/HplAt45dbC.nc
new file mode 100644 (file)
index 0000000..f7dcc2f
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * Mulle specific wiring for the AT45DB161D Flash storage.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+configuration HplAt45dbC
+{
+  provides interface HplAt45db;
+}
+implementation
+{
+  components  new HplAt45dbByteC(10),
+              new SoftSpiAt45dbC() as Spi,
+              HplAt45dbP,
+              HplM16c62pGeneralIOC as IOs,
+              RealMainP,
+              BusyWaitMicroC;
+
+  HplAt45db = HplAt45dbByteC;
+
+  HplAt45dbByteC.Resource -> Spi;
+  HplAt45dbByteC.FlashSpi -> Spi;
+  HplAt45dbByteC.HplAt45dbByte -> HplAt45dbP;
+
+  HplAt45dbP.VCC -> IOs.PortP32;
+  HplAt45dbP.WP -> IOs.PortP44;
+  HplAt45dbP.Select -> IOs.PortP45;
+  HplAt45dbP.RESET -> IOs.PortP46;
+
+  HplAt45dbP.FlashSpi -> Spi;
+  HplAt45dbP.BusyWait -> BusyWaitMicroC;
+  RealMainP.PlatformInit -> HplAt45dbP.Init;
+}
diff --git a/tos/platforms/mulle/chips/at45db/HplAt45dbP.nc b/tos/platforms/mulle/chips/at45db/HplAt45dbP.nc
new file mode 100644 (file)
index 0000000..fa20637
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2006, Technische Universitat Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitat Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Mulle specific HplAt45dbByte interface implementation
+ * for the AT45DB161D Flash storage.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+module HplAt45dbP
+{
+  provides
+  {
+    interface HplAt45dbByte;
+    interface Init;
+  }
+  uses
+  {
+    interface SpiByte as FlashSpi;
+    interface GeneralIO as VCC;
+    interface GeneralIO as Select;
+    interface GeneralIO as RESET;
+    interface GeneralIO as WP;
+    interface BusyWait<TMicro, uint16_t>;
+  }
+}
+implementation
+{
+  // TODO(Henrik) Move init code to a SplitControl interface and
+  //              change the busy wait into a TimerMilli.startOneShot.
+  command error_t Init.init() {
+    call Select.makeOutput();
+    call Select.set();
+    call VCC.makeOutput();
+    call VCC.clr();
+       // The device needs 20ms before is accepts a write.
+       call BusyWait.wait(20000);
+    return SUCCESS;
+  }
+
+  command void HplAt45dbByte.select() { call Select.clr(); }
+  command void HplAt45dbByte.deselect() { call Select.set(); }
+
+  task void idleTask()
+  {
+    uint8_t status;
+    status = call FlashSpi.write(0);
+    if (!(status & 0x80))
+    {
+      post idleTask();
+    }
+    else
+    {
+      signal HplAt45dbByte.idle();
+    }
+  }
+
+  command void HplAt45dbByte.waitIdle()
+  {
+    post idleTask();
+  }
+
+  command bool HplAt45dbByte.getCompareStatus()
+  {
+    uint8_t status;
+    status = call FlashSpi.write(0);
+    return (!(status & 0x40));
+  }
+}
diff --git a/tos/platforms/mulle/chips/at45db/HplAt45db_chip.h b/tos/platforms/mulle/chips/at45db/HplAt45db_chip.h
new file mode 100644 (file)
index 0000000..381ba92
--- /dev/null
@@ -0,0 +1,45 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2003 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2006 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+#ifndef __HPLAT45DB_CHIP_H__
+#define __HPLAT45DB_CHIP_H__
+
+// flash characteristics
+enum {
+  AT45_MAX_PAGES = 4096,
+  AT45_PAGE_SIZE = 528,
+  AT45_PAGE_SIZE_LOG2 = 9 // Ignores the last 16 bytes
+};
+
+typedef uint16_t at45page_t;
+typedef uint16_t at45pageoffset_t; // must fit 0 to AT45_PAGE_SIZE - 1
+
+#endif  // __HPLAT45DB_CHIP_H__
diff --git a/tos/platforms/mulle/chips/at45db/SoftSpiAt45dbC.nc b/tos/platforms/mulle/chips/at45db/SoftSpiAt45dbC.nc
new file mode 100755 (executable)
index 0000000..96a627c
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * A component that is going to use the Flash Spi bus should
+ * create a new component of this to get access to the bus.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "At45dbSpi.h"
+
+generic configuration SoftSpiAt45dbC()
+{
+  provides interface Resource;
+  provides interface SpiPacket;
+  provides interface SpiByte;
+}
+implementation
+{
+  enum
+  {
+    CLIENT_ID = unique(UQ_MULLE_SOFTSPIAT45DB),
+  };
+  
+  components SoftSpiAt45dbP as Spi;
+  Resource = Spi.Resource[CLIENT_ID];
+  SpiPacket = Spi.SpiPacket[CLIENT_ID]; 
+  SpiByte = Spi.SpiByte[CLIENT_ID]; 
+}
diff --git a/tos/platforms/mulle/chips/at45db/SoftSpiAt45dbP.nc b/tos/platforms/mulle/chips/at45db/SoftSpiAt45dbP.nc
new file mode 100755 (executable)
index 0000000..9efbb3f
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * Wiring for the software Spi bus used by the Mulle Flash storage.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+configuration SoftSpiAt45dbP
+{
+  provides interface Resource[uint8_t client];
+  provides interface SpiPacket[uint8_t client];
+  provides interface SpiByte[uint8_t client];
+}
+implementation
+{
+  components new SoftSpiMasterP(UQ_MULLE_SOFTSPIAT45DB) as Spi,
+      new SoftSpiBusP(),
+      HplM16c62pGeneralIOC as IOs;
+  
+  // Init the software SPI bus
+  SoftSpiBusP.MISO -> IOs.PortP40;
+  SoftSpiBusP.MOSI -> IOs.PortP41;
+  SoftSpiBusP.SCLK -> IOs.PortP42;
+
+  Spi.SoftSpiBus -> SoftSpiBusP;
+
+  Resource  = Spi.Resource;
+  SpiPacket = Spi.SpiPacket;
+  SpiByte = Spi.SpiByte;
+
+}
diff --git a/tos/platforms/mulle/chips/ds2782/DS2782InternalC.nc b/tos/platforms/mulle/chips/ds2782/DS2782InternalC.nc
new file mode 100644 (file)
index 0000000..d957cf8
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * The DS2782 wiring on the Mulle.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration DS2782InternalC {
+  provides interface StdControl;
+  provides interface HplDS2782;
+}
+
+implementation {
+  components new SoftI2CBatteryMonitorRTCC() as I2C;
+  components new HplDS2782LogicP(0x68) as Logic;
+  
+  Logic.I2CPacket -> I2C;
+  Logic.I2CResource -> I2C;
+  HplDS2782 = Logic;
+
+  StdControl = Logic;
+
+}
diff --git a/tos/platforms/mulle/chips/m16c62p/M16c62pAdcPlatformC.nc b/tos/platforms/mulle/chips/m16c62p/M16c62pAdcPlatformC.nc
new file mode 100644 (file)
index 0000000..5765fbe
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Mulle specific implementation of the M16c62pAdcPlatform interface.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+configuration M16c62pAdcPlatformC
+{
+  provides interface M16c62pAdcPlatform;
+}
+implementation
+{
+  components M16c62pAdcPlatformP, HplM16c62pGeneralIOC as IOs;
+
+  M16c62pAdcPlatform = M16c62pAdcPlatformP;
+  M16c62pAdcPlatformP -> IOs.PortP76;
+}
diff --git a/tos/platforms/mulle/chips/m16c62p/M16c62pAdcPlatformP.nc b/tos/platforms/mulle/chips/m16c62p/M16c62pAdcPlatformP.nc
new file mode 100644 (file)
index 0000000..02e7b62
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Mulle specific implementation of the M16c62pAdcPlatform interface.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+module M16c62pAdcPlatformP
+{
+  provides interface M16c62pAdcPlatform;
+  uses interface GeneralIO VRef;
+}
+implementation
+{
+  async command void M16c62pAdcPlatform.adcOn()
+  {
+    call VRef.makeOutput();
+    call VRef.set();
+  }
+  
+  async command void M16c62pAdcPlatform.adcOff()
+  {
+    call VRef.clr();
+  }
+}
diff --git a/tos/platforms/mulle/chips/m16c62p/M16c62pControlPlatformC.nc b/tos/platforms/mulle/chips/m16c62p/M16c62pControlPlatformC.nc
new file mode 100644 (file)
index 0000000..e71a862
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Mulle specific implementation of the M16c62pControlPlatform interface.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+module M16c62pControlPlatformC
+{
+  provides interface M16c62pControlPlatform;
+}
+implementation
+{
+  async command void M16c62pControlPlatform.PLLOn()
+  {
+    // Set all timers that uses the main clock
+    // as source to use F2 instead of F1 because
+    // the main clock will be twice as fast when PLL
+    // is on.
+    // Set the UARTS clock source to F2 instead of F1.
+
+    // NOTE: No need to turn on/off protections for registers,
+    // this is handeled by the caller of this code.
+    CLR_BIT(PCLKR.BYTE, 0); // Timers
+    CLR_BIT(PCLKR.BYTE, 1); // Uarts
+  }
+
+  async command void M16c62pControlPlatform.PLLOff()
+  {
+    // Restore settings done in PLLOn()
+    // NOTE: No need to turn on/off protections for registers,
+    // this is handeled by the caller of this code.
+    SET_BIT(PCLKR.BYTE, 0);
+    SET_BIT(PCLKR.BYTE, 1);
+  }
+}
diff --git a/tos/platforms/mulle/chips/mma7261qt/HplMMA7261QTC.nc b/tos/platforms/mulle/chips/mma7261qt/HplMMA7261QTC.nc
new file mode 100644 (file)
index 0000000..61c3ea4
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * MMA7261QT configuration.
+ *
+ * @author Henrik Makitaavola
+ */
+
+configuration HplMMA7261QTC
+{
+  provides interface Read<uint16_t> as AccelX;
+  provides interface Read<uint16_t> as AccelY;
+  provides interface Read<uint16_t> as AccelZ;
+  
+  provides interface GeneralIO as Sleep;
+  provides interface GeneralIO as GSelect1;
+  provides interface GeneralIO as GSelect2;
+}
+implementation
+{
+  components new AdcReadClientC() as _AccelX, 
+             new AdcReadClientC() as _AccelY,
+             new AdcReadClientC() as _AccelZ,
+             HplM16c62pGeneralIOC as IOs,
+             HplMMA7261QTP;
+             
+  HplMMA7261QTP.VCC -> IOs.PortP76;
+  HplMMA7261QTP.Sleep -> IOs.PortP12;
+  HplMMA7261QTP.GSelect1 -> IOs.PortP30;
+  HplMMA7261QTP.GSelect2 -> IOs.PortP31;
+  HplMMA7261QTP.AccelXPort -> IOs.PortP105;
+  HplMMA7261QTP.AccelYPort -> IOs.PortP104;
+  HplMMA7261QTP.AccelZPort -> IOs.PortP103;
+  
+  Sleep = IOs.PortP12;
+  GSelect1 = IOs.PortP30;
+  GSelect2 = IOs.PortP31;
+  
+  _AccelX.M16c62pAdcConfig -> HplMMA7261QTP.AccelXConf;
+  _AccelY.M16c62pAdcConfig -> HplMMA7261QTP.AccelYConf;
+  _AccelZ.M16c62pAdcConfig -> HplMMA7261QTP.AccelZConf;
+  
+  AccelX = _AccelX;
+  AccelY = _AccelY;
+  AccelZ = _AccelZ;
+  
+  components RealMainP;
+  RealMainP.PlatformInit -> HplMMA7261QTP.Init;
+  
+}
diff --git a/tos/platforms/mulle/chips/mma7261qt/HplMMA7261QTP.nc b/tos/platforms/mulle/chips/mma7261qt/HplMMA7261QTP.nc
new file mode 100644 (file)
index 0000000..45eb012
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * MMA7261QT implementation.
+ *
+ * @author Henrik Makitaavola
+ */
+
+module HplMMA7261QTP
+{
+  provides
+  {
+    interface Init;
+    interface M16c62pAdcConfig as AccelXConf;
+    interface M16c62pAdcConfig as AccelYConf;
+    interface M16c62pAdcConfig as AccelZConf;
+  }
+  
+  uses
+  {
+    interface GeneralIO as VCC;
+    interface GeneralIO as Sleep;
+    interface GeneralIO as GSelect1;
+    interface GeneralIO as GSelect2;
+    interface GeneralIO as AccelXPort;
+    interface GeneralIO as AccelYPort;
+    interface GeneralIO as AccelZPort;
+  }
+}
+implementation
+{
+  command error_t Init.init()
+  {
+    call VCC.makeOutput();
+    call VCC.set();
+    call Sleep.makeOutput();
+    call Sleep.clr();
+    call GSelect1.makeOutput();
+    call GSelect1.clr();
+    call GSelect2.makeOutput();
+    call GSelect2.clr();
+    call AccelXPort.makeInput();
+    call AccelXPort.clr();
+    call AccelYPort.makeInput();
+    call AccelYPort.clr();
+    call AccelZPort.makeInput();
+    call AccelZPort.clr();
+  }
+  
+  inline uint8_t prescaler() { return M16c62p_ADC_PRESCALE_4; }
+  inline uint8_t precision() { return M16c62p_ADC_PRECISION_8BIT; }
+  
+  async command uint8_t AccelXConf.getChannel()
+  {
+    return M16c62p_ADC_CHL_AN5;
+  }
+
+  async command uint8_t AccelXConf.getPrecision()
+  {
+    return precision();
+  }
+
+  async command uint8_t AccelXConf.getPrescaler()
+  {
+    return prescaler();
+  }
+  
+    async command uint8_t AccelYConf.getChannel()
+  {
+    return M16c62p_ADC_CHL_AN4;
+  }
+
+  async command uint8_t AccelYConf.getPrecision()
+  {
+    return precision();
+  }
+
+  async command uint8_t AccelYConf.getPrescaler()
+  {
+    return prescaler();
+  }
+  
+  async command uint8_t AccelZConf.getChannel()
+  {
+    return M16c62p_ADC_CHL_AN3;
+  }
+
+  async command uint8_t AccelZConf.getPrecision()
+  {
+    return precision();
+  }
+
+  async command uint8_t AccelZConf.getPrescaler()
+  {
+    return prescaler();
+  }
+}
diff --git a/tos/platforms/mulle/chips/rf230/HplRF230C.nc b/tos/platforms/mulle/chips/rf230/HplRF230C.nc
new file mode 100755 (executable)
index 0000000..c413b06
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Mulle specific wiring of the HplRF230C configuration.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#include <RadioConfig.h>
+
+configuration HplRF230C
+{
+  provides
+  {
+    interface GeneralIO as SELN;
+    interface Resource as SpiResource;
+    interface SpiByte;
+    interface FastSpiByte;
+
+    interface GeneralIO as SLP_TR;
+    interface GeneralIO as RSTN;
+
+    interface GpioCapture as IRQ;
+    interface Alarm<TRadio, uint16_t> as Alarm;
+    interface LocalTime<TRadio> as LocalTimeRadio;
+  }
+}
+implementation
+{
+  components HplRF230P;
+  IRQ = HplRF230P.IRQ;
+
+  components new SoftSpiRF230C() as Spi;
+  HplRF230P.Spi -> Spi;
+  SpiResource = Spi;
+  SpiByte = Spi;
+  FastSpiByte = HplRF230P.FastSpiByte;
+
+  components HplM16c62pGeneralIOC as IOs;
+  HplRF230P.PortVCC -> IOs.PortP77;
+  HplRF230P.PortIRQ -> IOs.PortP83;
+  SLP_TR = IOs.PortP07;
+  RSTN = IOs.PortP43;
+  SELN = IOs.PortP35;
+
+  components  HplM16c62pInterruptC as Irqs,
+      new M16c62pInterruptC() as Irq;
+  HplRF230P.GIRQ -> Irq;
+  Irq -> Irqs.Int1;
+
+  components AlarmRF23016C as AlarmRF230;
+  HplRF230P.Alarm -> AlarmRF230;
+  Alarm = AlarmRF230;
+
+  components PlatformP;
+  PlatformP.SubInit -> HplRF230P.PlatformInit;
+    
+  components LocalTimeMicroC;
+  LocalTimeRadio = LocalTimeMicroC;
+}
diff --git a/tos/platforms/mulle/chips/rf230/HplRF230P.nc b/tos/platforms/mulle/chips/rf230/HplRF230P.nc
new file mode 100755 (executable)
index 0000000..1973c68
--- /dev/null
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * Implementation of the time capture on RF230 interrupt and the
+ * FastSpiBus interface.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+module HplRF230P
+{
+  provides
+  {
+    interface GpioCapture as IRQ;
+    interface Init as PlatformInit;
+    interface FastSpiByte;
+  }
+
+  uses
+  {
+    interface GeneralIO as PortIRQ;
+       interface GeneralIO as PortVCC;
+    interface GpioInterrupt as GIRQ;
+    interface SoftSpiBus as Spi;
+    interface Alarm<TRadio, uint16_t> as Alarm;
+  }
+}
+implementation
+{
+  command error_t PlatformInit.init()
+  {
+    call PortIRQ.makeInput(); 
+    call PortIRQ.clr();
+    call GIRQ.disable();
+    call PortVCC.makeOutput(); 
+    call PortVCC.set(); 
+
+    return SUCCESS;
+  }
+
+  async event void GIRQ.fired()
+  {
+    signal IRQ.captured(call Alarm.getNow());
+  }
+  async event void Alarm.fired() {}
+
+  default async event void IRQ.captured(uint16_t time) {}
+
+  async command error_t IRQ.captureRisingEdge()
+  {
+    call GIRQ.enableRisingEdge();
+    return SUCCESS;
+  }
+
+  async command error_t IRQ.captureFallingEdge()
+  {
+    // falling edge comes when the IRQ_STATUS register of the RF230 is read
+    return FAIL;       
+  }
+
+  async command void IRQ.disable()
+  {
+    call GIRQ.disable();
+  }
+
+  uint8_t tmp_data;
+  async command void FastSpiByte.splitWrite(uint8_t data)
+  {
+    atomic tmp_data = data;
+  }
+
+  async command uint8_t FastSpiByte.splitRead()
+  {
+    atomic return call Spi.write(tmp_data);
+  }
+
+  async command uint8_t FastSpiByte.splitReadWrite(uint8_t data)
+  {
+    uint8_t b;
+    atomic
+    {
+      b = call Spi.write(tmp_data);
+      tmp_data = data;
+    }
+    return b;
+  }
+
+  async command uint8_t FastSpiByte.write(uint8_t data)
+  {
+    return call Spi.write(data);
+  }
+}
diff --git a/tos/platforms/mulle/chips/rf230/Mulle_RF230Spi.h b/tos/platforms/mulle/chips/rf230/Mulle_RF230Spi.h
new file mode 100755 (executable)
index 0000000..3ea8b3b
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Unique identifier for the RF230 SPI bus.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#ifndef __MULLE_RF230SPI_H__
+#define __MULLE_RF230SPI_H__
+
+#define UQ_MULLE_SOFTSPIRF230 "SoftSPIRF230C.SoftSPIPacket"
+
+#endif // __MULLE_RF230SPI_H__
diff --git a/tos/platforms/mulle/chips/rf230/RF230SplitControlP.nc b/tos/platforms/mulle/chips/rf230/RF230SplitControlP.nc
new file mode 100644 (file)
index 0000000..2f30cad
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * This module overrides the default SplitControl for the RF230 chip so that
+ * the PLL is turned on every time the RF230 chip is turned on.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+module RF230SplitControlP
+{
+  provides interface SplitControl;
+  uses interface SplitControl as SplitControlOrig;
+  uses interface SystemClockControl;
+}
+implementation
+{
+  command error_t SplitControl.start()
+  {
+#ifndef RF230_SLOW_SPI
+    call SystemClockControl.minSpeed(M16C62P_PLL_CLOCK);
+#endif
+    return call SplitControlOrig.start();
+  }
+
+  event void SplitControlOrig.startDone(error_t error)
+  {
+#ifndef RF230_SLOW_SPI
+    if (error != SUCCESS)
+    {
+      call SystemClockControl.minSpeed(M16C62P_DONT_CARE);
+    }
+#endif
+    signal SplitControl.startDone(error);
+  }
+
+  command error_t SplitControl.stop()
+  {
+    return call SplitControlOrig.stop();
+  }
+
+  event void SplitControlOrig.stopDone(error_t error)
+  {
+#ifndef RF230_SLOW_SPI
+    if (error == SUCCESS)
+    {
+      call SystemClockControl.minSpeed(M16C62P_DONT_CARE);
+    }
+#endif
+    signal SplitControl.stopDone(error);
+  }
+}
diff --git a/tos/platforms/mulle/chips/rf230/RadioConfig.h b/tos/platforms/mulle/chips/rf230/RadioConfig.h
new file mode 100644 (file)
index 0000000..b3835f7
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+/**
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#ifndef __RADIOCONFIG_H__
+#define __RADIOCONFIG_H__
+
+#include <RF230DriverLayer.h>
+#include "Timer.h"
+
+enum
+{
+       /**
+        * This is the value of the TRX_CTRL_0 register
+        * which configures the output pin currents and the CLKM clock
+        */
+       RF230_TRX_CTRL_0_VALUE = 0,
+
+       /**
+        * This is the default value of the CCA_MODE field in the PHY_CC_CCA register
+        * which is used to configure the default mode of the clear channel assessment
+        */
+       RF230_CCA_MODE_VALUE = RF230_CCA_MODE_3,
+
+       /**
+        * This is the value of the CCA_THRES register that controls the
+        * energy levels used for clear channel assessment
+        */
+       RF230_CCA_THRES_VALUE = 0xC7,
+};
+
+/* This is the default value of the TX_PWR field of the PHY_TX_PWR register. 0-15*/
+#ifndef RF230_DEF_RFPOWER
+#define RF230_DEF_RFPOWER      0
+#endif
+
+/* This is the default value of the CHANNEL field of the PHY_CC_CCA register. 11-26*/
+#ifndef RF230_DEF_CHANNEL
+#define RF230_DEF_CHANNEL      11
+#endif
+
+/*
+ * This is the command used to calculate the CRC for the RF230 chip. 
+ * TODO: Check why the default crcByte implementation is in a different endianness
+ */
+inline uint16_t RF230_CRCBYTE_COMMAND(uint16_t crc, uint8_t data)
+{
+    uint8_t lo8 = crc & 0x00FF;
+    uint8_t hi8 = (crc >> 8) & 0x00FF;
+    data ^= lo8; //lo8 (crc);
+    data ^= data << 4;
+
+    return ((((uint16_t)data << 8) | hi8 /*hi8 (crc)*/) ^ (uint8_t)(data >> 4) 
+        ^ ((uint16_t)data << 3));
+}
+
+/**
+ * This is the timer type of the radio alarm interface
+ */
+typedef TMicro TRadio;
+
+/**
+ * The number of alarm ticks per one second
+ */
+#define RADIO_ALARM_SEC 2500000 // 20MHz / 8
+
+#define RADIO_ALARM_MICROSEC   2.5// RADIO_ALARM_SEC/1000000
+
+/**
+ * The base two logarithm of the number of radio alarm ticks per one millisecond
+ */
+#define RADIO_ALARM_MILLI_EXP  11
+
+/**
+ * Make PACKET_LINK automaticaly enabled for Ieee154MessageC
+ */
+#if !defined(TFRAMES_ENABLED) && !defined(PACKET_LINK)
+#define PACKET_LINK
+#endif
+
+#endif  //__RADIOCONFIG_H__
diff --git a/tos/platforms/mulle/chips/rf230/SoftSpiRF230C.nc b/tos/platforms/mulle/chips/rf230/SoftSpiRF230C.nc
new file mode 100755 (executable)
index 0000000..3f4e154
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * A component that is going to use the RF230 Spi bus should
+ * create a new component of this to get access to the bus.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "Mulle_RF230Spi.h"
+
+generic configuration SoftSpiRF230C()
+{
+  provides interface Resource;
+  provides interface SpiPacket;
+  provides interface SpiByte;
+  provides interface SoftSpiBus;
+}
+implementation
+{
+  enum
+  {
+    CLIENT_ID = unique(UQ_MULLE_SOFTSPIRF230),
+  };
+  
+  components SoftSpiRF230P as Spi;
+  SoftSpiBus = Spi.SoftSpiBus;
+  Resource = Spi.Resource[CLIENT_ID];
+  SpiPacket = Spi.SpiPacket[CLIENT_ID]; 
+  SpiByte = Spi.SpiByte[CLIENT_ID]; 
+}
diff --git a/tos/platforms/mulle/chips/rf230/SoftSpiRF230P.nc b/tos/platforms/mulle/chips/rf230/SoftSpiRF230P.nc
new file mode 100755 (executable)
index 0000000..9423359
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Creates a new Software Spi bus that will be used by the RF230
+ * chip.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+configuration SoftSpiRF230P
+{
+  provides interface Resource[uint8_t client];
+  provides interface SpiPacket[uint8_t client];
+  provides interface SpiByte[uint8_t client];
+  provides interface SoftSpiBus;
+
+}
+implementation
+{
+  components new SoftSpiMasterP(UQ_MULLE_SOFTSPIRF230) as Spi,
+      new SoftSpiBusP(),
+      HplM16c62pGeneralIOC as IOs;
+  
+  // Init the software SPI bus
+  SoftSpiBusP.SCLK -> IOs.PortP33;
+  SoftSpiBusP.MISO -> IOs.PortP10;
+  SoftSpiBusP.MOSI -> IOs.PortP11;
+
+  Spi.SoftSpiBus -> SoftSpiBusP;
+  SoftSpiBus = SoftSpiBusP;
+
+  Resource  = Spi.Resource;
+  SpiPacket = Spi.SpiPacket;
+  SpiByte = Spi.SpiByte;
+}
diff --git a/tos/platforms/mulle/chips/rv8564/RV8564.nc b/tos/platforms/mulle/chips/rv8564/RV8564.nc
new file mode 100755 (executable)
index 0000000..3004be3
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface for the RV-8564-C2 real time clock.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+interface RV8564
+{
+  /**
+   * Turns the chip on.
+   */
+  command error_t on();
+
+  /**
+   * Turns the chip off.
+   */
+  command error_t off();
+
+  /**
+   * Checks if the chip is on.
+   *
+   * @return true if on.
+   */
+  command bool isOn();
+
+  /**
+   * Enables/disables the interrupts generated by the CLKOUT.
+   */
+  // TODO(henrik) This needs to be changed because there are different type of 
+  //              interrupts generated by the chip.
+  command void enableInterrupt();
+  command void disableInterrupt();
+
+  /**
+   * Reads from a register.
+   *
+   * @param reg The register to be read.
+   * @return The value of the register.
+   */
+  command error_t readRegister(uint8_t reg);
+
+  /**
+   * Writes to a register.
+   *
+   * @param reg The register that is written to.
+   * @param value The value that is written to the register.
+   */
+  command error_t writeRegister(uint8_t reg, uint8_t value);
+
+  /**
+   * Signals when a register read finished.
+   *
+   * @param val The value read from the register.
+   * @param reg The register the value was read from.
+   */
+  async event void readRegisterDone(uint8_t val, uint8_t reg);
+
+  /**
+   * Signals when a register write finished.
+   *
+   * @param reg The register the value was written to.
+   */
+  async event void writeRegisterDone(uint8_t reg);
+
+  /**
+   * Signal when an interrupt occurs.
+   */
+  async event void fired();
+  
+  /**
+   * Enables CLKOUT from the RTC.
+   */
+  command void enableCLKOUT();
+}
diff --git a/tos/platforms/mulle/chips/rv8564/RV8564C.nc b/tos/platforms/mulle/chips/rv8564/RV8564C.nc
new file mode 100755 (executable)
index 0000000..1f484f9
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Configuration of the RV-8564 Real-time Clock on the Mulle platform.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+configuration RV8564C
+{
+  provides interface RV8564 as RTC;
+}
+implementation
+{
+  components RV8564P as RTCP,
+    new SoftI2CBatteryMonitorRTCC() as I2C,
+    HplM16c62pGeneralIOC as IOs,
+    HplM16c62pInterruptC as Irqs,
+    new M16c62pInterruptC() as Irq;
+
+  Irq.HplM16c62pInterrupt -> Irqs.Int0;
+
+  RTC = RTCP;
+  RTCP.CLKOE -> IOs.PortP47;
+  RTCP.CLKOUT -> IOs.PortP92;
+  RTCP.GpioInterrupt -> Irq;
+  RTCP.I2C -> I2C;
+  RTCP.I2CResource -> I2C;
+}
diff --git a/tos/platforms/mulle/chips/rv8564/RV8564P.nc b/tos/platforms/mulle/chips/rv8564/RV8564P.nc
new file mode 100755 (executable)
index 0000000..84dab98
--- /dev/null
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Implementation of the RV-8564-C2 real time clock.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "rv8564.h"
+#include "I2C.h"
+module RV8564P
+{
+  provides interface RV8564 as RTC;
+  // TODO(henrik) Exactly how is the RTC connected to mulle, what is the functionallity of GeneralIO?
+  //              Maybe there is only a init needed because the chip is always on?
+  uses interface GeneralIO as CLKOE;
+  uses interface GeneralIO as CLKOUT;
+  uses interface GeneralIO;
+  uses interface GpioInterrupt;
+  uses interface I2CPacket<TI2CBasicAddr> as I2C;
+  uses interface Resource as I2CResource;
+}
+implementation
+{
+
+  enum
+  {
+    OFF,
+    IDLE,
+    READING,
+    WRITING
+  };
+  norace uint8_t state = OFF;
+  norace uint8_t read_register;
+  uint8_t read_register_value;
+  uint8_t write_buffer[2];
+
+  command error_t RTC.on()
+  {
+    if (state != OFF)
+    {
+      return SUCCESS;
+    }
+    state = IDLE;
+    return SUCCESS;
+  }
+
+  command error_t RTC.off()
+  {
+    if  (state == OFF)
+    {
+      return SUCCESS;
+    }
+    else if (state != IDLE)
+    {
+      return FAIL;
+    }
+    call CLKOE.clr();
+    call CLKOUT.clr();
+    return SUCCESS;
+  }
+
+  command bool RTC.isOn()
+  {
+    return ((state != OFF) ? true : false);
+  }
+
+  command void RTC.enableCLKOUT()
+  {
+       call CLKOUT.makeInput();
+       call CLKOUT.clr();
+       call CLKOE.makeOutput();
+       call CLKOE.set();
+  }
+  command void RTC.enableInterrupt()
+  {
+    call GpioInterrupt.enableFallingEdge();
+  }
+
+  command void RTC.disableInterrupt()
+  {
+    call GpioInterrupt.disable();
+  }
+
+  command error_t RTC.readRegister(uint8_t reg)
+  {
+    uint8_t val;
+    if (state != IDLE)
+    {  
+      return FAIL;
+    }
+    state = READING;
+    read_register = reg;
+    call I2CResource.request();
+    return SUCCESS;
+  }
+
+  command error_t RTC.writeRegister(uint8_t reg, uint8_t value)
+  { 
+    if (state != IDLE)
+    {
+      return FAIL;
+    }
+    state = WRITING;
+    atomic write_buffer[0] = reg;
+    atomic write_buffer[1] = value;
+    call I2CResource.request();
+    return SUCCESS;
+  }
+
+  event void I2CResource.granted()
+  {
+    atomic {
+      if (state == READING)
+      {
+        call I2C.write(I2C_START, RV8564_ADDR, 1, &read_register);
+      }
+      else if (state == WRITING)
+      {
+        call I2C.write(I2C_START | I2C_STOP, RV8564_ADDR, 2, write_buffer);    
+      }
+    }  
+  }
+
+  async event void GpioInterrupt.fired()
+  {
+    signal RTC.fired();
+  }
+
+  async event void I2C.readDone(error_t error, uint16_t addr, uint8_t length, uint8_t* data)
+  {
+    atomic
+    {
+      if (state == READING && data == &read_register_value)
+      {
+        state = IDLE;
+        call I2CResource.release();
+        signal RTC.readRegisterDone(read_register_value, read_register);
+      }        
+    }
+  }
+
+  async event void I2C.writeDone(error_t error, uint16_t addr, uint8_t length, uint8_t* data)
+  {
+    if (state == READING)
+    {
+      call I2C.read(I2C_START | I2C_STOP, RV8564_ADDR, 1, &read_register_value);
+    }
+    else if (state == WRITING)
+    {
+      state = IDLE;
+      call I2CResource.release();
+      signal RTC.writeRegisterDone(write_buffer[0]);
+    }
+  }
+
+  default async event void RTC.readRegisterDone(uint8_t val, uint8_t reg) {}
+  default async event void RTC.writeRegisterDone(uint8_t reg) {}
+  default async event void RTC.fired() { }
+}
diff --git a/tos/platforms/mulle/chips/rv8564/rv8564.h b/tos/platforms/mulle/chips/rv8564/rv8564.h
new file mode 100755 (executable)
index 0000000..e3563ae
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * This file is for the Microcrystal RV-8564 Real-time Clock on the Mulle
+ * platform.
+ * 
+ * @author: Gong Liang
+ */
+
+#ifndef __RV8564_H__
+#define __RV8564_H__
+
+/* constants */
+#define RV8564_ADDR    0xa2  //slave address   
+
+
+#define RV8564_CS1    0x00
+#define RV8564_CS2    0x01
+
+
+/* Control/Status registers */
+#define RV8564_CTR1 0x00         //00 Control status 1, 
+                                 //Test1 0 Stop 0, Test 0 0 0
+                                                                
+#define RV8564_CTR2 0x01         //01 Control status 2,
+                                 // 0 x  0 TI/TP, AF TF AIE TIE  
+                                                                // TI/TP=1,INT pulses 
+//Note that writing 1 to the alarm flags causes no change...0-1 is not applied.                                                                 
+                                                                
+#define RV8564_SEC    0x02          // 
+#define RV8564_MIN    0x03          //
+#define RV8564_HOUR   0x04          //
+#define RV8564_DAY    0x05          //
+#define RV8564_WEEK   0x06          //
+#define RV8564_MON    0x07          //
+#define RV8564_YEAR   0x08          //
+
+#define RV8564_MIN_ALARM    0x09    //
+#define RV8564_HR_ALARM     0x0A    //
+#define RV8564_DAY_ALARM    0x0B    //
+#define RV8564_WK_ALARM     0x0C    //
+
+
+#define RV8564_CLKF   0x0D       //FE x x x,  x x FD1 FD0
+                                 //                0   0    32768 Hz          
+                                 //                0   1    61024  Hz                 
+                                 //                1   0     32 Hz                           
+                                 //                1   1     1  Hz 
+
+
+
+
+#define RV8564_TC     0x0E       //TE x x x,  x x TD1 TD0
+                                 //                0   0    4096 Hz          
+                                 //                0   1    64   Hz                 
+                                 //                1   0     1 Sec                           
+                                 //                1   1     1 Min   
+                                                                                                                                                        
+#define RV8564_TIMER  0x0F       //128 64  32 16, 8 4 2 1
+
+/*********** Initial setting of the RV_8564ram, Set it before using (debug only) ***********/
+uint8_t RV_8564ram[16] = { 0x00, 0x13, 0x01, 0x01,
+                           0x01, 0x01, 0x01, 0x01,
+                           0x07, 0x80, 0x80, 0x80,
+                           0x80, 0x83, 0x83, 1 };
+
+
+#endif /* __RV8564_H__ */
+
diff --git a/tos/platforms/mulle/debug/m_printf.h b/tos/platforms/mulle/debug/m_printf.h
new file mode 100644 (file)
index 0000000..ae9dfec
--- /dev/null
@@ -0,0 +1,276 @@
+/*
+       Copyright 2001, 2002 Georges Menie (www.menie.org)
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU Lesser General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Lesser General Public License for more details.
+
+    You should have received a copy of the GNU Lesser General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+*/
+
+
+
+/**
+ * The file is a debug tool for the Mulle-TinyOS platform. To use this tool,
+ * just need 2 steps.
+ * First, add #inclued "m_printf.h" to your component.
+ * Sencond, use _printf() function in the m_printf.h to print what you want
+ * to see.
+ * attention: don't forget to start your serialport, and just initialization.
+ * The serialport baudrate is at 57600, and you can choose a terminal to watch
+ * the output, for example, cutecom in linux.
+ * For more information see www.eistec.se.
+ *
+ * Modification to adopt printf for Mulle-TinyOS is made by
+ * @author Fan Zhang
+ * @author Cheng Zhong
+ */
+#ifndef __M_PRINTF_H__
+#define __M_PRINTF_H__
+
+#include <stdarg.h>
+#include <string.h>
+/*
+ * void m16c62p_putc(int c) is for the m16c62p. send a char through
+ * serial port 1. 
+ */
+void m16c62p_putc(int c)
+{
+    while(U1C1.BIT.TI == 0);  // wait for transmit buffer empty flag
+    U1TB.BYTE.U1TBL = c;
+}
+#define putchar(c) m16c62p_putc(c)
+
+static void printchar(char **str, int c)
+{
+       //extern int putchar(int c);
+
+       if (str) {
+               **str = c;
+               ++(*str);
+       }
+       else (void)putchar(c);
+}
+
+#define PAD_RIGHT 1
+#define PAD_ZERO 2
+
+static int prints(char **out, const char *string, int width, int pad)
+{
+       register int pc = 0, padchar = ' ';
+
+       if (width > 0) 
+       {
+               register int len = 0;
+               register const char *ptr;
+               for (ptr = string; *ptr; ++ptr) ++len;
+               if (len >= width) width = 0;
+               else width -= len;
+               if (pad & PAD_ZERO) padchar = '0';
+       }
+       if (!(pad & PAD_RIGHT)) {
+               for ( ; width > 0; --width) {
+                       printchar (out, padchar);
+                       ++pc;
+               }
+       }
+       for ( ; *string ; ++string) {
+               printchar (out, *string);
+               ++pc;
+       }
+       for ( ; width > 0; --width) {
+               printchar (out, padchar);
+               ++pc;
+       }
+
+       return pc;
+}
+
+/* 
+ * the following should be enough for 32 bit int 
+*/
+#define PRINT_BUF_LEN 12
+
+static int printi(char **out, long int i, int b, int sg, int width, int pad, int letbase)
+{
+       char print_buf[PRINT_BUF_LEN];
+       register char *s;
+       register int t, neg = 0, pc = 0;
+       register unsigned long int u = i;
+
+       if (i == 0) {
+               print_buf[0] = '0';
+               print_buf[1] = '\0';
+               return prints (out, print_buf, width, pad);
+       }
+
+       if (sg && b == 10 && i < 0) {
+               neg = 1;
+               u = -i;
+       }
+
+       s = print_buf + PRINT_BUF_LEN-1;
+       *s = '\0';
+
+       while (u) {
+               t = u % b;
+               if( t >= 10 )
+                       t += letbase - '0' - 10;
+               *--s = t + '0';
+               u /= b;
+       }
+
+       if (neg) {
+               if( width && (pad & PAD_ZERO) ) {
+                       printchar (out, '-');
+                       ++pc;
+                       --width;
+               }
+               else {
+                       *--s = '-';
+               }
+       }
+
+       return pc + prints (out, s, width, pad);
+}
+
+static int print(char **out, const char *format, va_list args )
+{
+       register int width, pad;
+       register int pc = 0;
+       char scr[2];
+
+       for (; *format != 0; ++format) 
+       {
+               if (*format == '%') 
+               {
+                       ++format;
+                       width = pad = 0;
+                       if (*format == '\0') break;
+                       if (*format == '%') goto out;
+                       if (*format == '-') 
+                       {
+                               ++format;
+                               pad = PAD_RIGHT;
+                       }
+                       while (*format == '0') 
+                       {
+                               ++format;
+                               pad |= PAD_ZERO;
+                       }
+                       for ( ; *format >= '0' && *format <= '9'; ++format) 
+                       {
+                               width *= 10;
+                               width += *format - '0';
+                       }
+                       if( *format == 's' ) 
+                       {
+                               register char *s = (char *)va_arg( args, int);
+                               pc += prints (out, s?s:"(null)", width, pad);
+                               continue;
+                       }
+                       if( *format == 'd' ) 
+                       {
+                               pc += printi (out, va_arg( args, int ), 10, 1, width, pad, 'a');
+                               continue;
+                       }
+                       if( *format == 'x' ) 
+                       {
+                               pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'a');
+                               continue;
+                       }
+                       if( *format == 'X' ) 
+                       {
+                               pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'A');
+                               continue;
+                       }
+                       if( *format == 'u' ) 
+                       {
+                               pc += printi (out, va_arg( args, int ), 10, 0, width, pad, 'a');
+                               continue;
+                       }
+                       if( *format == 'l' ) 
+                       {
+                                      ++format;
+                               if( *format == 'u' ) 
+                                      {
+                                              pc += printi (out, va_arg( args, uint32_t ), 10, 0, width, pad, 'a');
+                                              continue;
+                                      }
+                       }
+                       if( *format == 'c' ) 
+                       {
+                               /* char are converted to int then pushed on the stack */
+                               scr[0] = (char)va_arg( args, int );
+                               scr[1] = '\0';
+                               pc += prints (out, scr, width, pad);
+                               continue;
+                       }
+               }
+               else 
+               {
+                    out:
+                       printchar (out, *format);
+                       ++pc;
+               }
+       }
+       if (out) **out = '\0';
+       va_end( args );
+       return pc;
+}
+/*
+ * A simple printf function. Support the following format:
+ * Code Format
+ * %c character
+ * %d signed decimal integers
+ * %i signed decimal integers, the same as %d
+ * %s a string of characters
+ * %o octal
+ * %x unsigned hexadecimal
+ * %X unsigned hexadecimal with uppercase
+ * %u unsigned decimal integers
+ * %lu 32 bits decimal unsigned long int=uint32_t
+ */
+int _printf(const char *format, ...)
+{
+       va_list args;
+
+       va_start( args, format );
+       return print( 0, format, args );
+}
+
+int sprintf(char *out, const char *format, ...)
+{
+       va_list args;
+
+       va_start( args, format );
+       return print( &out, format, args );
+}
+
+void _puts(const char *str)
+{
+ while( *str != '\0' )
+   putchar(*str++);
+
+ putchar('\n');
+}
+void printmsg(void *msg, uint8_t printLen)
+{
+       uint8_t i;
+       for(i=0; i < printLen; i++)
+       {
+               _printf("%x ", *( (uint8_t *)msg + i));
+               
+       }
+       _printf("\n");
+}
+#endif  // __M_PRINTF_H__
+
diff --git a/tos/platforms/mulle/hardware.h b/tos/platforms/mulle/hardware.h
new file mode 100755 (executable)
index 0000000..ff2ed9e
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#ifndef __HARDWARE_H__
+#define __HARDWARE_H__
+
+#define MAIN_CRYSTAL_SPEED 10 /*MHz*/
+#define PLL_MULTIPLIER M16C62P_PLL_2
+
+#ifndef PLL_ON
+#define RF230_SLOW_SPI
+#endif
+
+#include "m16c62phardware.h" // Header file for the MCU
+
+#endif  // __HARDWARE_H__
+
+
diff --git a/tos/platforms/mulle/platform.h b/tos/platforms/mulle/platform.h
new file mode 100755 (executable)
index 0000000..bfe6a31
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * Defines for the different speeds supported on the Mulle platform.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#ifndef __PLATFORM_H__
+#define __PLATFORM_H__
+
+
+#define MCU_SPEED_20MHz     M16C62P_PLL_CLOCK
+#define MCU_SPEED_10MHz     M16C62P_MAIN_CLOCK_DIV_0 
+#define MCU_SPEED_5MHz      M16C62P_MAIN_CLOCK_DIV_2 
+#define MCU_SPEED_2_5MHz    M16C62P_MAIN_CLOCK_DIV_4 
+#define MCU_SPEED_1_25MHz   M16C62P_MAIN_CLOCK_DIV_8 
+#define MCU_SPEED_0_625MHz  M16C62P_MAIN_CLOCK_DIV_16
+#define MCU_SPEED_32KHz     M16C62P_SUB_CLOCK
+
+#endif  // __PLATFORM_H__
diff --git a/tos/platforms/mulle/platform_message.h b/tos/platforms/mulle/platform_message.h
new file mode 100755 (executable)
index 0000000..bbdfd75
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#ifndef __PLATFORM_MESSAGE_H__
+#define __PLATFORM_MESSAGE_H__
+
+#include "Serial.h"
+#include <RF230Radio.h>
+
+
+typedef union message_header {
+       rf230packet_header_t rf230;
+       serial_header_t serial;
+} message_header_t;
+
+typedef union message_footer {
+       rf230packet_footer_t rf230;
+} message_footer_t;
+
+typedef union message_metadata {
+       rf230packet_metadata_t rf230;
+} message_metadata_t;
+
+
+#endif  // __PLATFORM_MESSAGE_H__
diff --git a/tos/platforms/mulle/softwarei2c/MulleI2C.h b/tos/platforms/mulle/softwarei2c/MulleI2C.h
new file mode 100755 (executable)
index 0000000..64ccd8e
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#ifndef __MULLEI2C_H__
+#define __MULLEI2C_H__
+
+#define UQ_MULLE_SOFTI2C_BATTERY_RTC "SoftI2CMasterC.Battery_RTC"
+
+#endif // __MULLEI2C_H__
diff --git a/tos/platforms/mulle/softwarei2c/SoftI2CBatteryMonitorRTCC.nc b/tos/platforms/mulle/softwarei2c/SoftI2CBatteryMonitorRTCC.nc
new file mode 100755 (executable)
index 0000000..905a5b0
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * The basic client abstraction of the software I2C on Mulle used
+ * by the RTC and battery monitor.
+ * The device drivers should instantiate one of these to ensure
+ * exclusive access to the I2C bus.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "MulleI2C.h"
+#include "I2C.h"
+generic configuration SoftI2CBatteryMonitorRTCC()
+{
+  provides interface Resource;
+  provides interface I2CPacket<TI2CBasicAddr>;
+}
+implementation
+{
+  enum
+  {
+    CLIENT_ID = unique(UQ_MULLE_SOFTI2C_BATTERY_RTC),
+  };
+  
+  components SoftI2CBatteryMonitorRTCP as I2C; 
+  Resource = I2C.Resource[CLIENT_ID];
+  I2CPacket = I2C.I2CPacket[CLIENT_ID]; 
+}
diff --git a/tos/platforms/mulle/softwarei2c/SoftI2CBatteryMonitorRTCP.nc b/tos/platforms/mulle/softwarei2c/SoftI2CBatteryMonitorRTCP.nc
new file mode 100644 (file)
index 0000000..bf4a3c5
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * The configuration that takes the underlying software I2C driver 
+ * on Mulle and turns it into a shared abstraction for the RTC and battery
+ * monitor.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "MulleI2C.h"
+#include "I2C.h"
+configuration SoftI2CBatteryMonitorRTCP
+{
+  provides interface Resource[uint8_t client];
+  provides interface I2CPacket<TI2CBasicAddr>[uint8_t client];
+}
+implementation
+{
+  components new SoftI2CMasterP(UQ_MULLE_SOFTI2C_BATTERY_RTC) as I2C,
+      new SoftI2CBusP(),
+      HplM16c62pGeneralIOC as IOs;
+  
+  // Init the software I2C bus
+  SoftI2CBusP.I2CClk -> IOs.PortP71;
+  SoftI2CBusP.I2CData -> IOs.PortP70;
+  SoftI2CBusP.I2CCtrl -> IOs.PortP75;
+
+  I2C.SoftI2CBus -> SoftI2CBusP;
+
+  Resource  = I2C.Resource;
+  I2CPacket = I2C.I2CPacket;
+}
+
diff --git a/tos/platforms/mulle/softwarei2c/SoftI2CBus.nc b/tos/platforms/mulle/softwarei2c/SoftI2CBus.nc
new file mode 100755 (executable)
index 0000000..6dba076
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface for a software I2C bus.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+interface SoftI2CBus
+{
+  /*
+   * Initializes bus default state.
+   */
+  async command void init();
+  
+  /*
+   * Turn the bus off.
+   */
+  async command void off();
+
+  /*
+   * Generates a start condition on the bus.
+   */
+  async command void start();
+
+  /*
+   * Generates a stop condition.
+   */
+  async command void stop();
+
+  /*
+   * Restarts a I2C bus transaction.
+   */
+  async command void restart();
+
+  /*
+   * Reads a byte from the I2C bus.
+   *
+   * @param ack If true ack the read byte else nack.
+   * @return A byte from the bus.
+   */
+  async command uint8_t readByte(bool ack);
+
+  /*
+   * Writes a byte on th I2C bus.
+   * Send the data( or address) C  and wait for acknowledge after finishing
+   * sending it. Nonacknowledge sets ACK=0 and normal sending sets ACK=1.
+   *
+   * @param byte the byte to write.
+   */
+  async command void writeByte(uint8_t byte);
+  
+  /*
+   * Master sends the ACK (LowLevel), working as a master-receiver.
+   */
+  async command void masterAck();
+
+  /*
+   * Master sends the NACK (HighLevel), working as a master-receiver.
+   */
+  async command void masterNack();
+}
diff --git a/tos/platforms/mulle/softwarei2c/SoftI2CBusP.nc b/tos/platforms/mulle/softwarei2c/SoftI2CBusP.nc
new file mode 100755 (executable)
index 0000000..ad333bc
--- /dev/null
@@ -0,0 +1,264 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Mulle specific implementation of a software I2C bus.
+ *
+ * @author Gong Liang
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+generic module SoftI2CBusP()
+{
+  provides interface SoftI2CBus as I2C;
+
+  uses interface GeneralIO as I2CClk;
+  uses interface GeneralIO as I2CData;
+  uses interface GeneralIO as I2CCtrl;
+}
+implementation
+{
+  /***************************************************************************************/
+  // Name:idle(), transition(),halfTransition()
+  // I2C-bus can be transferred at rates of up to 100 kbit/s in the Standard-mode  
+  // 10MHz main clock frequency
+  // The Baud rate of IIC bus communication can be adjusted by altering the loop times.
+  /***************************************************************************************/
+  // TODO(henrik) This must be altered to support different main clock speeds.
+  void idle(void)
+  {
+    volatile long int i;
+    for(i=0;i<1000;i++)
+    {
+      asm("nop");
+    }
+  }
+
+  void transition(void)
+  {
+    volatile int i;
+    for(i=0;i<100;i++)
+    {
+      asm("nop");
+    }
+  }
+
+  void halfTransition(void)
+  {
+    volatile int i;
+    for(i=0;i<50;i++)
+    {
+      asm("nop");
+    }
+  }
+
+  
+  async command void I2C.init()
+  {
+    call I2CData.makeOutput(); 
+    call I2CClk.makeOutput();
+    call I2CCtrl.makeOutput();
+    call I2CCtrl.set();
+    call I2CData.set();  // drive bus high (default)
+    call I2CClk.set();  // drive bus high (default)
+  }
+
+  async command void I2C.off()
+  {
+    // TODO(henrik): Exactly what should be set if I2C bus should be turned off?
+    call I2CData.makeOutput();
+    call I2CClk.makeOutput();
+    call I2CCtrl.makeOutput();
+    call I2CCtrl.clr();
+    call I2CClk.clr();
+    call I2CData.clr();
+  }
+
+  async command void I2C.start()
+  {
+    atomic 
+    {
+      call I2CData.makeOutput();
+      call I2CClk.clr();
+      call I2CData.set();
+      idle();
+      call I2CClk.set();
+      idle();
+      call I2CData.clr();
+      idle();
+      call I2CClk.clr();
+      idle();
+    }
+  }
+
+  async command void I2C.stop()
+  {
+    atomic
+    {
+      call I2CData.makeOutput();
+
+      call I2CData.set(); 
+      call I2CClk.clr();
+      idle();
+      call I2CData.clr();
+      idle();
+      call I2CClk.set();
+      idle();
+      call I2CData.set();
+      idle();
+    }
+  }
+
+  async command void I2C.restart()
+  {
+    atomic
+    {
+      call I2CClk.clr();
+      call I2CData.set();
+      call I2CClk.set();
+      idle();
+      call I2CData.clr();
+      idle();
+      call I2CClk.clr();
+    }
+  }
+
+  async command uint8_t I2C.readByte(bool ack)
+  {
+    uint8_t retChar;
+    uint8_t bitCnt;
+
+    atomic
+    {
+      call I2CData.makeInput();
+
+      retChar = 0;
+      
+      for (bitCnt=0; bitCnt<8; ++bitCnt)
+      {
+        asm("nop");
+        call I2CClk.clr();
+        transition();
+
+        call I2CClk.set();  // Validate the RevData on the SDA2 line
+        halfTransition();
+        retChar<<=1;        // Push each received bit toward MSB
+        if(call I2CData.get() == 1) retChar+=1; //  Read the bit on SDA2 line
+        halfTransition();
+      }
+
+      call I2CClk.clr();
+      if (ack) 
+      {
+        call I2C.masterAck();
+      }
+      else
+      {
+        call I2C.masterNack();
+      }
+    }
+    return retChar;
+  }
+
+  async command void I2C.writeByte(uint8_t byte)
+  {
+    uint8_t bitCnt;
+
+    atomic
+    {
+      call I2CData.makeOutput();
+
+      for (bitCnt=0; bitCnt<8; ++bitCnt)
+      {
+        if ((byte<<bitCnt) & 0x80)
+        {
+          call I2CData.set();  // MSB sending logic
+        }
+        else
+        {
+          call I2CData.clr();
+        }
+        transition();  // Use this function to adjust the baut rate of I2C bus
+
+        call I2CClk.set(); //Set SCL2 high to inform slave of receiving sth.
+        transition();      // Greater than 4¦Ìs
+        call I2CClk.clr();
+      }
+
+
+      call I2CData.set();  // Release SDA2 for ACK-waiting after sending 8 bits  
+      transition();
+
+      call I2CClk.set(); 
+      transition();
+      call I2CClk.clr();
+
+      idle(); 
+    }
+  }
+  
+  async command void I2C.masterAck()
+  {
+    atomic
+    {
+      call I2CData.makeOutput();
+      call I2CClk.clr();
+      call I2CData.clr(); // Low for ack
+      transition();
+      call I2CClk.set();
+      transition();
+      call I2CClk.clr();
+
+      call I2CData.makeInput();
+    }
+  }
+
+  async command void I2C.masterNack()
+  {
+    atomic 
+    {
+      call I2CData.makeOutput();
+      call I2CClk.clr();
+
+      call I2CData.set(); // High for nack
+      transition();
+      call I2CClk.set();
+      transition();
+      call I2CClk.clr();
+
+      call I2CData.makeInput();
+    }
+  }
+}
diff --git a/tos/platforms/mulle/softwarei2c/SoftI2CMasterImplP.nc b/tos/platforms/mulle/softwarei2c/SoftI2CMasterImplP.nc
new file mode 100755 (executable)
index 0000000..33817d6
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/*
+ * Copyright (c) 2006 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Philip Levis
+ */
+/**
+ * The configuration that takes the underlying software I2C on Mulle 
+ * and turns it into a shared abstraction.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#include "I2C.h"
+generic module SoftI2CMasterImplP()
+{
+  provides interface Resource[uint8_t client];
+  provides interface I2CPacket<TI2CBasicAddr>[uint8_t client];
+  uses interface Resource as SubResource[uint8_t];
+  uses interface I2CPacket<TI2CBasicAddr> as SubPacket;
+}
+implementation
+{
+  enum
+  {
+    NO_CLIENT = 0xff
+  };
+  
+  uint8_t currentClient = NO_CLIENT;
+
+  async command error_t Resource.request[uint8_t id]()
+  {
+    return call SubResource.request[id]();
+  }
+
+  async command error_t Resource.immediateRequest[uint8_t id]()
+  {
+    error_t rval = call SubResource.immediateRequest[id]();
+    if (rval == SUCCESS)
+    {
+      atomic currentClient = id;
+    }
+    return rval;
+  }
+
+  event void SubResource.granted[uint8_t id]()
+  {
+    atomic currentClient = id;
+    signal Resource.granted[id]();
+  }
+
+  async command error_t Resource.release[uint8_t id]()
+  {
+    return call SubResource.release[id]();
+  }
+
+  async command bool Resource.isOwner[uint8_t id]()
+  {
+    return call SubResource.isOwner[id]();
+  }
+  
+  async command error_t I2CPacket.write[uint8_t id](i2c_flags_t flags,
+                                                        uint16_t addr,
+                                                        uint8_t len,
+                                                        uint8_t* data)
+  {
+    atomic
+    {
+      if (currentClient != id)
+      {
+       return FAIL;
+      }
+    }
+    return call SubPacket.write(flags, addr, len, data);
+  }
+  
+  async command error_t I2CPacket.read[uint8_t id](i2c_flags_t flags,
+                                                       uint16_t addr,
+                                                       uint8_t len,
+                                                       uint8_t* data)
+  {
+    atomic
+    {
+      if (currentClient != id)
+      {
+       return FAIL;
+      }
+    }
+    return call SubPacket.read(flags, addr, len, data);
+  }
+
+  default event void Resource.granted[uint8_t id]() {}
+
+  async event void  SubPacket.readDone(
+      error_t error, uint16_t addr, uint8_t length, uint8_t* data)
+  {
+    signal  I2CPacket.readDone[currentClient](error, addr, length, data);
+  }
+
+  async event void SubPacket.writeDone(
+      error_t error, uint16_t addr, uint8_t length, uint8_t* data)
+  {
+    signal I2CPacket.writeDone[currentClient]( error, addr, length,  data);
+  }
+
+  default async event void  I2CPacket.readDone[uint8_t id](
+      error_t error, uint16_t addr, uint8_t length, uint8_t* data) {  }
+
+  default async event void I2CPacket.writeDone[uint8_t id](
+      error_t error, uint16_t addr, uint8_t length, uint8_t* data) {  }
+
+}
diff --git a/tos/platforms/mulle/softwarei2c/SoftI2CMasterP.nc b/tos/platforms/mulle/softwarei2c/SoftI2CMasterP.nc
new file mode 100755 (executable)
index 0000000..14de59f
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2006 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Philip Levis
+ */
+/**
+ * The configuration that takes the underlying software I2C driver 
+ * Mulle and turns it into a shared abstraction.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "MulleI2C.h"
+#include "I2C.h"
+generic configuration SoftI2CMasterP(char resourceName[])
+{
+  provides interface Resource[uint8_t client];
+  provides interface I2CPacket<TI2CBasicAddr>[uint8_t client];
+  uses interface SoftI2CBus;
+}
+implementation
+{
+  components new FcfsArbiterC(resourceName) as Arbiter;
+  components new AsyncPowerManagerP() as Power;
+  components new SoftI2CMasterImplP() as I2C;
+  components new SoftI2CMasterPacketP() as Master;
+    
+  Resource  = I2C;
+  I2CPacket = I2C;
+  
+  I2C.SubResource -> Arbiter;
+  I2C.SubPacket   -> Master;
+  
+  Power.AsyncStdControl -> Master;
+  Power.ResourceDefaultOwner -> Arbiter;
+
+  Master.I2C = SoftI2CBus;
+}
+
diff --git a/tos/platforms/mulle/softwarei2c/SoftI2CMasterPacketP.nc b/tos/platforms/mulle/softwarei2c/SoftI2CMasterPacketP.nc
new file mode 100755 (executable)
index 0000000..ce107f0
--- /dev/null
@@ -0,0 +1,266 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2006 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Philip Levis
+ */
+
+/**
+ * This driver implements an software I2C Master controller.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+#include "I2C.h"
+generic module SoftI2CMasterPacketP()
+{
+    provides interface AsyncStdControl;
+    provides interface I2CPacket<TI2CBasicAddr>;
+
+    uses interface SoftI2CBus as I2C;
+}
+implementation
+{
+    enum
+    {
+        I2C_OFF          = 0,
+        I2C_IDLE         = 1,
+        I2C_BUSY         = 2,      
+    } soft_i2c_state_t;
+
+    uint8_t state = I2C_OFF;
+    uint16_t _addr;
+    uint8_t _len;
+    uint8_t* _data;
+    error_t _error;
+
+    task void writeDoneTask()
+    {
+        atomic
+        {
+            state = I2C_IDLE;
+            signal I2CPacket.writeDone( _error, _addr, _len,  _data);
+        }
+    }
+
+    task void readDoneTask()
+    {
+        atomic
+        {
+            state = I2C_IDLE;
+            signal I2CPacket.readDone( _error, _addr, _len,  _data);
+        }
+    }
+
+    async command error_t AsyncStdControl.start()
+    {
+        atomic
+        {
+            if (state == I2C_OFF)
+            {
+                call I2C.init();
+                state = I2C_IDLE;
+                return SUCCESS;
+            }
+            else
+            {
+                return FAIL;
+            }
+        }
+    }
+
+    async command error_t AsyncStdControl.stop()
+    {
+        atomic
+        {
+            if (state == I2C_IDLE)
+            {
+                call I2C.off();
+                state = I2C_OFF;
+                return SUCCESS;
+            }
+            else
+            {
+                return FAIL;
+            }
+        }
+    }
+
+    async command error_t I2CPacket.read(i2c_flags_t flags,
+            uint16_t addr,
+            uint8_t len,
+            uint8_t* data)
+    {
+        int i;
+        atomic
+        {
+            if (state == I2C_IDLE)
+            {
+                state = I2C_BUSY;
+            }
+            else if (state == I2C_OFF)
+            {
+
+                return EOFF;
+            }
+            else
+            {
+
+                return EBUSY;
+            }
+        }
+        atomic
+        {
+            if (len < 1) // A 0-length packet with no start and no stop....
+            {
+                state = I2C_IDLE;
+                return FAIL;
+            }
+
+            if (flags & I2C_START)
+            {
+                call I2C.start();
+                call I2C.writeByte(addr+1); 
+            }
+
+            // Read the information.
+            for (i = 0; i < len-1; ++i)
+            {
+                data[i] = call I2C.readByte(true);
+            }
+            data[len-1] = call I2C.readByte(I2C_ACK_END);
+            if (flags & I2C_STOP)
+            {
+                call I2C.stop();
+            }
+
+            _error = SUCCESS;
+            _addr = addr;
+            _len = len;
+            _data = data;
+        }
+        post readDoneTask();
+
+        return SUCCESS;
+    }
+
+    async command error_t I2CPacket.write(i2c_flags_t flags,
+            uint16_t addr,
+            uint8_t len,
+            uint8_t* data)
+    {
+        int i;
+
+        atomic
+        {
+            if (state == I2C_IDLE)
+            {
+                state = I2C_BUSY;
+            }
+            else if (state == I2C_OFF)
+            {
+                return EOFF;
+            }
+            else
+            {
+
+                return EBUSY;
+            }
+        }
+        atomic
+        {
+            if (len < 1) // A 0-length packet with no start and no stop....
+            {
+                state = I2C_IDLE;
+                return FAIL;
+            }
+            if (flags & I2C_START)
+            {
+                call I2C.start();
+                call I2C.writeByte(addr);
+            }
+
+            // Send information.
+            for (i = 0; i < len; ++i)
+            {
+                call I2C.writeByte(data[i]);
+            }
+
+            if (flags & I2C_STOP)
+            {
+                call I2C.stop();
+            }
+
+            _data = data;
+            _addr = addr;
+            _len = len;
+            _error = SUCCESS;
+        }
+        post writeDoneTask();
+        return SUCCESS;
+    }
+
+
+
+}
diff --git a/tos/platforms/mulle/softwarespi/SoftSpiBus.nc b/tos/platforms/mulle/softwarespi/SoftSpiBus.nc
new file mode 100755 (executable)
index 0000000..78ffde7
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Interface for a software Spi bus.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+interface SoftSpiBus
+{
+  /**
+   * Initializes bus default state.
+   */
+  async command void init();
+  
+  /**
+   * Turn the bus off.
+   */
+  async command void off();
+
+  /**
+   * Reads a byte from the Spi bus.
+   *
+   * @return A byte from the bus.
+   */
+  async command uint8_t readByte();
+
+  /**
+   * Writes a byte on th Spi bus.
+   *
+   * @param byte the byte to write.
+   */
+  async command void writeByte(uint8_t byte);
+  
+  /**
+   * Read and write a byte to the bus at the same time.
+   *
+   * @param byte The byte to write.
+   * @return Byte read from the bus.
+   */
+  async command uint8_t write(uint8_t byte);
+}
diff --git a/tos/platforms/mulle/softwarespi/SoftSpiBusP.nc b/tos/platforms/mulle/softwarespi/SoftSpiBusP.nc
new file mode 100755 (executable)
index 0000000..016fb97
--- /dev/null
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Mulle specific implementation of a software Spi bus.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+generic module SoftSpiBusP()
+{
+    provides interface SoftSpiBus as Spi;
+
+    uses interface GeneralIO as SCLK;
+    uses interface GeneralIO as MISO;
+    uses interface GeneralIO as MOSI;
+}
+implementation
+{
+    async command void Spi.init()
+    {
+        call SCLK.makeOutput();
+        call MOSI.makeOutput();
+        call MISO.makeInput();
+        call SCLK.clr();
+    }
+
+    async command void Spi.off()
+    {
+        call SCLK.makeOutput();
+        call MISO.makeOutput();
+        call MOSI.makeOutput();
+        call SCLK.clr();
+        call MISO.clr();
+        call MOSI.clr();
+    }
+
+    async command uint8_t Spi.readByte()
+    {
+        uint8_t i;
+        uint8_t data = 0xde;
+
+        atomic
+        {
+            for(i=0 ; i < 8; ++i)
+            {
+                call SCLK.clr();
+                data = (data << 1) | (uint8_t) call MISO.get();
+                call SCLK.set();
+            }
+        }
+        return data;
+    }
+
+    async command void Spi.writeByte(uint8_t byte)
+    {
+        uint8_t  i = 8;
+        atomic
+        {
+            for (i = 0; i < 8 ; ++i)
+            {
+                if (byte & 0x80)
+                {
+                    call MOSI.set();
+                }
+                else
+                {
+                    call MOSI.clr();
+                }
+                call SCLK.clr();
+                call SCLK.set();
+                byte <<= 1;
+            }
+        }
+    }
+
+    async command uint8_t Spi.write(uint8_t byte)
+    {
+        uint8_t data = 0;
+        uint8_t mask = 0x80;
+
+        atomic do
+        {
+            if( (byte & mask) != 0 )
+                call MOSI.set();
+            else
+                call MOSI.clr();
+
+            call SCLK.clr();
+            if( call MISO.get() )
+                data |= mask;
+            call SCLK.set();
+        } while( (mask >>= 1) != 0 );
+
+        return data;
+    }
+}
diff --git a/tos/platforms/mulle/softwarespi/SoftSpiMasterImplP.nc b/tos/platforms/mulle/softwarespi/SoftSpiMasterImplP.nc
new file mode 100755 (executable)
index 0000000..116e02d
--- /dev/null
@@ -0,0 +1,170 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2006 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Philip Levis
+ */
+
+/**
+ * The configuration that takes an underlying software SPI on Mulle 
+ * and turns it into a shared abstraction.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic module SoftSpiMasterImplP()
+{
+  provides interface Resource[uint8_t client];
+  provides interface SpiPacket[uint8_t client];
+  provides interface SpiByte[uint8_t client];
+  uses interface Resource as SubResource[uint8_t];
+  uses interface SpiPacket as SubPacket;
+  uses interface SpiByte as SubByte;
+}
+implementation
+{
+
+  enum
+  {
+    NO_CLIENT = 0xff
+  };
+  
+  uint8_t currentClient = NO_CLIENT;
+
+  async command error_t Resource.request[uint8_t id]()
+  {
+    return call SubResource.request[id]();
+  }
+
+  async command error_t Resource.immediateRequest[uint8_t id]()
+  {
+    error_t rval = call SubResource.immediateRequest[id]();
+    if (rval == SUCCESS)
+    {
+      atomic currentClient = id;
+    }
+    return rval;
+  }
+
+  event void SubResource.granted[uint8_t id]()
+  {
+    atomic currentClient = id;
+    signal Resource.granted[id]();
+  }
+
+  async command error_t Resource.release[uint8_t id]()
+  {
+    return call SubResource.release[id]();
+  }
+
+  async command bool Resource.isOwner[uint8_t id]()
+  {
+    return call SubResource.isOwner[id]();
+  }
+  
+  async command uint8_t SpiByte.write[uint8_t id](uint8_t tx)
+  {
+    atomic
+    {
+      if (currentClient != id)
+      {
+       return FAIL;
+      }
+    }
+    return call SubByte.write(tx);
+  }
+
+  async command error_t SpiPacket.send[uint8_t id](uint8_t* txBuf,
+                                                   uint8_t* rxBuf,
+                                                   uint16_t len )
+  {
+    atomic
+    {
+      if (currentClient != id)
+      {
+       return FAIL;
+      }
+    }
+    return call SubPacket.send(txBuf, rxBuf, len);
+  }
+
+  async event void SubPacket.sendDone(uint8_t* txBuf,
+                                     uint8_t* rxBuf,
+                                     uint16_t len,
+                                     error_t error )
+  {
+    signal SpiPacket.sendDone[currentClient](txBuf, rxBuf, len, error);
+  }
+
+  default async event void SpiPacket.sendDone[uint8_t id](uint8_t* txBuf,
+                                           uint8_t* rxBuf,
+                                           uint16_t len,
+                                           error_t error) {}
+
+  default event void Resource.granted[uint8_t id]() {}
+
+
+}
+
diff --git a/tos/platforms/mulle/softwarespi/SoftSpiMasterP.nc b/tos/platforms/mulle/softwarespi/SoftSpiMasterP.nc
new file mode 100755 (executable)
index 0000000..e8803cc
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2006 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Philip Levis
+ */
+
+/**
+ * The configuration that takes a underlying software Spi driver 
+ * on Mulle and turns it into a shared abstraction.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic configuration SoftSpiMasterP(char resourceName[])
+{
+  provides interface Resource[uint8_t client];
+  provides interface SpiPacket[uint8_t client];
+  provides interface SpiByte[uint8_t client];
+  uses interface SoftSpiBus;
+}
+implementation
+{
+  components new FcfsArbiterC(resourceName) as Arbiter;
+  components new AsyncPowerManagerP() as Power;
+  components new SoftSpiMasterImplP() as Spi;
+  components new SoftSpiMasterPacketP() as Master;
+    
+  Resource  = Spi;
+  SpiPacket = Spi.SpiPacket;
+  SpiByte = Spi.SpiByte;
+  
+  Spi.SubResource -> Arbiter;
+  Spi.SubPacket   -> Master.SpiPacket;
+  Spi.SubByte     -> Master.SpiByte;
+  
+  Power.AsyncStdControl -> Master;
+  Power.ResourceDefaultOwner -> Arbiter;
+
+  Master.Spi = SoftSpiBus;
+}
+
diff --git a/tos/platforms/mulle/softwarespi/SoftSpiMasterPacketP.nc b/tos/platforms/mulle/softwarespi/SoftSpiMasterPacketP.nc
new file mode 100755 (executable)
index 0000000..87cbab8
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2006 Stanford University.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Stanford University nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Philip Levis
+ */
+
+/**
+ * This driver implements an software Spi Master controller.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+generic module SoftSpiMasterPacketP()
+{
+  provides interface AsyncStdControl;
+  provides interface SpiByte;
+  provides interface SpiPacket;
+  
+  uses interface SoftSpiBus as Spi;
+}
+implementation
+{
+  enum
+  {
+    SPI_OFF          = 0,
+    SPI_IDLE         = 1,
+    SPI_BUSY         = 2,      
+  } soft_spi_state_t;
+
+  uint8_t state = SPI_OFF;
+
+  async command error_t AsyncStdControl.start()
+  {
+    atomic
+    {
+      if (state == SPI_OFF)
+      {
+           call Spi.init();
+           state = SPI_IDLE;
+           return SUCCESS;
+      }
+      else
+      {
+           return FAIL;
+      }
+    }
+  }
+
+  async command error_t AsyncStdControl.stop()
+  {
+    atomic
+    {
+      if (state == SPI_IDLE)
+      {
+           call Spi.off();
+           state = SPI_OFF;
+           return SUCCESS;
+      }
+      else
+      {
+           return FAIL;
+      }
+    }
+  }
+
+  async command uint8_t SpiByte.write( uint8_t tx )
+  {
+    uint8_t rx;
+    atomic
+    {
+      if (state == SPI_IDLE)
+      {
+           state = SPI_BUSY;
+      }
+      else if (state == SPI_OFF)
+      {
+           return EOFF;
+      }
+      else
+      {
+           return EBUSY;
+      }
+    }
+    atomic
+    {
+      rx = call Spi.write(tx);
+      state = SPI_IDLE;
+    }
+    return rx;
+  }
+  
+  async command error_t SpiPacket.send( uint8_t* txBuf, uint8_t* rxBuf, uint16_t len )
+  {
+    uint8_t i;
+    atomic
+    {
+      if (state == SPI_IDLE)
+      {
+           state = SPI_BUSY;
+      }
+      else if (state == SPI_OFF)
+      {
+           return EOFF;
+      }
+      else
+      {
+           return EBUSY;
+      }
+    }
+    atomic
+    {
+      for(i = 0; i < len; ++i)
+      {
+        rxBuf[i] = call Spi.write(txBuf[i]);
+      }
+      state = SPI_IDLE;
+    }
+    signal SpiPacket.sendDone(txBuf, rxBuf, len, SUCCESS);
+    return SUCCESS;
+  }
+
+  default async event void SpiPacket.sendDone( uint8_t* txBuf,
+                                               uint8_t* rxBuf,
+                                               uint16_t len,
+                                               error_t error ) {}
+}
diff --git a/tos/platforms/mulle/system/LedsP.nc b/tos/platforms/mulle/system/LedsP.nc
new file mode 100755 (executable)
index 0000000..7a9679a
--- /dev/null
@@ -0,0 +1,152 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * The implementation of the standard 3 LED mote abstraction.
+ *
+ * @author Joe Polastre
+ * @author Philip Levis
+ *
+ * @date   March 21, 2005
+ */
+
+/**
+ * Mulle needs a slightly different LedsP.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+module LedsP @safe() {
+  provides {
+    interface Init;
+    interface Leds;
+  }
+  uses {
+    interface GeneralIO as Led0;
+    interface GeneralIO as Led1;
+    interface GeneralIO as Led2;
+  }
+}
+implementation {
+  command error_t Init.init() {
+    atomic {
+      dbg("Init", "LEDS: initialized.\n");
+      call Led0.makeOutput();
+      call Led1.makeOutput();
+      call Led2.makeOutput();
+      call Led0.clr();
+      call Led1.clr();
+      call Led2.clr();
+    }
+    return SUCCESS;
+  }
+
+  /* Note: the call is inside the dbg, as it's typically a read of a volatile
+     location, so can't be deadcode eliminated */
+#define DBGLED(n) \
+  dbg("LedsC", "LEDS: Led" #n " %s.\n", call Led ## n .get() ? "off" : "on");
+
+  async command void Leds.led0On() {
+    call Led0.set();
+    DBGLED(0);
+  }
+
+  async command void Leds.led0Off() {
+    call Led0.clr();
+    DBGLED(0);
+  }
+
+  async command void Leds.led0Toggle() {
+    call Led0.toggle();
+    DBGLED(0);
+  }
+
+  async command void Leds.led1On() {
+    call Led1.set();
+    DBGLED(1);
+  }
+
+  async command void Leds.led1Off() {
+    call Led1.clr();
+    DBGLED(1);
+  }
+
+  async command void Leds.led1Toggle() {
+    call Led1.toggle();
+    DBGLED(1);
+  }
+
+  async command void Leds.led2On() {
+    call Led2.set();
+    DBGLED(2);
+  }
+
+  async command void Leds.led2Off() {
+    call Led2.clr();
+    DBGLED(2);
+  }
+
+  async command void Leds.led2Toggle() {
+    call Led2.toggle();
+    DBGLED(2);
+  }
+
+  async command uint8_t Leds.get() {
+    uint8_t rval;
+    atomic {
+      rval = 0;
+      if (call Led0.get()) {
+       rval |= LEDS_LED0;
+      }
+      if (call Led1.get()) {
+       rval |= LEDS_LED1;
+      }
+      if (call Led2.get()) {
+       rval |= LEDS_LED2;
+      }
+    }
+    return rval;
+  }
+
+  async command void Leds.set(uint8_t val) {
+    atomic {
+      if (val & LEDS_LED0) {
+       call Leds.led0On();
+      }
+      else {
+       call Leds.led0Off();
+      }
+      if (val & LEDS_LED1) {
+       call Leds.led1On();
+      }
+      else {
+       call Leds.led1Off();
+      }
+      if (val & LEDS_LED2) {
+       call Leds.led2On();
+      }
+      else {
+       call Leds.led2Off();
+      }
+    }
+  }
+}
diff --git a/tos/platforms/mulle/timers/AlarmMicro16C.nc b/tos/platforms/mulle/timers/AlarmMicro16C.nc
new file mode 100755 (executable)
index 0000000..bf62fad
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * AlarmMicro16C provides a 16-bit TMicro alarm.
+ * It uses 1 hw timer that is used as a alarm.
+ * 
+ * NOTE: It uses the same source clock as the CounterMicro16C.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "TimerConfig.h"
+
+configuration AlarmMicro16C
+{
+  provides interface Alarm<TMicro,uint16_t>;
+}
+implementation
+{
+  components new M16c62pAlarm16C(TMicro) as AlarmFrom;
+  components new M16c62pTimerAInitC(TMR_COUNTER_MODE, M16C_TMRA_TES_TA_PREV, 0, false, false, false) as AlarmInit;
+
+  components HplM16c62pTimerC as Timers,
+      CounterMicro16C,
+      RealMainP;
+
+  AlarmFrom -> Timers.ALARM_MICRO16;
+  AlarmFrom.Counter -> CounterMicro16C;
+
+  AlarmInit -> Timers.ALARM_MICRO16;
+  AlarmInit -> Timers.ALARM_MICRO16_CTRL;
+  RealMainP.PlatformInit -> AlarmInit.Init;
+  Alarm = AlarmFrom;
+}
+  
+
diff --git a/tos/platforms/mulle/timers/AlarmMicro32C.nc b/tos/platforms/mulle/timers/AlarmMicro32C.nc
new file mode 100755 (executable)
index 0000000..c5c1e30
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * 32-bit microsecond Alarm component as per TEP102 HAL guidelines.
+ *
+ * @author Fan Zhang <fanzha@ltu.se>
+ */
+
+generic configuration AlarmMicro32C()
+{
+  provides interface Alarm<TMicro, uint32_t>;
+}
+implementation
+{
+  components AlarmMicro16C as Alarm16, CounterMicro32C as Counter32;
+  components new TransformAlarmC(TMicro, uint32_t, TMicro, uint16_t, 0) as Transform32;
+
+  Alarm = Transform32;
+  Transform32.AlarmFrom -> Alarm16;
+  Transform32.Counter -> Counter32;
+}
diff --git a/tos/platforms/mulle/timers/BusyWaitMicroC.nc b/tos/platforms/mulle/timers/BusyWaitMicroC.nc
new file mode 100755 (executable)
index 0000000..fc24efb
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Implementation of the HIL required micro busy wait.
+ * For more information see TEP 102.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+module BusyWaitMicroC
+{
+  provides interface BusyWait<TMicro, uint16_t>;
+}
+implementation
+{
+  // TODO(henrik) This will now only work on 10Mhz speed, easy to
+  //              add a signal from the control module of the mcu
+  //              to signal the change of speed and the wait function
+  //              can adjust to it.
+  // The wait function can not be inlined because then the code alignment may
+  // go lost thus making the busy wait around 30% slower.
+  async command void BusyWait.wait(uint16_t dt ) __attribute__((noinline)) {
+    atomic {
+      asm("nop"); // Nop needed to align function
+      asm volatile (
+          "sub.w #1,%[t]\n\t"
+          "jeq 2f\n\t"
+          "sub.w #1,%[t]\n\t"
+          "jeq 2f\n\t"
+          "1:\n\t"
+          "nop\n\t"
+          "add.w #1,%[t]\n\t"
+          "sub.w #1,%[t]\n\t"
+          "sub.w #1,%[t]\n\t"
+          "jgtu 1b\n\t"
+          "2:"
+          :   
+          : [t] "r" (dt)
+          );  
+    } 
+  } 
+}
diff --git a/tos/platforms/mulle/timers/CounterMicro16C.nc b/tos/platforms/mulle/timers/CounterMicro16C.nc
new file mode 100755 (executable)
index 0000000..2a691a4
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * CounterMicro16C provides a 16-bit TMicro counter.
+ * It uses 2 hw timers, one generates a micro tick and the other
+ * counts the micro ticks.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @see  Please refer to TEP 102 for more information about this component.
+ */
+
+#include "TimerConfig.h"
+
+configuration CounterMicro16C
+{
+  provides interface Counter<TMicro,uint16_t>;
+}
+implementation
+{
+  // Counter
+  components new M16c62pCounter16C(TMicro) as CounterFrom;
+  components new M16c62pTimerAInitC(TMR_COUNTER_MODE, M16C_TMRA_TES_TA_NEXT, 0xFFFF, true, true, true) as CounterInit;
+  
+  // Source
+  components new M16c62pTimerAInitC(TMR_TIMER_MODE, M16C_TMR_CS_F1_2, (MAIN_CRYSTAL_SPEED - 1), false, true, true) as TimerSourceInit;
+  
+  components HplM16c62pTimerC as Timers,
+      RealMainP, McuSleepC;
+
+  // Counter
+  CounterFrom.Timer -> Timers.COUNTER_MICRO16;
+  CounterInit -> Timers.COUNTER_MICRO16;
+  CounterInit -> Timers.COUNTER_MICRO16_CTRL;
+  RealMainP.PlatformInit -> CounterInit;
+  Counter = CounterFrom;
+
+  // Timer source
+  TimerSourceInit -> Timers.MICRO16_SOURCE;
+  TimerSourceInit -> Timers.MICRO16_SOURCE_CTRL;
+  RealMainP.PlatformInit -> TimerSourceInit;
+  
+}
diff --git a/tos/platforms/mulle/timers/CounterMicro32C.nc b/tos/platforms/mulle/timers/CounterMicro32C.nc
new file mode 100755 (executable)
index 0000000..3cd55fa
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ * 32-bit microsecond Counter component as per TEP102 HAL guidelines.
+ *
+ * @author Fan Zhang <fanzha@ltu.se>
+ */
+
+
+configuration CounterMicro32C
+{
+  provides interface Counter<TMicro, uint32_t>;
+}
+implementation
+{
+  components CounterMicro16C as Counter16, 
+    new TransformCounterC(TMicro, uint32_t, TMicro, uint16_t,
+                         0, uint16_t) as Transform32;
+
+  Counter = Transform32;
+  Transform32.CounterFrom -> Counter16;
+}
diff --git a/tos/platforms/mulle/timers/HilTimerMilliC.nc b/tos/platforms/mulle/timers/HilTimerMilliC.nc
new file mode 100755 (executable)
index 0000000..01af75f
--- /dev/null
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* "Copyright (c) 2000-2003 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * @author Cory Sharp <cssharp@eecs.berkeley.edu>
+ */
+
+/**
+ * HilTimerMilliC provides a parameterized interface to a virtualized
+ * millisecond timer and local time in milli precision.  TimerMilliC in
+ * tos/system/ uses this component to allocate new timers.
+ * See TEP 102 for more information.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "TimerConfig.h"
+configuration HilTimerMilliC
+{
+  provides interface Init;
+
+  provides interface Timer<TMilli> as TimerMilli[ uint8_t num ];
+  provides interface LocalTime<TMilli>;
+}
+implementation
+{
+  components new AlarmToTimerC(TMilli);
+  components new VirtualizeTimerC(TMilli,uniqueCount(UQ_TIMER_MILLI));
+  components new CounterToLocalTimeC(TMilli);
+  components HIL_TIMERS as AlarmCounterMilli32C;
+
+  TimerMilli = VirtualizeTimerC;
+  LocalTime = CounterToLocalTimeC;
+
+  VirtualizeTimerC.TimerFrom -> AlarmToTimerC;
+  AlarmToTimerC.Alarm -> AlarmCounterMilli32C.Alarm;
+  CounterToLocalTimeC.Counter -> AlarmCounterMilli32C.Counter;
+  Init = AlarmCounterMilli32C;
+}
diff --git a/tos/platforms/mulle/timers/LocalTimeMicroC.nc b/tos/platforms/mulle/timers/LocalTimeMicroC.nc
new file mode 100755 (executable)
index 0000000..b61be3b
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2008, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Miklos Maroti
+ */
+
+/**
+ * This configuration provides a local time represented in Micro seconds.
+ * 
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "Timer.h"
+
+configuration LocalTimeMicroC
+{
+       provides interface LocalTime<TMicro>;
+}
+
+implementation
+{
+       components CounterMicro16C;
+       components new TransformCounterC(TMicro, uint32_t, TMicro, uint16_t, 0, uint32_t);
+       components new CounterToLocalTimeC(TMicro);
+
+       LocalTime = CounterToLocalTimeC;
+       CounterToLocalTimeC.Counter -> TransformCounterC;
+       TransformCounterC.CounterFrom -> CounterMicro16C;
+}
diff --git a/tos/platforms/mulle/timers/TimerConfig.h b/tos/platforms/mulle/timers/TimerConfig.h
new file mode 100755 (executable)
index 0000000..eded530
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * The M16c/62p hardware timer configuration used by Mulle.
+ * 
+ * STOP MODE ENABLED:
+ *   TB0 bridges its tics from the RV8564 to TB2 in TMilli speed.
+ *   TA0 and TA1 are used to create a 32 bit counter. TA0 counts
+ *   tics from TB2 and TA1 counts TA0 underflows.
+ *   TB0 and TB1 are used to create a 32 bit Alarm. TB0 counts
+ *   tics from TB2 and TB1 counts TB0 underflows.
+ *
+ * STOP MODE DISABLED:
+ *   TA0 generates TMilli tics.
+ *   TB0 generates TMilli tics.
+ *   TA1 is a 16 bit counter that counts tics from TA0.
+ *   TB1 is a 16 bit alarm that counts tics from TB0.
+ *
+ * ALWAYS USED:
+ *  NOTE: Counter timers are turned off when the mcu goes into stop mode.
+ *   TA3 generates TMicro tics.
+ *   TA2 is a 16 bit TMicro counter that counts tics from TA3.
+ *   TA4 is a 16 bit TMicro alarm that counts tics from TA3.
+ *      TB3 is a 16 bit Radio counter.
+ *   TB4 is a 16 bit Radio alarm.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#ifndef __TIMERCONFIG_H__
+#define __TIMERCONFIG_H__
+
+#ifdef ENABLE_STOP_MODE
+  #define HIL_TIMERS RV8564AlarmCounterMilli32C
+#else
+  #define HIL_TIMERS AlarmCounterMilli32C
+#endif
+
+// Use hw timers alone.
+#define COUNTER_MILLI32_SOURCE TimerB0
+#define COUNTER_MILLI32_SOURCE_CTRL TimerB0Ctrl
+#define COUNTER_MILLI32 TimerB1
+#define COUNTER_MILLI32_CTRL TimerB1Ctrl
+
+#define ALARM_MILLI32_SOURCE TimerA0
+#define ALARM_MILLI32_SOURCE_CTRL TimerA0Ctrl
+#define ALARM_MILLI32 TimerA1
+#define ALARM_MILLI32_CTRL TimerA1Ctrl
+// End
+
+// Use the RV8564 chip to generate tics (stop mode enabled).
+#define MILLI32_SOURCE_RV8564 TimerB2
+#define MILLI32_SOURCE_RV8564_CTRL TimerB2Ctrl
+
+#define COUNTER_MILLI32_LOW TimerA0
+#define COUNTER_MILLI32_LOW_CTRL TimerA0Ctrl
+#define COUNTER_MILLI32_HIGH TimerA1
+#define COUNTER_MILLI32_HIGH_CTRL TimerA1Ctrl
+
+#define ALARM_MILLI32_LOW TimerB0
+#define ALARM_MILLI32_LOW_CTRL TimerB0Ctrl
+#define ALARM_MILLI32_HIGH TimerB1
+#define ALARM_MILLI32_HIGH_CTRL TimerB1Ctrl
+// end
+
+// Common settings.
+#define COUNTER_MICRO16 TimerA2
+#define COUNTER_MICRO16_CTRL TimerA2Ctrl
+#define MICRO16_SOURCE TimerA3
+#define MICRO16_SOURCE_CTRL TimerA3Ctrl
+#define ALARM_MICRO16 TimerA4
+#define ALARM_MICRO16_CTRL TimerA4Ctrl
+
+#define COUNTER_RF23016 TimerB3
+#define COUNTER_RF23016_CTRL TimerB3Ctrl
+#define ALARM_RF23016 TimerB4
+#define ALARM_RF23016_CTRL TimerB4Ctrl
+// end.
+
+#endif  // __TIMERCONFIG_H__
diff --git a/tos/platforms/mulle/timers/rf230/AlarmRF23016C.nc b/tos/platforms/mulle/timers/rf230/AlarmRF23016C.nc
new file mode 100644 (file)
index 0000000..aa5d13e
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * AlarmRF23016C provides a 16-bit TRF230 alarm.
+ * It uses 1 hw timer that is used as a alarm and runs with
+ * speed PLL_CLOCK_SPEED / 8.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "TimerConfig.h"
+#include <RadioConfig.h>
+
+configuration AlarmRF23016C
+{
+  provides interface Alarm<TRadio,uint16_t>;
+}
+implementation
+{
+  components new M16c62pAlarm16C(TRadio) as AlarmFrom;
+  components new M16c62pTimerBInitC(TMR_TIMER_MODE, M16C_TMR_CS_F8, 0, false, false, false) as AlarmInit;
+
+  components HplM16c62pTimerC as Timers,
+      CounterRF23016C,
+      RealMainP;
+
+  AlarmFrom -> Timers.ALARM_RF23016;
+  AlarmFrom.Counter -> CounterRF23016C;
+
+  AlarmInit -> Timers.ALARM_RF23016;
+  AlarmInit -> Timers.ALARM_RF23016_CTRL;
+  RealMainP.PlatformInit -> AlarmInit;
+  Alarm = AlarmFrom;
+}
+  
+
diff --git a/tos/platforms/mulle/timers/rf230/CounterRF23016C.nc b/tos/platforms/mulle/timers/rf230/CounterRF23016C.nc
new file mode 100644 (file)
index 0000000..fe34c84
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * CounterRF23016C provides a 16-bit TRF230 counter.
+ * It uses 1 hw timer that counts in PLL_CLOCK_SPEED / 8.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+
+#include "TimerConfig.h"
+#include <RadioConfig.h>
+
+configuration CounterRF23016C
+{
+  provides interface Counter<TRadio,uint16_t>;
+}
+implementation
+{
+  components new M16c62pCounter16C(TRadio) as CounterFrom;
+  components new M16c62pTimerBInitC(TMR_TIMER_MODE, M16C_TMR_CS_F8, 0xFFFF, false, true, true) as CounterInit;
+
+  components HplM16c62pTimerC as Timers,
+      RealMainP;
+  
+  CounterFrom.Timer -> Timers.COUNTER_RF23016;
+  CounterInit -> Timers.COUNTER_RF23016;
+  CounterInit -> Timers.COUNTER_RF23016_CTRL;
+  RealMainP.PlatformInit -> CounterInit;
+  Counter = CounterFrom;
+}
diff --git a/tos/platforms/mulle/timers/stop/RV8564AlarmCounterMilli32C.nc b/tos/platforms/mulle/timers/stop/RV8564AlarmCounterMilli32C.nc
new file mode 100755 (executable)
index 0000000..7d30e5c
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * RV8564AlarmCounterMilli32C provides a 32-bit TMilli alarm and counter.
+ * The counter and alarm is driven by the RV8564 chip on Mulle. This
+ * allows the M16c/62p mcu to be put into stop mode even when the timers
+ * are running.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @see  Please refer to TEP 102 for more information about this component.
+ */
+
+#include "TimerConfig.h"
+
+configuration RV8564AlarmCounterMilli32C
+{
+  provides interface Counter<TMilli,uint32_t>;
+  provides interface Alarm<TMilli,uint32_t>;
+  provides interface Init;
+}
+implementation
+{
+  components new M16c62pCounter32C(TMilli) as CounterFrom;
+  components new M16c62pTimerAInitC(TMR_COUNTER_MODE, M16C_TMRA_TES_TB2, 0xFFFF, false, true, true) as CounterInit1;
+  components new M16c62pTimerAInitC(TMR_COUNTER_MODE, M16C_TMRA_TES_TA_PREV, 0xFFFF, true, true, true) as CounterInit2;
+  
+  components new M16c62pAlarm32C(TMilli) as AlarmFrom;
+  components new M16c62pTimerBInitC(TMR_COUNTER_MODE, M16C_TMRB_CTR_ES_TBj, 0, false, false, true) as AlarmInit1;
+  components new M16c62pTimerBInitC(TMR_COUNTER_MODE, M16C_TMRB_CTR_ES_TBj, 0, false, false, true) as AlarmInit2;
+  
+  components new M16c62pTimerBInitC(TMR_COUNTER_MODE, M16C_TMRB_CTR_ES_TBiIN, 0, false, true, true) as TimerSourceInit;
+
+  components HplM16c62pTimerC as Timers,
+      RV8564AlarmCounterMilli32P,
+      HplM16c62pInterruptC as Irqs,
+      HplM16c62pGeneralIOC as IOs;
+
+  // Setup the IO pin that RV8564 generates the clock to.
+  RV8564AlarmCounterMilli32P -> IOs.PortP92;
+  Init = RV8564AlarmCounterMilli32P;
+  
+  // Counter
+  CounterFrom.TimerLow -> Timers.COUNTER_MILLI32_LOW;
+  CounterFrom.TimerHigh -> Timers.COUNTER_MILLI32_HIGH;
+  CounterInit1 -> Timers.COUNTER_MILLI32_LOW;
+  CounterInit1 -> Timers.COUNTER_MILLI32_LOW_CTRL;
+  CounterInit2 -> Timers.COUNTER_MILLI32_HIGH;
+  CounterInit2 -> Timers.COUNTER_MILLI32_HIGH_CTRL;
+  Init = CounterInit1;
+  Init = CounterInit2;
+  Counter = CounterFrom;
+
+  // Alarm
+  AlarmFrom.ATimerLow -> Timers.ALARM_MILLI32_LOW;
+  AlarmFrom.ATimerHigh -> Timers.ALARM_MILLI32_HIGH;
+  AlarmFrom.Counter -> CounterFrom;
+  AlarmInit1 -> Timers.ALARM_MILLI32_LOW;
+  AlarmInit1 -> Timers.ALARM_MILLI32_LOW_CTRL;
+  AlarmInit2 -> Timers.ALARM_MILLI32_HIGH;
+  AlarmInit2 -> Timers.ALARM_MILLI32_HIGH_CTRL;
+  Init = AlarmInit1;
+  Init = AlarmInit2;
+  Alarm = AlarmFrom;
+
+  // Timer source
+  TimerSourceInit -> Timers.MILLI32_SOURCE_RV8564;
+  TimerSourceInit -> Timers.MILLI32_SOURCE_RV8564_CTRL;
+  Init = TimerSourceInit;
+}
+
diff --git a/tos/platforms/mulle/timers/stop/RV8564AlarmCounterMilli32P.nc b/tos/platforms/mulle/timers/stop/RV8564AlarmCounterMilli32P.nc
new file mode 100755 (executable)
index 0000000..0dae1c3
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Init the port that the RV8564 chip is generating its tics to (TB0 in).
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ */
+module RV8564AlarmCounterMilli32P
+{
+  provides interface Init;
+  uses interface GeneralIO as IO;
+}
+implementation
+{
+  command error_t Init.init()
+  {
+    call IO.makeInput();
+    call IO.clr();
+    return SUCCESS;
+  }
+}
diff --git a/tos/platforms/mulle/timers/wait/AlarmCounterMilli32C.nc b/tos/platforms/mulle/timers/wait/AlarmCounterMilli32C.nc
new file mode 100755 (executable)
index 0000000..f48d7d4
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2009 Communication Group and Eislab at
+ * Lulea University of Technology
+ *
+ * Contact: Laurynas Riliskis, LTU
+ * Mail: laurynas.riliskis@ltu.se
+ * All rights reserved.
+ *
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of Communication Group at Lulea University of Technology
+ *   nor the names of its contributors may be used to endorse or promote
+ *    products derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL STANFORD
+ * UNIVERSITY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * AlarmCounterMilli32C provides a 32-bit TMilli alarm and counter.
+ *
+ * @author Henrik Makitaavola <henrik.makitaavola@gmail.com>
+ * @see  Please refer to TEP 102 for more information about this component.
+ */
+
+#include "TimerConfig.h"
+
+configuration AlarmCounterMilli32C
+{
+  provides interface Counter<TMilli,uint32_t>;
+  provides interface Alarm<TMilli,uint32_t>;
+  provides interface Init;
+}
+implementation
+{
+  components new M16c62pCounter16C(TMilli) as CounterFrom;
+  components new M16c62pTimerBInitC(TMR_COUNTER_MODE, M16C_TMRB_CTR_ES_TBj, 0xFFFF, true, true, false) as CounterInit;
+  components new M16c62pTimerBInitC(TMR_TIMER_MODE, M16C_TMR_CS_F1_2, (1000 * MAIN_CRYSTAL_SPEED) - 1, false, true, true) as CounterSourceInit;
+  components new TransformCounterC(TMilli,uint32_t, TMilli,uint16_t, 0,uint16_t) as TCounter;
+  
+  components new M16c62pAlarm16C(TMilli) as AlarmFrom;
+  components new M16c62pTimerAInitC(TMR_COUNTER_MODE, M16C_TMRA_TES_TA_PREV, 0, false, false, false) as AlarmInit;
+  components new M16c62pTimerAInitC(TMR_TIMER_MODE, M16C_TMR_CS_F1_2, (1000 * MAIN_CRYSTAL_SPEED) - 1, false, true, true) as AlarmSourceInit;
+  components new TransformAlarmC(TMilli,uint32_t,TMilli,uint16_t,0) as TAlarm;
+  
+
+  components HplM16c62pTimerC as Timers;
+
+  // Counter
+  CounterFrom.Timer -> Timers.COUNTER_MILLI32;
+  CounterInit -> Timers.COUNTER_MILLI32;
+  CounterInit -> Timers.COUNTER_MILLI32_CTRL;
+  Init = CounterInit;
+  CounterSourceInit -> Timers.COUNTER_MILLI32_SOURCE;
+  CounterSourceInit -> Timers.COUNTER_MILLI32_SOURCE_CTRL;
+  Init = CounterSourceInit;
+
+  // Alarm
+  AlarmFrom -> Timers.ALARM_MILLI32;
+  AlarmFrom.Counter -> CounterFrom;
+  AlarmInit -> Timers.ALARM_MILLI32;
+  AlarmInit -> Timers.ALARM_MILLI32_CTRL;
+  Init = AlarmInit.Init;
+  AlarmSourceInit -> Timers.ALARM_MILLI32_SOURCE;
+  AlarmSourceInit -> Timers.ALARM_MILLI32_SOURCE_CTRL;
+  Init = AlarmSourceInit;
+
+  // Transformations
+  TCounter.CounterFrom -> CounterFrom;
+  Counter = TCounter;
+  TAlarm.AlarmFrom -> AlarmFrom;
+  TAlarm.Counter -> TCounter;
+  Alarm = TAlarm;
+}
+
index 9ae17389d97cfaeb8dc706ba8b3ab9e29d0b8418..c9e8dc3b77c06db380778c7b1aa062844b99e4e7 100644 (file)
@@ -14,10 +14,14 @@ push( @includes, qw(
 
 @opts = qw(
 
-  -gcc=gcc
   -fnesc-target=pc
   -fnesc-no-debug
 
 );
 
+if (defined($ENV{"GCC"})) {
+  push @opts, "-gcc=$ENV{'GCC'}";
+} else {
+  push @opts, "-gcc=gcc";
+}
 push @opts, "-fnesc-scheduler=TinySchedulerC,TinySchedulerC.TaskBasic,TaskBasic,TaskBasic,runTask,postTask" if !$with_scheduler_flag;
index 4e2f7984303223d4f508b52cc39d20d1388f9063..59da9bc7215e8808ad47d9958faf815e2f23b792 100644 (file)
@@ -14,4 +14,26 @@ inline __nesc_atomic_t __nesc_atomic_start(void) @spontaneous() {
 inline void __nesc_atomic_end(__nesc_atomic_t x) @spontaneous() { }
 inline void __nesc_atomic_sleep() { }
 
+/* Floating-point network-type support */
+typedef float nx_float __attribute__((nx_base_be(afloat)));
+
+inline float __nesc_ntoh_afloat(const void *COUNT(sizeof(float)) source) @safe() {
+  float f;
+  memcpy(&f, source, sizeof(float));
+  return f;
+}
+
+inline float __nesc_hton_afloat(void *COUNT(sizeof(float)) target, float value) @safe() {
+  memcpy(target, &value, sizeof(float));
+  return value;
+}
+
+// enum so components can override power saving,
+// as per TEP 112.
+// As this is not a real platform, just set it to 0.
+enum {
+  TOS_SLEEP_NONE = 0,
+};
+
+
 #endif
index 31e7cc29219ae5200139e6a08969d609b54ebd7b..47886257e506b164b654dbd711d299c0eea547e3 100644 (file)
  * OF THE POSSIBILITY OF SUCH DAMAGE
  */
 
-/** 
+/**
  * DemoSensorC is a generic sensor device that provides a 16-bit
  * value. The platform author chooses which sensor actually sits
  * behind DemoSensorC, and though it's probably Voltage, Light, or
  * Temperature, there are no guarantees.
  *
  * This particular DemoSensorC on the telosb platform provides a
- * voltage reading, using VoltageC. 
+ * voltage reading, using VoltageC.
  *
  * To convert from ADC counts to actual voltage, divide this reading
  * by 4096 and multiply by 3.
  *
  * @author Gilman Tolle <gtolle@archrock.com>
  * @version $Revision: 1.4 $ $Date: 2006/12/12 18:23:45 $
- * 
+ *
  */
 
 generic configuration DemoSensorC()
index 8060fa78a91dbca169156d97ef5dd38c95b48682..da4c4f4e013cef422d04d4a65764439e80423d14 100644 (file)
@@ -29,7 +29,7 @@
  * OF THE POSSIBILITY OF SUCH DAMAGE
  */
 
-/** 
+/**
  * DemoSensorNowC is a generic sensor device that provides a 16-bit
  * value that can be read from async context. The platform author
  * chooses which sensor actually sits behind DemoSensorNowC, and
@@ -44,7 +44,7 @@
  *
  * @author Gilman Tolle <gtolle@archrock.com>
  * @version $Revision: 1.4 $ $Date: 2006/12/12 18:23:45 $
- * 
+ *
  */
 
 generic configuration DemoSensorNowC()
index 5518a2dce4c32be5e3497aace688276b2386152b..08d40d5dafe895b8650da60f4b80e8da7db0983d 100644 (file)
  * OF THE POSSIBILITY OF SUCH DAMAGE
  */
 
-/** 
+/**
  * DemoSensorStreamC is a generic sensor device that provides a 16-bit
  * value. The platform author chooses which sensor actually sits
  * behind DemoSensorStreamC, and though it's probably Voltage, Light, or
  * Temperature, there are no guarantees.
  *
  * This particular DemoSensorStreamC on the telosb platform provides a
- * voltage reading, using VoltageStreamC. 
+ * voltage reading, using VoltageStreamC.
  *
  * To convert from ADC counts to actual voltage, divide this reading
  * by 4096 and multiply by 3.
  *
  * @author Gilman Tolle <gtolle@archrock.com>
  * @version $Revision: 1.4 $ $Date: 2006/12/12 18:23:45 $
- * 
+ *
  */
 
 generic configuration DemoSensorStreamC()
index 6bf34d6a1f860c688f3347911fd1aae662721280..56d6a7cec2295a0192d8e16786fd72aa8a7abb35 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration HplUserButtonC {
   provides interface GeneralIO;
   provides interface GpioInterrupt;
index d158470087904617cd0c06c913fed7744772e71b..816e544a7301c317312d2a28e3b51c402f696adf 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 module MotePlatformC @safe() {
   provides interface Init;
 }
@@ -48,7 +48,7 @@ implementation {
        P1SEL = 0;      /* 0 0 0 0 0 0 0 0 */
        P1OUT = 0;      /* 0 0 0 0 0 0 0 0 */
        P1DIR = 0;      /* 0 0 0 0 0 0 0 0 */
+
        /* Port 2: 7-0:- */
        P2SEL = 0;      /* 0 0 0 0 0 0 0 0 */
        P2OUT = 0;      /* 0 0 0 0 0 0 0 0 */
index e9954e04e000ca3ec362b9328d9322fb562288d7..9f1cad7f09680f9ad6c38b62b16baa78b15f1a2f 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "hardware.h"
 
 configuration PlatformLedsC {
index 947477acaf9839748a8d9347b8fb20cb8b8266bb..034547d19da9cbfc3e74f2c9d611ae87bdb2aee7 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 module PlatformSerialP {
   provides interface StdControl;
   uses interface Resource;
index 02762e64ca6f67cb9be4f5ecd144fea1e999e2d3..25ef1b9d3db0f9e6876ef395a1e2de8093976c7d 100644 (file)
@@ -79,9 +79,9 @@ implementation {
   task void sendEvent() {
     bool pinHigh;
     pinHigh = m_pinHigh;
-    
+
     signal Notify.notify( pinHigh );
-    
+
     if ( pinHigh ) {
       call GpioInterrupt.enableFallingEdge();
     } else {
index 0d74849a57c262384e8fef3bf2f290a21d8c59c1..97f124ed883cf2329be734133b1f6b1c8065ba9d 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #ifndef USERBUTTON_H
 #define USERBUTTON_H
 
index c496bd2bcc05dbd57ff26ca40984d41e8ccd7df3..ff374ceccd123ab9ac5879f6d4da781fa89695c2 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include <UserButton.h>
 
 configuration UserButtonC {
index 6b36d2db04c3195c2e60c987b20ccfdbb441b92f..eee88845681962def48a5a1dd2c6c08d9cc4e656 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include <UserButton.h>
 
 module UserButtonP {
@@ -41,8 +41,8 @@ module UserButtonP {
   uses interface Notify<bool> as NotifyLower;
 }
 implementation {
-  
-  command button_state_t Get.get() { 
+
+  command button_state_t Get.get() {
     /* Olimex P169 user button pin is high when released - active low */
     if ( call GetLower.get() ) {
       return BUTTON_RELEASED;
@@ -67,6 +67,6 @@ implementation {
       signal Notify.notify( BUTTON_PRESSED );
     }
   }
-  
+
   default event void Notify.notify( button_state_t val ) { }
 }
index ecaad4be61cbb7735887174ef64ba61936cf14f9..1a3a7e8db078ae31f566c41005353be606c87274 100644 (file)
@@ -8,10 +8,13 @@
 
 push( @includes, qw(
 
+      .
   %T/platforms/shimmer
   %T/platforms/shimmer/chips/cc2420
   %T/platforms/shimmer/chips/mma7260
   %T/platforms/shimmer/chips/sd
+  %T/platforms/shimmer/chips/bluetooth
+  %T/platforms/shimmer/chips/msp430
   %T/chips/cc2420
   %T/chips/cc2420/alarm
   %T/chips/cc2420/control
@@ -25,6 +28,7 @@ push( @includes, qw(
   %T/chips/cc2420/spi
   %T/chips/cc2420/transmit
   %T/chips/cc2420/unique
+  %T/chips/cc2420/security
   %T/chips/msp430
   %T/chips/msp430/adc12
   %T/chips/msp430/dma
index 8c3031dd6133d1464799f9d946fff200018a41dd..0d22877b7a32c7c0a1adc7ffa5d584a32ce80a0d 100644 (file)
@@ -35,7 +35,7 @@
  *
  */
 /**
- * The Active Message layer on the SHIMER platform. This is a naming wrapper
+ * The Active Message layer on the SHIMMER platform. This is a naming wrapper
  * around the CC2420 Active Message layer.
  *
  * @author Konrad Lorincz
@@ -55,6 +55,7 @@ configuration ActiveMessageC {
     interface PacketAcknowledgements;
     interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
     interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+    interface LowPowerListening;
   }
 }
 implementation {
@@ -68,6 +69,7 @@ implementation {
   Packet       = AM;
   AMPacket     = AM;
   PacketAcknowledgements = AM;
+  LowPowerListening = AM;
 
   components CC2420PacketC;
   PacketTimeStamp32khz = CC2420PacketC;
diff --git a/tos/platforms/shimmer/HplUserButtonC.nc b/tos/platforms/shimmer/HplUserButtonC.nc
new file mode 100644 (file)
index 0000000..5363a4b
--- /dev/null
@@ -0,0 +1,57 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telos platform
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ * (not much to) port to shimmer
+ * @author Steve Ayer
+ * @date February, 2010
+ */
+
+configuration HplUserButtonC {
+  provides interface GeneralIO;
+  provides interface GpioInterrupt;
+}
+implementation {
+  components HplMsp430GeneralIOC as GeneralIOC;
+  components HplMsp430InterruptC as InterruptC;
+
+  components new Msp430GpioC() as UserButtonC;
+  UserButtonC -> GeneralIOC.Port20;
+  GeneralIO = UserButtonC;
+
+  components new Msp430InterruptC() as InterruptUserButtonC;
+  InterruptUserButtonC.HplInterrupt -> InterruptC.Port20;
+  GpioInterrupt = InterruptUserButtonC.Interrupt;
+}
diff --git a/tos/platforms/shimmer/Ieee154MessageC.nc b/tos/platforms/shimmer/Ieee154MessageC.nc
new file mode 100644 (file)
index 0000000..2099d1b
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+
+/**
+ *
+ * @author Stephen Dawson-Haggerty
+ */
+configuration Ieee154MessageC  {
+  provides {
+    interface SplitControl;
+
+    interface Resource as SendResource[uint8_t clientId];
+    interface Ieee154Send;
+    interface Receive as Ieee154Receive;
+
+    interface Ieee154Packet;
+    interface Packet;
+
+    interface PacketAcknowledgements;
+    interface LinkPacketMetadata;
+    interface LowPowerListening;
+    interface PacketLink;
+  }
+
+} implementation {
+  components CC2420Ieee154MessageC as Msg;
+
+  SplitControl = Msg;
+  SendResource = Msg;
+  Ieee154Send  = Msg;
+  Ieee154Receive = Msg;
+  Ieee154Packet = Msg;
+  Packet = Msg;
+  
+  PacketAcknowledgements = Msg;
+  LinkPacketMetadata = Msg;
+  LowPowerListening = Msg;
+  PacketLink = Msg;
+}
index d00231cf8e4cab95981f1ce1208dd6d281e9a8a5..4037abdebdca94090971a18f28ce5a5f6d46570c 100644 (file)
+/*
+ * Copyright (c) 2006, Intel Corporation
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * Redistributions of source code must retain the above copyright notice, 
+ * this list of conditions and the following disclaimer. 
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution. 
+ *
+ * Neither the name of the Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software 
+ * without specific prior written permission. 
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Steven Ayer
+ * @date June 2006
+ */
+
 module MotePlatformC {
   provides interface Init;
 }
 implementation {
   command error_t Init.init() {
+    
     //LEDS
-    TOSH_SET_RED_LED_PIN();
-    TOSH_SET_GREEN_LED_PIN();
-    TOSH_SET_YELLOW_LED_PIN();
     TOSH_MAKE_RED_LED_OUTPUT();
-    TOSH_MAKE_GREEN_LED_OUTPUT();
     TOSH_MAKE_YELLOW_LED_OUTPUT();
+    TOSH_MAKE_ORANGE_LED_OUTPUT();
+    TOSH_MAKE_GREEN_LED_OUTPUT();
+    TOSH_SEL_RED_LED_IOFUNC();
+    TOSH_SEL_YELLOW_LED_IOFUNC();
+    TOSH_SEL_ORANGE_LED_IOFUNC();
+    TOSH_SEL_GREEN_LED_IOFUNC();
+
+    TOSH_SET_RED_LED_PIN();
+    TOSH_SET_YELLOW_LED_PIN();
+    TOSH_SET_ORANGE_LED_PIN();
+    TOSH_SET_GREEN_LED_PIN();
 
     //RADIO PINS
     //CC2420 pins
-    TOSH_MAKE_SOMI0_INPUT();
-    TOSH_MAKE_SIMO0_INPUT();
-    TOSH_MAKE_UCLK0_INPUT();
-    TOSH_MAKE_SOMI1_INPUT();
-    TOSH_MAKE_SIMO1_INPUT();
-    TOSH_MAKE_UCLK1_INPUT();
-    TOSH_SET_RADIO_RESET_PIN();
-    TOSH_MAKE_RADIO_RESET_OUTPUT();
-    TOSH_CLR_RADIO_VREF_PIN();
-    TOSH_MAKE_RADIO_VREF_OUTPUT();
-    TOSH_SET_RADIO_CSN_PIN();
     TOSH_MAKE_RADIO_CSN_OUTPUT();
-    TOSH_MAKE_RADIO_FIFOP_INPUT();
-    TOSH_MAKE_RADIO_SFD_INPUT();
+    TOSH_SEL_RADIO_CSN_IOFUNC();
+    TOSH_SET_RADIO_CSN_PIN();
+
+    TOSH_MAKE_CSN_OUTPUT();
+    TOSH_SEL_CSN_IOFUNC();
+    TOSH_SET_CSN_PIN();
+
+    // should be reset_n
+    TOSH_MAKE_RADIO_RESET_OUTPUT();
+    TOSH_SEL_RADIO_RESET_IOFUNC();
+    TOSH_CLR_RADIO_RESET_PIN();
 
     TOSH_MAKE_RADIO_1V8_EN_OUTPUT();
     TOSH_SEL_RADIO_1V8_EN_IOFUNC();
     TOSH_CLR_RADIO_1V8_EN_PIN();
 
-    TOSH_MAKE_CSN_OUTPUT();
-    TOSH_SEL_CSN_IOFUNC();
-    TOSH_SET_CSN_PIN();
+    TOSH_MAKE_RADIO_CCA_INPUT();
+    TOSH_MAKE_RADIO_FIFO_INPUT();
+    TOSH_MAKE_RADIO_FIFOP_INPUT();
+    TOSH_MAKE_RADIO_SFD_INPUT();
+    TOSH_MAKE_RADIO_TIMED_SFD_INPUT();
+    TOSH_SEL_RADIO_CCA_IOFUNC();
+    TOSH_SEL_RADIO_FIFO_IOFUNC();
+    TOSH_SEL_RADIO_FIFOP_IOFUNC();
+    TOSH_SEL_RADIO_SFD_IOFUNC();
+    TOSH_SEL_RADIO_TIMED_SFD_IOFUNC();
+
+    TOSH_MAKE_ONEWIRE_PWR_OUTPUT();
+    TOSH_SET_ONEWIRE_PWR_PIN();
+
+    TOSH_SEL_SD_CS_N_IOFUNC();
+    TOSH_MAKE_SD_CS_N_OUTPUT();
+    TOSH_SET_SD_CS_N_PIN();
+
+    // BT PINS
+    TOSH_MAKE_BT_RESET_OUTPUT();  
+    TOSH_SEL_BT_RESET_IOFUNC();    
+    TOSH_CLR_BT_RESET_PIN();   // mitsumi module disabled by clr
+
+    TOSH_MAKE_BT_RTS_INPUT();      
+    TOSH_SEL_BT_RTS_IOFUNC();
+
+    TOSH_MAKE_BT_PIO_INPUT();
+    TOSH_SEL_BT_PIO_IOFUNC();
+
+    TOSH_MAKE_BT_CTS_OUTPUT();
+    TOSH_SEL_BT_CTS_IOFUNC();
+
+    TOSH_MAKE_BT_TXD_OUTPUT();
+    TOSH_SEL_BT_TXD_MODFUNC();
+
+    TOSH_MAKE_BT_RXD_INPUT();
+    TOSH_SEL_BT_RXD_MODFUNC();
+
+    // BSL Prog Pins tristate em
+
+    TOSH_MAKE_PROG_IN_OUTPUT();
+    TOSH_MAKE_PROG_OUT_OUTPUT();
+    TOSH_SET_PROG_OUT_PIN();    // some expansion boards have enable low
+    TOSH_SEL_PROG_IN_IOFUNC();
+    TOSH_SEL_PROG_OUT_IOFUNC();
+
+    // USART lines, attached to a pullup
+    TOSH_SEL_UCLK0_IOFUNC();
+    TOSH_MAKE_UCLK0_OUTPUT();
+    TOSH_SET_UCLK0_PIN();
+    TOSH_SEL_UCLK1_IOFUNC();
+    TOSH_MAKE_UCLK1_OUTPUT();
+    TOSH_SET_UCLK1_PIN();
 
+    TOSH_SEL_SIMO0_IOFUNC();
+    TOSH_MAKE_SIMO0_OUTPUT();
+    TOSH_SET_SIMO0_PIN();
+    TOSH_SEL_SOMI0_IOFUNC();
+    TOSH_MAKE_SOMI0_INPUT();
+
+    TOSH_SEL_SIMO1_IOFUNC();
+    TOSH_MAKE_SIMO1_OUTPUT();
+    TOSH_SET_SIMO1_PIN();
+    TOSH_SEL_SOMI1_IOFUNC();
+    TOSH_MAKE_SOMI1_INPUT();
+
+    // ADC lines
+    TOSH_MAKE_ADC_0_OUTPUT();
+    TOSH_MAKE_ADC_1_OUTPUT();
+    TOSH_MAKE_ADC_2_OUTPUT();
+    TOSH_MAKE_ADC_6_OUTPUT();
+    TOSH_MAKE_ADC_7_OUTPUT();
+
+    TOSH_SEL_ADC_0_IOFUNC();
+    TOSH_SEL_ADC_1_IOFUNC();
+    TOSH_SEL_ADC_2_IOFUNC();
+    TOSH_SEL_ADC_6_IOFUNC();
+    TOSH_SEL_ADC_7_IOFUNC();
+  
+    TOSH_MAKE_ADC_ACCELZ_INPUT();
+    TOSH_MAKE_ADC_ACCELY_INPUT();
+    TOSH_MAKE_ADC_ACCELX_INPUT();
+    TOSH_SEL_ADC_ACCELZ_MODFUNC();
+    TOSH_SEL_ADC_ACCELY_MODFUNC();
+    TOSH_SEL_ADC_ACCELX_MODFUNC();
+  
+    TOSH_SEL_ROSC_IOFUNC();
+    TOSH_MAKE_ROSC_INPUT();
+
+    // DAC lines
+    // Default is not to use DAC mode.  Please define pin usage if you want to use them
+    
+    // UART pins
+    // These declarations are to allow the UART module to work since it's using the names.
+    // The UART module will set them to the right direction when initialized
+
+    // ftdi/gio pins.  Unused for now so we do not set directionality or function
 
-    //UART PINS
-    TOSH_MAKE_UTXD0_INPUT();
-    TOSH_MAKE_URXD0_INPUT();
-    TOSH_MAKE_UTXD1_INPUT();
-    TOSH_MAKE_URXD1_INPUT();
+
+    // 1-wire function
+    TOSH_MAKE_ONEWIRE_PWR_OUTPUT();
+    TOSH_SEL_ONEWIRE_PWR_IOFUNC();
+    TOSH_MAKE_ONEWIRE_INPUT();
+    TOSH_SEL_ONEWIRE_IOFUNC();
+
+    // Accelerometer pin definitions
+    TOSH_SEL_ACCEL_SEL0_IOFUNC();
+    TOSH_SEL_ACCEL_SEL1_IOFUNC();
+    TOSH_SEL_ACCEL_SLEEP_N_IOFUNC();
+  
+    TOSH_MAKE_ACCEL_SEL0_OUTPUT();
+    TOSH_MAKE_ACCEL_SEL1_OUTPUT();
+    TOSH_MAKE_ACCEL_SLEEP_N_OUTPUT();
+
+    /*
+     * unless the accel_sel0 pin is cleared, 
+     * a severe quiescent power hit occurs on the msp430
+     * we go from 3.7 ua to 65.1 ua when asleep!
+     */
+    TOSH_CLR_ACCEL_SEL0_PIN();
+    TOSH_CLR_ACCEL_SEL1_PIN();
+    TOSH_CLR_ACCEL_SLEEP_N_PIN();
+
+
+    // idle expansion header pins
+    TOSH_MAKE_SER0_CTS_OUTPUT();
+    TOSH_SEL_SER0_CTS_IOFUNC();
+    TOSH_MAKE_SER0_RTS_OUTPUT();
+    TOSH_SEL_SER0_RTS_IOFUNC();
+    TOSH_MAKE_GIO0_INPUT();
+    TOSH_SEL_GIO0_IOFUNC();
+    TOSH_MAKE_GIO1_OUTPUT();
+    TOSH_SEL_GIO1_IOFUNC();
+    TOSH_MAKE_UTXD0_OUTPUT();
+    TOSH_SEL_UTXD0_IOFUNC();
+    TOSH_MAKE_URXD0_OUTPUT();
+    TOSH_SEL_URXD0_IOFUNC();
+    TOSH_MAKE_RADIO_VREF_OUTPUT();
+    TOSH_SEL_RADIO_VREF_IOFUNC();
 
     return SUCCESS;
   }
index c3e6d19262b7fbe3bbdfc477d687ac30f6c1cc75..e23e742a6dc2ac8fe8a64d9536528af34025f1d5 100644 (file)
@@ -48,28 +48,28 @@ implementation
   Msp430TimerControl[0] = Msp430TimerC.ControlB0;
   Msp430Compare[0] = Msp430TimerC.CompareB0;
 
-  // Timer pin B1 is used by the CC2420 radio's SFD pin
-  // this is the only difference between the default 32khz map
-  // and the map on telos
-
   Msp430Timer[1] = Msp430TimerC.TimerB;
-  Msp430TimerControl[1] = Msp430TimerC.ControlB2;
-  Msp430Compare[1] = Msp430TimerC.CompareB2;
+  Msp430TimerControl[1] = Msp430TimerC.ControlB1;
+  Msp430Compare[1] = Msp430TimerC.CompareB1;
 
   Msp430Timer[2] = Msp430TimerC.TimerB;
-  Msp430TimerControl[2] = Msp430TimerC.ControlB3;
-  Msp430Compare[2] = Msp430TimerC.CompareB3;
+  Msp430TimerControl[2] = Msp430TimerC.ControlB2;
+  Msp430Compare[2] = Msp430TimerC.CompareB2;
 
   Msp430Timer[3] = Msp430TimerC.TimerB;
-  Msp430TimerControl[3] = Msp430TimerC.ControlB4;
-  Msp430Compare[3] = Msp430TimerC.CompareB4;
+  Msp430TimerControl[3] = Msp430TimerC.ControlB3;
+  Msp430Compare[3] = Msp430TimerC.CompareB3;
 
   Msp430Timer[4] = Msp430TimerC.TimerB;
-  Msp430TimerControl[4] = Msp430TimerC.ControlB5;
-  Msp430Compare[4] = Msp430TimerC.CompareB5;
+  Msp430TimerControl[4] = Msp430TimerC.ControlB4;
+  Msp430Compare[4] = Msp430TimerC.CompareB4;
 
   Msp430Timer[5] = Msp430TimerC.TimerB;
-  Msp430TimerControl[5] = Msp430TimerC.ControlB6;
-  Msp430Compare[5] = Msp430TimerC.CompareB6;
+  Msp430TimerControl[5] = Msp430TimerC.ControlB5;
+  Msp430Compare[5] = Msp430TimerC.CompareB5;
+
+  Msp430Timer[6] = Msp430TimerC.TimerB;
+  Msp430TimerControl[6] = Msp430TimerC.ControlB6;
+  Msp430Compare[6] = Msp430TimerC.CompareB6;
 }
 
index 5fc1d274eb8e4b69f69ba45b694daa3f82567e3f..b6d2dd0c57ea5f3020a9503128a80d72769f6067 100644 (file)
 /**
  * @author Joe Polastre
  * @version $Revision$ $Date$
+ *
+ * @author Mike Healy
+ * @date April 20, 2009 - added support for 4th (green) LED on SHIMMER
  */
+
 #include "hardware.h"
 
 configuration PlatformLedsC {
   provides interface GeneralIO as Led0;
   provides interface GeneralIO as Led1;
   provides interface GeneralIO as Led2;
+  provides interface GeneralIO as Led3;
   uses interface Init;
 }
 implementation
@@ -39,6 +44,7 @@ implementation
     , new Msp430GpioC() as Led0Impl
     , new Msp430GpioC() as Led1Impl
     , new Msp430GpioC() as Led2Impl
+    , new Msp430GpioC() as Led3Impl
     ;
   components PlatformP;
 
@@ -53,5 +59,8 @@ implementation
   Led2 = Led2Impl;
   Led2Impl -> GeneralIOC.Port42;
 
+  Led3 = Led3Impl;
+  Led3Impl -> GeneralIOC.Port43;
+
 }
 
diff --git a/tos/platforms/shimmer/SwitchToggleC.nc b/tos/platforms/shimmer/SwitchToggleC.nc
new file mode 100644 (file)
index 0000000..024c179
--- /dev/null
@@ -0,0 +1,73 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Generic layer to translate a GIO into a toggle switch
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ * port to shimmer-style
+ * @author Steve Ayer
+ * @date   February, 2010
+ */
+
+#include <UserButton.h>
+
+generic module SwitchToggleC() {
+  provides interface Notify<bool>;
+
+  uses interface GeneralIO;
+  uses interface GpioInterrupt;
+}
+implementation {
+  task void sendEvent();
+
+  command error_t Notify.enable() {
+    call GeneralIO.makeInput();
+
+    return call GpioInterrupt.enableRisingEdge();
+  }
+
+  command error_t Notify.disable() {
+    call GeneralIO.makeOutput();
+    return call GpioInterrupt.disable();
+  }
+
+  async event void GpioInterrupt.fired() {
+    call GpioInterrupt.disable();
+
+    post sendEvent();
+  }
+
+  task void sendEvent() {
+    signal Notify.notify( BUTTON_PRESSED );
+  }
+}
index 46c346456af1db519d84f50baec23e96f4f04db4..01f117075328def24cbd107cc3ac3fd61b3eb5be 100644 (file)
@@ -47,6 +47,8 @@ configuration TimeSyncMessageC {
     interface Receive as Snoop[am_id_t id];
     interface Packet;
     interface AMPacket;
+    interface PacketAcknowledgements;
+    interface LowPowerListening;
 
     interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
     interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
@@ -67,6 +69,8 @@ implementation {
   Snoop        = AM.Snoop;
   Packet       = AM;
   AMPacket     = AM;
+  PacketAcknowledgements = AM;
+  LowPowerListening = AM;
 
   TimeSyncAMSend32khz       = AM;
   TimeSyncAMSendMilli       = AM;
diff --git a/tos/platforms/shimmer/UserButton.h b/tos/platforms/shimmer/UserButton.h
new file mode 100644 (file)
index 0000000..d020741
--- /dev/null
@@ -0,0 +1,44 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telosb platform
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ */
+
+#ifndef USERBUTTON_H
+#define USERBUTTON_H
+
+typedef enum { BUTTON_RELEASED = 0, BUTTON_PRESSED = 1 } button_state_t;
+
+#endif
diff --git a/tos/platforms/shimmer/UserButtonC.nc b/tos/platforms/shimmer/UserButtonC.nc
new file mode 100644 (file)
index 0000000..465b1bd
--- /dev/null
@@ -0,0 +1,65 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telosb platform. Get
+ * returns the current state of the button by reading the pin,
+ * regardless of whether enable() or disable() has been called on the
+ * Interface. Notify.enable() and Notify.disable() modify the
+ * underlying interrupt state of the pin, and have the effect of
+ * enabling or disabling notifications that the button has changed
+ * state.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ * port to shimmer-style
+ * @author Steve Ayer
+ * @date   February, 2010
+ */
+
+#include <UserButton.h>
+
+configuration UserButtonC {
+  provides interface Notify<button_state_t>;
+}
+implementation {
+  components HplUserButtonC;
+  components new SwitchToggleC();
+  SwitchToggleC.GpioInterrupt -> HplUserButtonC.GpioInterrupt;
+  SwitchToggleC.GeneralIO -> HplUserButtonC.GeneralIO;
+
+  components UserButtonP;
+  Notify = UserButtonP;
+
+  components new TimerMilliC() as debounceTimer;
+  UserButtonP.NotifyLower -> SwitchToggleC.Notify;
+  UserButtonP.debounceTimer -> debounceTimer;
+}
diff --git a/tos/platforms/shimmer/UserButtonP.nc b/tos/platforms/shimmer/UserButtonP.nc
new file mode 100644 (file)
index 0000000..5f079ba
--- /dev/null
@@ -0,0 +1,74 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telosb platform
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ * port to shimmer-style
+ * @author Steve Ayer
+ * @date   February, 2010
+ */
+
+#include <UserButton.h>
+
+module UserButtonP {
+  provides interface Notify<button_state_t>;
+
+  uses interface Notify<bool> as NotifyLower;
+  uses interface Timer<TMilli> as debounceTimer;
+}
+implementation {
+  command error_t Notify.enable() {
+    return call NotifyLower.enable();
+  }
+
+  command error_t Notify.disable() {
+    return call NotifyLower.disable();
+  }
+
+  event void debounceTimer.fired() {
+    call Notify.enable();    // re-enable interrupt
+    signal Notify.notify( BUTTON_PRESSED );
+  }
+
+  task void debounce() {
+    call debounceTimer.startOneShot(125);
+  }
+
+  event void NotifyLower.notify( bool val ) {
+    // we've only enabled interrupt from rising edge
+    post debounce();
+  }
+  
+  default event void Notify.notify( button_state_t val ) { }
+}
diff --git a/tos/platforms/shimmer/chips/bluetooth/Bluetooth.nc b/tos/platforms/shimmer/chips/bluetooth/Bluetooth.nc
new file mode 100644 (file)
index 0000000..6dbf75e
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2007, Intel Corporation
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * Redistributions of source code must retain the above copyright notice, 
+ * this list of conditions and the following disclaimer. 
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution. 
+ *
+ * Neither the name of the Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software 
+ * without specific prior written permission. 
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ *  Authors:  Steve Ayer, Adrian Burns
+ *            February, 2007
+ */
+/**
+ * @author Steve Ayer
+ * @author Adrian Burns
+ * @date February, 2007
+ *
+ * @author Mike Healy
+ * @date April 20, 2009 - ported to TinyOS 2.x 
+ */
+
+
+
+#include "RovingNetworks.h"
+
+interface Bluetooth {
+
+   /* write SPP (Serial Port Profile) data to the connected BT device */
+   command error_t write(const uint8_t *buf, uint16_t len);
+
+   /* after this command is called there will be no link to the connected device */
+   command error_t disconnect();
+
+   /* commands useful for Master(client) applications only */
+   /* do an BT Inquiry to discover all listening devices within range */
+   command void discoverDevices();
+
+   /* connect to a specific device that was previously discovered */
+   command error_t connect(uint8_t * addr);
+
+   // enum SLAVE_MODE, MASTER_MODE, TRIGGER_MASTER_MODE, AUTO_MASTER_MODE
+   command void setRadioMode(uint8_t mode);           
+
+   command void setDiscoverable(bool disc);
+   command void setEncryption(bool enc);
+   command void setAuthentication(bool auth);
+   command void setName(char * name);                  // max 16 chars
+   command void setPIN(char * name);                   // max 16 chars
+   command void setServiceClass(char * class);         // max 4 chars (hex word)
+   command void setServiceName(char * name);         // max 16 chars 
+   command void setDeviceClass(char * class);         // max 4 chars (hex word)
+   command void disableRemoteConfig(bool disableConfig);
+   /*
+    * rate_factor is baudrate * 0.004096, e.g. to set 115200, pass in "472"
+    */
+   command void setRawBaudrate(char * rate_factor);      // max 4 chars, must be integer
+
+   /* 
+    * provide one of the following as a string argument:  
+    * { 1200, 2400, 4800, 9600, 19.2, 38.4, 57.6, 115K, 230K, 460K, 921K } 
+    */
+   command void setBaudrate(char * new_baud); 
+
+   /* save power by minimising time Inquiry/Page scanning, call these commands from */
+   /* your StdControl.init() - module reset necessary for changes to take effect */
+   command void setPagingTime(char * hexval_time); // max 4 chars (hex word)
+   command void setInquiryTime(char * hexval_time); // max 4 chars (hex word)
+   command void resetDefaults();
+
+   /* whether or not it succeeded */
+   async event void connectionMade(uint8_t status);
+   async event void connectionClosed(uint8_t reason);
+   async event void commandModeEnded();
+   /*
+    * buffered data depends upon line demarcation or eot for this...
+    *     event void dataAvailable(uint8_t * data, uint16_t len);
+    * and this...
+    *    event void discoveryStatus(uint8_t * devices);
+    *
+    */
+   async event void dataAvailable(uint8_t data);
+   event void writeDone();
+}
+
+
diff --git a/tos/platforms/shimmer/chips/bluetooth/RovingNetworks.h b/tos/platforms/shimmer/chips/bluetooth/RovingNetworks.h
new file mode 100644 (file)
index 0000000..5a7d82d
--- /dev/null
@@ -0,0 +1,32 @@
+/* radioMode in enableBluetooth() can be set to one of the following modes,
+ see the RovingNetworks AT command set for further details on module configuration */
+
+#ifndef ROVINGNETWORKS_H
+#define ROVINGNETWORKS_H
+enum {
+  SLAVE_MODE,
+  MASTER_MODE,
+  TRIGGER_MASTER_MODE,
+  AUTO_MASTER_MODE    
+};
+
+enum { 
+  NADA,
+  INITIAL,
+  FINAL
+};
+/*
+const char * SETMODE =  "SM,";
+const char * SETMASTERMODE =  "SM,1";
+const char * SETSLAVEMODE =   "SM,0";
+const char * DISCOVERRADIOS = "I,";
+const char * DISCOVERRADIOS2 = ",0";
+
+const char * SETFASTBAUD    = "SU,115";
+const char * ENTERCOMMANDMODE = "$$$";
+const char * SETSLEEPMODE   = "SW,0300";
+const char * DIALRADIO      = "C,";
+const char * HANGUPRADIO    = "R,1";
+const char * WAKERADIO      = "";
+*/
+#endif
diff --git a/tos/platforms/shimmer/chips/bluetooth/RovingNetworksC.nc b/tos/platforms/shimmer/chips/bluetooth/RovingNetworksC.nc
new file mode 100644 (file)
index 0000000..046b12a
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2007, Intel Corporation
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * Redistributions of source code must retain the above copyright notice, 
+ * this list of conditions and the following disclaimer. 
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution. 
+ *
+ * Neither the name of the Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software 
+ * without specific prior written permission. 
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ *  Author:  Steve Ayer
+ *           February, 2007
+ */
+/**
+ * @author Steve Ayer
+ * @author Adrian Burns
+ * @date February, 2007
+ *
+ * @author Mike Healy
+ * @date April 20, 2009 - ported to TinyOS 2.x 
+ */
+
+
+
+configuration RovingNetworksC {
+   provides {
+      interface StdControl;
+      interface Bluetooth;
+      interface Init;
+   }
+}
+implementation {
+   components 
+     RovingNetworksP,
+     MainC,
+     HplMsp430InterruptC,  
+     HplMsp430Usart1C,     
+     LedsC;
+
+   StdControl = RovingNetworksP;
+   Bluetooth = RovingNetworksP;
+   Init = RovingNetworksP;
+
+   RovingNetworksP.UARTControl            -> HplMsp430Usart1C.HplMsp430Usart;
+   RovingNetworksP.UARTData               -> HplMsp430Usart1C.HplMsp430UsartInterrupts;
+   RovingNetworksP.RTSInterrupt           -> HplMsp430InterruptC.Port16;
+   RovingNetworksP.ConnectionInterrupt    -> HplMsp430InterruptC.Port15;
+   RovingNetworksP.Leds                   -> LedsC;
+
+}
diff --git a/tos/platforms/shimmer/chips/bluetooth/RovingNetworksP.nc b/tos/platforms/shimmer/chips/bluetooth/RovingNetworksP.nc
new file mode 100644 (file)
index 0000000..b81aa48
--- /dev/null
@@ -0,0 +1,555 @@
+/*
+ * Copyright (c) 2007, Intel Corporation
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * Redistributions of source code must retain the above copyright notice, 
+ * this list of conditions and the following disclaimer. 
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution. 
+ *
+ * Neither the name of the Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software 
+ * without specific prior written permission. 
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ *  Author:  Steve Ayer
+ *           February, 2007
+ */
+/**
+ * @author Steve Ayer
+ * @author Adrian Burns
+ * @date February, 2007
+ *
+ * @author Mike Healy
+ * @date April 20, 2009 - ported to TinyOS 2.x 
+ */
+
+
+#include "RovingNetworks.h"
+#include "shimmerMessage.h"
+
+module RovingNetworksP {
+  provides {
+    interface Init;
+    interface StdControl;
+    interface Bluetooth;
+  }
+  uses {
+    interface HplMsp430Usart as UARTControl;
+    interface HplMsp430UsartInterrupts as UARTData;
+    interface HplMsp430Interrupt as RTSInterrupt;
+    interface HplMsp430Interrupt as ConnectionInterrupt;
+    interface Leds;
+  }
+}
+
+implementation {
+  extern int sprintf(char *str, const char *format, ...) __attribute__ ((C));
+  extern int snprintf(char *str, size_t len, const char *format, ...) __attribute__ ((C));
+
+  uint8_t radioMode, charsSent, setupStep;
+  bool discoverable, authenticate, encrypt, setNameRequest, setPINRequest, runDiscoveryRequest, resetDefaultsRequest,
+    setSvcClassRequest, setDevClassRequest, setSvcNameRequest, setRawBaudrate, setBaudrate, disableRemoteConfig, newMode,
+    setCustomInquiryTime, setCustomPagingTime;
+  norace bool transmissionOverflow, messageInProgress;
+  char expectedCommandResponse[8], newName[17], newPIN[17], newSvcClass[5], newDevClass[5], newSvcName[17], newRawBaudrate[5],
+    newBaudrate[5], newInquiryTime[5], newPagingTime[5];
+  
+  norace struct Message outgoingMsg;
+  norace struct Message incomingMsg;
+   
+
+  task void sendNextChar() {
+    if(charsSent < outgoingMsg.length) {
+      call UARTControl.tx(msg_get_uint8(&outgoingMsg, charsSent));
+      atomic charsSent++;
+    } 
+    else{
+      messageInProgress = FALSE;
+      atomic if(!*expectedCommandResponse)
+       signal Bluetooth.writeDone();
+    }      
+  }
+  
+  command error_t Bluetooth.write(const uint8_t * buf, uint16_t len) { 
+    if(messageInProgress)
+      return FAIL;
+
+    messageInProgress = TRUE;
+    atomic charsSent = 0;
+    msg_clear(&outgoingMsg);
+    msg_append_buf(&outgoingMsg, buf, len);
+
+    if(!transmissionOverflow){
+      post sendNextChar();
+    }
+       
+    return SUCCESS;
+  }
+    
+  void initRN() {
+    register uint16_t i;
+    /*
+     * powerup state is reset == low (true); mike conrad of roving networks sez: 
+     * wait about 1/2 s after reset toggle
+     */
+    TOSH_SET_BT_RESET_PIN();    
+    for(i = 0; i< 400; i++)
+      TOSH_uwait(5000);
+
+    TOSH_MAKE_BT_PIO_INPUT();   // this is the connection interrupt pin, was default output
+    
+    call RTSInterrupt.edge(TRUE);  // initially, we look for a connection
+    call RTSInterrupt.enable();  // request to send raises when bt has trans overflow
+    call RTSInterrupt.clear();
+    
+    call ConnectionInterrupt.edge(TRUE);  // initially, we look for a connection
+    call ConnectionInterrupt.clear();
+    call ConnectionInterrupt.enable();  // interrupt upon connection state change (raises when connected, falls when dropped)
+
+    TOSH_CLR_BT_CTS_PIN();     // toggling cts wakes it up
+    TOSH_SET_BT_CTS_PIN();     
+    TOSH_uwait(5000);
+    TOSH_CLR_BT_CTS_PIN();     // tell bt module msp430 is ready
+  }
+
+  void setupUART() {
+    msp430_uart_union_config_t RN_uart_config = { {ubr: UBR_1MHZ_115200, umctl: UMCTL_1MHZ_115200, 
+                                                  ssel: 0x02, pena: 0, pev: 0, spb: 0, clen: 1,listen: 0, mm: 0, ckpl: 0, urxse: 0, urxeie: 0, 
+                                                  urxwie: 0, utxe : 1, urxe :1} };
+
+    call UARTControl.setModeUart(&RN_uart_config); // set to UART mode
+#ifdef USE_8MHZ_CRYSTAL           // we need exact divisors, else the thing acts unpredictably
+    call UARTControl.setUbr(0x08);
+    call UARTControl.setUmctl(0xee);
+#endif
+
+    /*
+     * to run the bt module at 230k, first the application must configure it
+     * using its default uart speed of 115200, then reset the uart to 230k here
+     * see accompanying bluetoothBaudrateConfiguration.pdf doc for details
+     * yes, doc is written for tos-1.x, but setClockRate() is just broken into
+     * two calls here in tos-2.x
+     *
+     call UARTControl.setUbr(0x04);
+     call UARTControl.setUmctl(0x82);
+    */
+    
+    call UARTControl.enableTxIntr();
+    call UARTControl.enableRxIntr();
+  }
+
+  void disableRN() {
+    TOSH_CLR_BT_RESET_PIN();
+    call UARTControl.disableUart();
+    call RTSInterrupt.disable();  
+    call ConnectionInterrupt.disable();  
+  }
+
+  error_t writeCommand(char * cmd, char * response) {
+    atomic strcpy(expectedCommandResponse, response);
+    if(call Bluetooth.write(cmd, strlen(cmd)) == FAIL)
+      return FAIL;
+
+    return SUCCESS;
+  }
+
+  command void Bluetooth.setRadioMode(uint8_t mode){
+    newMode = TRUE;
+    radioMode = mode;
+  }    
+
+  command void Bluetooth.setDiscoverable(bool disc){
+    discoverable = disc;  
+  }    
+
+  command void Bluetooth.setEncryption(bool enc){
+    encrypt = enc; 
+  }    
+
+  command void Bluetooth.setAuthentication(bool auth){
+    authenticate = auth;
+  }    
+
+  command void Bluetooth.disableRemoteConfig(bool disableConfig){
+    disableRemoteConfig = disableConfig;
+  }    
+
+  command void Bluetooth.resetDefaults(){
+    resetDefaultsRequest = TRUE;
+  }    
+
+  command void Bluetooth.setName(char * name){
+    setNameRequest = TRUE;
+    snprintf(newName, 17, "%s", name);
+  }    
+
+  command void Bluetooth.setDeviceClass(char * class){
+    setDevClassRequest = TRUE;
+    snprintf(newDevClass, 5, "%s", class);
+  }    
+
+  command void Bluetooth.setServiceClass(char * class){
+    setSvcClassRequest = TRUE;
+    snprintf(newSvcClass, 5, "%s", class);
+  }    
+
+  command void Bluetooth.setServiceName(char * name){
+    setSvcNameRequest = TRUE;
+    snprintf(newSvcName, 5, "%s", name);
+  }    
+
+  /* 
+   * this one makes sense only to roving networks
+   * the supplied "rate_factor" is the baudrate * 0.004096
+   * this factor must be an integer value...
+   */
+  command void Bluetooth.setRawBaudrate(char * rate_factor){
+    setRawBaudrate = TRUE;
+    snprintf(newRawBaudrate, 5, "%s", rate_factor);
+  }    
+
+  /* 
+   * to set the baudrate of the BT to MSP serial interface 
+   * as per RovingNetworks command spec EG "SU,96" or "SU,230"
+   * SU,<rate> - Baudrate, {1200, 2400, 4800, 9600, 19.2, 
+   * 38.4, 57.6, 115K, 230K, 460K, 921K },
+   * BUT, the MSP USARTS will not run at > 230K in UART mode, 
+   * see MSP user guide
+   */
+  command void Bluetooth.setBaudrate(char * new_baud){
+    setBaudrate = TRUE;
+    snprintf(newBaudrate, 5, "%s", new_baud);
+  }    
+
+  command void Bluetooth.setPIN(char * PIN){
+    setPINRequest = TRUE;
+    snprintf(newPIN, 17, "%s", PIN);
+  }    
+
+  /* 
+   * Sets the Inquiry Scan Window - amount of time device 
+   * spends enabling inquiry scan (discoverability).
+   * Minimum = (hex word) "0012", corresponding to about 1% duty cycle.
+   * Maximum = (hex word) "1000"
+   */
+  command void Bluetooth.setInquiryTime(char * hexval_time){
+    setCustomInquiryTime = TRUE;
+    snprintf(newInquiryTime, 5, "%s", hexval_time);
+  }    
+
+  /* 
+   * Sets the Paging Scan Window - amount of time device 
+   * spends enabling page scan (connectability).
+   * Minimum = (hex word) "0012", corresponding to about 1% duty cycle.
+   * Maximum = (hex word) "1000"
+   */
+  command void Bluetooth.setPagingTime(char * hexval_time){
+    setCustomPagingTime = TRUE;
+    snprintf(newPagingTime, 5, "%s", hexval_time);
+  }    
+
+  /*
+   * this one is weird.  we need to do one at a time; the only way
+   * to get back is if the previous command responds properly and calls
+   * back to runSetCommands().  so if we get into command mode, each time here 
+   * we have to send another command.  we keep falling down the switch 
+   * until we find it, eventually hitting end.
+   */
+  task void runSetCommands() {
+    char commandbuf[32];
+
+    switch(setupStep) {
+    case 0:
+      setupStep++;
+      writeCommand("$$$", "CMD");
+      break;
+    case 1:
+      setupStep++;
+      // reset factory defaults
+      if(resetDefaultsRequest){
+       writeCommand("SF,1\r", "AOK");
+       break;
+      }
+    case 2:
+      setupStep++;
+      // default is slave (== 0), otherwise set mode
+      if(newMode){
+       sprintf(commandbuf, "SM,%d\r", radioMode);
+       writeCommand(commandbuf, "AOK");
+       break;
+      }
+    case 3:
+      setupStep++;
+      /*
+       * device is discoverable with a non-zero inquiry scan window
+       * default "time" is 0x0200 (units unspecified)
+       */
+      if(!discoverable){
+       writeCommand("SI,0000\r", "AOK");
+       break;
+      }
+    case 4:
+      setupStep++;
+      // device default is off
+      if(authenticate){
+       writeCommand("SA,1\r", "AOK");
+       break;
+      }
+    case 5:
+      setupStep++;
+      // device default is off
+      if(encrypt){
+       writeCommand("SE,1\r", "AOK");
+       break;
+      }
+    case 6:
+      setupStep++;
+      // default is none
+      if(setNameRequest){
+       sprintf(commandbuf, "SN,%s\r", newName);
+       writeCommand(commandbuf, "AOK");
+       break;
+      }
+    case 7:
+      setupStep++;
+      // default is none
+      if(setPINRequest){
+       sprintf(commandbuf, "SP,%s\r", newPIN);
+       writeCommand(commandbuf, "AOK");
+       break;
+      }
+    case 8:
+      setupStep++;
+      if(setSvcClassRequest){
+       sprintf(commandbuf, "SC,%s\r", newSvcClass);
+       writeCommand(commandbuf, "AOK");
+       break;
+      }
+    case 9:
+      setupStep++;
+      if(setDevClassRequest){
+       sprintf(commandbuf, "SD,%s\r", newDevClass);
+       writeCommand(commandbuf, "AOK");
+       break;
+      }
+    case 10:
+      setupStep++;
+      if(setSvcNameRequest){
+       sprintf(commandbuf, "SS,%s\r", newSvcName);
+       writeCommand(commandbuf, "AOK");
+       break;
+      }
+    case 11:
+      setupStep++;
+      if(setRawBaudrate){
+       // set the baudrate to suit the MSP430 running at 8Mhz
+       sprintf(commandbuf, "SZ,%s\r", newRawBaudrate);
+       writeCommand(commandbuf, "AOK");
+       break;
+      }
+    case 12:
+      setupStep++;
+      if(disableRemoteConfig){
+       // disable remote configuration to enhance throughput
+       writeCommand("ST,0\r", "AOK");
+      }
+      else{
+       // disable remote configuration to enhance throughput
+       writeCommand("ST,60\r", "AOK");
+      }
+      break;
+    case 13:
+      setupStep++;
+      if(setCustomInquiryTime){
+       sprintf(commandbuf, "SI,%s\r", newInquiryTime);
+       writeCommand(commandbuf, "AOK");
+      }
+      else{
+       // to save power only leave inquiry on for approx 40msec (every 1.28 secs)
+       writeCommand("SI,0040\r", "AOK");
+      }
+      break;
+    case 14:
+      setupStep++;
+      if(setCustomPagingTime){
+       sprintf(commandbuf, "SJ,%s\r", newPagingTime);
+       writeCommand(commandbuf, "AOK");
+      }
+      else{
+       // to save power only leave paging on for approx 80msec (every 1.28 secs)
+       writeCommand("SJ,0080\r", "AOK");
+      }
+      break;
+    case 15:
+      setupStep++;
+      if(setBaudrate){
+        // set the baudrate to suit the MSP430 running at 8Mhz
+        sprintf(commandbuf, "SU,%s\r", newBaudrate);
+        writeCommand(commandbuf, "AOK");
+        break;
+      }
+
+    case 16:
+      setupStep++;
+      // exit command mode
+      writeCommand("---\r", "END");
+      break;
+    default:
+      break;
+    }
+  }  
+
+  command error_t Init.init(){
+    TOSH_MAKE_BT_RTS_INPUT();      
+    
+    TOSH_MAKE_BT_RXD_INPUT();
+    TOSH_SEL_BT_RXD_MODFUNC();
+    
+    // this powers it up on models so equipped, otherwise harmless 
+#ifdef BT_PWR_LOGIC_TRUE
+    TOSH_SET_SW_BT_PWR_N_PIN();
+#else  
+    TOSH_CLR_SW_BT_PWR_N_PIN();   
+#endif
+    
+    newMode = FALSE;
+    radioMode = SLAVE_MODE;   
+    discoverable = TRUE;
+    authenticate = FALSE;
+    encrypt = FALSE;
+    resetDefaultsRequest = FALSE;
+    setNameRequest = FALSE;
+    setPINRequest = FALSE;
+    setSvcClassRequest = FALSE;
+    setSvcNameRequest = FALSE;
+    setDevClassRequest = FALSE;
+    setRawBaudrate = FALSE;
+    disableRemoteConfig = FALSE;
+    setCustomInquiryTime = FALSE;
+    setCustomPagingTime = FALSE;
+    setBaudrate = FALSE;
+
+    setupStep = 0;
+    atomic *expectedCommandResponse = 0;   // NULL pointer
+    transmissionOverflow = FALSE, messageInProgress = FALSE;
+
+    initRN();
+    setupUART();
+
+    return SUCCESS;
+  }
+
+  command error_t StdControl.start(){
+    TOSH_uwait(15000);
+    post runSetCommands();
+
+    return SUCCESS;
+  }
+
+  command error_t StdControl.stop(){
+    disableRN();
+    
+#ifdef BT_PWR_LOGIC_TRUE
+    TOSH_CLR_SW_BT_PWR_N_PIN();
+#else  
+    TOSH_SET_SW_BT_PWR_N_PIN();   
+#endif
+    
+    return SUCCESS;
+  }
+  
+  /* after this command is called there will be no link to the connected device */
+  command error_t Bluetooth.disconnect(){
+    call Bluetooth.write("K,\r", 3);
+  }
+
+  /* commands useful for Master(client) applications only */
+  /* do an BT Inquiry to discover all listening devices within range */
+  command void Bluetooth.discoverDevices() {
+    if(!radioMode)     // we're a slave, shouldn't do this
+      return;
+
+    runDiscoveryRequest = TRUE;
+  }    
+
+  /* connect to a specific device that was previously discovered */
+  command error_t Bluetooth.connect(uint8_t * addr) {
+    char buffer[64];
+
+    sprintf(buffer, "C,%s\r", addr);
+    return writeCommand(buffer, "AOK");
+  }
+     
+  async event void UARTData.rxDone(uint8_t data) {        
+    if(!*expectedCommandResponse){
+      signal Bluetooth.dataAvailable(data);
+    }
+    else{
+      if(isalpha(data)){
+       msg_append_uint8(&incomingMsg, data);
+       if(msg_cmp_buf(&incomingMsg,            // which is affirmative
+                      0, 
+                      expectedCommandResponse,
+                      strlen(expectedCommandResponse))){
+         msg_clear(&incomingMsg);      
+         if(!strcmp(expectedCommandResponse, "END"))
+           signal Bluetooth.commandModeEnded();  //call Leds.greenOn();
+         else
+           post runSetCommands();
+         atomic *expectedCommandResponse = '\0';
+       }
+      }
+      else
+       msg_clear(&incomingMsg);
+    }
+  }
+
+  async event void UARTData.txDone() {
+    if (!transmissionOverflow) {
+      post sendNextChar();
+    }
+  }
+    
+  // Interrupt associated with radio flow control.  Ensures that there are no buffer overflows.
+  async event void RTSInterrupt.fired() {
+    if (call RTSInterrupt.getValue() == TRUE) {
+      transmissionOverflow = 1;
+      call RTSInterrupt.edge(FALSE);
+    } 
+    else{
+      atomic transmissionOverflow = 0;
+      post sendNextChar();
+      call RTSInterrupt.edge(TRUE);
+    }
+    atomic call RTSInterrupt.clear();
+  }
+  
+  async event void ConnectionInterrupt.fired() {
+    if(call ConnectionInterrupt.getValue() == TRUE){
+      call ConnectionInterrupt.edge(FALSE);
+      signal Bluetooth.connectionMade(SUCCESS);
+    }
+    else{
+      call ConnectionInterrupt.edge(TRUE);
+      signal Bluetooth.connectionClosed(0);
+    }
+    atomic call ConnectionInterrupt.clear();
+  }
+}
diff --git a/tos/platforms/shimmer/chips/bluetooth/bluetoothBaudrateConversion.pdf b/tos/platforms/shimmer/chips/bluetooth/bluetoothBaudrateConversion.pdf
new file mode 100644 (file)
index 0000000..f029e14
Binary files /dev/null and b/tos/platforms/shimmer/chips/bluetooth/bluetoothBaudrateConversion.pdf differ
diff --git a/tos/platforms/shimmer/chips/msp430/msp430hardware.h b/tos/platforms/shimmer/chips/msp430/msp430hardware.h
new file mode 100644 (file)
index 0000000..7911e9b
--- /dev/null
@@ -0,0 +1,288 @@
+
+/* "Copyright (c) 2000-2003 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+// @author Vlado Handziski <handzisk@tkn.tu-berlin.de>
+// @author Joe Polastre <polastre@cs.berkeley.edu>
+// @author Cory Sharp <cssharp@eecs.berkeley.edu>
+
+#ifndef _H_msp430hardware_h
+#define _H_msp430hardware_h
+
+#include <io.h>
+#include <signal.h>
+#include "msp430regtypes.h"
+#include "Msp430DcoSpec.h"
+
+// CPU memory-mapped register access will cause nesc to issue race condition
+// warnings.  Race conditions are a significant conern when accessing CPU
+// memory-mapped registers, because they can change even while interrupts
+// are disabled.  This means that the standard nesc tools for resolving race
+// conditions, atomic statements that disable interrupt handling, do not
+// resolve CPU register race conditions.  So, CPU registers access must be
+// treated seriously and carefully.
+
+// The macro MSP430REG_NORACE allows individual modules to internally
+// redeclare CPU registers as norace, eliminating nesc's race condition
+// warnings for their access.  This macro should only be used after the
+// specific CPU register use has been verified safe and correct.  Example
+// use:
+//
+//    module MyLowLevelModule
+//    {
+//      // ...
+//    }
+//    implementation
+//    {
+//      MSP430REG_NORACE(TACCTL0);
+//      // ...
+//    }
+
+#undef norace
+
+#define MSP430REG_NORACE_EXPAND(type,name,addr) \
+norace static volatile type name asm(#addr)
+
+#define MSP430REG_NORACE3(type,name,addr) \
+MSP430REG_NORACE_EXPAND(type,name,addr)
+
+// MSP430REG_NORACE and MSP430REG_NORACE2 presume naming conventions among
+// type, name, and addr, which are defined in the local header
+// msp430regtypes.h and mspgcc's header io.h and its children.
+
+#define MSP430REG_NORACE2(rename,name) \
+MSP430REG_NORACE3(TYPE_##name,rename,name##_)
+
+#define MSP430REG_NORACE(name) \
+MSP430REG_NORACE3(TYPE_##name,name,name##_)
+
+// Avoid the type-punned pointer warnings from gcc 3.3, which are warning about
+// creating potentially broken object code.  Union casts are the appropriate work
+// around.  Unfortunately, they require a function definiton.
+#define DEFINE_UNION_CAST(func_name,to_type,from_type) \
+to_type func_name(from_type x) @safe() { union {from_type f; to_type t;} c = {f:x}; return c.t; }
+
+// redefine ugly defines from msp-gcc
+#ifndef DONT_REDEFINE_SR_FLAGS
+#undef C
+#undef Z
+#undef N
+#undef V
+#undef GIE
+#undef CPUOFF
+#undef OSCOFF
+#undef SCG0
+#undef SCG1
+#undef LPM0_bits
+#undef LPM1_bits
+#undef LPM2_bits
+#undef LPM3_bits
+#undef LPM4_bits
+#define SR_C       0x0001
+#define SR_Z       0x0002
+#define SR_N       0x0004
+#define SR_V       0x0100
+#define SR_GIE     0x0008
+#define SR_CPUOFF  0x0010
+#define SR_OSCOFF  0x0020
+#define SR_SCG0    0x0040
+#define SR_SCG1    0x0080
+#define LPM0_bits           SR_CPUOFF
+#define LPM1_bits           SR_SCG0+SR_CPUOFF
+#define LPM2_bits           SR_SCG1+SR_CPUOFF
+#define LPM3_bits           SR_SCG1+SR_SCG0+SR_CPUOFF
+#define LPM4_bits           SR_SCG1+SR_SCG0+SR_OSCOFF+SR_CPUOFF
+#endif//DONT_REDEFINE_SR_FLAGS
+
+#ifdef interrupt
+#undef interrupt
+#endif
+
+#ifdef wakeup
+#undef wakeup
+#endif
+
+#ifdef signal
+#undef signal
+#endif
+
+
+// Re-definitions for safe tinyOS
+// These rely on io.h being included at the top of this file
+// thus pulling the affected header files before the re-definitions
+#ifdef SAFE_TINYOS
+#undef ADC12MEM
+#define ADC12MEM            TCAST(int* ONE, ADC12MEM_) /* ADC12 Conversion Memory (for C) */
+#undef ADC12MCTL
+#define ADC12MCTL           TCAST(char * ONE, ADC12MCTL_)
+#endif
+
+// define platform constants that can be changed for different compilers
+// these are all msp430-gcc specific (add as necessary)
+
+#ifdef __msp430_headers_adc10_h
+#define __msp430_have_adc10
+#endif
+
+#ifdef __msp430_headers_adc12_h
+#define __msp430_have_adc12
+#endif
+
+// backwards compatibility to older versions of the header files
+#ifdef __MSP430_HAS_I2C__
+#define __msp430_have_usart0_with_i2c
+#endif
+
+// I2CBusy flag is not defined by current MSP430-GCC
+#ifdef __msp430_have_usart0_with_i2c
+#ifndef I2CBUSY
+#define I2CBUSY   (0x01 << 5)
+#endif
+MSP430REG_NORACE2(U0CTLnr,U0CTL);
+MSP430REG_NORACE2(I2CTCTLnr,I2CTCTL);
+MSP430REG_NORACE2(I2CDCTLnr,I2CDCTL);
+#endif
+
+// The signal attribute has opposite meaning in msp430-gcc than in avr-gcc
+#define TOSH_SIGNAL(signame) \
+  void sig_##signame() __attribute__((interrupt (signame), wakeup)) @C()
+
+// TOSH_INTERRUPT allows nested interrupts
+#define TOSH_INTERRUPT(signame) \
+  void isr_##signame() __attribute__((interrupt (signame), signal, wakeup)) @C()
+
+inline void TOSH_wait(void)
+{
+  nop(); nop();
+}
+
+// #define TOSH_CYCLE_TIME_NS 250
+// Our worst case is 250 ns = 1 cycle.
+
+inline void TOSH_wait_250ns(void)
+{
+  nop();
+}
+
+/* 
+   Following the suggestion of the mspgcc.sourceforge.net site
+   for an intelligent pause routine
+*/
+void brief_pause(register unsigned int n)
+{
+  asm volatile(        "1: \n\t"
+               "dec    %0 \n\t"
+               "jne    1b\n\t"
+               :  "+r" (n));
+}
+
+#define TOSH_uwait(n)   brief_pause((((unsigned long long)n) * TARGET_DCO_KHZ * 1024 / 1000000 - 2) / 3)
+
+#define SET_FLAG(port, flag) ((port) |= (flag))
+#define CLR_FLAG(port, flag) ((port) &= ~(flag))
+#define READ_FLAG(port, flag) ((port) & (flag))
+
+// TOSH_ASSIGN_PIN creates functions that are effectively marked as
+// "norace".  This means race conditions that result from their use will not
+// be detectde by nesc.
+
+#define TOSH_ASSIGN_PIN_HEX(name, port, hex) \
+void TOSH_SET_##name##_PIN() @safe() { MSP430REG_NORACE2(r,P##port##OUT); r |= hex; } \
+void TOSH_CLR_##name##_PIN() @safe() { MSP430REG_NORACE2(r,P##port##OUT); r &= ~hex; } \
+void TOSH_TOGGLE_##name##_PIN() @safe(){ MSP430REG_NORACE2(r,P##port##OUT); r ^= hex; } \
+uint8_t TOSH_READ_##name##_PIN() @safe() { MSP430REG_NORACE2(r,P##port##IN); return (r & hex); } \
+void TOSH_MAKE_##name##_OUTPUT() @safe() { MSP430REG_NORACE2(r,P##port##DIR); r |= hex; } \
+void TOSH_MAKE_##name##_INPUT() @safe() { MSP430REG_NORACE2(r,P##port##DIR); r &= ~hex; } \
+void TOSH_SEL_##name##_MODFUNC() @safe() { MSP430REG_NORACE2(r,P##port##SEL); r |= hex; } \
+void TOSH_SEL_##name##_IOFUNC() @safe() { MSP430REG_NORACE2(r,P##port##SEL); r &= ~hex; }
+
+#define TOSH_ASSIGN_PIN(name, port, bit) \
+TOSH_ASSIGN_PIN_HEX(name,port,(1<<(bit)))
+
+typedef uint8_t mcu_power_t @combine("mcombine");
+mcu_power_t mcombine(mcu_power_t m1, mcu_power_t m2) @safe() {
+  return (m1 < m2) ? m1: m2;
+}
+enum {
+  MSP430_POWER_ACTIVE = 0,
+  MSP430_POWER_LPM0   = 1,
+  MSP430_POWER_LPM1   = 2,
+  MSP430_POWER_LPM2   = 3,
+  MSP430_POWER_LPM3   = 4,
+  MSP430_POWER_LPM4   = 5
+};
+
+void __nesc_disable_interrupt(void) @safe()
+{
+  dint();
+  nop();
+}
+
+void __nesc_enable_interrupt(void) @safe()
+{
+  eint();
+}
+
+typedef bool __nesc_atomic_t;
+__nesc_atomic_t __nesc_atomic_start(void);
+void __nesc_atomic_end(__nesc_atomic_t reenable_interrupts);
+
+#ifndef NESC_BUILD_BINARY
+/* @spontaneous() functions should not be included when NESC_BUILD_BINARY
+   is #defined, to avoid duplicate functions definitions when binary
+   components are used. Such functions do need a prototype in all cases,
+   though. */
+__nesc_atomic_t __nesc_atomic_start(void) @spontaneous() @safe()
+{
+  __nesc_atomic_t result = ((READ_SR & SR_GIE) != 0);
+  __nesc_disable_interrupt();
+  asm volatile("" : : : "memory"); /* ensure atomic section effect visibility */
+  return result;
+}
+
+void __nesc_atomic_end(__nesc_atomic_t reenable_interrupts) @spontaneous() @safe()
+{
+  asm volatile("" : : : "memory"); /* ensure atomic section effect visibility */
+  if( reenable_interrupts )
+    __nesc_enable_interrupt();
+}
+#endif
+
+/* Floating-point network-type support.
+   These functions must convert to/from a 32-bit big-endian integer that follows
+   the layout of Java's java.lang.float.floatToRawIntBits method.
+   Conveniently, for the MSP430 family, this is a straight byte copy...
+*/
+
+typedef float nx_float __attribute__((nx_base_be(afloat)));
+
+inline float __nesc_ntoh_afloat(const void *COUNT(sizeof(float)) source) @safe() {
+  float f;
+  memcpy(&f, source, sizeof(float));
+  return f;
+}
+
+inline float __nesc_hton_afloat(void *COUNT(sizeof(float)) target, float value) @safe() {
+  memcpy(target, &value, sizeof(float));
+  return value;
+}
+
+#endif//_H_msp430hardware_h
+
index 3d911e98317da9e30f022504110634e8b62dd454..243d53e9dba42c728aab8a06f589b361a469f6ab 100644 (file)
  */                      
 #include "SD.h"
 
-interface SD 
-{
-    /**
-     * Returns the card size in bytes.
-     *
-     * @return the card size in bytes.
-     */
-    command uint32_t readCardSize();
+interface SD {
+  /**
+   * Returns the card size in bytes.
+   *
+   * @return the card size in bytes.
+   */
+  command uint32_t readCardSize();
 
-    /**
-     * Reads 512 bytes from the SD at sector and copies it to bufferPtr
-     *
-     * @param sector the sector on the SD card (in multiples of 512 bytes).
-     * @param bufferPtr pointer to where the SD will copy the data to.  Must be 512 bytes.
-     * @return <code>SUCCESS<code> if it was read successfully; <code>FAIL<code> otherwise
-    */
-    command error_t readBlock(const uint32_t sector, void *bufferPtr);
+  /**
+   * Reads 512 bytes from the SD at sector and copies it to bufferPtr
+   *
+   * @param sector the sector on the SD card (in multiples of 512 bytes).
+   * @param bufferPtr pointer to where the SD will copy the data to.  Must be 512 bytes.
+   * @return <code>SUCCESS<code> if it was read successfully; <code>FAIL<code> otherwise
+   */
+  command error_t readBlock(const uint32_t sector, uint8_t * buffer);
 
-    /**
-     * Writes 512 bytes from the bufferPtr to the SD card
-     *
-     * @param sector the sector on the SD card (in multiples of 512 bytes
-     *                       where to write the data to).
-     * @param bufferPtr pointer to data to be added.  Must be 512 bytes.
-     * @return <code>SUCCESS<code> if it was written successfully; <code>FAIL<code> otherwise
-     */
-    command error_t writeBlock(const uint32_t sector, void *bufferPtr);
+  /**
+   * Writes 512 bytes from the bufferPtr to the SD card
+   *
+   * @param sector the sector on the SD card (in multiples of 512 bytes
+   *                       where to write the data to).
+   * @param bufferPtr pointer to data to be added.  Must be 512 bytes.
+   * @return <code>SUCCESS<code> if it was written successfully; <code>FAIL<code> otherwise
+   */
+  command error_t writeBlock(const uint32_t sector, uint8_t * buffer);
+
+  /**
+   * the device has control over the sd card
+   */
+  async event void available();     
+
+  /**
+   * the device has lost control of the sd and should cease 
+   * attempts to talk to the card
+   */
+  async event void unavailable();
 }
index c74f7b39786855c5ad553fdc09184e151bcbf331..1362692069efc497938d11766f642dde1d28b79e 100644 (file)
  */
 /**                                   
  * @author Steve Ayer
+ * @date   July 2006
+ * @date   July 2009 (reworked, updated to maintained version)
  * @author Konrad Lorincz
  * @date March 25, 2008 - ported to TOS 2.x
  */
 
-configuration SDC 
-{
-    provides interface SD;
+configuration SDC {
+  provides {
+    interface SD;
+    interface StdControl;
+  }
 }
-implementation 
-{
-    components MainC, SDP;
-    SDP -> MainC.Boot;
-    SD = SDP;
+implementation {
+  components SDP, new Msp430Usart0C(), HplMsp430InterruptP, LedsC;
+  
+  SD = SDP;
+  StdControl = SDP;
 
-    components HplMsp430Usart0C;
-    SDP.HplMsp430Usart -> HplMsp430Usart0C;
-    SDP.HplMsp430UsartInterrupts -> HplMsp430Usart0C;
+  SDP.Usart -> Msp430Usart0C;
+  SDP.DockInterrupt  -> HplMsp430InterruptP.Port25;
+  SDP.Leds       -> LedsC;
 }
index e0eeb9c72b95a7028ed50bdef826e96714007bad..407ba48763874da46db51d89acc921ded3f54db2 100644 (file)
@@ -3,7 +3,7 @@
 * REPRESENTATIONS, EITHER EXPRESS, IMPLIED OR STATUTORY, 
 * INCLUDING ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS 
 * FOR A PARTICULAR PURPOSE, LACK OF VIRUSES, ACCURACY OR 
-* COMPLETENESS OF RESPONSES, RESULTS AND LACK OF NEGLIGENCE.           
+* COMPLETENESS OF RESPONSES, RESULTS AND LACK OF NEGLIGENCE. 
 * TI DISCLAIMS ANY WARRANTY OF TITLE, QUIET ENJOYMENT, QUIET 
 * POSSESSION, AND NON-INFRINGEMENT OF ANY THIRD PARTY 
 * INTELLECTUAL PROPERTY RIGHTS WITH REGARD TO THE PROGRAM OR 
  *
  * functional pieces based upon or copied from Texas Instruments sample code
  *
- */
- /**                                   
- * @author Steve Ayer
- * @author Konrad Lorincz
- * @date March 25, 2008 - ported to TOS 2.x
+ * @author  Steve Ayer
+ * @date    May 2006
+ * @date    July 2009  (extensive rework, tep conformance)
+ * @author  Konrad Lorincz  (initial port to tos-2)
+ * @date    March 25, 2008
  */
 
 #include "SD.h"
+#include "msp430usart.h"
 
-module SDP 
-{
-    provides interface SD;
-
-    uses interface Boot;
-    uses interface HplMsp430Usart;
-    uses interface HplMsp430UsartInterrupts;
+module SDP {
+  provides {
+    interface StdControl;
+    interface SD;
+  }
+  uses {
+    interface HplMsp430Usart as Usart;
+    interface HplMsp430Interrupt as DockInterrupt;
+    interface Leds;
+  }
 }
-implementation 
-{                                                                      
 
-#define SPI_TX_DONE        while(call HplMsp430Usart.isTxEmpty() == FALSE);
+implementation {
+  error_t cardInit();
+  
+#define SPI_TX_DONE        while(call Usart.isTxEmpty() == FALSE);
 
 #define CS_LOW()    TOSH_CLR_SD_CS_N_PIN();              // Card Select
 #define CS_HIGH()   SPI_TX_DONE; TOSH_SET_SD_CS_N_PIN();
 
-    async event void HplMsp430UsartInterrupts.txDone()             {/*do nothing*/}
-    async event void HplMsp430UsartInterrupts.rxDone(uint8_t data) {/*do nothing*/}
+  /* 
+   * this routine is supposed to prevent windows from locking up when 
+   * the device is docked.
+   */
+  void powerCycle() {
+    // wait until the tx buf is clear before killing the card
+    CS_HIGH();
 
+    // this connects the path from mcu to card
+    TOSH_MAKE_DOCK_N_OUTPUT();
+    TOSH_SET_DOCK_N_PIN();
 
-  // This is from TOS 1.x!
-  void setModeSPI()
-  {
-      // call USARTControl.disableUART();
-      atomic ME1 &= ~(UTXE0 | URXE0);   // USART0 UART module enable
-      TOSH_SEL_UTXD0_IOFUNC();
-      TOSH_SEL_URXD0_IOFUNC();
+    TOSH_SET_SW_SD_PWR_N_PIN();    
+    TOSH_CLR_SD_CS_N_PIN();             
 
-      //call USARTControl.disableI2C();
-      //#ifdef __msp430_have_usart0_with_i2c
-      //if (call USARTControl.isI2C())
-        atomic U0CTL &= ~(I2C | I2CEN | SYNC);
-      //#endif
+    /* 
+     * here we have to clear all input pins to the card, as
+     * the card in spi mode will leech power from any pin
+     */
+    call Usart.disableSpi();
+    TOSH_CLR_SD_DI_PIN();
+    TOSH_CLR_SD_DO_PIN();
+    TOSH_CLR_SD_CLK_PIN();
 
+    TOSH_uwait(60000);  
 
-    atomic {
-      TOSH_SEL_SIMO0_MODFUNC();
-      TOSH_SEL_SOMI0_MODFUNC();
-      TOSH_SEL_UCLK0_MODFUNC();
+    TOSH_SET_SD_CS_N_PIN();             
+    TOSH_CLR_SW_SD_PWR_N_PIN();    
 
-      IE1 &= ~(UTXIE0 | URXIE0);  // interrupt disable    
+    // undo the override above
+    TOSH_MAKE_DOCK_N_INPUT();
+  }
+    
+  command error_t StdControl.start(){
+    TOSH_CLR_SW_SD_PWR_N_PIN();    // powers up module on models so equipped
+
+    /* 
+     * this pin, when low, tells us that the sd card is unavailable to the processor
+     * it should be attached to a pullup unless platform has a docking pin doing an sd override;
+     * generally, we need to avoid talking to the sd with the mcu when the pin is low;
+     * if it's low now, we'll fire an interrupt when the sd is available to software.
+     */
+    if(!TOSH_READ_DOCK_N_PIN()){
+      call DockInterrupt.edge(TRUE);    // watch for it to go high, off the dock
+      powerCycle();
+      signal SD.unavailable();
+    }
+    else{
+      call DockInterrupt.edge(FALSE);    // tell us when we're docked
 
-      U0CTL = SWRST;
-      U0CTL |= CHAR | SYNC | MM;  // 8-bit char, SPI-mode, USART as master
-      U0CTL &= ~(0x20); 
+      cardInit();
 
-      U0TCTL = STC ;     // 3-pin
-      U0TCTL |= CKPH;    // half-cycle delayed UCLK
+      signal SD.available();
+    }
 
-      // call USARTControl.setClockSource(SSEL_SMCLK)
-      U0TCTL &= ~(SSEL_0 | SSEL_1 | SSEL_2 | SSEL_3);
-      U0TCTL |= (SSEL_SMCLK & 0x7F); 
+    call DockInterrupt.enable();
+    call DockInterrupt.clear();
+    
+    return SUCCESS;
+  }
 
-      // call USARTControl.setClockRate(UBR_SMCLK_115200, UMCTL_SMCLK_115200);
-      // UBR_SMCLK_115200=0x0009, UMCTL_SMCLK_115200=0x10,
-      U0BR0 = 0x0009 & 0x0FF;
-      U0BR1 = ((0x0009) >> 8) & 0x0FF;
-      U0MCTL = 0x10;
+  command error_t StdControl.stop(){
+    TOSH_SET_SW_SD_PWR_N_PIN();    // powers down module
+    TOSH_CLR_SD_CS_N_PIN();
 
-      ME1 &= ~(UTXE0 | URXE0); //USART UART module disable
-      ME1 |= USPIE0;   // USART SPI module enable
-      U0CTL &= ~SWRST;  
+    call DockInterrupt.disable();
+    call DockInterrupt.clear();
 
-      IFG1 &= ~(UTXIFG0 | URXIFG0);
-      IE1 &= ~(UTXIE0 | URXIE0);  // interrupt disabled    
+    return SUCCESS;
+  }
+
+  async event void DockInterrupt.fired() {
+    if (call DockInterrupt.getValue() == TRUE){      // off the dock
+      cardInit();
+
+      call DockInterrupt.edge(FALSE);
+      signal SD.available();                         // tell the app that it can talk to the sd card
+    }
+    else{
+      call DockInterrupt.edge(TRUE);      
+      signal SD.unavailable();                         // tell the app to stop talking to the card
+      powerCycle();
     }
+    call DockInterrupt.clear();
   }
 
-  // setup usart1 in spi mode
   void initSPI() {
+    msp430_spi_union_config_t * config;
+
     TOSH_MAKE_SD_CS_N_OUTPUT();
     TOSH_SEL_SD_CS_N_IOFUNC();
 
-    // call USARTControl.setClockSource(SSEL_SMCLK);
-    // call USARTControl.setClockRate(UBR_SMCLK_115200, UMCTL_SMCLK_115200);
-    // call USARTControl.setModeSPI();
-    setModeSPI();  // the above 3 commands are implemented in this call
+    config = &msp430_spi_default_config;
+    
+    call Usart.setModeSpi(config);
+
+    /*
+     * set the clock to 115200 for sd init, default is smclk / 2
+     * cardInit raises speed back to 512k at end of init routine
+     */
+    call Usart.setUbr(UBR_1MHZ_115200);
+    call Usart.setUmctl(UMCTL_1MHZ_115200);
+
+    call Usart.enableRxIntr();
 
     TOSH_SET_SD_CS_N_PIN();
 
-    while(call HplMsp430Usart.isTxEmpty() == FALSE);
+    while(call Usart.isTxEmpty() == FALSE);
   }
 
   uint8_t spiSendByte (const uint8_t data){
     atomic{
-      while(call HplMsp430Usart.isTxEmpty() == FALSE);   
-
-      call HplMsp430Usart.tx(data);
-
-      while(call HplMsp430Usart.isRxIntrPending() == FALSE);    // rx buffer has a character
+      while(call Usart.isTxEmpty() == FALSE);   
+      
+      call Usart.tx(data);
+      
+      while(call Usart.isRxIntrPending() == FALSE);    // rx buffer has a character
     }
     
-    return call HplMsp430Usart.rx();
+    return call Usart.rx();
   }
-    
+  
   void sendCmd(const uint8_t cmd, uint32_t data, const uint8_t crc){
     uint8_t frame[6];
     register int8_t i;
@@ -238,7 +286,7 @@ implementation
     for(i = 0; i < 65; i++){
       response = spiSendByte(0xff);
       response &= 0x1f;
-
+      
       switch(response){
       case 0x05: 
        rvalue = MMC_SUCCESS;
@@ -266,7 +314,7 @@ implementation
     return response;
   }
 
-  mmcerror_t SD_setIdle() {
+  error_t setIdle(){
     char response;
     CS_LOW();
 
@@ -290,8 +338,9 @@ implementation
     return MMC_SUCCESS;
   }
 
-  mmcerror_t SD_init() {
+  error_t cardInit(){
     register uint8_t i;
+    uint8_t r;
 
     initSPI();
 
@@ -300,25 +349,25 @@ implementation
     for(i = 0; i < 10; i++)
       spiSendByte(0xff);
     
-    return SD_setIdle();
-  }
+    r = setIdle();
 
-    event void Boot.booted()
-    {
-        SD_init();
-    }
+    // here's where we set the clock speed up to smclk / 2 (512k)
+    
+    call Usart.setUbr(0x0002);
+    call Usart.setUmctl(0x00);
 
+    return r;
+  }
 
-  // we don't have pin for this one yet; it uses cd pin, which we don't have wired in mock-up
   // change block length to 2^len bytes; default is 512
-  mmcerror_t SD_setBlockLength (const uint16_t len) {
+  error_t setBlockLength (const uint16_t len) {
     CS_LOW ();
 
     sendCmd(MMC_SET_BLOCKLEN, len, 0xff);
 
     // get response from card, should be 0; so, shouldn't this be 'while'?
     if(getResponse() != 0x00){
-      SD_init();
+      cardInit();
       sendCmd(MMC_SET_BLOCKLEN, len, 0xff);
       getResponse();
     }
@@ -331,16 +380,19 @@ implementation
     return MMC_SUCCESS;
   }
     
-
-  // see macro in module for writing to a sector instead of an address
-  mmcerror_t SD_readBlock(const uint32_t address, const uint16_t count, uint8_t * buffer){
+  /* 
+   * renamed to clear the way for renaming what was readSector -- which called this -- 
+   * to be renamed readBlock.  --sma
+   */
+  
+  error_t read_block(const uint32_t address, const uint16_t count, uint8_t * buffer){
     register uint16_t i = 0;
     uint8_t rvalue = MMC_RESPONSE_ERROR;
-
+    
     // Set the block length to read
-    if(SD_setBlockLength(count) == MMC_SUCCESS){   // block length can be set
+    if(setBlockLength(count) == MMC_SUCCESS){   // block length can be set
       CS_LOW ();
-
+      
       sendCmd(MMC_READ_SINGLE_BLOCK, address, 0xff);
       // Send 8 Clock pulses of delay, check if the MMC acknowledged the read block command
       // it will do this by sending an affirmative response
@@ -348,11 +400,11 @@ implementation
       if(getResponse() == 0x00){
        // now look for the data token to signify the start of the data
        if(getXXResponse(MMC_START_DATA_BLOCK_TOKEN) == MMC_START_DATA_BLOCK_TOKEN){
-
+         
          // clock the actual data transfer and receive the bytes; spi_read automatically finds the Data Block
          for (i = 0; i < count; i++)
            buffer[i] = spiSendByte(0xff);   // is executed with card inserted
-
+         
          // get CRC bytes (not really needed by us, but required by MMC)
          spiSendByte(0xff);
          spiSendByte(0xff);
@@ -371,20 +423,30 @@ implementation
     else{
       rvalue = MMC_BLOCK_SET_ERROR;           // 1
     }
-
+    
     CS_HIGH ();
     spiSendByte(0xff);
-
+    
     return rvalue;
   }
 
-  mmcerror_t SD_writeBlock(const uint32_t address, const uint16_t count, uint8_t * buffer){
+  /*
+   * need to test dock pin for some platforms
+   * on others this will be attached to a pullup
+   */
+  command error_t SD.readBlock(const uint32_t sector, uint8_t * buffer) {
+    if(!TOSH_READ_DOCK_N_PIN())
+      return MMC_INIT_ERROR;
+
+    return read_block(sector * 512, 512, buffer);
+  }
+
+  error_t write_block(const uint32_t address, const uint16_t count, uint8_t * buffer){
     register uint16_t i;
     uint8_t rvalue = MMC_RESPONSE_ERROR;         // MMC_SUCCESS;
 
     // Set the block length to write
-    if(SD_setBlockLength (count) == MMC_SUCCESS){   // block length could be set
-      //      call Leds.yellowOn();
+    if(setBlockLength (count) == MMC_SUCCESS){   // block length could be set
       CS_LOW ();
       sendCmd(MMC_WRITE_BLOCK, address, 0xff);
 
@@ -420,63 +482,48 @@ implementation
     CS_HIGH ();
     // Send 8 Clock pulses of delay.
     spiSendByte(0xff);
-    //    call Leds.greenOn();
-    return rvalue;
-  }
 
-  command error_t SD.readBlock(const uint32_t sector, void *bufferPtr)
-  {
-    mmcerror_t mmcerror = SD_readBlock(sector * 512, 512, bufferPtr);
-    if (mmcerror == MMC_SUCCESS)
-      return SUCCESS;
-    else
-      return FAIL;
+    return rvalue;
   }
 
+  command error_t SD.writeBlock(const uint32_t sector, uint8_t * buffer){
+    /*
+     * need to test dock pin for some platforms
+     * on others this will be attached to a pullup
+     */
+    if(!TOSH_READ_DOCK_N_PIN())
+      return MMC_INIT_ERROR;
 
-  command error_t SD.writeBlock(const uint32_t sector, void *bufferPtr)
-  {
-    mmcerror_t mmcerror = SD_writeBlock(sector * 512, 512, bufferPtr);
-    if (mmcerror == MMC_SUCCESS)
-      return SUCCESS;
-    else
-      return FAIL;
+    return write_block(sector * 512, 512, buffer);
   }
 
-
-  // register read of length len into buffer
-  mmcerror_t SD_readRegister(const uint8_t reg, const uint8_t len, uint8_t * buffer){
-    uint8_t uc, rvalue = MMC_TIMEOUT_ERROR;
-
-    if((SD_setBlockLength (len)) == MMC_SUCCESS){
-      CS_LOW ();
-      // CRC not used: 0xff as last byte
-      sendCmd(reg, 0x000000, 0xff);
-
-      // wait for response
-      // in the R1 format (0x00 is no errors)
-      if(getResponse() == 0x00){
-       if(getXXResponse(0xfe) == 0xfe)
-         for(uc = 0; uc < len; uc++)
-           buffer[uc] = spiSendByte(0xff);  
-
-       // get CRC bytes (not really needed by us, but required by MMC)
-       spiSendByte(0xff);
-       spiSendByte(0xff);
-       rvalue = MMC_SUCCESS;
+  /*
+   * feel our way out over the cliff of the card to estimate the size
+   * turns out cmd9 is not supported on sdio, as there's no csd register
+   */
+  uint32_t hackGetCardSize() {
+    uint32_t howbig = 0;
+    uint8_t b[512];
+    error_t failed;
+    
+    /* we'll estimate based upon popular sizes of cards, e.g. 128mb, 256 mb, 512mb, 1gb, 2gb
+     * experimentally, we find that 512mb == ~990900 sectors, 1gb == ~1983000 sectors
+     * extrapolating down, we'll say that 247700 should be readable on a 128mb
+     * reading beyond that returns an error
+     */
+
+    failed = call SD.readBlock(0, b);
+    failed = call SD.readBlock(200000, b);
+    // if we can't get this far, we're toast anyway
+    if(!failed){
+      howbig = 247000;
+      while(!call SD.readBlock(howbig, b)){
+       howbig = howbig * 2;
       }
-      else
-       rvalue = MMC_RESPONSE_ERROR;
-
-      CS_HIGH ();
-
-      // Send 8 Clock pulses of delay.
-      spiSendByte(0xff);
+      howbig = howbig / 2;
     }
-    CS_HIGH ();
-
-    return rvalue;
-  } 
+    return howbig;
+  }
 
   // Read the Card Size from the CSD Register
   // this command is unsupported on sdio-only, like sandisk micro sd cards
@@ -487,6 +534,8 @@ implementation
     uint16_t i, j, b, response, mmc_C_SIZE;
     uint8_t mmc_READ_BL_LEN, mmc_C_SIZE_MULT;
 
+    //    return hackGetCardSize();
+    
     CS_LOW ();
 
     spiSendByte(MMC_READ_CSD);   // CMD 9
@@ -562,4 +611,3 @@ implementation
   }
 
 }
-
index d4769930ca60fe01e4f746df0170e3618712a0d2..e3008caa66c05912ce675260eb98decca784deff 100644 (file)
 
 #include "msp430hardware.h"
 
-#define SHIMMER 1
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = MSP430_POWER_ACTIVE,
+};
 
 // LEDs
 TOSH_ASSIGN_PIN(RED_LED,    4, 0);
@@ -56,16 +60,21 @@ TOSH_ASSIGN_PIN(RADIO_1V8_EN,    4, 7);
 TOSH_ASSIGN_PIN(RADIO_VREF,      5, 6);    // unused in shimmer
 TOSH_ASSIGN_PIN(SW_BT_PWR_N,     5, 6);    //   "    "    "
 TOSH_ASSIGN_PIN(SW_SD_PWR_N,     5, 6);    //   "    "    "
+TOSH_ASSIGN_PIN(DOCK_N,          2, 5);    // not used, but has to be a pull-up for sd card to work
 
 TOSH_ASSIGN_PIN(RADIO_SFD,       5, 0);
 TOSH_ASSIGN_PIN(RADIO_SIMO1,     5, 1);
 TOSH_ASSIGN_PIN(RADIO_SOMI1,     5, 2);
 TOSH_ASSIGN_PIN(RADIO_CSN,       5, 4);
-TOSH_ASSIGN_PIN(CSN,       5, 4);
+TOSH_ASSIGN_PIN(CSN,             5, 4);
 TOSH_ASSIGN_PIN(RADIO_RESET,     5, 7);
 
+// redefinitions for the sd card driver
+TOSH_ASSIGN_PIN(SD_CLK, 3, 3);
+TOSH_ASSIGN_PIN(SD_DO, 3, 2);
+TOSH_ASSIGN_PIN(SD_DI, 3, 1);
 
-// Don't think these are needed
+// this happens in hplcc2420pinsc
 TOSH_ASSIGN_PIN(CC_FIFOP, 2, 6);
 TOSH_ASSIGN_PIN(CC_FIFO, 1, 0);
 TOSH_ASSIGN_PIN(CC_SFD, 1, 2);
@@ -143,174 +152,7 @@ TOSH_ASSIGN_PIN(ACCEL_SEL0,  4, 4);
 TOSH_ASSIGN_PIN(ACCEL_SEL1,  4, 5);
 TOSH_ASSIGN_PIN(ACCEL_SLEEP_N, 4, 6);
 
-void TOSH_SET_PIN_DIRECTIONS(void)
-{
-  //LEDS
-  TOSH_MAKE_RED_LED_OUTPUT();
-  TOSH_MAKE_YELLOW_LED_OUTPUT();
-  TOSH_MAKE_ORANGE_LED_OUTPUT();
-  TOSH_MAKE_GREEN_LED_OUTPUT();
-  TOSH_SEL_RED_LED_IOFUNC();
-  TOSH_SEL_YELLOW_LED_IOFUNC();
-  TOSH_SEL_ORANGE_LED_IOFUNC();
-  TOSH_SEL_GREEN_LED_IOFUNC();
 
-  //RADIO PINS
-  //CC2420 pins
-  TOSH_MAKE_RADIO_CSN_OUTPUT();
-  TOSH_SEL_RADIO_CSN_IOFUNC();
-  TOSH_SET_RADIO_CSN_PIN();
-
-  TOSH_MAKE_CSN_OUTPUT();
-  TOSH_SEL_CSN_IOFUNC();
-  TOSH_SET_CSN_PIN();
-
-  // should be reset_n
-  TOSH_MAKE_RADIO_RESET_OUTPUT();
-  TOSH_SEL_RADIO_RESET_IOFUNC();
-  TOSH_CLR_RADIO_RESET_PIN();
-
-  TOSH_MAKE_RADIO_1V8_EN_OUTPUT();
-  TOSH_SEL_RADIO_1V8_EN_IOFUNC();
-  TOSH_CLR_RADIO_1V8_EN_PIN();
-
-  TOSH_MAKE_RADIO_CCA_INPUT();
-  TOSH_MAKE_RADIO_FIFO_INPUT();
-  TOSH_MAKE_RADIO_FIFOP_INPUT();
-  TOSH_MAKE_RADIO_SFD_INPUT();
-  TOSH_SEL_RADIO_CCA_IOFUNC();
-  TOSH_SEL_RADIO_FIFO_IOFUNC();
-  TOSH_SEL_RADIO_FIFOP_IOFUNC();
-  TOSH_SEL_RADIO_SFD_IOFUNC();
-
-  TOSH_MAKE_ONEWIRE_PWR_OUTPUT();
-  TOSH_SET_ONEWIRE_PWR_PIN();
-
-  TOSH_SEL_SD_CS_N_IOFUNC();
-  TOSH_MAKE_SD_CS_N_OUTPUT();
-  TOSH_SET_SD_CS_N_PIN();
-
-  // BT PINS
-  TOSH_MAKE_BT_RESET_OUTPUT();  
-  TOSH_SEL_BT_RESET_IOFUNC();    
-  TOSH_CLR_BT_RESET_PIN();   // mitsumi module disabled by clr
-
-  TOSH_MAKE_BT_RTS_INPUT();      
-  TOSH_SEL_BT_RTS_IOFUNC();
-
-  TOSH_MAKE_BT_PIO_INPUT();
-  TOSH_SEL_BT_PIO_IOFUNC();
-
-  TOSH_MAKE_BT_CTS_OUTPUT();
-  TOSH_SEL_BT_CTS_IOFUNC();
-
-  TOSH_MAKE_BT_TXD_OUTPUT();
-  TOSH_SEL_BT_TXD_MODFUNC();
-
-  TOSH_MAKE_BT_RXD_INPUT();
-  TOSH_SEL_BT_RXD_MODFUNC();
-
-  // BSL Prog Pins tristate em
-  TOSH_MAKE_PROG_IN_OUTPUT();
-  TOSH_MAKE_PROG_OUT_OUTPUT();
-  TOSH_SEL_PROG_IN_IOFUNC();
-  TOSH_SEL_PROG_OUT_IOFUNC();
-
-  // USART lines, attached to a pullup
-  TOSH_SEL_UCLK0_IOFUNC();
-  TOSH_MAKE_UCLK0_OUTPUT();
-  TOSH_SET_UCLK0_PIN();
-  TOSH_SEL_UCLK1_IOFUNC();
-  TOSH_MAKE_UCLK1_OUTPUT();
-  TOSH_SET_UCLK1_PIN();
-
-  TOSH_SEL_SIMO0_IOFUNC();
-  TOSH_MAKE_SIMO0_OUTPUT();
-  TOSH_SET_SIMO0_PIN();
-  TOSH_SEL_SOMI0_IOFUNC();
-  TOSH_MAKE_SOMI0_INPUT();
-
-  TOSH_SEL_SIMO1_IOFUNC();
-  TOSH_MAKE_SIMO1_OUTPUT();
-  TOSH_SET_SIMO1_PIN();
-  TOSH_SEL_SOMI1_IOFUNC();
-  TOSH_MAKE_SOMI1_INPUT();
-
-  // ADC lines
-  TOSH_MAKE_ADC_0_OUTPUT();
-  TOSH_MAKE_ADC_1_OUTPUT();
-  TOSH_MAKE_ADC_2_OUTPUT();
-  TOSH_MAKE_ADC_6_OUTPUT();
-  TOSH_MAKE_ADC_7_OUTPUT();
-
-  TOSH_SEL_ADC_0_IOFUNC();
-  TOSH_SEL_ADC_1_IOFUNC();
-  TOSH_SEL_ADC_2_IOFUNC();
-  TOSH_SEL_ADC_6_IOFUNC();
-  TOSH_SEL_ADC_7_IOFUNC();
-  
-  TOSH_MAKE_ADC_ACCELZ_INPUT();
-  TOSH_MAKE_ADC_ACCELY_INPUT();
-  TOSH_MAKE_ADC_ACCELX_INPUT();
-  TOSH_SEL_ADC_ACCELZ_MODFUNC();
-  TOSH_SEL_ADC_ACCELY_MODFUNC();
-  TOSH_SEL_ADC_ACCELX_MODFUNC();
-  
-  TOSH_SEL_ROSC_IOFUNC();
-  TOSH_MAKE_ROSC_INPUT();
-
-  // DAC lines
-  // Default is not to use DAC mode.  Please define pin usage if you want to use them
-    
-  // UART pins
-  // These declarations are to allow the UART module to work since it's using the names.
-  // The UART module will set them to the right direction when initialized
-
-  // ftdi/gio pins.  Unused for now so we do not set directionality or function
-
-
-  // 1-wire function
-  TOSH_MAKE_ONEWIRE_PWR_OUTPUT();
-  TOSH_SEL_ONEWIRE_PWR_IOFUNC();
-  TOSH_MAKE_ONEWIRE_INPUT();
-  TOSH_SEL_ONEWIRE_IOFUNC();
-
-  // Accelerometer pin definitions
-  TOSH_SEL_ACCEL_SEL0_IOFUNC();
-  TOSH_SEL_ACCEL_SEL1_IOFUNC();
-  TOSH_SEL_ACCEL_SLEEP_N_IOFUNC();
-  
-  TOSH_MAKE_ACCEL_SEL0_OUTPUT();
-  TOSH_MAKE_ACCEL_SEL1_OUTPUT();
-  TOSH_MAKE_ACCEL_SLEEP_N_OUTPUT();
-
-  /*
-   * unless the accel_sel0 pin is cleared, 
-   * a severe quiescent power hit occurs on the msp430
-   * we go from 3.7 ua to 65.1 ua when asleep!
-   */
-  TOSH_CLR_ACCEL_SEL0_PIN();
-  TOSH_CLR_ACCEL_SEL1_PIN();
-  TOSH_CLR_ACCEL_SLEEP_N_PIN();
-
-
-  // idle expansion header pins
-  TOSH_MAKE_SER0_CTS_OUTPUT();
-  TOSH_SEL_SER0_CTS_IOFUNC();
-  TOSH_MAKE_SER0_RTS_OUTPUT();
-  TOSH_SEL_SER0_RTS_IOFUNC();
-  TOSH_MAKE_GIO0_INPUT();
-  TOSH_SEL_GIO0_IOFUNC();
-  TOSH_MAKE_GIO1_OUTPUT();
-  TOSH_SEL_GIO1_IOFUNC();
-  TOSH_MAKE_UTXD0_OUTPUT();
-  TOSH_SEL_UTXD0_IOFUNC();
-  TOSH_MAKE_URXD0_OUTPUT();
-  TOSH_SEL_URXD0_IOFUNC();
-  TOSH_MAKE_RADIO_VREF_OUTPUT();
-  TOSH_SEL_RADIO_VREF_IOFUNC();
-
-}
 
 #endif // _H_hardware_h
 
diff --git a/tos/platforms/shimmer/shimmerMessage.h b/tos/platforms/shimmer/shimmerMessage.h
new file mode 100644 (file)
index 0000000..d1851cb
--- /dev/null
@@ -0,0 +1,382 @@
+/**
+ * Copyright (c) 2004,2005 Hewlett-Packard Company
+ * All rights reserved
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ *       copyright notice, this list of conditions and the following
+ *       disclaimer in the documentation and/or other materials provided
+ *       with the distribution.
+ *     * Neither the name of the Hewlett-Packard Company nor the names of its
+ *       contributors may be used to endorse or promote products derived
+ *       from this software without specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Simple message format for exchanging network data.
+ * We use the 'start' index to allow messages to have data
+ * prepended.
+ *
+ * Each message contains a 'next' field, which allows us
+ * to maintain queues.
+ *
+ * Note that we encode 16 and 32 bit values in network byte
+ * order, which is MSB (most significant byte) first.
+ *
+ * However, 802.15.4 multibyte fields are always encoded LSB,
+ * or least significant byte first.  The Chipcon radio also
+ * stores values LSB, as does the TI MSP processor.
+ * This really only shows up when we are setting the PanID and
+ * short address of our messages.
+ * 
+ * @author Andrew Christian
+ */
+
+#ifndef _MESSAGE_H
+#define _MESSAGE_H
+
+
+#define MESSAGE_MAX_LENGTH 128
+
+struct Message {
+  uint8_t data[ MESSAGE_MAX_LENGTH ];
+  uint8_t start;
+  uint8_t length;
+  struct Message *next;
+};
+
+/*
+ * this is useful for tracking down allocs w/out frees.  add a uint8_t who to the Message structure and then see who holds
+ * all the messages using param...
+#ifdef DEBUG_MESSAGE
+enum {
+  MSG_WHO_FREE=0,
+  MSG_WHO_CLIENT_HAWR,
+  MSG_WHO_CLIENT_HSNOOZET,
+  MSG_WHO_CLIENT_AR,
+  MSG_WHO_CLIENT_HSCANT,
+  MSG_WHO_CC2420H_DELAYEDRXFIFO,
+  MSG_WHO_UIP_SENDMESSAGE,
+  MSG_WHO_UIP_SENDUDPMESSAGE  
+};
+#endif
+*/
+
+
+/**
+ * Message manipulation functions.
+ *
+ * All integers are sent in network byte order - MSB first
+ */
+
+inline void msg_set_uint8( struct Message *msg, uint8_t offset, uint8_t data )
+{
+  uint8_t i = msg->start + offset;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[ i] = data;
+}
+
+inline void msg_set_uint16( struct Message *msg, uint8_t offset, uint16_t data )
+{
+  uint8_t i = msg->start + offset;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff00) >> 8;
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff);
+}
+
+inline void msg_set_saddr( struct Message *msg, uint8_t offset, uint16_t data )
+{
+  uint8_t i = msg->start + offset;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff);
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff00) >> 8;
+}
+
+inline void msg_set_uint32( struct Message *msg, uint8_t offset, uint32_t data )
+{
+  uint8_t i = msg->start + offset;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff000000) >> 24;
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0x00ff0000) >> 16;
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0x0000ff00) >> 8;
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff);
+}
+
+inline void msg_set_buf( struct Message *msg, uint8_t offset, const uint8_t *buf, uint8_t len )
+{
+  uint8_t i = msg->start + offset;
+  for ( ; len ; len--, i++ ) {
+    if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+    msg->data[i] = *buf++;
+  }
+}
+
+inline uint8_t msg_get_uint8( const struct Message *msg, uint8_t offset )
+{
+  uint8_t i = msg->start + offset;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  return msg->data[ i ];
+}
+
+inline int8_t msg_get_int8( const struct Message *msg, uint8_t offset )
+{
+  uint8_t i = msg->start + offset;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  return ((int8_t *)(msg->data))[ i ];
+}
+
+inline uint16_t msg_get_uint16( const struct Message *msg, uint8_t offset )
+{
+  uint8_t i = msg->start + offset;
+  uint16_t result;
+
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  result = (msg->data[i] << 8);
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  result |= msg->data[i];
+  return result;
+}
+
+inline uint16_t msg_get_saddr( const struct Message *msg, uint8_t offset )
+{
+  uint8_t i = msg->start + offset;
+  uint16_t result;
+
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  result = msg->data[i];
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  result |= (msg->data[i] << 8);
+  return result;
+}
+
+inline void msg_get_buf( const struct Message *msg, uint8_t offset, uint8_t *buf, uint8_t len )
+{
+  uint8_t i = msg->start + offset;
+  for ( ; len ; len--, i++ ) {
+    if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+    *buf++ = msg->data[i];
+  }
+}
+
+inline void msg_get_str( const struct Message *msg, uint8_t offset, uint8_t *str, uint8_t len )
+{
+  uint8_t i = msg->start + offset;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+
+  while (--len && msg->data[i] ) {
+    *str++ = msg->data[i++];
+    if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  }
+
+  *str = 0;
+}
+
+inline bool msg_cmp_buf( const struct Message *msg, uint8_t offset, const uint8_t *buf, uint8_t len )
+{
+  uint8_t i = msg->start + offset;
+  for ( ; len ; len--, i++ ) {
+    if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+    if ( *buf++ != msg->data[i])
+      return FALSE;
+  }
+  return TRUE;
+}
+
+inline bool msg_cmp_str( const struct Message *msg, uint8_t offset, const uint8_t *buf )
+{
+  uint8_t i = msg->start + offset;
+  while (1) {
+    if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+    if ( *buf++ != msg->data[i])
+      return FALSE;
+    if ( msg->data[i] == 0 )
+      return TRUE;
+    i++;
+  }
+  return TRUE;
+}
+
+inline void msg_append_uint8( struct Message *msg, uint8_t data )
+{
+  uint8_t i = msg->start + msg->length;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  
+  msg->data[ i ] = data;
+  msg->length++;
+}
+
+inline void msg_append_uint16( struct Message *msg, uint16_t data )
+{
+  uint8_t i = msg->start + msg->length;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff00) >> 8;
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff);
+  msg->length += 2;
+}
+
+inline void msg_append_saddr( struct Message *msg, uint16_t data )
+{
+  uint8_t i = msg->start + msg->length;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff);
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff00) >> 8;
+  msg->length += 2;
+}
+
+inline void msg_append_uint32( struct Message *msg, uint32_t data )
+{
+  uint8_t i = msg->start + msg->length;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff000000) >> 24;
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0x00ff0000) >> 16;
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0x0000ff00) >> 8;
+  if ( ++i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = (data & 0xff);
+  msg->length += 4;
+}
+
+inline void msg_append_buf( struct Message *msg, const uint8_t *buf, uint8_t len )
+{
+  uint8_t i = msg->start + msg->length;
+  msg->length += len;
+  for ( ; len ; len--, i++ ) {
+    if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+    msg->data[i] = *buf++;
+  }
+}
+
+inline void msg_append_str( struct Message *msg, const uint8_t *str )
+{
+  uint8_t i = msg->start + msg->length;
+  for ( ; *str ; i++ ) {
+    if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+    msg->data[i] = *str++;
+    msg->length++;
+  }
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  msg->data[i] = 0;
+  msg->length++;
+}
+
+inline void msg_prepend_uint8( struct Message *msg, uint8_t data )
+{
+  msg->length++;
+  if ( msg->start == 0 )
+    msg->start = MESSAGE_MAX_LENGTH - 1;
+  else
+    msg->start--;
+
+  msg->data[ msg->start ] = data;
+}
+
+inline void msg_add_to_front( struct Message *msg, uint8_t count )
+{
+  if ( msg->start < count )
+    msg->start = MESSAGE_MAX_LENGTH - count + msg->start;
+  else
+    msg->start -= count;
+  msg->length += count;
+}
+
+inline void msg_drop_from_front( struct Message *msg, uint8_t count )
+{
+  msg->start  += count;
+  if ( msg->start >= MESSAGE_MAX_LENGTH ) msg->start -= MESSAGE_MAX_LENGTH;
+  msg->length -= count;
+}
+
+inline void msg_add_to_end( struct Message *msg, uint8_t count )
+{
+  msg->length += count;
+}
+
+inline void msg_drop_from_end( struct Message *msg, uint8_t count )
+{
+  msg->length -= count;
+}
+
+inline uint8_t * msg_get_pointer( struct Message *msg, uint8_t offset )
+{
+  uint8_t i = msg->start + offset;
+  if ( i >= MESSAGE_MAX_LENGTH ) i -= MESSAGE_MAX_LENGTH;
+  return msg->data + i;
+}
+
+inline void msg_clear( struct Message *msg )
+{
+  msg->length = 0;
+  msg->start  = 0;
+}
+
+inline void    msg_set_length( struct Message *msg, uint8_t len )  { msg->length = len; }
+inline uint8_t msg_get_length( const struct Message *msg )         { return msg->length; }
+inline uint8_t msg_get_max_length( void )         { return MESSAGE_MAX_LENGTH; }
+
+/**
+ * Message queue functions.  Message queues are simple
+ * linked lists.
+ */
+
+inline struct Message * pop_queue( struct Message **head )
+{
+  struct Message *result = *head;
+  if ( result != NULL )
+    *head = (*head)->next;
+  return result;
+}
+
+inline void push_queue( struct Message **head, struct Message *item )
+{
+  item->next = *head;
+  *head = item;
+}
+
+inline void append_queue( struct Message **head, struct Message *item )
+{
+  if (*head == NULL) {
+    *head = item;
+  }
+  else {
+    struct Message *bm = *head;
+    while ( bm->next != NULL )
+      bm = bm->next;
+    bm->next = item;
+  }
+  item->next = NULL;
+}
+
+inline uint8_t count_queue( struct Message *head )
+{
+  uint8_t count = 0;
+  while ( head ) {
+    count++;
+    head = head->next;
+  }
+  return count;
+}
+
+#endif // _BASIC_MESSAGE_H
diff --git a/tos/platforms/shimmer2/.platform b/tos/platforms/shimmer2/.platform
new file mode 100644 (file)
index 0000000..df824e8
--- /dev/null
@@ -0,0 +1,85 @@
+# SHIMMER2 - platform includes
+# Steve Ayer, June 2009; derived from Konrad Lorincz's SHIMMER platform
+#
+# Includes that should take precedence come first.  Platforms come before
+# chips because they may override files.  These must be specified as
+# @includes instead of -I's to @opts, otherwise the %T won't be processed
+# by ncc.
+
+push( @includes, qw(
+
+      .
+  %T/platforms/shimmer2
+  %T/platforms/shimmer2/chips/msp430
+  %T/platforms/shimmer2/chips/cc2420
+  %T/platforms/shimmer2/chips/mma7260
+  %T/platforms/shimmer2/chips/sd
+  %T/platforms/shimmer2/chips/bluetooth
+  %T/platforms/shimmer2/chips/tilt
+  %T/platforms/shimmer
+  %T/platforms/shimmer/chips/msp430
+  %T/platforms/shimmer/chips/mma7260
+  %T/platforms/shimmer/chips/sd
+  %T/platforms/shimmer/chips/bluetooth
+  %T/chips/cc2420
+  %T/chips/cc2420/alarm
+  %T/chips/cc2420/control
+  %T/chips/cc2420/csma
+  %T/chips/cc2420/interfaces
+  %T/chips/cc2420/link
+  %T/chips/cc2420/lowpan
+  %T/chips/cc2420/lpl
+  %T/chips/cc2420/packet
+  %T/chips/cc2420/receive
+  %T/chips/cc2420/spi
+  %T/chips/cc2420/transmit
+  %T/chips/cc2420/unique
+  %T/chips/cc2420/security
+  %T/chips/msp430
+  %T/chips/msp430/adc12
+  %T/chips/msp430/dma
+  %T/chips/msp430/pins
+  %T/chips/msp430/timer
+  %T/chips/msp430/usart
+  %T/chips/msp430/sensors
+  %T/lib/timer
+  %T/lib/serial
+  %T/lib/adc
+  %T/lib/power
+  ) );
+
+@opts = qw(
+
+  -gcc=msp430-gcc
+  -mmcu=msp430x1611
+  -fnesc-target=msp430
+  -fnesc-no-debug
+);
+
+push @opts, "-fnesc-scheduler=TinySchedulerC,TinySchedulerC.TaskBasic,TaskBasic,TaskBasic,runTask,postTask" if !$with_scheduler_flag;
+push @opts, "-mingw-gcc" if $cygwin;
+
+$ENV{'CIL_MACHINE'} =
+    "version_major=3 " .
+    "version_minor=2 " .
+    "version=msp430-3.2.3 " .
+    "short=2,2 " .
+    "int=2,2 " .
+    "long=4,2 " .
+    "long_long=8,2 " .
+    "pointer=2,2 " .
+    "enum=2,2 " .
+    "float=4,2 " .
+    "double=4,2 " .
+    "long_double=4,2 " .
+    "void=1,1 " .
+    "fun=1,2 " .
+    "wchar_size_size=2,2 " .
+    "alignof_string=1 " .
+    "max_alignment=1 " .
+    "char_wchar_signed=true,true " .
+    "const_string_literals=true " .
+    "big_endian=false " .
+    "underscore_name=false " .
+    "__builtin_va_list=true " .
+    "__thread_is_keyword=true";
diff --git a/tos/platforms/shimmer2/ActiveMessageC.nc b/tos/platforms/shimmer2/ActiveMessageC.nc
new file mode 100644 (file)
index 0000000..0d22877
--- /dev/null
@@ -0,0 +1,77 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2004-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2004-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+/*
+ *
+ * Authors:            Philip Levis
+ * Date last modified:  $Id$
+ *
+ */
+/**
+ * The Active Message layer on the SHIMMER platform. This is a naming wrapper
+ * around the CC2420 Active Message layer.
+ *
+ * @author Konrad Lorincz
+ */
+#include "Timer.h"
+
+configuration ActiveMessageC {
+  provides {
+    interface SplitControl;
+
+    interface AMSend[uint8_t id];
+    interface Receive[uint8_t id];
+    interface Receive as Snoop[uint8_t id];
+
+    interface Packet;
+    interface AMPacket;
+    interface PacketAcknowledgements;
+    interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
+    interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+    interface LowPowerListening;
+  }
+}
+implementation {
+  components CC2420ActiveMessageC as AM;
+
+  SplitControl = AM;
+  
+  AMSend       = AM;
+  Receive      = AM.Receive;
+  Snoop        = AM.Snoop;
+  Packet       = AM;
+  AMPacket     = AM;
+  PacketAcknowledgements = AM;
+  LowPowerListening = AM;
+
+  components CC2420PacketC;
+  PacketTimeStamp32khz = CC2420PacketC;
+  PacketTimeStampMilli = CC2420PacketC;
+}
diff --git a/tos/platforms/shimmer2/HplUserButtonC.nc b/tos/platforms/shimmer2/HplUserButtonC.nc
new file mode 100644 (file)
index 0000000..13437d8
--- /dev/null
@@ -0,0 +1,57 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telos platform
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ *
+ * @author Mike Healy
+ * @date May 9, 2009 - modified for use with SHIMMER2
+ */
+
+configuration HplUserButtonC {
+  provides interface GeneralIO;
+  provides interface GpioInterrupt;
+}
+implementation {
+  components HplMsp430GeneralIOC as GeneralIOC;
+  components HplMsp430InterruptC as InterruptC;
+
+  components new Msp430GpioC() as UserButtonC;
+  UserButtonC -> GeneralIOC.Port20;
+  GeneralIO = UserButtonC;
+
+  components new Msp430InterruptC() as InterruptUserButtonC;
+  InterruptUserButtonC.HplInterrupt -> InterruptC.Port20;
+  GpioInterrupt = InterruptUserButtonC.Interrupt;
+}
diff --git a/tos/platforms/shimmer2/Leds.nc b/tos/platforms/shimmer2/Leds.nc
new file mode 100644 (file)
index 0000000..631b106
--- /dev/null
@@ -0,0 +1,125 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2005-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * Commands for controlling three LEDs. A platform can provide this
+ * interface if it has more than or fewer than three LEDs. In the
+ * former case, these commands refer to the first three LEDs. In the
+ * latter case, some of the commands are null operations, and the set
+ * of non-null operations must be contiguous and start at Led1. That
+ * is, on platforms with 2 LEDs, LED 3's commands are null operations,
+ * while on platforms with 1 LED, LED 2 and LED 3's commands are null
+ * opertations.
+ *
+ * @author Joe Polastre
+ * @author Philip Levis
+ *
+ */
+
+#include "Leds.h"
+
+interface Leds {
+
+  /**
+   * Turn on LED 0. The color of this LED depends on the platform.
+   */
+  async command void led0On();
+
+  /**
+   * Turn off LED 0. The color of this LED depends on the platform.
+   */
+  async command void led0Off();
+
+  /**
+   * Toggle LED 0; if it was off, turn it on, if was on, turn it off.
+   * The color of this LED depends on the platform.
+   */
+  async command void led0Toggle();
+
+  /**
+   * Turn on LED 1. The color of this LED depends on the platform.
+   */
+  async command void led1On();
+
+  /**
+   * Turn off LED 1. The color of this LED depends on the platform.
+   */
+  async command void led1Off();
+
+   /**
+   * Toggle LED 1; if it was off, turn it on, if was on, turn it off.
+   * The color of this LED depends on the platform.
+   */
+  async command void led1Toggle();
+
+  /**
+   * Turn on LED 2. The color of this LED depends on the platform.
+   */
+  async command void led2On();
+
+  /**
+   * Turn off LED 2. The color of this LED depends on the platform.
+   */
+  async command void led2Off();
+
+   /**
+   * Toggle LED 2; if it was off, turn it on, if was on, turn it off.
+   * The color of this LED depends on the platform.
+   */
+  async command void led2Toggle();
+  
+  /**
+   * Get the current LED settings as a bitmask. Each bit corresponds to
+   * whether an LED is on; bit 0 is LED 0, bit 1 is LED 1, etc. You can
+   * also use the enums LEDS_LED0, LEDS_LED1. For example, this expression
+   * will determine whether LED 2 is on:
+   *
+   * <pre> (call Leds.get() & LEDS_LED2) </pre>
+   *
+   * This command supports up to 8 LEDs; if a platform has fewer, then
+   * those LEDs should always be off (their bit is zero). Also see
+   * <tt>set()</tt>.
+   *
+   * @return a bitmask describing which LEDs are on and which are off
+   */ 
+  async command uint8_t get();
+
+  
+  /**
+   * Set the current LED configuration using a bitmask.  Each bit
+   * corresponds to whether an LED is on; bit 0 is LED 0, bit 1 is LED
+   * 1, etc. You can also use the enums LEDS_LED0, LEDS_LED1. For example,
+   * this statement will configure the LEDs so LED 0 and LED 2 are on:
+   *
+   * <pre> call Leds.set(LEDS_LED0 | LEDS_LED2); </pre>
+   *
+   * This statement will turn LED 1 on if it was not already:
+   *
+   * <pre>call Leds.set(call Leds.get() | LEDS_LED1);</pre>
+   *
+   * @param  val   a bitmask describing the on/off settings of the LEDs
+   */
+   async command void set(uint8_t val);
+  
+}
diff --git a/tos/platforms/shimmer2/LedsC.nc b/tos/platforms/shimmer2/LedsC.nc
new file mode 100644 (file)
index 0000000..c3634bb
--- /dev/null
@@ -0,0 +1,48 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+/**
+ *
+ * The basic TinyOS LEDs abstraction.
+ *
+ * @author Phil Buonadonna
+ * @author David Gay
+ * @author Philip Levis
+ * @author Joe Polastre
+ *
+ */
+
+
+configuration LedsC {
+  provides interface Leds;
+}
+implementation {
+  components LedsP, PlatformLedsC;
+
+  Leds = LedsP;
+
+  LedsP.Init <- PlatformLedsC.Init;
+  LedsP.Led0 -> PlatformLedsC.Led0;
+  LedsP.Led1 -> PlatformLedsC.Led1;
+  LedsP.Led2 -> PlatformLedsC.Led2;
+}
+
diff --git a/tos/platforms/shimmer2/LedsP.nc b/tos/platforms/shimmer2/LedsP.nc
new file mode 100644 (file)
index 0000000..1daa36c
--- /dev/null
@@ -0,0 +1,148 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * The implementation of the standard 3 LED mote abstraction.
+ *
+ * @author Joe Polastre
+ * @author Philip Levis
+ *
+ * @date   March 21, 2005
+ *
+ */
+
+module LedsP @safe() {
+  provides {
+    interface Init;
+    interface Leds;
+  }
+  uses {
+    interface GeneralIO as Led0;
+    interface GeneralIO as Led1;
+    interface GeneralIO as Led2;
+  }
+}
+implementation {
+  command error_t Init.init() {
+    atomic {
+      dbg("Init", "LEDS: initialized.\n");
+      call Led0.makeOutput();
+      call Led1.makeOutput();
+      call Led2.makeOutput();
+      call Led0.set();
+      call Led1.set();
+      call Led2.set();
+    }
+    return SUCCESS;
+  }
+
+  /* Note: the call is inside the dbg, as it's typically a read of a volatile
+     location, so can't be deadcode eliminated */
+#define DBGLED(n) \
+  dbg("LedsC", "LEDS: Led" #n " %s.\n", call Led ## n .get() ? "off" : "on");
+
+  async command void Leds.led0On() {
+    call Led0.clr();
+    DBGLED(0);
+  }
+
+  async command void Leds.led0Off() {
+    call Led0.set();
+    DBGLED(0);
+  }
+
+  async command void Leds.led0Toggle() {
+    call Led0.toggle();
+    DBGLED(0);
+  }
+
+  async command void Leds.led1On() {
+    call Led1.clr();
+    DBGLED(1);
+  }
+
+  async command void Leds.led1Off() {
+    call Led1.set();
+    DBGLED(1);
+  }
+
+  async command void Leds.led1Toggle() {
+    call Led1.toggle();
+    DBGLED(1);
+  }
+
+  async command void Leds.led2On() {
+    call Led2.clr();
+    DBGLED(2);
+  }
+
+  async command void Leds.led2Off() {
+    call Led2.set();
+    DBGLED(2);
+  }
+
+  async command void Leds.led2Toggle() {
+    call Led2.toggle();
+    DBGLED(2);
+  }
+
+  async command uint8_t Leds.get() {
+    uint8_t rval;
+    atomic {
+      rval = 0;
+      if (!call Led0.get()) {
+             rval |= LEDS_LED0;
+      }
+      if (!call Led1.get()) {
+             rval |= LEDS_LED1;
+      }
+      if (!call Led2.get()) {
+             rval |= LEDS_LED2;
+      }
+    }
+    return rval;
+  }
+
+  async command void Leds.set(uint8_t val) {
+    atomic {
+      if (val & LEDS_LED0) {
+             call Leds.led0On();
+      }
+      else {
+             call Leds.led0Off();
+      }
+      if (val & LEDS_LED1) {
+             call Leds.led1On();
+      }
+      else {
+             call Leds.led1Off();
+      }
+      if (val & LEDS_LED2) {
+             call Leds.led2On();
+      }
+      else {
+             call Leds.led2Off();
+      }
+    }
+  }
+}
diff --git a/tos/platforms/shimmer2/MoteClockC.nc b/tos/platforms/shimmer2/MoteClockC.nc
new file mode 100644 (file)
index 0000000..12df90b
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2007, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universität Berlin nor the names
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * $Id$
+ *
+ */
+
+ /**
+ * @author Vlado Handziski <handzisk@tkn.tu-berlind.de>
+ */
+configuration MoteClockC
+{
+  provides interface Init as MoteClockInit;
+}
+implementation
+
+{
+  components Msp430ClockC;
+  
+  MoteClockInit = Msp430ClockC.Init;
+}
diff --git a/tos/platforms/shimmer2/MotePlatformC.nc b/tos/platforms/shimmer2/MotePlatformC.nc
new file mode 100644 (file)
index 0000000..880c531
--- /dev/null
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) 2007, Intel Corporation
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * Redistributions of source code must retain the above copyright notice, 
+ * this list of conditions and the following disclaimer. 
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution. 
+ *
+ * Neither the name of the Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software 
+ * without specific prior written permission. 
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Steven Ayer
+ * @date   July 2007
+ * 
+ * tos-2.x port June 2009
+ *
+ */
+
+module MotePlatformC {
+  provides interface Init;
+}
+
+implementation {
+
+  command error_t Init.init() {
+    
+    // have to tell mux to connect path from msp430 to sd
+    TOSH_SEL_DOCK_N_IOFUNC();
+    TOSH_MAKE_DOCK_N_OUTPUT();
+    TOSH_SET_DOCK_N_PIN();
+
+    // bus arbitration pins 
+    TOSH_SEL_SW_SD_PWR_N_IOFUNC();
+    TOSH_MAKE_SW_SD_PWR_N_OUTPUT();
+
+    TOSH_SEL_SD_CS_N_IOFUNC();
+    TOSH_MAKE_SD_CS_N_OUTPUT();
+
+    TOSH_SEL_SD_CLK_IOFUNC();
+    TOSH_MAKE_SD_CLK_OUTPUT();
+    TOSH_SEL_SD_DO_IOFUNC();
+    TOSH_MAKE_SD_DO_INPUT();
+    TOSH_SEL_SD_DI_IOFUNC();
+    TOSH_MAKE_SD_DI_OUTPUT();
+  
+    // power down sd module; overridden by dock pin on programming board
+    /*
+     * other pins are zeroed to reset card
+     * at end of this routine, we raise them again (they have pullups, too)
+     */
+    TOSH_SET_SW_SD_PWR_N_PIN();     
+    TOSH_CLR_SD_CS_N_PIN();
+    TOSH_CLR_SD_DI_PIN();
+    TOSH_CLR_SD_CLK_PIN();
+  
+    TOSH_SEL_SW_BT_PWR_N_IOFUNC();
+    TOSH_MAKE_SW_BT_PWR_N_OUTPUT();
+    TOSH_SET_SW_BT_PWR_N_PIN();     // power down bt module; overridden by dock pin on programming board
+
+    //LEDS
+    TOSH_SEL_RED_LED_IOFUNC();
+    TOSH_MAKE_RED_LED_OUTPUT();
+    TOSH_SEL_YELLOW_LED_IOFUNC();
+    TOSH_MAKE_YELLOW_LED_OUTPUT();
+    TOSH_SEL_GREEN_LED_IOFUNC();
+    TOSH_MAKE_GREEN_LED_OUTPUT();
+
+    TOSH_SET_RED_LED_PIN();
+    TOSH_SET_YELLOW_LED_PIN();
+    TOSH_SET_GREEN_LED_PIN();
+
+    //RADIO PINS
+    //CC2420 pins
+    TOSH_MAKE_RADIO_VREF_OUTPUT();
+    TOSH_SEL_RADIO_VREF_IOFUNC();
+    TOSH_CLR_RADIO_VREF_PIN();    // power down 
+
+    TOSH_MAKE_RADIO_CSN_OUTPUT();
+    TOSH_SEL_RADIO_CSN_IOFUNC();
+    TOSH_SET_RADIO_CSN_PIN();
+
+    // should be reset_n
+    TOSH_MAKE_RADIO_RESET_OUTPUT();
+    TOSH_SEL_RADIO_RESET_IOFUNC();
+    TOSH_CLR_RADIO_RESET_PIN();
+
+    TOSH_SEL_RADIO_CCA_IOFUNC();
+    TOSH_MAKE_RADIO_CCA_INPUT();
+    TOSH_SEL_RADIO_FIFO_IOFUNC();
+    TOSH_MAKE_RADIO_FIFO_INPUT();
+    TOSH_SEL_RADIO_FIFOP_IOFUNC();
+    TOSH_MAKE_RADIO_FIFOP_INPUT();
+    TOSH_SEL_RADIO_SFD_IOFUNC();
+    TOSH_MAKE_RADIO_SFD_INPUT();
+
+    TOSH_SEL_TILT_IOFUNC();
+    TOSH_MAKE_TILT_INPUT();
+
+    // BT PINS
+    TOSH_MAKE_BT_RESET_OUTPUT();  
+    TOSH_SEL_BT_RESET_IOFUNC();    
+    TOSH_CLR_BT_RESET_PIN();   // mitsumi module disabled by clr
+
+    TOSH_MAKE_BT_RTS_INPUT();      
+    TOSH_SEL_BT_RTS_IOFUNC();
+
+    TOSH_MAKE_BT_PIO_INPUT();
+    TOSH_SEL_BT_PIO_IOFUNC();
+
+    TOSH_MAKE_BT_CTS_OUTPUT();
+    TOSH_SEL_BT_CTS_IOFUNC();
+
+    TOSH_MAKE_BT_TXD_OUTPUT();
+    TOSH_SEL_BT_TXD_IOFUNC();
+
+    TOSH_MAKE_BT_RXD_INPUT();
+    TOSH_SEL_BT_RXD_IOFUNC();
+
+    // BSL Prog Pins tristate em
+    TOSH_MAKE_PROG_IN_OUTPUT();
+    TOSH_MAKE_PROG_OUT_OUTPUT();
+    TOSH_SET_PROG_OUT_PIN();    // some expansion boards have enable low
+    TOSH_SEL_PROG_IN_IOFUNC();
+    TOSH_SEL_PROG_OUT_IOFUNC();
+
+    // ADC lines
+    TOSH_SEL_ADC_0_IOFUNC();
+    TOSH_MAKE_ADC_0_OUTPUT();
+    TOSH_SEL_ADC_1_IOFUNC();
+    TOSH_MAKE_ADC_1_OUTPUT();
+    TOSH_SEL_ADC_2_IOFUNC();
+    TOSH_MAKE_ADC_2_OUTPUT();
+    TOSH_SEL_ADC_6_IOFUNC();
+    TOSH_MAKE_ADC_6_OUTPUT();
+    TOSH_SEL_ADC_7_IOFUNC();
+    TOSH_MAKE_ADC_7_OUTPUT();
+
+    TOSH_SEL_ADC_ACCELZ_IOFUNC();
+    TOSH_MAKE_ADC_ACCELZ_INPUT();
+    TOSH_SEL_ADC_ACCELY_IOFUNC();
+    TOSH_MAKE_ADC_ACCELY_INPUT();
+    TOSH_SEL_ADC_ACCELX_IOFUNC();
+    TOSH_MAKE_ADC_ACCELX_INPUT();
+  
+    TOSH_SEL_ROSC_IOFUNC();
+    TOSH_MAKE_ROSC_INPUT();
+
+    // 1-wire function
+    TOSH_SEL_ONEWIRE_IOFUNC();
+    TOSH_MAKE_ONEWIRE_OUTPUT();
+    TOSH_SET_ONEWIRE_PIN();
+
+    /*
+     *  Accelerometer pin definitions
+     * unless the accel_sel0 pin is cleared, 
+     * a severe quiescent power hit occurs on the msp430
+     * we go from 3.7 ua to 65.1 ua when asleep!
+     */
+    TOSH_SEL_ACCEL_SEL0_IOFUNC();
+    TOSH_MAKE_ACCEL_SEL0_OUTPUT();
+    TOSH_CLR_ACCEL_SEL0_PIN();
+    TOSH_SEL_ACCEL_SEL1_IOFUNC();
+    TOSH_MAKE_ACCEL_SEL1_OUTPUT();
+    TOSH_CLR_ACCEL_SEL1_PIN();
+    TOSH_SEL_ACCEL_SLEEP_N_IOFUNC();
+    TOSH_MAKE_ACCEL_SLEEP_N_OUTPUT();
+    TOSH_CLR_ACCEL_SLEEP_N_PIN();
+
+    // idle expansion header pins
+    TOSH_SEL_SER0_CTS_IOFUNC();
+    TOSH_MAKE_SER0_CTS_OUTPUT();
+    TOSH_SEL_SER0_RTS_IOFUNC();
+    TOSH_MAKE_SER0_RTS_OUTPUT();
+
+    // this pin is now tied to the user button on the prog board
+    TOSH_SEL_GIO0_IOFUNC();
+    TOSH_MAKE_GIO0_INPUT();
+
+    TOSH_SEL_GIO1_IOFUNC();
+    TOSH_MAKE_GIO1_OUTPUT();
+
+    TOSH_SEL_UTXD0_IOFUNC();
+    TOSH_MAKE_UTXD0_OUTPUT();
+    TOSH_SEL_URXD0_IOFUNC();
+    TOSH_MAKE_URXD0_OUTPUT();
+
+    TOSH_SEL_UTXD1_IOFUNC();
+    TOSH_MAKE_UTXD1_OUTPUT();
+    TOSH_SEL_URXD1_IOFUNC();
+    TOSH_MAKE_URXD1_OUTPUT();
+    TOSH_SEL_UCLK1_IOFUNC();
+    TOSH_MAKE_UCLK1_OUTPUT();
+    TOSH_SEL_SIMO1_IOFUNC();
+    TOSH_MAKE_SIMO1_OUTPUT();
+    TOSH_SEL_SOMI1_IOFUNC();
+    TOSH_MAKE_SOMI1_INPUT();
+
+    TOSH_SET_SD_CS_N_PIN();
+    TOSH_SET_SD_DI_PIN();
+    TOSH_SET_SD_CLK_PIN();
+
+    // these are attached to the same pullup as above
+    TOSH_SET_SIMO1_PIN();
+    TOSH_SET_UCLK1_PIN();
+
+    // set it back to default state
+    TOSH_MAKE_DOCK_N_INPUT();
+
+    return SUCCESS;
+  }
+}
diff --git a/tos/platforms/shimmer2/Msp430Timer32khzMapC.nc b/tos/platforms/shimmer2/Msp430Timer32khzMapC.nc
new file mode 100644 (file)
index 0000000..e23e742
--- /dev/null
@@ -0,0 +1,75 @@
+//$Id$
+
+/* "Copyright (c) 2000-2003 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * MSP430Timer32khzMapC presents as paramaterized interfaces all of
+ * the 32khz hardware timers on the MSP430 that are available for
+ * compile time allocation by "new Alarm32khz16C()", "new
+ * AlarmMilli32C()", and so on.  
+ *
+ * Platforms based on the MSP430 are * encouraged to copy in and
+ * override this file, presenting only the * hardware timers that are
+ * available for allocation on that platform.
+ *
+ * @author Cory Sharp <cssharp@eecs.berkeley.edu>
+ * @version $Revision$ $Date$
+ */
+
+configuration Msp430Timer32khzMapC
+{
+  provides interface Msp430Timer[ uint8_t id ];
+  provides interface Msp430TimerControl[ uint8_t id ];
+  provides interface Msp430Compare[ uint8_t id ];
+}
+implementation
+{
+  components Msp430TimerC;
+
+  Msp430Timer[0] = Msp430TimerC.TimerB;
+  Msp430TimerControl[0] = Msp430TimerC.ControlB0;
+  Msp430Compare[0] = Msp430TimerC.CompareB0;
+
+  Msp430Timer[1] = Msp430TimerC.TimerB;
+  Msp430TimerControl[1] = Msp430TimerC.ControlB1;
+  Msp430Compare[1] = Msp430TimerC.CompareB1;
+
+  Msp430Timer[2] = Msp430TimerC.TimerB;
+  Msp430TimerControl[2] = Msp430TimerC.ControlB2;
+  Msp430Compare[2] = Msp430TimerC.CompareB2;
+
+  Msp430Timer[3] = Msp430TimerC.TimerB;
+  Msp430TimerControl[3] = Msp430TimerC.ControlB3;
+  Msp430Compare[3] = Msp430TimerC.CompareB3;
+
+  Msp430Timer[4] = Msp430TimerC.TimerB;
+  Msp430TimerControl[4] = Msp430TimerC.ControlB4;
+  Msp430Compare[4] = Msp430TimerC.CompareB4;
+
+  Msp430Timer[5] = Msp430TimerC.TimerB;
+  Msp430TimerControl[5] = Msp430TimerC.ControlB5;
+  Msp430Compare[5] = Msp430TimerC.CompareB5;
+
+  Msp430Timer[6] = Msp430TimerC.TimerB;
+  Msp430TimerControl[6] = Msp430TimerC.ControlB6;
+  Msp430Compare[6] = Msp430TimerC.CompareB6;
+}
+
diff --git a/tos/platforms/shimmer2/NoLedsC.nc b/tos/platforms/shimmer2/NoLedsC.nc
new file mode 100644 (file)
index 0000000..1ad2bde
--- /dev/null
@@ -0,0 +1,57 @@
+// $Id$
+
+/*
+ * "Copyright (c) 2000-2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * A null operation replacement for the LedsC component. As many
+ * components might concurrently signal information through LEDs,
+ * using LedsC and NoLedsC allows an application builder to select
+ * which components control the LEDs.
+ *
+ * @author Philip Levis
+ * @date   March 19, 2005
+ *
+ */
+
+module NoLedsC {
+  provides interface Init;
+  provides interface Leds;
+}
+implementation {
+
+  command error_t Init.init() {return SUCCESS;}
+
+  async command void Leds.led0On() {}
+  async command void Leds.led0Off() {}
+  async command void Leds.led0Toggle() {}
+
+  async command void Leds.led1On() {}
+  async command void Leds.led1Off() {}
+  async command void Leds.led1Toggle() {}
+
+  async command void Leds.led2On() {}
+  async command void Leds.led2Off() {}
+  async command void Leds.led2Toggle() {}
+
+  async command uint8_t Leds.get() {return 0;}
+  async command void Leds.set(uint8_t val) {}
+}
diff --git a/tos/platforms/shimmer2/PlatformC.nc b/tos/platforms/shimmer2/PlatformC.nc
new file mode 100644 (file)
index 0000000..b8a67b7
--- /dev/null
@@ -0,0 +1,38 @@
+/* "Copyright (c) 2000-2005 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * @author Joe Polastre and Cory Sharp
+ * @version $Revision$ $Date$
+ */
+#include "hardware.h"
+
+configuration PlatformC
+{
+  provides interface Init;
+}
+implementation
+{
+  components PlatformP, MotePlatformC, MoteClockC;
+
+  Init = PlatformP;
+  PlatformP.MoteClockInit -> MoteClockC;
+  PlatformP.MoteInit -> MotePlatformC;
+}
diff --git a/tos/platforms/shimmer2/PlatformLedsC.nc b/tos/platforms/shimmer2/PlatformLedsC.nc
new file mode 100644 (file)
index 0000000..8a19ba9
--- /dev/null
@@ -0,0 +1,58 @@
+// $Id$
+
+/* "Copyright (c) 2000-2005 The Regents of the University of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement
+ * is hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
+ * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * @author Joe Polastre
+ * @version $Revision$ $Date$
+ */
+
+#include "hardware.h"
+
+configuration PlatformLedsC {
+  provides interface GeneralIO as Led0;
+  provides interface GeneralIO as Led1;
+  provides interface GeneralIO as Led2;
+  uses interface Init;
+}
+implementation
+{
+  components 
+      HplMsp430GeneralIOC as GeneralIOC
+    , new Msp430GpioC() as Led0Impl
+    , new Msp430GpioC() as Led1Impl
+    , new Msp430GpioC() as Led2Impl
+    ;
+  components PlatformP;
+
+  Init = PlatformP.LedsInit;
+
+  Led0 = Led0Impl;
+  Led0Impl -> GeneralIOC.Port40;
+
+  Led1 = Led1Impl;
+  Led1Impl -> GeneralIOC.Port42;
+
+  Led2 = Led2Impl;
+  Led2Impl -> GeneralIOC.Port43;
+
+}
+
diff --git a/tos/platforms/shimmer2/PlatformP.nc b/tos/platforms/shimmer2/PlatformP.nc
new file mode 100644 (file)
index 0000000..b8dc943
--- /dev/null
@@ -0,0 +1,19 @@
+#include "hardware.h"
+
+module PlatformP{
+  provides interface Init;
+  uses interface Init as MoteClockInit;
+  uses interface Init as MoteInit;
+  uses interface Init as LedsInit;
+}
+implementation {
+  command error_t Init.init() {
+    call MoteClockInit.init();
+    call MoteInit.init();
+    call LedsInit.init();
+    return SUCCESS;
+  }
+
+  default command error_t LedsInit.init() { return SUCCESS; }
+
+}
diff --git a/tos/platforms/shimmer2/PlatformSerialC.nc b/tos/platforms/shimmer2/PlatformSerialC.nc
new file mode 100644 (file)
index 0000000..967e9da
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2009, Shimmer Research, Ltd.
+ * All rights reserved
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ *       copyright notice, this list of conditions and the following
+ *       disclaimer in the documentation and/or other materials provided
+ *       with the distribution.
+ *     * Neither the name of Shimmer Research, Ltd. nor the names of its
+ *       contributors may be used to endorse or promote products derived
+ *       from this software without specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * mostly copied from shimmer
+ *
+ * @author Steve Ayer
+ * @date   June 2009
+ */
+
+configuration PlatformSerialC {
+  provides interface StdControl;
+  provides interface UartStream;
+  provides interface UartByte;
+}
+
+implementation {
+  components new Msp430Uart0C() as UartC;
+  UartStream = UartC;  
+  UartByte = UartC;
+  
+  components ShimmerSerialP;
+  StdControl = ShimmerSerialP;
+  ShimmerSerialP.Msp430UartConfigure <- UartC.Msp430UartConfigure;
+  ShimmerSerialP.Resource -> UartC.Resource;
+}
diff --git a/tos/platforms/shimmer2/ShimmerSerialP.nc b/tos/platforms/shimmer2/ShimmerSerialP.nc
new file mode 100644 (file)
index 0000000..a1f61ea
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2009, Shimmer Research, Ltd.
+ * All rights reserved
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ *       copyright notice, this list of conditions and the following
+ *       disclaimer in the documentation and/or other materials provided
+ *       with the distribution.
+ *     * Neither the name of Shimmer Research, Ltd. nor the names of its
+ *       contributors may be used to endorse or promote products derived
+ *       from this software without specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Steve Ayer
+ * @date June 2009
+ */
+
+module ShimmerSerialP {
+  provides interface StdControl;
+  provides interface Msp430UartConfigure;
+  uses interface Resource;
+}
+
+implementation {
+  msp430_uart_union_config_t msp430_uart_shimmer2_config = { 
+    { ubr: UBR_1MHZ_115200, 
+      umctl: UMCTL_1MHZ_115200, 
+      ssel: 0x02, 
+      pena: 0, 
+      pev: 0, 
+      spb: 0, 
+      clen: 1, 
+      listen: 0, 
+      mm: 0, 
+      ckpl: 0, 
+      urxse: 0, 
+      urxeie: 1, 
+      urxwie: 0, 
+      utxe : 1, 
+      urxe : 1 
+    } 
+  };
+
+  command error_t StdControl.start(){
+    return call Resource.immediateRequest();
+  }
+  
+  command error_t StdControl.stop(){
+    call Resource.release();
+    return SUCCESS;
+  }
+
+  event void Resource.granted(){}
+
+  async command msp430_uart_union_config_t * Msp430UartConfigure.getConfig(){
+    return &msp430_uart_shimmer2_config;
+  }
+}
diff --git a/tos/platforms/shimmer2/chips/cc2420/HplCC2420AlarmC.nc b/tos/platforms/shimmer2/chips/cc2420/HplCC2420AlarmC.nc
new file mode 100644 (file)
index 0000000..0d56a8b
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * HPL implementation of 32khz alarms for the ChipCon CC2420 radio
+ * connected to a TI MSP430 processor.
+ *
+ * @author Jonathan Hui <jhui@archrock.com>
+ * @version $Revision$ $Date$
+ */
+
+generic configuration HplCC2420AlarmC() {
+
+  provides interface Init;
+  provides interface Alarm<T32khz,uint32_t> as Alarm32khz32;
+
+}
+
+implementation {
+
+  components new Alarm32khz32C();
+
+  Init = Alarm32khz32C;
+  Alarm32khz32 = Alarm32khz32C;
+  
+}
diff --git a/tos/platforms/shimmer2/chips/cc2420/HplCC2420InterruptsC.nc b/tos/platforms/shimmer2/chips/cc2420/HplCC2420InterruptsC.nc
new file mode 100644 (file)
index 0000000..c4b2ad4
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * HPL implementation of interrupts and captures for the ChipCon
+ * CC2420 radio connected to a TI MSP430 processor.
+ *
+ * @author Jonathan Hui <jhui@archrock.com>
+ * @version $Revision$ $Date$
+ */
+/**
+ * Ported to the SHIMMER platform. 
+ *
+ * @author Konrad Lorincz
+ * @date May 14, 2008
+ * re-written to use interrupt-driven sfd capture; 
+ * shimmer2 does not have sfd wired to a timer pin
+ * @author Steve Ayer
+ * @date January, 2010
+ */
+
+configuration HplCC2420InterruptsC {
+
+  provides interface GpioCapture as CaptureSFD;
+  provides interface GpioInterrupt as InterruptSFD;
+
+  provides interface GpioInterrupt as InterruptCCA;
+  provides interface GpioInterrupt as InterruptFIFOP;
+
+}
+
+implementation {
+
+  components HplMsp430InterruptC;
+  components new Msp430InterruptC() as InterruptCCAC;
+  components new Msp430InterruptC() as InterruptFIFOPC;
+  components new Msp430InterruptC() as InterruptSFDC;
+
+  InterruptCCAC.HplInterrupt -> HplMsp430InterruptC.Port27;
+  InterruptFIFOPC.HplInterrupt -> HplMsp430InterruptC.Port12;
+  InterruptSFDC.HplInterrupt -> HplMsp430InterruptC.Port10;
+
+  components HplCC2420InterruptsP;
+  components LocalTimeMilliC;
+  components new GpioCaptureC() as CaptureSFDC;
+  components HplCC2420PinsC;
+
+  CaptureSFD = HplCC2420InterruptsP.CaptureSFD;
+
+  HplCC2420InterruptsP.InterruptSFD ->  InterruptSFDC.Interrupt;
+  HplCC2420InterruptsP.LocalTime     -> LocalTimeMilliC;
+
+  InterruptCCA = InterruptCCAC.Interrupt;
+  InterruptFIFOP = InterruptFIFOPC.Interrupt;
+  InterruptSFD = InterruptSFDC.Interrupt;
+}
diff --git a/tos/platforms/shimmer2/chips/cc2420/HplCC2420InterruptsP.nc b/tos/platforms/shimmer2/chips/cc2420/HplCC2420InterruptsP.nc
new file mode 100644 (file)
index 0000000..f08c1ab
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2010, Shimmer Research, Ltd.
+ * All rights reserved
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ *       copyright notice, this list of conditions and the following
+ *       disclaimer in the documentation and/or other materials provided
+ *       with the distribution.
+ *     * Neither the name of Shimmer Research, Ltd. nor the names of its
+ *       contributors may be used to endorse or promote products derived
+ *       from this software without specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Steve Ayer
+ * @date   January, 2010
+ *
+ * this implements an interrupt-driven capture interface for the cc2420
+ * tx-mode use of sfd.  shimmer2 does not have sfd routed to a timer pin
+ * on the msp430, so cc2420's capture mechanism fails.  
+ * this module will trigger a capture.captured event after receiving the
+ * appropriate interrupt from the shimmer2 sfd pin (1.0)
+ */
+
+module HplCC2420InterruptsP @safe() {
+  provides{
+    interface GpioCapture as CaptureSFD;
+  }
+
+  uses{
+    interface GpioInterrupt as InterruptSFD;
+    interface LocalTime<TMilli>;
+  }
+}
+
+implementation {
+  async command error_t CaptureSFD.captureRisingEdge() { 
+    call InterruptSFD.enableRisingEdge();
+    return SUCCESS;
+  }
+
+  async command error_t CaptureSFD.captureFallingEdge() { 
+    call InterruptSFD.enableFallingEdge();
+    return SUCCESS;
+  }
+  
+  async command void CaptureSFD.disable() {
+    call InterruptSFD.disable();
+  }
+
+  async event void InterruptSFD.fired() {
+    uint32_t t = call LocalTime.get();
+
+    signal CaptureSFD.captured((uint16_t)(t & 0x0000ffff));
+  }
+}
+
diff --git a/tos/platforms/shimmer2/chips/cc2420/HplCC2420PinsC.nc b/tos/platforms/shimmer2/chips/cc2420/HplCC2420PinsC.nc
new file mode 100644 (file)
index 0000000..8aa2467
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * HPL implementation of general-purpose I/O for the ChipCon CC2420
+ * radio connected to a TI MSP430 processor.
+ *
+ * @author Jonathan Hui <jhui@archrock.com>
+ * @version $Revision$ $Date$
+ */
+/**
+ * Ported to the SHIMMER platform. 
+ *
+ * @author Konrad Lorincz
+ * @date May 14, 2008
+ */
+
+configuration HplCC2420PinsC {
+
+  provides interface GeneralIO as CCA;
+  provides interface GeneralIO as CSN;
+  provides interface GeneralIO as FIFO;
+  provides interface GeneralIO as FIFOP;
+  provides interface GeneralIO as RSTN;
+  provides interface GeneralIO as SFD;
+  provides interface GeneralIO as VREN;
+
+}
+
+implementation {
+
+  components HplMsp430GeneralIOC as GeneralIOC;
+  components new Msp430GpioC() as CCAM;
+  components new Msp430GpioC() as CSNM;
+  components new Msp430GpioC() as FIFOM;
+  components new Msp430GpioC() as FIFOPM;
+  components new Msp430GpioC() as RSTNM;
+  components new Msp430GpioC() as SFDM;
+  components new Msp430GpioC() as VRENM;
+
+  CCAM -> GeneralIOC.Port27;
+  CSNM -> GeneralIOC.Port54;
+  FIFOM -> GeneralIOC.Port15;
+  FIFOPM -> GeneralIOC.Port12;
+  RSTNM -> GeneralIOC.Port57;
+  SFDM -> GeneralIOC.Port10;
+  VRENM -> GeneralIOC.Port56;
+
+  CCA = CCAM;
+  CSN = CSNM;
+  FIFO = FIFOM;
+  FIFOP = FIFOPM;
+  RSTN = RSTNM;
+  SFD = SFDM;
+  VREN = VRENM;
+  
+}
+
diff --git a/tos/platforms/shimmer2/chips/cc2420/HplCC2420SpiC.nc b/tos/platforms/shimmer2/chips/cc2420/HplCC2420SpiC.nc
new file mode 100644 (file)
index 0000000..0179f93
--- /dev/null
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2005-2006 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * HPL implementation of the SPI bus for the ChipCon CC2420 radio
+ * connected to a TI MSP430 processor.
+ *
+ * @author Jonathan Hui <jhui@archrock.com>
+ * @version $Revision$ $Date$
+ */
+/**
+ * Ported to the SHIMMER platform. 
+ *
+ * @author Konrad Lorincz
+ */
+
+generic configuration HplCC2420SpiC() {
+  
+  provides interface Resource;
+  provides interface SpiByte;
+  provides interface SpiPacket;
+  
+}
+
+implementation {
+
+  components new Msp430Spi1C() as SpiC;
+  
+  Resource = SpiC;
+  SpiByte = SpiC;
+  SpiPacket = SpiC;
+  
+}
+
diff --git a/tos/platforms/shimmer2/chips/tilt/HplTiltDetectorC.nc b/tos/platforms/shimmer2/chips/tilt/HplTiltDetectorC.nc
new file mode 100644 (file)
index 0000000..b894600
--- /dev/null
@@ -0,0 +1,57 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telos platform
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ * (not much to) port to shimmer
+ * @author Steve Ayer
+ * @date February, 2010
+ */
+
+configuration HplUserButtonC {
+  provides interface GeneralIO;
+  provides interface GpioInterrupt;
+}
+implementation {
+  components HplMsp430GeneralIOC as GeneralIOC;
+  components HplMsp430InterruptC as InterruptC;
+
+  components new Msp430GpioC() as TiltDetectorC;
+  TiltDetectorC -> GeneralIOC.Port24;
+  GeneralIO = TiltDetectorC;
+
+  components new Msp430InterruptC() as InterruptTiltDetectorC;
+  InterruptTiltDetectorC.HplInterrupt -> InterruptC.Port24;
+  GpioInterrupt = InterruptTiltDetectorC.Interrupt;
+}
diff --git a/tos/platforms/shimmer2/chips/tilt/TiltDetectorC.nc b/tos/platforms/shimmer2/chips/tilt/TiltDetectorC.nc
new file mode 100644 (file)
index 0000000..51492de
--- /dev/null
@@ -0,0 +1,63 @@
+/**
+ * Copyright (c) 2007 Arch Rock Corporation
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * - Redistributions of source code must retain the above copyright
+ *   notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ *   notice, this list of conditions and the following disclaimer in the
+ *   documentation and/or other materials provided with the
+ *   distribution.
+ * - Neither the name of the Arch Rock Corporation nor the names of
+ *   its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
+ * ARCHED ROCK OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE
+ */
+
+/**
+ * Implementation of the user button for the telosb platform. Get
+ * returns the current state of the button by reading the pin,
+ * regardless of whether enable() or disable() has been called on the
+ * Interface. Notify.enable() and Notify.disable() modify the
+ * underlying interrupt state of the pin, and have the effect of
+ * enabling or disabling notifications that the button has changed
+ * state.
+ *
+ * @author Gilman Tolle <gtolle@archrock.com>
+ * @version $Revision$
+ * port to shimmer2 tilt switch
+ * @author Steve Ayer
+ * @date   February, 2010
+ */
+
+configuration TiltDetectorC {
+  provides interface Notify<button_state_t>;
+}
+implementation {
+  components HplTiltDetectorC;
+  components new SwitchToggleC();
+  SwitchToggleC.GpioInterrupt -> HplTiltDetectorC.GpioInterrupt;
+  SwitchToggleC.GeneralIO -> HplTiltDetectorC.GeneralIO;
+
+  components UserButtonP;
+  Notify = UserButtonP;
+
+  components new TimerMilliC() as debounceTimer;
+  UserButtonP.NotifyLower -> SwitchToggleC.Notify;
+  UserButtonP.debounceTimer -> debounceTimer;
+}
diff --git a/tos/platforms/shimmer2/hardware.h b/tos/platforms/shimmer2/hardware.h
new file mode 100644 (file)
index 0000000..90d857e
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2007, Intel Corporation
+ * All rights reserved.
+ * 
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * 
+ * Redistributions of source code must retain the above copyright notice, 
+ * this list of conditions and the following disclaimer. 
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following disclaimer in the documentation
+ * and/or other materials provided with the distribution. 
+ *
+ * Neither the name of the Intel Corporation nor the names of its contributors
+ * may be used to endorse or promote products derived from this software 
+ * without specific prior written permission. 
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
+ * POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @author Steven Ayer
+ * @date   July 2007
+ */
+
+
+#ifndef _H_hardware_h
+#define _H_hardware_h
+
+#include "msp430hardware.h"
+/*
+ * these left from tos-1.x...
+ *
+ *#include "MSP430ADC12.h"
+ *
+ *#include "CC2420Const.h"
+ */
+
+
+// LEDs
+TOSH_ASSIGN_PIN(RED_LED,    4, 0);
+TOSH_ASSIGN_PIN(YELLOW_LED, 4, 2);
+TOSH_ASSIGN_PIN(GREEN_LED,  4, 3);
+
+// CC2420 RADIO
+TOSH_ASSIGN_PIN(RADIO_FIFO,  1, 5);
+TOSH_ASSIGN_PIN(RADIO_FIFOP, 1, 2);
+TOSH_ASSIGN_PIN(RADIO_CCA,   2, 7);
+
+// vref is legacy from telos and cc2420 lib; schematic and cc2420 pin say vreg_en
+TOSH_ASSIGN_PIN(RADIO_VREF,  5, 6);   
+
+TOSH_ASSIGN_PIN(RADIO_SFD,   1, 0);
+TOSH_ASSIGN_PIN(RADIO_SIMO1, 5, 1);
+TOSH_ASSIGN_PIN(RADIO_SOMI1, 5, 2);
+TOSH_ASSIGN_PIN(RADIO_CSN,   5, 4);
+TOSH_ASSIGN_PIN(RADIO_RESET, 5, 7);
+
+// this happens in hplcc2420pinsc
+TOSH_ASSIGN_PIN(CC_FIFOP, 1, 2);
+TOSH_ASSIGN_PIN(CC_FIFO, 1, 5);
+TOSH_ASSIGN_PIN(CC_SFD, 1, 0);
+TOSH_ASSIGN_PIN(CC_VREN, 5, 6);
+TOSH_ASSIGN_PIN(CC_RSTN, 5, 7);
+
+// BT pins
+TOSH_ASSIGN_PIN(BT_PIO,      2, 6);
+TOSH_ASSIGN_PIN(BT_RTS,      1, 6);
+TOSH_ASSIGN_PIN(BT_CTS,      1, 7);
+TOSH_ASSIGN_PIN(BT_TXD,      3, 6);
+TOSH_ASSIGN_PIN(BT_RXD,      3, 7);
+TOSH_ASSIGN_PIN(BT_RESET,    5, 5);
+
+//BSL Pins
+TOSH_ASSIGN_PIN(PROG_OUT,  1, 1);
+TOSH_ASSIGN_PIN(PROG_IN,   2, 2);
+
+// SD uart chip-select
+TOSH_ASSIGN_PIN(SD_CS_N, 3, 0);
+
+TOSH_ASSIGN_PIN(TILT,  2, 4);
+
+// ADC lines on the testpoints
+TOSH_ASSIGN_PIN(ADC_0, 6, 0);
+TOSH_ASSIGN_PIN(ADC_1, 6, 1);
+TOSH_ASSIGN_PIN(ADC_2, 6, 2);
+TOSH_ASSIGN_PIN(ADC_6, 6, 6);
+TOSH_ASSIGN_PIN(ADC_7, 6, 7);
+
+TOSH_ASSIGN_PIN(ADC_ACCELZ, 6, 3);
+TOSH_ASSIGN_PIN(ADC_ACCELY,  6, 4);
+TOSH_ASSIGN_PIN(ADC_ACCELX, 6, 5);
+
+TOSH_ASSIGN_PIN(DAC0_AN, 6, 6);
+TOSH_ASSIGN_PIN(DAC1_AN, 6, 7);
+
+TOSH_ASSIGN_PIN(VSENSE_ADC6, 6, 6);
+TOSH_ASSIGN_PIN(VSENSE_ADC7,  6, 7);
+
+// bus arbitration pins
+TOSH_ASSIGN_PIN(SW_SD_PWR_N, 4, 5);
+TOSH_ASSIGN_PIN(SW_BT_PWR_N, 4, 6);
+
+// if used as expansion GPIOs
+TOSH_ASSIGN_PIN(SER0_RTS, 1, 3);
+TOSH_ASSIGN_PIN(SER0_CTS, 1, 4);
+
+TOSH_ASSIGN_PIN(SIMO0, 3, 1);
+TOSH_ASSIGN_PIN(SOMI0, 3, 2);
+TOSH_ASSIGN_PIN(UCLK0, 3, 3);
+TOSH_ASSIGN_PIN(UTXD0, 3, 4);
+TOSH_ASSIGN_PIN(URXD0, 3, 5);
+
+// redefinitions for the sd card driver
+TOSH_ASSIGN_PIN(SD_DI, 3, 1);
+TOSH_ASSIGN_PIN(SD_DO, 3, 2);
+TOSH_ASSIGN_PIN(SD_CLK, 3, 3);
+
+
+TOSH_ASSIGN_PIN(SIMO1, 5, 1);
+TOSH_ASSIGN_PIN(SOMI1, 5, 2);
+TOSH_ASSIGN_PIN(UCLK1, 5, 3);
+TOSH_ASSIGN_PIN(UTXD1, 3, 6);
+TOSH_ASSIGN_PIN(URXD1, 3, 7);
+
+TOSH_ASSIGN_PIN(GIO0, 2, 0);
+TOSH_ASSIGN_PIN(GIO1, 2, 1);
+TOSH_ASSIGN_PIN(GIO2, 2, 5);  // second internal expansion gpio
+
+// 1-Wire
+TOSH_ASSIGN_PIN(ONEWIRE, 4, 7);
+
+// ROSC
+TOSH_ASSIGN_PIN(ROSC, 2, 5);
+
+// docked signal from programming board
+TOSH_ASSIGN_PIN(DOCK_N, 2, 3);
+
+// ACCEL
+TOSH_ASSIGN_PIN(ACCEL_SEL0,  4, 1);
+TOSH_ASSIGN_PIN(ACCEL_SEL1,  4, 4);
+TOSH_ASSIGN_PIN(ACCEL_SLEEP_N, 5, 0);
+
+#endif // _H_hardware_h
+
diff --git a/tos/platforms/shimmer2/platform.h b/tos/platforms/shimmer2/platform.h
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/tos/platforms/shimmer2/platform_message.h b/tos/platforms/shimmer2/platform_message.h
new file mode 100644 (file)
index 0000000..75532b9
--- /dev/null
@@ -0,0 +1,59 @@
+/* $Id$
+ * "Copyright (c) 2005 The Regents of the University  of California.  
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ * 
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * 
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ * Copyright (c) 2002-2005 Intel Corporation
+ * All rights reserved.
+ *
+ * This file is distributed under the terms in the attached INTEL-LICENSE     
+ * file. If you do not find these files, copies can be found by writing to
+ * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, 
+ * 94704.  Attention:  Intel License Inquiry.
+ */
+
+/**
+ * Defining the platform-independently named packet structures to be the
+ * chip-specific CC1000 packet structures.
+ *
+ * @author Philip Levis
+ * @version $Revision$ $Date$
+ */
+
+
+#ifndef PLATFORM_MESSAGE_H
+#define PLATFORM_MESSAGE_H
+
+#include <CC2420.h>
+#include <Serial.h>
+
+typedef union message_header {
+  cc2420_header_t cc2420;
+  serial_header_t serial;
+} message_header_t;
+
+typedef union TOSRadioFooter {
+  cc2420_footer_t cc2420;
+} message_footer_t;
+
+typedef union TOSRadioMetadata {
+  cc2420_metadata_t cc2420;
+  serial_metadata_t serial;
+} message_metadata_t;
+
+#endif
index 0e6514918a789e171ded9886c37713fbdff7f72a..aaf2bfffcc34e4020c4e620057499ebb9c11a0ae 100644 (file)
@@ -58,6 +58,7 @@ configuration ActiveMessageC {
     interface PacketAcknowledgements;
     interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
     interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
+    interface LowPowerListening;
   }
 }
 implementation {
@@ -71,6 +72,7 @@ implementation {
   Packet       = AM;
   AMPacket     = AM;
   PacketAcknowledgements = AM;
+  LowPowerListening = AM;
 
   components CC2420PacketC;
   PacketTimeStamp32khz = CC2420PacketC;
diff --git a/tos/platforms/telosa/Ieee154MessageC.nc b/tos/platforms/telosa/Ieee154MessageC.nc
new file mode 100644 (file)
index 0000000..2099d1b
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+
+/**
+ *
+ * @author Stephen Dawson-Haggerty
+ */
+configuration Ieee154MessageC  {
+  provides {
+    interface SplitControl;
+
+    interface Resource as SendResource[uint8_t clientId];
+    interface Ieee154Send;
+    interface Receive as Ieee154Receive;
+
+    interface Ieee154Packet;
+    interface Packet;
+
+    interface PacketAcknowledgements;
+    interface LinkPacketMetadata;
+    interface LowPowerListening;
+    interface PacketLink;
+  }
+
+} implementation {
+  components CC2420Ieee154MessageC as Msg;
+
+  SplitControl = Msg;
+  SendResource = Msg;
+  Ieee154Send  = Msg;
+  Ieee154Receive = Msg;
+  Ieee154Packet = Msg;
+  Packet = Msg;
+  
+  PacketAcknowledgements = Msg;
+  LinkPacketMetadata = Msg;
+  LowPowerListening = Msg;
+  PacketLink = Msg;
+}
index 432200eafcfb161f206c5df3e66b95521c1d3e4c..da45e29b3f6e184c8826da4cf71683842aa7b210 100644 (file)
@@ -47,6 +47,8 @@ configuration TimeSyncMessageC {
     interface Receive as Snoop[am_id_t id];
     interface Packet;
     interface AMPacket;
+    interface PacketAcknowledgements;
+    interface LowPowerListening;
 
     interface PacketTimeStamp<T32khz, uint32_t> as PacketTimeStamp32khz;
     interface PacketTimeStamp<TMilli, uint32_t> as PacketTimeStampMilli;
@@ -67,6 +69,8 @@ implementation {
   Snoop        = AM.Snoop;
   Packet       = AM;
   AMPacket     = AM;
+  PacketAcknowledgements = AM;
+  LowPowerListening = AM;
   TimeSyncAMSend32khz       = AM;
   TimeSyncAMSendMilli       = AM;
   TimeSyncPacket32khz       = AM;
index b48ffbab12862b66bcc8452de15648853ab2a21d..61ed0f01ac2346a14f00fa68e4fa1bd4737cc713 100644 (file)
@@ -32,19 +32,19 @@ configuration HplAt45dbC {
 }
 implementation {
 
-  components  new HplAt45dbByteC(9),
-                                                       new Msp430Spi0C() as Spi,
-                                                       HplAt45dbP,
-                                                       HplMsp430GeneralIOC as MspGeneralIO,
-                                                       new Msp430GpioC() as Select;
+  components new HplAt45dbByteC(9),
+       new Msp430Spi0C() as Spi,
+       HplAt45dbP,
+       HplMsp430GeneralIOC as MspGeneralIO,
+       new Msp430GpioC() as Select;
 
-       HplAt45db = HplAt45dbByteC;
+  HplAt45db = HplAt45dbByteC;
 
   HplAt45dbByteC.Resource -> Spi;
   HplAt45dbByteC.FlashSpi -> Spi;
   HplAt45dbByteC.HplAt45dbByte -> HplAt45dbP;
 
-       Select -> MspGeneralIO.Port44;
-       HplAt45dbP.Select -> Select;
-       HplAt45dbP.FlashSpi -> Spi;
+  Select -> MspGeneralIO.Port44;
+  HplAt45dbP.Select -> Select;
+  HplAt45dbP.FlashSpi -> Spi;
 }
index b7e73980a5e85d53e432adf091123830ae1683b0..79fc4c009f95c136c65a0affdbb74ac1ca363a61 100644 (file)
@@ -33,7 +33,7 @@ module HplAt45dbP {
     interface HplAt45dbByte;
   }
   uses {
-               interface SpiByte as FlashSpi;
+    interface SpiByte as FlashSpi;
     interface GeneralIO as Select;
   }
 }
@@ -47,23 +47,23 @@ implementation
     call Select.set();
   }
 
-       task void idleTask() {
-               uint8_t status;
-               status = call FlashSpi.write(0);
-               if (!(status & 0x80)) {
-                       post idleTask();
-               } else {
-                       signal HplAt45dbByte.idle();
-               }
-       }
+  task void idleTask() {
+    uint8_t status;
+    status = call FlashSpi.write(0);
+    if (!(status & 0x80)) {
+      post idleTask();
+    } else {
+      signal HplAt45dbByte.idle();
+    }
+  }
 
   command void HplAt45dbByte.waitIdle() {
-               post idleTask();
+    post idleTask();
   }
 
   command bool HplAt45dbByte.getCompareStatus() {
-               uint8_t status;
-               status = call FlashSpi.write(0);
+    uint8_t status;
+    status = call FlashSpi.write(0);
     return (!(status & 0x40));
   }
 }
index 405ba4f3c932ff4e9bf26c2ca41c9709b98f1c1b..b1b1939551bc20a85a9d303630e7355f752bda82 100644 (file)
@@ -4,6 +4,12 @@
 
 #include "msp430hardware.h"
 
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = MSP430_POWER_ACTIVE,
+};
+
 // LEDs
 TOSH_ASSIGN_PIN(RED_LED, 5, 4);
 TOSH_ASSIGN_PIN(GREEN_LED, 5, 5);
index 5fab8f266ded070330723927cc8cad79f1a27b4d..25c6401cbc070b9c0f4deaa77de138d18f48c0e1 100644 (file)
@@ -25,6 +25,7 @@ push( @includes, qw(
   %T/chips/cc2420/spi
   %T/chips/cc2420/transmit
   %T/chips/cc2420/unique
+  %T/chips/cc2420/security
   %T/chips/msp430
   %T/chips/msp430/adc12
   %T/chips/msp430/dma
index 8b720fa288fc8ca3fcdfbe99e6b52f33ed703058..50bac24689954ccec386ff08e0268e2c9b8d5555 100644 (file)
@@ -2,9 +2,12 @@
 #define _H_hardware_h
 
 #include "msp430hardware.h"
-//#include "MSP430ADC12.h"
-//#include "CC2420Const.h"
-//#include "AM.h"
+
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = MSP430_POWER_ACTIVE,
+};
 
 // LEDs
 TOSH_ASSIGN_PIN(RED_LED, 5, 4);
diff --git a/tos/platforms/telosb/mac/tkn154/Ieee802154BeaconEnabledC.nc b/tos/platforms/telosb/mac/tkn154/Ieee802154BeaconEnabledC.nc
new file mode 100644 (file)
index 0000000..74ce855
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154.h"
+configuration Ieee802154BeaconEnabledC
+{
+  provides
+  {
+    // MCPS-SAP
+    interface MCPS_DATA;
+    interface MCPS_PURGE;
+
+    // MLME-SAP
+    interface MLME_ASSOCIATE;
+    interface MLME_BEACON_NOTIFY;
+    interface MLME_COMM_STATUS;
+    interface MLME_DISASSOCIATE;
+    interface MLME_GET;
+/*    interface MLME_GTS;*/
+    interface MLME_ORPHAN;
+    interface MLME_POLL;
+    interface MLME_RESET;
+    interface MLME_RX_ENABLE;
+    interface MLME_SCAN;
+    interface MLME_SET;
+    interface MLME_START;
+    interface MLME_SYNC;
+    interface MLME_SYNC_LOSS;
+    interface IEEE154Frame;
+    interface IEEE154BeaconFrame;
+    interface IEEE154TxBeaconPayload;
+    interface SplitControl as PromiscuousMode;
+    interface Get<uint64_t> as LocalExtendedAddress;
+    interface Timestamp;
+    interface Packet;
+  }
+}
+implementation
+{
+  components TKN154BeaconEnabledP as MAC;
+
+  MLME_START = MAC;
+  MLME_GET = MAC;
+  MLME_SET = MAC;
+  MLME_RESET = MAC;
+  MLME_SYNC = MAC;
+  MLME_SYNC_LOSS = MAC;
+  MLME_BEACON_NOTIFY = MAC;
+  MLME_SCAN = MAC;
+  MCPS_DATA = MAC;
+  MCPS_PURGE = MAC;
+  MLME_ASSOCIATE = MAC;
+  MLME_DISASSOCIATE = MAC;
+  MLME_COMM_STATUS = MAC;
+  MLME_RX_ENABLE = MAC;
+  MLME_POLL = MAC;
+  MLME_ORPHAN = MAC;
+  IEEE154Frame = MAC;
+  IEEE154BeaconFrame = MAC;
+  LocalExtendedAddress = MAC;
+  IEEE154TxBeaconPayload = MAC;
+  PromiscuousMode = MAC;
+  Packet = MAC;
+
+  components CC2420TKN154C as PHY,
+             new Alarm62500hz32C() as PHYAlarm1,
+             new Alarm62500hz32VirtualizedC() as PHYAlarm2,
+             new Alarm62500hz32C() as TKN154TimingPAlarm,
+             LocalTime62500hzC, TKN154TimingP;
+
+  // wire PHY to the PIB
+  PHY.PIBUpdate[IEEE154_macShortAddress] -> MAC.PIBUpdate[IEEE154_macShortAddress];
+  PHY.PIBUpdate[IEEE154_macPANId] -> MAC.PIBUpdate[IEEE154_macPANId];
+  PHY.PIBUpdate[IEEE154_phyCurrentChannel] -> MAC.PIBUpdate[IEEE154_phyCurrentChannel];
+  PHY.PIBUpdate[IEEE154_phyTransmitPower] -> MAC.PIBUpdate[IEEE154_phyTransmitPower];
+  PHY.PIBUpdate[IEEE154_phyCCAMode] -> MAC.PIBUpdate[IEEE154_phyCCAMode];
+  PHY.PIBUpdate[IEEE154_macPanCoordinator] -> MAC.PIBUpdate[IEEE154_macPanCoordinator];
+
+  Timestamp = PHY;
+  PHY.Alarm1 -> PHYAlarm1;
+  PHY.Alarm2 -> PHYAlarm2;
+  PHY.LocalTime -> LocalTime62500hzC;
+  PHY.CaptureTime -> TKN154TimingP;
+  PHY.ReliableWait -> TKN154TimingP;
+  PHY.ReferenceTime -> TKN154TimingP;
+  PHY.TimeCalc -> MAC;
+  TKN154TimingP.TimeCalc -> MAC;
+  TKN154TimingP.Leds -> LedsC;
+  TKN154TimingP.CCA -> PHY;
+  TKN154TimingP.SymbolAlarm -> TKN154TimingPAlarm;
+
+  components new Alarm62500hz32VirtualizedC() as  MACAlarm1,
+             new Alarm62500hz32VirtualizedC() as  MACAlarm2,
+             new Alarm62500hz32VirtualizedC() as  MACAlarm3,
+             new Alarm62500hz32VirtualizedC() as  MACAlarm4,
+             new Alarm62500hz32VirtualizedC() as  MACAlarm5,
+             new Alarm62500hz32VirtualizedC() as  MACAlarm6,
+             new Alarm62500hz32VirtualizedC() as  MACAlarm7,
+             new Alarm62500hz32VirtualizedC() as  MACAlarm8,
+             new Alarm62500hz32VirtualizedC() as  MACAlarm9,
+
+             new Timer62500C() as  MACTimer1,
+             new Timer62500C() as  MACTimer2,
+             new Timer62500C() as  MACTimer3,
+             new Timer62500C() as  MACTimer4,
+             new Timer62500C() as  MACTimer5;
+
+  MAC.Alarm1 ->  MACAlarm1;
+  MAC.Alarm2 ->  MACAlarm2;
+  MAC.Alarm3 ->  MACAlarm3;
+  MAC.Alarm4 ->  MACAlarm4;
+  MAC.Alarm5 ->  MACAlarm5;
+  MAC.Alarm6 ->  MACAlarm6;
+  MAC.Alarm7 ->  MACAlarm7;
+  MAC.Alarm8 ->  MACAlarm8;
+  MAC.Alarm9 ->  MACAlarm9;
+
+  MAC.Timer1 -> MACTimer1;
+  MAC.Timer2 -> MACTimer2;
+  MAC.Timer3 -> MACTimer3;
+  MAC.Timer4 -> MACTimer4;
+  MAC.Timer5 -> MACTimer5;
+  MAC.LocalTime -> LocalTime62500hzC;
+
+  // wire MAC <-> PHY
+  MAC.RadioTx -> PHY;
+  MAC.SlottedCsmaCa -> PHY;
+  MAC.RadioRx -> PHY;
+  MAC.RadioOff -> PHY;
+  MAC.EnergyDetection -> PHY;
+  MAC.PhySplitControl -> PHY;
+  MAC.RadioPromiscuousMode -> PHY.RadioPromiscuousMode;
+  PHY.FrameUtility -> MAC;
+
+  components RandomC, LedsC, NoLedsC;
+  MAC.Random -> RandomC;
+  MAC.Leds -> LedsC;
+  PHY.Random -> RandomC;
+
+#ifdef TKN154_DEBUG
+  components DebugC;
+#endif
+}
diff --git a/tos/platforms/telosb/mac/tkn154/Ieee802154MacC.nc b/tos/platforms/telosb/mac/tkn154/Ieee802154MacC.nc
deleted file mode 100644 (file)
index f59ebd7..0000000
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (c) 2008, Technische Universitaet Berlin
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met:
- * - Redistributions of source code must retain the above copyright notice,
- *   this list of conditions and the following disclaimer.
- * - Redistributions in binary form must reproduce the above copyright 
- *   notice, this list of conditions and the following disclaimer in the 
- *   documentation and/or other materials provided with the distribution.
- * - Neither the name of the Technische Universitaet Berlin nor the names 
- *   of its contributors may be used to endorse or promote products derived
- *   from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
- * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
- * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
- * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * - Revision -------------------------------------------------------------
- * $Revision$
- * $Date$
- * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
- * ========================================================================
- */
-#include "TKN154.h"
-#include "TKN154_DEBUG.h"
-configuration Ieee802154MacC
-{
-  provides
-  {
-    // MCPS-SAP
-    interface MCPS_DATA;
-    interface MCPS_PURGE;
-
-    // MLME-SAP
-    interface MLME_ASSOCIATE;
-    interface MLME_BEACON_NOTIFY;
-    interface MLME_COMM_STATUS;
-    interface MLME_DISASSOCIATE;
-    interface MLME_GET;
-/*    interface MLME_GTS;*/
-    interface MLME_ORPHAN;
-    interface MLME_POLL;
-    interface MLME_RESET;
-    interface MLME_RX_ENABLE;
-    interface MLME_SCAN;
-    interface MLME_SET;
-    interface MLME_START;
-    interface MLME_SYNC;
-    interface MLME_SYNC_LOSS;
-    interface IEEE154Frame;
-    interface IEEE154BeaconFrame;
-    interface IEEE154TxBeaconPayload;
-    interface SplitControl as PromiscuousMode;
-    interface Get<uint64_t> as LocalExtendedAddress;
-    interface Timestamp;
-    interface Packet;
-  }
-}
-implementation
-{
-  components TKN154P as MAC;
-
-  MLME_START = MAC;
-  MLME_GET = MAC;
-  MLME_SET = MAC;
-  MLME_RESET = MAC;
-  MLME_SYNC = MAC;
-  MLME_SYNC_LOSS = MAC;
-  MLME_BEACON_NOTIFY = MAC;
-  MLME_SCAN = MAC;
-  MCPS_DATA = MAC;
-  MCPS_PURGE = MAC;
-  MLME_ASSOCIATE = MAC;
-  MLME_DISASSOCIATE = MAC;
-  MLME_COMM_STATUS = MAC;
-  MLME_RX_ENABLE = MAC;
-  MLME_POLL = MAC;
-  MLME_ORPHAN = MAC;
-  IEEE154Frame = MAC;
-  IEEE154BeaconFrame = MAC;
-  LocalExtendedAddress = MAC;
-  IEEE154TxBeaconPayload = MAC;
-  PromiscuousMode = MAC;
-  Packet = MAC;
-
-  components CC2420TKN154C as PHY,
-             new Alarm62500hz32VirtualizedC() as PHYAlarm1,
-             new Alarm62500hz32VirtualizedC() as PHYAlarm2,
-             LocalTime62500hzC, TKN154TimingP;
-
-  // wire PHY to the PIB
-  PHY.PIBUpdate[IEEE154_macShortAddress] -> MAC.PIBUpdate[IEEE154_macShortAddress];
-  PHY.PIBUpdate[IEEE154_macPANId] -> MAC.PIBUpdate[IEEE154_macPANId];
-  PHY.PIBUpdate[IEEE154_phyCurrentChannel] -> MAC.PIBUpdate[IEEE154_phyCurrentChannel];
-  PHY.PIBUpdate[IEEE154_phyTransmitPower] -> MAC.PIBUpdate[IEEE154_phyTransmitPower];
-  PHY.PIBUpdate[IEEE154_phyCCAMode] -> MAC.PIBUpdate[IEEE154_phyCCAMode];
-  PHY.PIBUpdate[IEEE154_macPanCoordinator] -> MAC.PIBUpdate[IEEE154_macPanCoordinator];
-
-  Timestamp = PHY;
-  PHY.Alarm1 -> PHYAlarm1;
-  PHY.Alarm2 -> PHYAlarm2;
-  PHY.LocalTime -> LocalTime62500hzC;
-  PHY.CaptureTime -> TKN154TimingP;
-  PHY.ReliableWait -> TKN154TimingP;
-  PHY.ReferenceTime -> TKN154TimingP;
-  PHY.TimeCalc -> MAC;
-  PHY.Leds -> LedsC;
-  TKN154TimingP.TimeCalc -> MAC;
-  TKN154TimingP.LocalTime -> LocalTime62500hzC;
-
-  components new Alarm62500hz32VirtualizedC() as  MACAlarm1,
-             new Alarm62500hz32VirtualizedC() as  MACAlarm2,
-             new Alarm62500hz32VirtualizedC() as  MACAlarm3,
-             new Alarm62500hz32VirtualizedC() as  MACAlarm4,
-             new Alarm62500hz32VirtualizedC() as  MACAlarm5,
-             new Alarm62500hz32VirtualizedC() as  MACAlarm6,
-             new Alarm62500hz32VirtualizedC() as  MACAlarm7,
-             new Alarm62500hz32VirtualizedC() as  MACAlarm8,
-             new Alarm62500hz32VirtualizedC() as  MACAlarm9,
-
-             new Timer62500C() as  MACTimer1,
-             new Timer62500C() as  MACTimer2,
-             new Timer62500C() as  MACTimer3,
-             new Timer62500C() as  MACTimer4,
-             new Timer62500C() as  MACTimer5;
-
-  MAC.Alarm1 ->  MACAlarm1;
-  MAC.Alarm2 ->  MACAlarm2;
-  MAC.Alarm3 ->  MACAlarm3;
-  MAC.Alarm4 ->  MACAlarm4;
-  MAC.Alarm5 ->  MACAlarm5;
-  MAC.Alarm6 ->  MACAlarm6;
-  MAC.Alarm7 ->  MACAlarm7;
-  MAC.Alarm8 ->  MACAlarm8;
-  MAC.Alarm9 ->  MACAlarm9;
-
-  MAC.Timer1 -> MACTimer1;
-  MAC.Timer2 -> MACTimer2;
-  MAC.Timer3 -> MACTimer3;
-  MAC.Timer4 -> MACTimer4;
-  MAC.Timer5 -> MACTimer5;
-  MAC.LocalTime -> LocalTime62500hzC;
-
-  // wire MAC <-> PHY
-  MAC.RadioTx -> PHY;
-  MAC.RadioRx -> PHY;
-  MAC.RadioOff -> PHY;
-  MAC.EnergyDetection -> PHY;
-  MAC.PhySplitControl -> PHY;
-  MAC.RadioPromiscuousMode -> PHY.RadioPromiscuousMode;
-  PHY.FrameUtility -> MAC;
-
-  components RandomC, LedsC, NoLedsC;
-  MAC.Random -> RandomC;
-  MAC.Leds -> LedsC;
-
-#ifdef TKN154_SERIAL_DEBUG
-  components SerialDebugC as Debug;
-#else
-  components NoDebugP as Debug;
-#endif
-  MAC.Ieee802154Debug -> Debug;
-}
diff --git a/tos/platforms/telosb/mac/tkn154/Ieee802154NonBeaconEnabledC.nc b/tos/platforms/telosb/mac/tkn154/Ieee802154NonBeaconEnabledC.nc
new file mode 100644 (file)
index 0000000..4bc755a
--- /dev/null
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Revision$
+ * $Date$
+ * @author: Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+#include "TKN154.h"
+configuration Ieee802154NonBeaconEnabledC
+{
+  provides
+  {
+    // MCPS-SAP
+    interface MCPS_DATA;
+    interface MCPS_PURGE;
+
+    // MLME-SAP
+    interface MLME_ASSOCIATE;
+    interface MLME_BEACON_NOTIFY;
+    interface MLME_COMM_STATUS;
+    interface MLME_DISASSOCIATE;
+    interface MLME_GET;
+    interface MLME_ORPHAN;
+    interface MLME_POLL;
+    interface MLME_RESET;
+    interface MLME_RX_ENABLE;
+    interface MLME_SCAN;
+    interface MLME_SET;
+    interface MLME_START;
+    interface IEEE154Frame;
+    interface IEEE154BeaconFrame;
+    interface IEEE154TxBeaconPayload;
+    interface SplitControl as PromiscuousMode;
+    interface Get<uint64_t> as LocalExtendedAddress;
+    interface Timestamp;
+    interface Packet;
+  }
+}
+implementation
+{
+  components TKN154NonBeaconEnabledP as MAC;
+
+  MLME_START = MAC;
+  MLME_GET = MAC;
+  MLME_SET = MAC;
+  MLME_RESET = MAC;
+  MLME_BEACON_NOTIFY = MAC;
+  MLME_SCAN = MAC;
+  MCPS_DATA = MAC;
+  MCPS_PURGE = MAC;
+  MLME_ASSOCIATE = MAC;
+  MLME_DISASSOCIATE = MAC;
+  MLME_COMM_STATUS = MAC;
+  MLME_RX_ENABLE = MAC;
+  MLME_POLL = MAC;
+  MLME_ORPHAN = MAC;
+  IEEE154Frame = MAC;
+  IEEE154BeaconFrame = MAC;
+  IEEE154TxBeaconPayload = MAC;
+  LocalExtendedAddress = MAC;
+  PromiscuousMode = MAC;
+  Packet = MAC;
+
+  components CC2420TKN154C as PHY,
+             new Alarm62500hz32C() as PHYAlarm1,
+             new Alarm62500hz32VirtualizedC() as PHYAlarm2,
+             new Alarm62500hz32C() as TKN154TimingPAlarm,
+             LocalTime62500hzC, TKN154TimingP;
+
+  // wire PHY to the PIB
+  PHY.PIBUpdate[IEEE154_macShortAddress] -> MAC.PIBUpdate[IEEE154_macShortAddress];
+  PHY.PIBUpdate[IEEE154_macPANId] -> MAC.PIBUpdate[IEEE154_macPANId];
+  PHY.PIBUpdate[IEEE154_phyCurrentChannel] -> MAC.PIBUpdate[IEEE154_phyCurrentChannel];
+  PHY.PIBUpdate[IEEE154_phyTransmitPower] -> MAC.PIBUpdate[IEEE154_phyTransmitPower];
+  PHY.PIBUpdate[IEEE154_phyCCAMode] -> MAC.PIBUpdate[IEEE154_phyCCAMode];
+  PHY.PIBUpdate[IEEE154_macPanCoordinator] -> MAC.PIBUpdate[IEEE154_macPanCoordinator];
+
+  Timestamp = PHY;
+  PHY.Alarm1 -> PHYAlarm1;
+  PHY.Alarm2 -> PHYAlarm2;
+  PHY.LocalTime -> LocalTime62500hzC;
+  PHY.CaptureTime -> TKN154TimingP;
+  PHY.ReliableWait -> TKN154TimingP;
+  PHY.ReferenceTime -> TKN154TimingP;
+  PHY.TimeCalc -> MAC;
+  TKN154TimingP.TimeCalc -> MAC;
+  TKN154TimingP.Leds -> LedsC;
+  TKN154TimingP.CCA -> PHY;
+  TKN154TimingP.SymbolAlarm -> TKN154TimingPAlarm;
+
+  components new Timer62500C() as  MACTimer1,
+             new Timer62500C() as  MACTimer2,
+             new Timer62500C() as  MACTimer3,
+             new Timer62500C() as  MACTimer4,
+             new Timer62500C() as  MACTimer5;
+
+  MAC.Timer1 -> MACTimer1;
+  MAC.Timer2 -> MACTimer2;
+  MAC.Timer3 -> MACTimer3;
+  MAC.Timer4 -> MACTimer4;
+  MAC.Timer5 -> MACTimer5;
+  MAC.LocalTime -> LocalTime62500hzC;
+
+  // wire MAC <-> PHY
+  MAC.RadioTx -> PHY;
+  MAC.UnslottedCsmaCa -> PHY;
+  MAC.RadioRx -> PHY;
+  MAC.RadioOff -> PHY;
+  MAC.EnergyDetection -> PHY;
+  MAC.PhySplitControl -> PHY;
+  MAC.RadioPromiscuousMode -> PHY.RadioPromiscuousMode;
+  PHY.FrameUtility -> MAC;
+
+  components RandomC, LedsC, NoLedsC;
+  MAC.Random -> RandomC;
+  MAC.Leds -> LedsC;
+  PHY.Random -> RandomC;
+
+#ifdef TKN154_DEBUG
+  components DebugC;
+#endif
+}
index 2d72821179f89dca6aeb885fc6f90826fb4fac5f..b109e1d792fd17333d70c1c5fa0bc5179b070ee8 100644 (file)
@@ -1,3 +1,7 @@
+ifdef TKN154_PIERCEBOARD
+CFLAGS += -I$(TOSDIR)/platforms/telosb/mac/tkn154/timer/pierceboard
+endif
+
 CFLAGS += -I$(TOSDIR)/platforms/telosb/mac/tkn154 \
        -I$(TOSDIR)/platforms/telosb/mac/tkn154/timer \
        -I$(TOSDIR)/chips/cc2420_tkn154
index d9713c201d0985a60f553d5b45fa8ad8d96caa11..fe2782b7ea753c53d1d9a915b8663d15c9be3edc 100644 (file)
  */
 
 /** 
- * NOTE:
  * In slotted CSMA-CA frames must be sent on backoff boundaries (slot width:
- * 320 us). On TelosB the only clock source with sufficient accuracy is the
- * external quartz, unfortunately it is not precise enough (32.768 Hz).
- * Therefore, currently the following code is not even trying to achieve
- * accurate timing. 
+ * 320 us). The TelosB platform lacks a clock with sufficient precision and
+ * accuracy, i.e. for slotted CSMA-CA the timing is *not* standard compliant
+ * (this code is experimental)
  */
 
 #include "TKN154_platform.h"
@@ -49,24 +47,26 @@ module TKN154TimingP
   provides interface ReliableWait;
   provides interface ReferenceTime;
   uses interface TimeCalc;
-  uses interface LocalTime<T62500hz>;
+  uses interface GetNow<bool> as CCA;
+  uses interface Alarm<T62500hz,uint32_t> as SymbolAlarm;
+  uses interface Leds;
 }
 implementation
 {
+  enum {
+    S_WAIT_OFF,
+    S_WAIT_RX,
+    S_WAIT_TX,
+    S_WAIT_BACKOFF,
+  };
+  uint8_t m_state = S_WAIT_OFF;
 
-#define UWAIT1 nop();nop();nop();nop()
-#define UWAIT2 UWAIT1;UWAIT1
-#define UWAIT4 UWAIT2;UWAIT2
-#define UWAIT8 UWAIT4;UWAIT4
-
-  async command void CaptureTime.convert(uint16_t time, ieee154_reftime_t *localTime, int16_t offset)
+  async command error_t CaptureTime.convert(uint16_t time, ieee154_timestamp_t *localTime, int16_t offset)
   {
     // TimerB is used for capturing, it is sourced by ACLK (32768Hz),
-    // we now need to convert the capture "time" into ieee154_reftime_t.
+    // we now need to convert the capture "time" into ieee154_timestamp_t.
     // With the 32768Hz quartz we don't have enough precision anyway,
     // so the code below generates a timestamp that is not accurate
-    // (deviating about +-50 microseconds; this could probably
-    // improved if we don't go through LocalTime)
     uint16_t tbr1, tbr2, delta;
     uint32_t now;
     atomic {
@@ -74,51 +74,78 @@ implementation
         tbr1 = TBR;
         tbr2 = TBR;
       } while (tbr1 != tbr2); // majority vote required (see msp430 manual)
-      now = call LocalTime.get(); 
+      now = call SymbolAlarm.getNow(); 
     }
     if (time < tbr1)
       delta = tbr1 - time;
     else
       delta = ~(time - tbr1) + 1;
-    *localTime = now - delta*2 + offset;
+    *localTime = now - delta * 2 + offset; /* one tick of TimerB ~ two symbols */
+    return SUCCESS;
   }
 
-  async command void ReliableWait.busyWait(uint16_t dt)
+  async command bool ReliableWait.ccaOnBackoffBoundary(ieee154_timestamp_t *slot0)
   {
-    uint32_t start = call LocalTime.get();
-    while (!call TimeCalc.hasExpired(start, dt))
-      ;
+    // There is no point in trying
+    return (call CCA.getNow() ? 20: 0);
   }
 
-  async command void ReliableWait.waitCCA(ieee154_reftime_t *t0, uint16_t dt)
+  async command bool CaptureTime.isValidTimestamp(uint16_t risingSFDTime, uint16_t fallingSFDTime)
   {
-    while (!call TimeCalc.hasExpired(*t0, dt))
-      ;
-    signal ReliableWait.waitCCADone();
+    // smallest packet (ACK) takes 
+    // length field (1) + MPDU (5) = 6 byte => 12 * 16 us = 192 us 
+    return (fallingSFDTime - risingSFDTime) > 5;
   }
 
-  async command void ReliableWait.waitTx(ieee154_reftime_t *t0, uint16_t dt)
+  async command void ReliableWait.waitRx(uint32_t t0, uint32_t dt)
   {
-    while (!call TimeCalc.hasExpired(*t0, dt))
-      ;
-    signal ReliableWait.waitTxDone();
+    if (m_state != S_WAIT_OFF){
+      ASSERT(0);
+      return;
+    }
+    m_state = S_WAIT_RX;
+    call SymbolAlarm.startAt(t0 - 16, dt); // subtract 12 symbols required for Rx calibration
   }
 
-  async command void ReliableWait.waitRx(ieee154_reftime_t *t0, uint16_t dt)
+  async command void ReliableWait.waitTx(ieee154_timestamp_t *t0, uint32_t dt)
+  {
+    if (m_state != S_WAIT_OFF){
+      ASSERT(0);
+      return;
+    }
+    m_state = S_WAIT_TX;
+    call SymbolAlarm.startAt(*t0 - 16, dt); // subtract 12 symbols required for Tx calibration
+  }
+    
+  async command void ReliableWait.waitBackoff(uint32_t dt)
   {
-    while (!call TimeCalc.hasExpired(*t0, dt))
-      ;
-    signal ReliableWait.waitRxDone();
+    if (m_state != S_WAIT_OFF){
+      ASSERT(0);
+      return;
+    }
+    m_state = S_WAIT_BACKOFF;
+    call SymbolAlarm.start(dt);
   }
-  async command void ReferenceTime.getNow(ieee154_reftime_t* reftime, uint16_t dt)
+
+  async event void SymbolAlarm.fired() 
+  {
+    switch (m_state)
+    {
+      case S_WAIT_RX: m_state = S_WAIT_OFF; signal ReliableWait.waitRxDone(); break;
+      case S_WAIT_TX: m_state = S_WAIT_OFF; signal ReliableWait.waitTxDone(); break;
+      case S_WAIT_BACKOFF: m_state = S_WAIT_OFF; signal ReliableWait.waitBackoffDone(); break;
+      default: ASSERT(0); break;
+    }
+  }
+
+  async command void ReferenceTime.getNow(ieee154_timestamp_t* timestamp, uint16_t dt)
   {
-    *reftime = call LocalTime.get();
+    *timestamp = call SymbolAlarm.getNow() + dt;
   }
 
-  async command uint32_t ReferenceTime.toLocalTime(ieee154_reftime_t* refTime)
+  async command uint32_t ReferenceTime.toLocalTime(const ieee154_timestamp_t* timestamp)
   {
-    return *refTime;
+    return *timestamp;
   } 
 
 }
index e129e2550377a11738d0a59d6237dd6c3c59aff0..fe5ae790bd1ed7e0988d49cbd049328632f44a87 100644 (file)
 
 /**************************************************** 
  * The following constants define guard times on Tmote Sky / TelosB. 
- * All values are in symbol time (1 symbol = 16 us)
+ * All values are in symbol time (1 symbol = 16 us) and assume the 
+ * default system configuration (MCLK running at 4 MHz)
  */
 
 enum {
-  // guard time to give up the token before actual end of CAP/CFP
-  IEEE154_RADIO_GUARD_TIME = 1000,
+  // the expected maximum time between calling a transmit() operation and
+  // the radio putting the first byte on the channel assuming no CSMA-CA
+  IEEE154_RADIO_TX_DELAY = 400,
 
-  // the expected time for a RadioTx.prepare() operation to execute (return)
-  IEEE154_RADIO_TX_PREPARE_DELAY = 220,
+  // the expected maximum time between calling a receive() operation and the 
+  // the radio actually being put in receive mode
+  IEEE154_RADIO_RX_DELAY = 400,
 
-  // the *guaranteed maximum* time between calling a RadioTx.transmit() and the
-  // first PPDU bit being put onto the channel, assuming that RadioTx.transmit() 
-  // is called inside an atomic block
-  IEEE154_RADIO_TX_SEND_DELAY = 100,
-
-  // the expected time for a RadioRx.prepare() operation to execute (return)
-  IEEE154_RADIO_RX_PREPARE_DELAY = 300,
-
-  // the *guaranteed maximum* time between calling a RadioTx.transmit() and the
-  // first PPDU bit being put onto the channel, assuming that RadioTx.transmit() 
-  // is called inside an atomic block
-  IEEE154_RADIO_RX_DELAY = 100,
-
-  // defines at what time the MAC payload for a beacon frame is assembled prior
-  // to the next scheduled beacon transmission time; must be smaller than both
-  // the beacon interval and IEEE154_RADIO_TX_PREPARE_DELAY
+  // defines at what time the MAC payload for a beacon frame is assembled before
+  // the next scheduled beacon transmission time; the value must be smaller than 
+  // the beacon interval plus the time for preparing the Tx operation
   BEACON_PAYLOAD_UPDATE_INTERVAL = 2500, 
 };
 
-typedef uint32_t ieee154_reftime_t;
+typedef uint32_t ieee154_timestamp_t;
 
 #endif
 
index bbff8982d172a60903745ef4f249a39dbcbee008..f13513df76fb702c0787a3cd61a361a45eed1922 100644 (file)
@@ -6,27 +6,11 @@
 
 #include <Serial.h>
 
-#ifndef IEEE154_OLD_INTERFACES
+/* The following include pulls in the ieee154_header_t/ieee154_metadata_t definitions */
 #include <TKN154_MAC.h>
-#else
-typedef struct {
-  uint8_t control;  // stores length (lower 7 bits), top bit -> promiscuous mode
-  uint8_t mhr[23];
-} ieee154_header_t;
-
-typedef struct {
-  uint8_t rssi;
-  uint8_t linkQuality;
-  uint32_t timestamp;
-} ieee154_metadata_t;
-#endif
 
-#ifdef TOSH_DATA_LENGTH
-#undef TOSH_DATA_LENGTH
-#endif
-// TOSH_DATA_LENGTH may be smaller than 118, but then we'll
-// not be able to receive/send all IEEE 802.15.4 packets 
-#define TOSH_DATA_LENGTH 118
+/* TOSH_DATA_LENGTH should be the maximum length of the MAC payload */
+#define TOSH_DATA_LENGTH IEEE154_aMaxMACPayloadSize
 
 typedef union message_header {
   ieee154_header_t ieee154;
index f0a4f13b5ef642835acbaa35a37203a010371d53..290543cd56d3d2a6d8d43bacd47541e515099866 100644 (file)
@@ -9,8 +9,6 @@ implementation
   components new VirtualizeAlarmC(T32khz, uint32_t, uniqueCount(UQ_ALARM_32KHZ32));
 
   Alarm = VirtualizeAlarmC;
-
-  MainC -> Alarm32khz32C.Init;
   MainC -> VirtualizeAlarmC.Init;
   VirtualizeAlarmC.AlarmFrom -> Alarm32khz32C;
 }
index 20f0822d49e1d7863038d7f834e28b9ad3770734..e601285549487f9288a26f2e8b1e9e98afa16bd2 100644 (file)
@@ -40,12 +40,17 @@ module Alarm32khzTo62500hzTransformC
 }
 implementation
 {
-/**
- * This is the place where we cheat: since we don't have a clock source
- * running at 62500 Hz, we cast 2 symbols to 1 tick of the 32768
- * clock, which introduces a small (5%) error.
-*/
-#warning "Warning: MAC timing is not standard compliant (the symbol clock is based on the 32768 Hz oscillator)!"
+
+  /**
+   * TelosB lacks a clock that satisfies the precision and accuracy 
+   * requirements of the IEEE 802.15.4 standard (62500 Hz, +-40 ppm).
+   * As a workaround, we cast one tick of the 32768 Hz clock to two
+   * IEEE 802.15.4 symbols, which introduces a small (5%) error.
+   * As a consequence the timing of the beacon interval and slotted 
+   * CSMA-CA algorithm is not standard-compliant anymore.
+   */
+
+#warning "Warning: MAC timing is not standard compliant!"
 
   async command void Alarm.start[ uint8_t num ](uint32_t dt){ call AlarmFrom.start[num](dt >> 1);}
   async command void Alarm.stop[ uint8_t num ](){ call AlarmFrom.stop[num]();}
@@ -61,15 +66,17 @@ implementation
 
   async command void Alarm.startAt[ uint8_t num ](uint32_t t0, uint32_t dt){
     // t0 occured before "now"
-    uint32_t now = call Alarm.getNow[num](), elapsed;
-    if (t0 <= now)
-      elapsed = now - t0;
-    else
-      elapsed = ~(t0 - now) + 1;
-    if (elapsed > dt)
-      elapsed = dt;
-    dt -= elapsed;
-    call AlarmFrom.start[num](dt >> 1);
+    atomic {
+      uint32_t now = call Alarm.getNow[num](), elapsed;
+      if (t0 < now)
+        elapsed = now - t0;
+      else
+        elapsed = ~(t0 - now) + 1;
+      if (elapsed > dt)
+        dt = elapsed;
+      dt -= elapsed;
+      call Alarm.start[num](dt);
+    }
   }
 
   /******************** Defaults ****************************/
diff --git a/tos/platforms/telosb/mac/tkn154/timer/Alarm62500hz32C.nc b/tos/platforms/telosb/mac/tkn154/timer/Alarm62500hz32C.nc
new file mode 100644 (file)
index 0000000..b73e637
--- /dev/null
@@ -0,0 +1,17 @@
+#include "Timer62500hz.h"
+generic configuration Alarm62500hz32C()
+{
+  provides interface Alarm<T62500hz,uint32_t> as Alarm;
+}
+implementation
+{
+  components new Alarm32khz32C(), MainC;
+  components new Alarm62500hz32P();
+
+  Alarm = Alarm62500hz32P;
+
+#if defined(PLATFORM_TELOSB)
+  MainC -> Alarm32khz32C.Init;
+#endif
+  Alarm62500hz32P.AlarmFrom -> Alarm32khz32C;
+}
diff --git a/tos/platforms/telosb/mac/tkn154/timer/Alarm62500hz32P.nc b/tos/platforms/telosb/mac/tkn154/timer/Alarm62500hz32P.nc
new file mode 100644 (file)
index 0000000..7d6d886
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2008, Technische Universitaet Berlin
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without 
+ * modification, are permitted provided that the following conditions 
+ * are met:
+ * - Redistributions of source code must retain the above copyright notice,
+ *   this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright 
+ *   notice, this list of conditions and the following disclaimer in the 
+ *   documentation and/or other materials provided with the distribution.
+ * - Neither the name of the Technische Universitaet Berlin nor the names 
+ *   of its contributors may be used to endorse or promote products derived
+ *   from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
+ * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
+ * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE 
+ * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * - Revision -------------------------------------------------------------
+ * $Date$
+ * @author Jan Hauer <hauer@tkn.tu-berlin.de>
+ * ========================================================================
+ */
+
+generic module Alarm62500hz32P()
+
+{
+  provides interface Alarm<T62500hz,uint32_t> as Alarm;
+  uses interface Alarm<T32khz,uint32_t> as AlarmFrom;
+}
+implementation
+{
+/**
+ * TelosB lacks a clock with the precision and accuracy 
+ * required by the 802.15.4 standard (62500 Hz, 40 ppm).
+ * As a workaround, we cast one tick of the 32768 Hz clock to 
+ * two 802.15.4 symbols, which introduces a small (5%) error.
+ * Thus the channel access in particular in beacon-enabled PANs 
+ * (slotted CSMA-CA) is not be standard-compliant!
+ */
+
+  async command void Alarm.start(uint32_t dt){ call AlarmFrom.start(dt >> 1);}
+  async command void Alarm.stop(){ call AlarmFrom.stop();}
+  async event void AlarmFrom.fired(){ signal Alarm.fired();}
+  async command bool Alarm.isRunning(){ return call AlarmFrom.isRunning();}
+  async command uint32_t Alarm.getAlarm(){ return call AlarmFrom.getAlarm() << 1;}
+
+  async command uint32_t Alarm.getNow(){ 
+    // this might shift out the most significant bit
+    // that's why Alarm.startAt() is converted to a Alarm.start()
+    return call AlarmFrom.getNow() << 1; 
+  }
+
+  async command void Alarm.startAt(uint32_t t0, uint32_t dt){
+    // t0 occured before "now"
+    atomic {
+      uint32_t now = call Alarm.getNow(), elapsed;
+      if (t0 < now)
+        elapsed = now - t0;
+      else
+        elapsed = ~(t0 - now) + 1;
+      if (elapsed > dt)
+        dt = elapsed;
+      dt -= elapsed;
+      call Alarm.start(dt);
+    }
+  }
+
+  /******************** Defaults ****************************/
+
+  default async command void AlarmFrom.start(uint32_t dt){ }
+  default async command void AlarmFrom.stop(){ }
+  default async command bool AlarmFrom.isRunning(){ return FALSE;}
+  default async event void Alarm.fired(){}
+  default async command void AlarmFrom.startAt(uint32_t t0, uint32_t dt){ }
+  default async command uint32_t AlarmFrom.getNow(){ return 0;}
+  default async command uint32_t AlarmFrom.getAlarm(){ return 0;}
+}
index eaa8005192d9f8910fc0a0ee4e4b30d14db13821..b5a939cd2950b665f9702b75d67ac4bffef3f4f2 100644 (file)
 
 #include "msp430hardware.h"
 
+// enum so components can override power saving,
+// as per TEP 112.
+enum {
+  TOS_SLEEP_NONE = MSP430_POWER_ACTIVE,
+};
 
 // XE1205 radio
 TOSH_ASSIGN_PIN(NSS_DATA, 1, 0);
index 31e7cc29219ae5200139e6a08969d609b54ebd7b..47886257e506b164b654dbd711d299c0eea547e3 100644 (file)
  * OF THE POSSIBILITY OF SUCH DAMAGE
  */
 
-/** 
+/**
  * DemoSensorC is a generic sensor device that provides a 16-bit
  * value. The platform author chooses which sensor actually sits
  * behind DemoSensorC, and though it's probably Voltage, Light, or
  * Temperature, there are no guarantees.
  *
  * This particular DemoSensorC on the telosb platform provides a
- * voltage reading, using VoltageC. 
+ * voltage reading, using VoltageC.
  *
  * To convert from ADC counts to actual voltage, divide this reading
  * by 4096 and multiply by 3.
  *
  * @author Gilman Tolle <gtolle@archrock.com>
  * @version $Revision: 1.4 $ $Date: 2006/12/12 18:23:45 $
- * 
+ *
  */
 
 generic configuration DemoSensorC()
index 8060fa78a91dbca169156d97ef5dd38c95b48682..da4c4f4e013cef422d04d4a65764439e80423d14 100644 (file)
@@ -29,7 +29,7 @@
  * OF THE POSSIBILITY OF SUCH DAMAGE
  */
 
-/** 
+/**
  * DemoSensorNowC is a generic sensor device that provides a 16-bit
  * value that can be read from async context. The platform author
  * chooses which sensor actually sits behind DemoSensorNowC, and
@@ -44,7 +44,7 @@
  *
  * @author Gilman Tolle <gtolle@archrock.com>
  * @version $Revision: 1.4 $ $Date: 2006/12/12 18:23:45 $
- * 
+ *
  */
 
 generic configuration DemoSensorNowC()
index 5518a2dce4c32be5e3497aace688276b2386152b..08d40d5dafe895b8650da60f4b80e8da7db0983d 100644 (file)
  * OF THE POSSIBILITY OF SUCH DAMAGE
  */
 
-/** 
+/**
  * DemoSensorStreamC is a generic sensor device that provides a 16-bit
  * value. The platform author chooses which sensor actually sits
  * behind DemoSensorStreamC, and though it's probably Voltage, Light, or
  * Temperature, there are no guarantees.
  *
  * This particular DemoSensorStreamC on the telosb platform provides a
- * voltage reading, using VoltageStreamC. 
+ * voltage reading, using VoltageStreamC.
  *
  * To convert from ADC counts to actual voltage, divide this reading
  * by 4096 and multiply by 3.
  *
  * @author Gilman Tolle <gtolle@archrock.com>
  * @version $Revision: 1.4 $ $Date: 2006/12/12 18:23:45 $
- * 
+ *
  */
 
 generic configuration DemoSensorStreamC()
index 6a87fddfa2d580dca250320ac39661ea19110728..9963c605d889f16df69b39ac3c6c2e46aecdd7a7 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration HplUserButtonC {
   provides interface GeneralIO;
   provides interface GpioInterrupt;
index 4a76d7a30b47846e4c274d9db5d3050e19b1eef1..466560921af0527233b5142d6d8ead3c0e8ae379 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Set the DCO and ACLK specs here, effectively overriding those in
  * $TOSDIR/tos/chips/msp430/timer/Msp430DcoSpec.h  This is a little hokey.
  * I think I'd rather do it using a generic interface.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration MoteClockC {
   provides interface Init as MoteClockInit;
 }
index 68dcdd06e0ec42ddf417ff22ef16846f2106b60a..ca169f2758f1ec079134cef2b355f1377dd0c402 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "Msp430Timer.h"
 
 module MoteClockP {
index ebf625e87c65568e6818b3fd61a82e8e23f1564d..6882e6e8f15e36da42620592ce679049919a0291 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 module MotePlatformC @safe() {
   provides interface Init;
 }
@@ -51,7 +51,7 @@ implementation {
        P1OUT = 0x31;   /* 0 0 1 1 0 0 0 1 */
        P1DIR = 0x08;   /* 0 0 0 0 1 0 0 0 */
        P1REN = 0x35;   /* 0 0 1 1 0 1 0 1 */
+
        /* Port 2:
         * 7:-, 6:-, 5:BUTTONn, 4:USB_SUSPENDn, 3:-, 2:BSL_RX, 1:USBPGn,
         * 0:SOLARPGn
index ce7112985bc59fa65c4757afd63e1b3d267a4d4e..05b78044eeea34679d83ec4aff1c594beb74ed55 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include "hardware.h"
 
 configuration PlatformLedsC {
index 06cb3241843f4fd3b2bc3915e2d9ac33241c004d..28f4354ed1c17757958ed94c222b22a6bbd38567 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration PlatformSerialC {
   provides interface StdControl;
   provides interface UartStream;
index 02762e64ca6f67cb9be4f5ecd144fea1e999e2d3..25ef1b9d3db0f9e6876ef395a1e2de8093976c7d 100644 (file)
@@ -79,9 +79,9 @@ implementation {
   task void sendEvent() {
     bool pinHigh;
     pinHigh = m_pinHigh;
-    
+
     signal Notify.notify( pinHigh );
-    
+
     if ( pinHigh ) {
       call GpioInterrupt.enableFallingEdge();
     } else {
index 0d74849a57c262384e8fef3bf2f290a21d8c59c1..97f124ed883cf2329be734133b1f6b1c8065ba9d 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #ifndef USERBUTTON_H
 #define USERBUTTON_H
 
index c496bd2bcc05dbd57ff26ca40984d41e8ccd7df3..ff374ceccd123ab9ac5879f6d4da781fa89695c2 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include <UserButton.h>
 
 configuration UserButtonC {
index c5f20fe6e3b62589d1bf43d6259c0c3c2ea5c893..42e817efb62f2841be38b227b9e84c2f9bbe94a0 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 #include <UserButton.h>
 
 module UserButtonP {
@@ -41,8 +41,8 @@ module UserButtonP {
   uses interface Notify<bool> as NotifyLower;
 }
 implementation {
-  
-  command button_state_t Get.get() { 
+
+  command button_state_t Get.get() {
     /* tmirws user button pin is high when released - active low */
     if ( call GetLower.get() ) {
       return BUTTON_RELEASED;
@@ -67,6 +67,6 @@ implementation {
       signal Notify.notify( BUTTON_PRESSED );
     }
   }
-  
+
   default event void Notify.notify( button_state_t val ) { }
 }
index 903053ba9425554bc83ca74a8741f378cb6dfa8c..dd7d59bf15178dce325e82a71498eb33fda8ccd7 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * USCI Spi test program runs the peripheral in loopback mode.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 module At25dfSpiConfigP {
   provides interface AsyncConfigure<const msp430_usci_spi_t*> as Configure;
 }
 implementation {
-  const static msp430_usci_spi_t def = { 
+  const static msp430_usci_spi_t def = {
     ctl0: UCSYNC | UCMODE_0 | UCMST | UCMSB | UCCKPL, /* SPI mode0 master, MSB first */
     ctl1: UCSWRST | UCSSEL_3,  /* clock spi from SMCLK */
     brx: 1,
index 2b9cc174609333cff355186a765738fd023e51c6..57b0e25ba7acb57c239e7ebc7bd283f58758e68f 100644 (file)
@@ -1,17 +1,17 @@
 
-/* "Copyright (c) 2000-2003 The Regents of the University of California.  
+/* "Copyright (c) 2000-2003 The Regents of the University of California.
  * All rights reserved.
  *
  * Permission to use, copy, modify, and distribute this software and its
  * documentation for any purpose, without fee, and without written agreement
  * is hereby granted, provided that the above copyright notice, the following
  * two paragraphs and the author appear in all copies of this software.
- * 
+ *
  * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
  * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY
  * OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- * 
+ *
  * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
index f0b30b2d5220f38194ad9cdd9a71ee72f9436b92..23cd6982da8fa7e6816de6774fa54debae501284 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Pin assignments for the bq24032 on the tmicore.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration BQ2403XPinsC {
   provides {
     interface GeneralIO as BQstat1;
index a05e768b650a8177547fd9a5c97211ec0a06b2ee..e4a4b2f72908f1b73687bda19b4cf744ff550619 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Pin assignments for the cp2103 on the tmicore.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration CP210XPinsC {
   provides {
     interface GeneralIO as USB_SUSPENDn;
index 1b981ed3643bd30ad608bc88f77f6efa880bf52c..ade28aa418e0a32092b593af7e5d1701d3fc050a 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
  /**
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 module MotePlatformC @safe() {
   provides interface Init;
 }
@@ -51,7 +51,7 @@ implementation {
        P1OUT = 0x10;   /* 0 0 0 1 0 0 0 0 */
        P1DIR = 0x08;   /* 0 0 0 0 1 0 0 0 */
        P1REN = 0x14;   /* 0 0 0 1 0 1 0 0 */
+
        /* Port 2:
         * 7:SHT_DATA, 6:SCP_DRDY, 5:BUTTONn, 4:USB_SUSPENDn, 3:GM_PWRMON,
         * 2:BSL_RX, 1:USBPGn, 0:SOLARPGn
index da2fb01e896aa4173f86319cb178d96c1018ec5e..525955e979451e19e600b3794b1bfd3bf5146900 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Platform specific pin mapping for the Scp1000.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration Scp1000PinsC {
   provides {
     interface GeneralIO as CSn;
index 82d25a1f0e8a74eea71087a6a1cc0b82565877f3..7fc01fa6c06afb7e5e069b728410d4a8c68700be 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Platform dependent scp1000 pin initialization.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
 
 #include "Scp1000.h"
+
 generic module Scp1000PinsP() @safe()
 {
   provides {
index a8b692d6979080fdcce789a47f21e2853034e2d3..5a220df61806e44debda82e156ac82522b196c70 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Platform dependent SPI mapping for Scp1000.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 configuration Scp1000SpiC {
   provides {
     interface Resource;
index ffe7e7957c6bf5edb6900b35a7046855d3a5764f..91314a6e4324cef264982ee3f8b56cdec0424748 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * SPI configuration for Scp1000.
- * 
+ *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 module Scp1000SpiConfigC {
   provides interface AsyncConfigure<const msp430_usci_spi_t*> as Configure;
 }
 implementation {
-  const static msp430_usci_spi_t def = { 
+  const static msp430_usci_spi_t def = {
     ctl0: UCSYNC | UCMODE_0 | UCMST | UCMSB | UCCKPL, /* SPI mode0 master, MSB first */
     ctl1: UCSWRST | UCSSEL_3,  /* clock spi from SMCLK */
     brx: 2,                    /* part says max 500KHz; this is 524288Hz */
index 41155e450df4812da13ee108d431ae0ccd41afbc..60a96c6f3dac66b87ba0977a4c9da0b066bf924a 100644 (file)
@@ -53,7 +53,7 @@ implementation {
   SensirionSht11LogicP.DATA -> HplSensirionSht11C.DATA;
   SensirionSht11LogicP.CLOCK -> HplSensirionSht11C.SCK;
   SensirionSht11LogicP.InterruptDATA -> HplSensirionSht11C.InterruptDATA;
-  
+
   components SensirionBusyWaitC;
   SensirionSht11LogicP.BusyWait -> SensirionBusyWaitC;
 
index 295cf7ea8f3764f1ef3cfb76bcd20f615c57ac4f..cb715145b4fb0b93ffb1c46a8bf7c922c802cead 100644 (file)
@@ -73,7 +73,7 @@ implementation {
 
   components new FcfsArbiterC( "Sht11.Resource" ) as Arbiter;
   Resource = Arbiter;
-  
+
   components new SplitControlPowerManagerC();
   SplitControlPowerManagerC.SplitControl -> HplSensirionSht11P;
   SplitControlPowerManagerC.ArbiterInfo -> Arbiter.ArbiterInfo;
index 777891f3bb6d673c5b99a1b49edeb6ba0ef9acd9..47b7569e8b5aec0b798a012546baa3c7752f0509 100644 (file)
@@ -55,7 +55,7 @@ implementation {
     call Timer.startOneShot( 11 );
     return SUCCESS;
   }
-  
+
   event void Timer.fired() {
     signal SplitControl.startDone( SUCCESS );
   }
index 468589c5aa8dc34ade68300cec468bf1f6d804b8..177a040633f802e184ff67a57a608fd076f7eb67 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Implement an open drain output using an HplMsp430GeneralIO, represented as
  * a GeneralIO.  This component uses the Msp430's internal pull up/down
@@ -34,7 +34,7 @@
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 generic configuration Msp430OpenDrainC()
 {
   provides interface GeneralIO;
index a0950f506bfce7a3cefee81deef8438bacd4b6fd..d34be3d9841cbbb0f8bffe6afa2ecd13ed24f0cb 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Implement an open drain output using an HplMsp430GeneralIO, represented as
  * a GeneralIO.  Uses the pull-up resistor built into the msp430 for each io
@@ -35,7 +35,7 @@
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 generic module Msp430OpenDrainP()
 {
   provides {
index 5af6a2dd7b8e5cf4ca19bb3c5aa6e52c62dd84b4..e89e26f34685c0b1e634776111164f685cb6044d 100644 (file)
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Implement an open drain output using a GeneralIO, represented as a
  * GeneralIO.  Requires an external pull-up for proper operation.
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 generic configuration OpenDrainC()
 {
   provides interface GeneralIO;
index adc96364f3408c7a3860afe3ed59736db1375f3f..9cc2246297ebfbe6a30cf818dc0e5b0c8561c42a 100644 (file)
@@ -26,7 +26,7 @@
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
+
 /**
  * Implement an open drain output using a GeneralIO, represented as a
  * GeneralIO.  clr() puts the pin in input mode, simulating open drain and
@@ -39,7 +39,7 @@
  *
  * @author R. Steve McKown <rsmckown@gmail.com>
  */
+
 generic module OpenDrainP()
 {
   provides {
index eba17537e52b32f748fc2554f5d047a2b91a8552..7d293a3127c52c2c1f6b1b8e2f7cf4791747a2d6 100644 (file)
@@ -46,14 +46,15 @@ generic configuration AMSenderC(am_id_t AMId) {
 }
 
 implementation {
-  components new AMQueueEntryP(AMId) as AMQueueEntryP;
-  components AMQueueP, ActiveMessageC;
 
-  AMQueueEntryP.Send -> AMQueueP.Send[unique(UQ_AMQUEUE_SEND)];
-  AMQueueEntryP.AMPacket -> ActiveMessageC;
-  
-  AMSend = AMQueueEntryP;
-  Packet = ActiveMessageC;
-  AMPacket = ActiveMessageC;
-  Acks = ActiveMessageC;
+#if defined(LOW_POWER_LISTENING)
+  components new LplAMSenderC(AMId) as SenderC;
+#else
+  components new DirectAMSenderC(AMId) as SenderC;
+#endif
+
+  AMSend = SenderC;
+  Packet = SenderC;
+  AMPacket = SenderC;
+  Acks = SenderC;
 }
index f7b2fcedab33f221b78ada452ab1a10c46efed2f..b07f975dc4e5b2b2e762a90c020aff7772ec43cf 100644 (file)
@@ -110,6 +110,7 @@ implementation {
       if(state == RES_BUSY && resId == id) {
         if(call Queue.isEmpty() == FALSE) {
           reqResId = call Queue.dequeue();
+          resId = NO_RES;
           state = RES_GRANTING;
           post grantedTask();
           call ResourceConfigure.unconfigure[id]();
index b3387934d2f64f18acd62b3f33c4b7298e560f51..816484795b10db3f6d3875e457ca37130d1d73f4 100644 (file)
@@ -75,22 +75,22 @@ implementation
 
   async command bool BitVector.get(uint16_t bitnum)
   {
-    return (m_bits[getIndex(bitnum)] & getMask(bitnum)) ? TRUE : FALSE;
+    atomic {return (m_bits[getIndex(bitnum)] & getMask(bitnum)) ? TRUE : FALSE;}
   }
 
   async command void BitVector.set(uint16_t bitnum)
   {
-    m_bits[getIndex(bitnum)] |= getMask(bitnum);
+    atomic {m_bits[getIndex(bitnum)] |= getMask(bitnum);}
   }
 
   async command void BitVector.clear(uint16_t bitnum)
   {
-    m_bits[getIndex(bitnum)] &= ~getMask(bitnum);
+    atomic {m_bits[getIndex(bitnum)] &= ~getMask(bitnum);}
   }
 
   async command void BitVector.toggle(uint16_t bitnum)
   {
-    m_bits[getIndex(bitnum)] ^= getMask(bitnum);
+    atomic {m_bits[getIndex(bitnum)] ^= getMask(bitnum);}
   }
 
   async command void BitVector.assign(uint16_t bitnum, bool value)
diff --git a/tos/system/DirectAMSenderC.nc b/tos/system/DirectAMSenderC.nc
new file mode 100644 (file)
index 0000000..cb4fe07
--- /dev/null
@@ -0,0 +1,59 @@
+// $Id$
+/*
+ * "Copyright (c) 2006 Stanford University. All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and
+ * its documentation for any purpose, without fee, and without written
+ * agreement is hereby granted, provided that the above copyright
+ * notice, the following two paragraphs and the author appear in all
+ * copies of this software.
+ * 
+ * IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+ * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
+ * IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ * 
+ * STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE
+ * PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
+ * HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
+ * ENHANCEMENTS, OR MODIFICATIONS."
+ */
+
+/**
+ * The virtualized active message send abstraction. Each instantiation
+ * of AMSenderC has its own queue of depth one. Therefore, it does not
+ * have to contend with other AMSenderC instantiations for queue space.
+ * The underlying implementation schedules the packets in these queues
+ * using some form of fair-share queueing.
+ *
+ * @author Philip Levis
+ * @date   Jan 16 2006
+ * @see    TEP 116: Packet Protocols
+ */ 
+
+#include "AM.h"
+
+generic configuration DirectAMSenderC(am_id_t AMId) {
+  provides {
+    interface AMSend;
+    interface Packet;
+    interface AMPacket;
+    interface PacketAcknowledgements as Acks;
+  }
+}
+
+implementation {
+  components new AMQueueEntryP(AMId) as AMQueueEntryP;
+  components AMQueueP, ActiveMessageC;
+
+  AMQueueEntryP.Send -> AMQueueP.Send[unique(UQ_AMQUEUE_SEND)];
+  AMQueueEntryP.AMPacket -> ActiveMessageC;
+  
+  AMSend = AMQueueEntryP;
+  Packet = ActiveMessageC;
+  AMPacket = ActiveMessageC;
+  Acks = ActiveMessageC;
+}
index 565ba25fca0f96297bf7b7c4ad4ef81b1a92c41e..23e41dd26a5c4077b7f11f6a9dadd3e266253c9d 100644 (file)
@@ -48,11 +48,11 @@ implementation {
   }  
   
   async command bool FcfsQueue.isEmpty() {
-    return (qHead == NO_ENTRY);
+    atomic return (qHead == NO_ENTRY);
   }
        
   async command bool FcfsQueue.isEnqueued(resource_client_id_t id) {
-       return resQ[id] != NO_ENTRY || qTail == id; 
+       atomic return resQ[id] != NO_ENTRY || qTail == id; 
   }
 
   async command resource_client_id_t FcfsQueue.dequeue() {
diff --git a/tos/system/LplAMSenderC.nc b/tos/system/LplAMSenderC.nc
new file mode 100644 (file)
index 0000000..ec5d561
--- /dev/null
@@ -0,0 +1,28 @@
+#include "AM.h"
+
+generic configuration LplAMSenderC(am_id_t AMId)
+{
+  provides {
+    interface AMSend;
+    interface Packet;
+    interface AMPacket;
+    interface PacketAcknowledgements as Acks;
+  }
+}
+
+implementation
+{
+  components new DirectAMSenderC(AMId);
+  components new LplAMSenderP();
+  components ActiveMessageC;
+  components SystemLowPowerListeningC;
+
+  AMSend = LplAMSenderP;
+  Packet = DirectAMSenderC;
+  AMPacket = DirectAMSenderC;
+  Acks = DirectAMSenderC;
+
+  LplAMSenderP.SubAMSend -> DirectAMSenderC;
+  LplAMSenderP.Lpl -> ActiveMessageC;
+  LplAMSenderP.SystemLowPowerListening -> SystemLowPowerListeningC;
+}
diff --git a/tos/system/LplAMSenderP.nc b/tos/system/LplAMSenderP.nc
new file mode 100644 (file)
index 0000000..62ccb5d
--- /dev/null
@@ -0,0 +1,23 @@
+generic module LplAMSenderP()
+{
+  provides interface AMSend;
+  uses {
+    interface AMSend as SubAMSend;
+    interface LowPowerListening as Lpl;
+    interface SystemLowPowerListening;
+  }
+}
+
+implementation
+{
+  command error_t AMSend.send(am_addr_t addr, message_t* msg, uint8_t len)
+  {
+    call Lpl.setRemoteWakeupInterval(msg, call SystemLowPowerListening.getDefaultRemoteWakeupInterval());
+    return call SubAMSend.send(addr, msg, len);
+  }
+
+  event void SubAMSend.sendDone(message_t* msg, error_t error) { signal AMSend.sendDone(msg, error); }
+  command error_t AMSend.cancel(message_t* msg) { return call SubAMSend.cancel(msg); }
+  command uint8_t AMSend.maxPayloadLength() { return call SubAMSend.maxPayloadLength(); }
+  command void* AMSend.getPayload(message_t* msg, uint8_t len) { return call SubAMSend.getPayload(msg, len); }
+}
index 9f61d0ecebf6891495ba7da4ff1c5c95ee76a736..a6caac44772021d385d0103ff47695a6ca50073f 100644 (file)
@@ -49,6 +49,10 @@ configuration MainC {
 implementation {
   components PlatformC, RealMainP, TinySchedulerC;
 
+#ifdef SAFE_TINYOS
+  components SafeFailureHandlerC;
+#endif
+
   RealMainP.Scheduler -> TinySchedulerC;
   RealMainP.PlatformInit -> PlatformC;
 
index 14dbec6659d266e7c1b2111664568d69aaae786e..9011d6cfd273898c93c904d0fde6c6a4e3fffd1f 100644 (file)
@@ -105,7 +105,7 @@ implementation {
       return FAIL;
     }
     else {
-      uint8_t emptyIndex = (index + free);
+      uint16_t emptyIndex = (index + free);
       if (emptyIndex >= size) {
         emptyIndex -= size;
       }
index 92a14fc6fe169f8d7290db072b2e6eb983a8f8eb..ecf714aabed9f3c9221104001e4ce80cab0a74ab 100644 (file)
@@ -111,7 +111,9 @@ implementation {
   
   command queue_t Queue.element(uint8_t idx) {
     idx += head;
-    idx %= QUEUE_SIZE;
+    if (idx >= QUEUE_SIZE) {
+      idx -= QUEUE_SIZE;
+    }
     return queue[idx];
   }  
 
index ac4c839e40c6660866a555f1ad0e346a39229b67..30f185f2e99926602161b29f6652717f326437a4 100644 (file)
@@ -99,6 +99,7 @@ implementation {
     atomic {
       if(state == RES_BUSY && resId == id) {
         if(call Queue.isEmpty() == FALSE) {
+          resId = NO_RES;
           reqResId = call Queue.dequeue();
           state = RES_GRANTING;
           post grantedTask();
diff --git a/tos/system/SystemLowPowerListeningC.nc b/tos/system/SystemLowPowerListeningC.nc
new file mode 100644 (file)
index 0000000..2aa909c
--- /dev/null
@@ -0,0 +1,10 @@
+configuration SystemLowPowerListeningC
+{
+  provides interface SystemLowPowerListening;
+}
+
+implementation
+{
+  components SystemLowPowerListeningP;
+  SystemLowPowerListening = SystemLowPowerListeningP;
+}
diff --git a/tos/system/SystemLowPowerListeningP.nc b/tos/system/SystemLowPowerListeningP.nc
new file mode 100644 (file)
index 0000000..564db67
--- /dev/null
@@ -0,0 +1,18 @@
+#include "Lpl.h"
+
+module SystemLowPowerListeningP
+{
+  provides interface SystemLowPowerListening;
+}
+
+implementation
+{
+  uint16_t remoteWakeup = LPL_DEF_REMOTE_WAKEUP;
+  uint16_t delayAfterReceive = DELAY_AFTER_RECEIVE;
+
+  command void SystemLowPowerListening.setDefaultRemoteWakeupInterval(uint16_t intervalMs) { remoteWakeup = intervalMs; }
+  command void SystemLowPowerListening.setDelayAfterReceive(uint16_t intervalMs) { delayAfterReceive = intervalMs; }
+
+  command uint16_t SystemLowPowerListening.getDefaultRemoteWakeupInterval() { return remoteWakeup; }
+  command uint16_t SystemLowPowerListening.getDelayAfterReceive() { return delayAfterReceive; }
+}
diff --git a/tos/types/Ieee154.h b/tos/types/Ieee154.h
new file mode 100644 (file)
index 0000000..e71c242
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * "Copyright (c) 2008, 2009 The Regents of the University  of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+ /*
+ *
+ * @author Stephen Dawson-Haggerty <stevedh@eecs.berkeley.edu>
+ * @version $Revision$ $Date$
+ */
+
+#ifndef __IEEE154_H__
+#define __IEEE154_H__
+
+#define IEEE154_SEND_CLIENT "IEEE154_SEND_CLIENT"
+
+typedef uint16_t ieee154_panid_t;
+typedef uint16_t ieee154_saddr_t;
+
+enum {
+  IEEE154_BROADCAST_ADDR = 0xffff,
+};
+
+#endif
diff --git a/tos/types/IeeeEui64.h b/tos/types/IeeeEui64.h
new file mode 100644 (file)
index 0000000..9062fa7
--- /dev/null
@@ -0,0 +1,36 @@
+// $Id$
+/*
+ * Copyright (c) 2007, Vanderbilt University
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
+ * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ *
+ * Author: Janos Sallai
+ * Author: Gilman Tolle, Jonathan Hui (TEP 122)
+ */
+
+#ifndef IEEEEUI64_H
+#define IEEEEUI64_H
+
+enum { IEEE_EUI64_LENGTH = 8 };
+
+typedef struct ieee_eui64 {
+  uint8_t data[IEEE_EUI64_LENGTH];
+} ieee_eui64_t;
+
+#endif // IEEEEUI64_H
\ No newline at end of file
diff --git a/tos/types/Lpl.h b/tos/types/Lpl.h
new file mode 100644 (file)
index 0000000..05219ba
--- /dev/null
@@ -0,0 +1,23 @@
+#ifndef LPL_H
+#define LPL_H
+
+/**
+ * Amount of time, in milliseconds, to keep the radio on after
+ * a successful receive addressed to this node
+ */
+#ifndef DELAY_AFTER_RECEIVE
+#define DELAY_AFTER_RECEIVE 100
+#endif
+
+/**
+ * The LPL defaults to stay-on.
+ */
+#ifndef LPL_DEF_LOCAL_WAKEUP
+#define LPL_DEF_LOCAL_WAKEUP 0
+#endif
+
+#ifndef LPL_DEF_REMOTE_WAKEUP
+#define LPL_DEF_REMOTE_WAKEUP 0
+#endif
+
+#endif
index dc66c268e5985eb36e7ae870106b5fec41d0ed8f..69a0a4373101bf88966981af0542a5a3dd1b0764 100644 (file)
@@ -18,4 +18,11 @@ typedef nx_struct message_t {
   nx_uint8_t metadata[sizeof(message_metadata_t)];
 } message_t;
 
+/*
+ * This resource is used to arbitrate access between ActiveMessageC,
+ * Ieee154MessageC and possibly future MessageC components to the 
+ * underlying radio driver.
+ */
+#define RADIO_SEND_RESOURCE "RADIO_SEND_RESOURCE"
+
 #endif